PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
ruleutils.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include "access/amapi.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/partition.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_am.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_language.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_partitioned_table.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_trigger.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/tablespace.h"
#include "common/keywords.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/tlist.h"
#include "parser/parse_node.h"
#include "parser/parse_agg.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "parser/parser.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "rewrite/rewriteSupport.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/hsearch.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/tqual.h"
#include "utils/typcache.h"
#include "utils/varlena.h"
#include "utils/xml.h"
Include dependency graph for ruleutils.c:

Go to the source code of this file.

Data Structures

struct  deparse_context
 
struct  deparse_namespace
 
struct  deparse_columns
 
struct  NameHashEntry
 

Macros

#define PRETTYINDENT_STD   8
 
#define PRETTYINDENT_JOIN   4
 
#define PRETTYINDENT_VAR   4
 
#define PRETTYINDENT_LIMIT   40 /* wrap limit */
 
#define PRETTYFLAG_PAREN   1
 
#define PRETTYFLAG_INDENT   2
 
#define WRAP_COLUMN_DEFAULT   0
 
#define PRETTY_PAREN(context)   ((context)->prettyFlags & PRETTYFLAG_PAREN)
 
#define PRETTY_INDENT(context)   ((context)->prettyFlags & PRETTYFLAG_INDENT)
 
#define deparse_columns_fetch(rangetable_index, dpns)   ((deparse_columns *) list_nth((dpns)->rtable_columns, (rangetable_index)-1))
 
#define only_marker(rte)   ((rte)->inh ? "" : "ONLY ")
 

Functions

static char * deparse_expression_pretty (Node *expr, List *dpcontext, bool forceprefix, bool showimplicit, int prettyFlags, int startIndent)
 
static char * pg_get_viewdef_worker (Oid viewoid, int prettyFlags, int wrapColumn)
 
static char * pg_get_triggerdef_worker (Oid trigid, bool pretty)
 
static void decompile_column_index_array (Datum column_index_array, Oid relId, StringInfo buf)
 
static char * pg_get_ruledef_worker (Oid ruleoid, int prettyFlags)
 
static char * pg_get_indexdef_worker (Oid indexrelid, int colno, const Oid *excludeOps, bool attrsOnly, bool showTblSpc, int prettyFlags, bool missing_ok)
 
static char * pg_get_statisticsobj_worker (Oid statextid, bool missing_ok)
 
static char * pg_get_partkeydef_worker (Oid relid, int prettyFlags, bool attrsOnly, bool missing_ok)
 
static char * pg_get_constraintdef_worker (Oid constraintId, bool fullCommand, int prettyFlags, bool missing_ok)
 
static textpg_get_expr_worker (text *expr, Oid relid, const char *relname, int prettyFlags)
 
static int print_function_arguments (StringInfo buf, HeapTuple proctup, bool print_table_args, bool print_defaults)
 
static void print_function_rettype (StringInfo buf, HeapTuple proctup)
 
static void print_function_trftypes (StringInfo buf, HeapTuple proctup)
 
static void set_rtable_names (deparse_namespace *dpns, List *parent_namespaces, Bitmapset *rels_used)
 
static void set_deparse_for_query (deparse_namespace *dpns, Query *query, List *parent_namespaces)
 
static void set_simple_column_names (deparse_namespace *dpns)
 
static bool has_dangerous_join_using (deparse_namespace *dpns, Node *jtnode)
 
static void set_using_names (deparse_namespace *dpns, Node *jtnode, List *parentUsing)
 
static void set_relation_column_names (deparse_namespace *dpns, RangeTblEntry *rte, deparse_columns *colinfo)
 
static void set_join_column_names (deparse_namespace *dpns, RangeTblEntry *rte, deparse_columns *colinfo)
 
static bool colname_is_unique (char *colname, deparse_namespace *dpns, deparse_columns *colinfo)
 
static char * make_colname_unique (char *colname, deparse_namespace *dpns, deparse_columns *colinfo)
 
static void expand_colnames_array_to (deparse_columns *colinfo, int n)
 
static void identify_join_columns (JoinExpr *j, RangeTblEntry *jrte, deparse_columns *colinfo)
 
static void flatten_join_using_qual (Node *qual, List **leftvars, List **rightvars)
 
static char * get_rtable_name (int rtindex, deparse_context *context)
 
static void set_deparse_planstate (deparse_namespace *dpns, PlanState *ps)
 
static void push_child_plan (deparse_namespace *dpns, PlanState *ps, deparse_namespace *save_dpns)
 
static void pop_child_plan (deparse_namespace *dpns, deparse_namespace *save_dpns)
 
static void push_ancestor_plan (deparse_namespace *dpns, ListCell *ancestor_cell, deparse_namespace *save_dpns)
 
static void pop_ancestor_plan (deparse_namespace *dpns, deparse_namespace *save_dpns)
 
static void make_ruledef (StringInfo buf, HeapTuple ruletup, TupleDesc rulettc, int prettyFlags)
 
static void make_viewdef (StringInfo buf, HeapTuple ruletup, TupleDesc rulettc, int prettyFlags, int wrapColumn)
 
static void get_query_def (Query *query, StringInfo buf, List *parentnamespace, TupleDesc resultDesc, int prettyFlags, int wrapColumn, int startIndent)
 
static void get_values_def (List *values_lists, deparse_context *context)
 
static void get_with_clause (Query *query, deparse_context *context)
 
static void get_select_query_def (Query *query, deparse_context *context, TupleDesc resultDesc)
 
static void get_insert_query_def (Query *query, deparse_context *context)
 
static void get_update_query_def (Query *query, deparse_context *context)
 
static void get_update_query_targetlist_def (Query *query, List *targetList, deparse_context *context, RangeTblEntry *rte)
 
static void get_delete_query_def (Query *query, deparse_context *context)
 
static void get_utility_query_def (Query *query, deparse_context *context)
 
static void get_basic_select_query (Query *query, deparse_context *context, TupleDesc resultDesc)
 
static void get_target_list (List *targetList, deparse_context *context, TupleDesc resultDesc)
 
static void get_setop_query (Node *setOp, Query *query, deparse_context *context, TupleDesc resultDesc)
 
static Nodeget_rule_sortgroupclause (Index ref, List *tlist, bool force_colno, deparse_context *context)
 
static void get_rule_groupingset (GroupingSet *gset, List *targetlist, bool omit_parens, deparse_context *context)
 
static void get_rule_orderby (List *orderList, List *targetList, bool force_colno, deparse_context *context)
 
static void get_rule_windowclause (Query *query, deparse_context *context)
 
static void get_rule_windowspec (WindowClause *wc, List *targetList, deparse_context *context)
 
static char * get_variable (Var *var, int levelsup, bool istoplevel, deparse_context *context)
 
static void get_special_variable (Node *node, deparse_context *context, void *private)
 
static void resolve_special_varno (Node *node, deparse_context *context, void *private, void(*callback)(Node *, deparse_context *, void *))
 
static Nodefind_param_referent (Param *param, deparse_context *context, deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
 
static void get_parameter (Param *param, deparse_context *context)
 
static const char * get_simple_binary_op_name (OpExpr *expr)
 
static bool isSimpleNode (Node *node, Node *parentNode, int prettyFlags)
 
static void appendContextKeyword (deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
 
static void removeStringInfoSpaces (StringInfo str)
 
static void get_rule_expr (Node *node, deparse_context *context, bool showimplicit)
 
static void get_rule_expr_toplevel (Node *node, deparse_context *context, bool showimplicit)
 
static void get_oper_expr (OpExpr *expr, deparse_context *context)
 
static void get_func_expr (FuncExpr *expr, deparse_context *context, bool showimplicit)
 
static void get_agg_expr (Aggref *aggref, deparse_context *context, Aggref *original_aggref)
 
static void get_agg_combine_expr (Node *node, deparse_context *context, void *private)
 
static void get_windowfunc_expr (WindowFunc *wfunc, deparse_context *context)
 
static void get_coercion_expr (Node *arg, deparse_context *context, Oid resulttype, int32 resulttypmod, Node *parentNode)
 
static void get_const_expr (Const *constval, deparse_context *context, int showtype)
 
static void get_const_collation (Const *constval, deparse_context *context)
 
static void simple_quote_literal (StringInfo buf, const char *val)
 
static void get_sublink_expr (SubLink *sublink, deparse_context *context)
 
static void get_tablefunc (TableFunc *tf, deparse_context *context, bool showimplicit)
 
static void get_from_clause (Query *query, const char *prefix, deparse_context *context)
 
static void get_from_clause_item (Node *jtnode, Query *query, deparse_context *context)
 
static void get_column_alias_list (deparse_columns *colinfo, deparse_context *context)
 
static void get_from_clause_coldeflist (RangeTblFunction *rtfunc, deparse_columns *colinfo, deparse_context *context)
 
static void get_tablesample_def (TableSampleClause *tablesample, deparse_context *context)
 
static void get_opclass_name (Oid opclass, Oid actual_datatype, StringInfo buf)
 
static NodeprocessIndirection (Node *node, deparse_context *context)
 
static void printSubscripts (ArrayRef *aref, deparse_context *context)
 
static char * get_relation_name (Oid relid)
 
static char * generate_relation_name (Oid relid, List *namespaces)
 
static char * generate_qualified_relation_name (Oid relid)
 
static char * generate_function_name (Oid funcid, int nargs, List *argnames, Oid *argtypes, bool has_variadic, bool *use_variadic_p, ParseExprKind special_exprkind)
 
static char * generate_operator_name (Oid operid, Oid arg1, Oid arg2)
 
static textstring_to_text (char *str)
 
static char * flatten_reloptions (Oid relid)
 
Datum pg_get_ruledef (PG_FUNCTION_ARGS)
 
Datum pg_get_ruledef_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_wrap (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_name (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_name_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_triggerdef (PG_FUNCTION_ARGS)
 
Datum pg_get_triggerdef_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_indexdef (PG_FUNCTION_ARGS)
 
Datum pg_get_indexdef_ext (PG_FUNCTION_ARGS)
 
char * pg_get_indexdef_string (Oid indexrelid)
 
char * pg_get_indexdef_columns (Oid indexrelid, bool pretty)
 
Datum pg_get_statisticsobjdef (PG_FUNCTION_ARGS)
 
Datum pg_get_partkeydef (PG_FUNCTION_ARGS)
 
char * pg_get_partkeydef_columns (Oid relid, bool pretty)
 
Datum pg_get_partition_constraintdef (PG_FUNCTION_ARGS)
 
Datum pg_get_constraintdef (PG_FUNCTION_ARGS)
 
Datum pg_get_constraintdef_ext (PG_FUNCTION_ARGS)
 
char * pg_get_constraintdef_command (Oid constraintId)
 
Datum pg_get_expr (PG_FUNCTION_ARGS)
 
Datum pg_get_expr_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_userbyid (PG_FUNCTION_ARGS)
 
Datum pg_get_serial_sequence (PG_FUNCTION_ARGS)
 
Datum pg_get_functiondef (PG_FUNCTION_ARGS)
 
Datum pg_get_function_arguments (PG_FUNCTION_ARGS)
 
Datum pg_get_function_identity_arguments (PG_FUNCTION_ARGS)
 
Datum pg_get_function_result (PG_FUNCTION_ARGS)
 
static bool is_input_argument (int nth, const char *argmodes)
 
Datum pg_get_function_arg_default (PG_FUNCTION_ARGS)
 
char * deparse_expression (Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
 
Listdeparse_context_for (const char *aliasname, Oid relid)
 
Listdeparse_context_for_plan_rtable (List *rtable, List *rtable_names)
 
Listset_deparse_context_planstate (List *dpcontext, Node *planstate, List *ancestors)
 
Listselect_rtable_names_for_explain (List *rtable, Bitmapset *rels_used)
 
static RangeTblEntryget_simple_values_rte (Query *query)
 
static const char * get_name_for_var_field (Var *var, int fieldno, int levelsup, deparse_context *context)
 
static void get_rule_expr_paren (Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
 
const char * quote_identifier (const char *ident)
 
char * quote_qualified_identifier (const char *qualifier, const char *ident)
 
char * generate_collation_name (Oid collid)
 

Variables

static SPIPlanPtr plan_getrulebyoid = NULL
 
static const char * query_getrulebyoid = "SELECT * FROM pg_catalog.pg_rewrite WHERE oid = $1"
 
static SPIPlanPtr plan_getviewrule = NULL
 
static const char * query_getviewrule = "SELECT * FROM pg_catalog.pg_rewrite WHERE ev_class = $1 AND rulename = $2"
 
bool quote_all_identifiers = false
 

Macro Definition Documentation

#define deparse_columns_fetch (   rangetable_index,
  dpns 
)    ((deparse_columns *) list_nth((dpns)->rtable_columns, (rangetable_index)-1))
#define only_marker (   rte)    ((rte)->inh ? "" : "ONLY ")

Definition at line 463 of file ruleutils.c.

Referenced by get_delete_query_def(), get_from_clause_item(), and get_update_query_def().

#define PRETTY_PAREN (   context)    ((context)->prettyFlags & PRETTYFLAG_PAREN)
#define PRETTYINDENT_JOIN   4

Definition at line 83 of file ruleutils.c.

Referenced by get_from_clause_item().

#define PRETTYINDENT_LIMIT   40 /* wrap limit */

Definition at line 86 of file ruleutils.c.

Referenced by appendContextKeyword().

#define PRETTYINDENT_VAR   4

Definition at line 84 of file ruleutils.c.

Referenced by get_from_clause(), get_rule_expr(), and get_target_list().

Function Documentation

static void appendContextKeyword ( deparse_context context,
const char *  str,
int  indentBefore,
int  indentAfter,
int  indentPlus 
)
static

Definition at line 7458 of file ruleutils.c.

References appendStringInfoChar(), appendStringInfoSpaces(), appendStringInfoString(), buf, deparse_context::buf, deparse_context::indentLevel, Max, PRETTY_INDENT, PRETTYINDENT_LIMIT, PRETTYINDENT_STD, and removeStringInfoSpaces().

Referenced by get_basic_select_query(), get_delete_query_def(), get_from_clause(), get_from_clause_item(), get_insert_query_def(), get_rule_expr(), get_rule_windowclause(), get_select_query_def(), get_setop_query(), get_target_list(), get_update_query_def(), get_utility_query_def(), and get_with_clause().

7460 {
7461  StringInfo buf = context->buf;
7462 
7463  if (PRETTY_INDENT(context))
7464  {
7465  int indentAmount;
7466 
7467  context->indentLevel += indentBefore;
7468 
7469  /* remove any trailing spaces currently in the buffer ... */
7471  /* ... then add a newline and some spaces */
7472  appendStringInfoChar(buf, '\n');
7473 
7474  if (context->indentLevel < PRETTYINDENT_LIMIT)
7475  indentAmount = Max(context->indentLevel, 0) + indentPlus;
7476  else
7477  {
7478  /*
7479  * If we're indented more than PRETTYINDENT_LIMIT characters, try
7480  * to conserve horizontal space by reducing the per-level
7481  * indentation. For best results the scale factor here should
7482  * divide all the indent amounts that get added to indentLevel
7483  * (PRETTYINDENT_STD, etc). It's important that the indentation
7484  * not grow unboundedly, else deeply-nested trees use O(N^2)
7485  * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
7486  */
7487  indentAmount = PRETTYINDENT_LIMIT +
7488  (context->indentLevel - PRETTYINDENT_LIMIT) /
7489  (PRETTYINDENT_STD / 2);
7490  indentAmount %= PRETTYINDENT_LIMIT;
7491  /* scale/wrap logic affects indentLevel, but not indentPlus */
7492  indentAmount += indentPlus;
7493  }
7494  appendStringInfoSpaces(buf, indentAmount);
7495 
7496  appendStringInfoString(buf, str);
7497 
7498  context->indentLevel += indentAfter;
7499  if (context->indentLevel < 0)
7500  context->indentLevel = 0;
7501  }
7502  else
7503  appendStringInfoString(buf, str);
7504 }
#define PRETTY_INDENT(context)
Definition: ruleutils.c:97
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
static void removeStringInfoSpaces(StringInfo str)
Definition: ruleutils.c:7512
#define PRETTYINDENT_STD
Definition: ruleutils.c:82
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void appendStringInfoSpaces(StringInfo str, int count)
Definition: stringinfo.c:187
#define PRETTYINDENT_LIMIT
Definition: ruleutils.c:86
#define Max(x, y)
Definition: c.h:800
StringInfo buf
Definition: ruleutils.c:108
static bool colname_is_unique ( char *  colname,
deparse_namespace dpns,
deparse_columns colinfo 
)
static

Definition at line 4093 of file ruleutils.c.

References deparse_columns::colnames, i, lfirst, deparse_columns::new_colnames, deparse_columns::num_cols, deparse_columns::num_new_cols, deparse_columns::parentUsing, and deparse_namespace::using_names.

Referenced by make_colname_unique().

4095 {
4096  int i;
4097  ListCell *lc;
4098 
4099  /* Check against already-assigned column aliases within RTE */
4100  for (i = 0; i < colinfo->num_cols; i++)
4101  {
4102  char *oldname = colinfo->colnames[i];
4103 
4104  if (oldname && strcmp(oldname, colname) == 0)
4105  return false;
4106  }
4107 
4108  /*
4109  * If we're building a new_colnames array, check that too (this will be
4110  * partially but not completely redundant with the previous checks)
4111  */
4112  for (i = 0; i < colinfo->num_new_cols; i++)
4113  {
4114  char *oldname = colinfo->new_colnames[i];
4115 
4116  if (oldname && strcmp(oldname, colname) == 0)
4117  return false;
4118  }
4119 
4120  /* Also check against USING-column names that must be globally unique */
4121  foreach(lc, dpns->using_names)
4122  {
4123  char *oldname = (char *) lfirst(lc);
4124 
4125  if (strcmp(oldname, colname) == 0)
4126  return false;
4127  }
4128 
4129  /* Also check against names already assigned for parent-join USING cols */
4130  foreach(lc, colinfo->parentUsing)
4131  {
4132  char *oldname = (char *) lfirst(lc);
4133 
4134  if (strcmp(oldname, colname) == 0)
4135  return false;
4136  }
4137 
4138  return true;
4139 }
List * using_names
Definition: ruleutils.c:155
#define lfirst(lc)
Definition: pg_list.h:106
int i
List * parentUsing
Definition: ruleutils.c:249
char ** new_colnames
Definition: ruleutils.c:242
char ** colnames
Definition: ruleutils.c:225
static void decompile_column_index_array ( Datum  column_index_array,
Oid  relId,
StringInfo  buf 
)
static

Definition at line 2156 of file ruleutils.c.

References appendStringInfo(), appendStringInfoString(), DatumGetArrayTypeP, DatumGetInt16, deconstruct_array(), get_relid_attribute_name(), INT2OID, NULL, and quote_identifier().

Referenced by pg_get_constraintdef_worker().

2158 {
2159  Datum *keys;
2160  int nKeys;
2161  int j;
2162 
2163  /* Extract data from array of int16 */
2164  deconstruct_array(DatumGetArrayTypeP(column_index_array),
2165  INT2OID, 2, true, 's',
2166  &keys, NULL, &nKeys);
2167 
2168  for (j = 0; j < nKeys; j++)
2169  {
2170  char *colName;
2171 
2172  colName = get_relid_attribute_name(relId, DatumGetInt16(keys[j]));
2173 
2174  if (j == 0)
2176  else
2177  appendStringInfo(buf, ", %s", quote_identifier(colName));
2178  }
2179 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10280
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define INT2OID
Definition: pg_type.h:308
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
#define DatumGetInt16(X)
Definition: postgres.h:450
char * get_relid_attribute_name(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:801
uintptr_t Datum
Definition: postgres.h:372
#define NULL
Definition: c.h:229
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3475
#define DatumGetArrayTypeP(X)
Definition: array.h:242
List* deparse_context_for ( const char *  aliasname,
Oid  relid 
)

Definition at line 3036 of file ruleutils.c.

References RangeTblEntry::alias, deparse_namespace::ctes, RangeTblEntry::eref, RangeTblEntry::inFromCl, RangeTblEntry::inh, RangeTblEntry::lateral, list_make1, makeAlias(), makeNode, NIL, NULL, palloc0(), RangeTblEntry::relid, RangeTblEntry::relkind, RELKIND_RELATION, deparse_namespace::rtable, RTE_RELATION, RangeTblEntry::rtekind, set_rtable_names(), and set_simple_column_names().

Referenced by pg_get_constraintdef_worker(), pg_get_expr_worker(), pg_get_indexdef_worker(), pg_get_partition_constraintdef(), pg_get_partkeydef_worker(), StoreAttrDefault(), StoreRelCheck(), and transformPartitionBound().

3037 {
3038  deparse_namespace *dpns;
3039  RangeTblEntry *rte;
3040 
3041  dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3042 
3043  /* Build a minimal RTE for the rel */
3044  rte = makeNode(RangeTblEntry);
3045  rte->rtekind = RTE_RELATION;
3046  rte->relid = relid;
3047  rte->relkind = RELKIND_RELATION; /* no need for exactness here */
3048  rte->alias = makeAlias(aliasname, NIL);
3049  rte->eref = rte->alias;
3050  rte->lateral = false;
3051  rte->inh = false;
3052  rte->inFromCl = true;
3053 
3054  /* Build one-element rtable */
3055  dpns->rtable = list_make1(rte);
3056  dpns->ctes = NIL;
3057  set_rtable_names(dpns, NIL, NULL);
3059 
3060  /* Return a one-deep namespace stack */
3061  return list_make1(dpns);
3062 }
#define NIL
Definition: pg_list.h:69
Alias * alias
Definition: parsenodes.h:1034
#define list_make1(x1)
Definition: pg_list.h:139
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:384
static void set_rtable_names(deparse_namespace *dpns, List *parent_namespaces, Bitmapset *rels_used)
Definition: ruleutils.c:3180
void * palloc0(Size size)
Definition: mcxt.c:878
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
static void set_simple_column_names(deparse_namespace *dpns)
Definition: ruleutils.c:3393
RTEKind rtekind
Definition: parsenodes.h:936
Alias * eref
Definition: parsenodes.h:1035
#define RELKIND_RELATION
Definition: pg_class.h:160
List* deparse_context_for_plan_rtable ( List rtable,
List rtable_names 
)

Definition at line 3078 of file ruleutils.c.

References deparse_namespace::ctes, list_make1, NIL, palloc0(), deparse_namespace::rtable, deparse_namespace::rtable_names, and set_simple_column_names().

Referenced by ExplainPrintPlan().

3079 {
3080  deparse_namespace *dpns;
3081 
3082  dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3083 
3084  /* Initialize fields that stay the same across the whole plan tree */
3085  dpns->rtable = rtable;
3086  dpns->rtable_names = rtable_names;
3087  dpns->ctes = NIL;
3088 
3089  /*
3090  * Set up column name aliases. We will get rather bogus results for join
3091  * RTEs, but that doesn't matter because plan trees don't contain any join
3092  * alias Vars.
3093  */
3095 
3096  /* Return a one-deep namespace stack */
3097  return list_make1(dpns);
3098 }
#define NIL
Definition: pg_list.h:69
List * rtable_names
Definition: ruleutils.c:150
#define list_make1(x1)
Definition: pg_list.h:139
void * palloc0(Size size)
Definition: mcxt.c:878
static void set_simple_column_names(deparse_namespace *dpns)
Definition: ruleutils.c:3393
char* deparse_expression ( Node expr,
List dpcontext,
bool  forceprefix,
bool  showimplicit 
)

Definition at line 2977 of file ruleutils.c.

References deparse_expression_pretty().

Referenced by AlterDomainDefault(), DefineDomain(), domainAddConstraint(), pg_get_function_arg_default(), print_function_arguments(), show_expression(), show_grouping_set_keys(), show_plan_tlist(), show_sort_group_keys(), show_tablesample(), StoreAttrDefault(), StoreRelCheck(), and transformPartitionBound().

2979 {
2980  return deparse_expression_pretty(expr, dpcontext, forceprefix,
2981  showimplicit, 0, 0);
2982 }
static char * deparse_expression_pretty(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit, int prettyFlags, int startIndent)
Definition: ruleutils.c:3004
static char * deparse_expression_pretty ( Node expr,
List dpcontext,
bool  forceprefix,
bool  showimplicit,
int  prettyFlags,
int  startIndent 
)
static

Definition at line 3004 of file ruleutils.c.

References buf, deparse_context::buf, StringInfoData::data, EXPR_KIND_NONE, get_rule_expr(), deparse_context::indentLevel, initStringInfo(), deparse_context::namespaces, NIL, deparse_context::prettyFlags, deparse_context::special_exprkind, deparse_context::varprefix, deparse_context::windowClause, deparse_context::windowTList, WRAP_COLUMN_DEFAULT, and deparse_context::wrapColumn.

Referenced by deparse_expression(), pg_get_constraintdef_worker(), pg_get_expr_worker(), pg_get_indexdef_worker(), pg_get_partition_constraintdef(), and pg_get_partkeydef_worker().

3007 {
3009  deparse_context context;
3010 
3011  initStringInfo(&buf);
3012  context.buf = &buf;
3013  context.namespaces = dpcontext;
3014  context.windowClause = NIL;
3015  context.windowTList = NIL;
3016  context.varprefix = forceprefix;
3017  context.prettyFlags = prettyFlags;
3018  context.wrapColumn = WRAP_COLUMN_DEFAULT;
3019  context.indentLevel = startIndent;
3020  context.special_exprkind = EXPR_KIND_NONE;
3021 
3022  get_rule_expr(expr, &context, showimplicit);
3023 
3024  return buf.data;
3025 }
List * namespaces
Definition: ruleutils.c:109
#define NIL
Definition: pg_list.h:69
#define WRAP_COLUMN_DEFAULT
Definition: ruleutils.c:93
static char * buf
Definition: pg_test_fsync.c:66
ParseExprKind special_exprkind
Definition: ruleutils.c:116
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
List * windowTList
Definition: ruleutils.c:111
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7563
List * windowClause
Definition: ruleutils.c:110
StringInfo buf
Definition: ruleutils.c:108
static void expand_colnames_array_to ( deparse_columns colinfo,
int  n 
)
static

Definition at line 4191 of file ruleutils.c.

References deparse_columns::colnames, NULL, deparse_columns::num_cols, palloc0(), and repalloc().

Referenced by set_join_column_names(), set_relation_column_names(), and set_using_names().

4192 {
4193  if (n > colinfo->num_cols)
4194  {
4195  if (colinfo->colnames == NULL)
4196  colinfo->colnames = (char **) palloc0(n * sizeof(char *));
4197  else
4198  {
4199  colinfo->colnames = (char **) repalloc(colinfo->colnames,
4200  n * sizeof(char *));
4201  memset(colinfo->colnames + colinfo->num_cols, 0,
4202  (n - colinfo->num_cols) * sizeof(char *));
4203  }
4204  colinfo->num_cols = n;
4205  }
4206 }
void * palloc0(Size size)
Definition: mcxt.c:878
#define NULL
Definition: c.h:229
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:963
char ** colnames
Definition: ruleutils.c:225
static Node * find_param_referent ( Param param,
deparse_context context,
deparse_namespace **  dpns_p,
ListCell **  ancestor_cell_p 
)
static

Definition at line 7033 of file ruleutils.c.

References deparse_namespace::ancestors, arg, SubPlan::args, Assert, forboth, PlanState::initPlan, innerPlanState, IsA, lfirst, lfirst_int, linitial, deparse_context::namespaces, NestLoop::nestParams, NIL, NULL, PARAM_EXEC, Param::paramid, Param::paramkind, NestLoopParam::paramno, NestLoopParam::paramval, SubPlan::parParam, PlanState::plan, deparse_namespace::planstate, SubPlanState::planstate, SubPlanState::subplan, and PlanState::subPlan.

Referenced by get_name_for_var_field(), and get_parameter().

7035 {
7036  /* Initialize output parameters to prevent compiler warnings */
7037  *dpns_p = NULL;
7038  *ancestor_cell_p = NULL;
7039 
7040  /*
7041  * If it's a PARAM_EXEC parameter, look for a matching NestLoopParam or
7042  * SubPlan argument. This will necessarily be in some ancestor of the
7043  * current expression's PlanState.
7044  */
7045  if (param->paramkind == PARAM_EXEC)
7046  {
7047  deparse_namespace *dpns;
7048  PlanState *child_ps;
7049  bool in_same_plan_level;
7050  ListCell *lc;
7051 
7052  dpns = (deparse_namespace *) linitial(context->namespaces);
7053  child_ps = dpns->planstate;
7054  in_same_plan_level = true;
7055 
7056  foreach(lc, dpns->ancestors)
7057  {
7058  PlanState *ps = (PlanState *) lfirst(lc);
7059  ListCell *lc2;
7060 
7061  /*
7062  * NestLoops transmit params to their inner child only; also, once
7063  * we've crawled up out of a subplan, this couldn't possibly be
7064  * the right match.
7065  */
7066  if (IsA(ps, NestLoopState) &&
7067  child_ps == innerPlanState(ps) &&
7068  in_same_plan_level)
7069  {
7070  NestLoop *nl = (NestLoop *) ps->plan;
7071 
7072  foreach(lc2, nl->nestParams)
7073  {
7074  NestLoopParam *nlp = (NestLoopParam *) lfirst(lc2);
7075 
7076  if (nlp->paramno == param->paramid)
7077  {
7078  /* Found a match, so return it */
7079  *dpns_p = dpns;
7080  *ancestor_cell_p = lc;
7081  return (Node *) nlp->paramval;
7082  }
7083  }
7084  }
7085 
7086  /*
7087  * Check to see if we're crawling up from a subplan.
7088  */
7089  foreach(lc2, ps->subPlan)
7090  {
7091  SubPlanState *sstate = (SubPlanState *) lfirst(lc2);
7092  SubPlan *subplan = sstate->subplan;
7093  ListCell *lc3;
7094  ListCell *lc4;
7095 
7096  if (child_ps != sstate->planstate)
7097  continue;
7098 
7099  /* Matched subplan, so check its arguments */
7100  forboth(lc3, subplan->parParam, lc4, subplan->args)
7101  {
7102  int paramid = lfirst_int(lc3);
7103  Node *arg = (Node *) lfirst(lc4);
7104 
7105  if (paramid == param->paramid)
7106  {
7107  /* Found a match, so return it */
7108  *dpns_p = dpns;
7109  *ancestor_cell_p = lc;
7110  return arg;
7111  }
7112  }
7113 
7114  /* Keep looking, but we are emerging from a subplan. */
7115  in_same_plan_level = false;
7116  break;
7117  }
7118 
7119  /*
7120  * Likewise check to see if we're emerging from an initplan.
7121  * Initplans never have any parParams, so no need to search that
7122  * list, but we need to know if we should reset
7123  * in_same_plan_level.
7124  */
7125  foreach(lc2, ps->initPlan)
7126  {
7127  SubPlanState *sstate = (SubPlanState *) lfirst(lc2);
7128 
7129  if (child_ps != sstate->planstate)
7130  continue;
7131 
7132  /* No parameters to be had here. */
7133  Assert(sstate->subplan->parParam == NIL);
7134 
7135  /* Keep looking, but we are emerging from an initplan. */
7136  in_same_plan_level = false;
7137  break;
7138  }
7139 
7140  /* No luck, crawl up to next ancestor */
7141  child_ps = ps;
7142  }
7143  }
7144 
7145  /* No referent found */
7146  return NULL;
7147 }
List * namespaces
Definition: ruleutils.c:109
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
List * nestParams
Definition: plannodes.h:686
List * initPlan
Definition: execnodes.h:849
List * subPlan
Definition: execnodes.h:851
ParamKind paramkind
Definition: primnodes.h:244
Definition: nodes.h:509
Var * paramval
Definition: plannodes.h:693
#define linitial(l)
Definition: pg_list.h:111
struct PlanState * planstate
Definition: execnodes.h:755
SubPlan * subplan
Definition: execnodes.h:754
#define lfirst_int(lc)
Definition: pg_list.h:107
Plan * plan
Definition: execnodes.h:832
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
int paramid
Definition: primnodes.h:245
List * parParam
Definition: primnodes.h:709
PlanState * planstate
Definition: ruleutils.c:157
void * arg
#define innerPlanState(node)
Definition: execnodes.h:873
List * args
Definition: primnodes.h:710
static void flatten_join_using_qual ( Node qual,
List **  leftvars,
List **  rightvars 
)
static

Definition at line 4342 of file ruleutils.c.

References AND_EXPR, OpExpr::args, BoolExpr::args, Assert, BoolExpr::boolop, elog, ERROR, IsA, lappend(), lfirst, linitial, list_length(), lsecond, nodeTag, and strip_implicit_coercions().

Referenced by identify_join_columns().

4343 {
4344  if (IsA(qual, BoolExpr))
4345  {
4346  /* Handle AND nodes by recursion */
4347  BoolExpr *b = (BoolExpr *) qual;
4348  ListCell *lc;
4349 
4350  Assert(b->boolop == AND_EXPR);
4351  foreach(lc, b->args)
4352  {
4354  leftvars, rightvars);
4355  }
4356  }
4357  else if (IsA(qual, OpExpr))
4358  {
4359  /* Otherwise we should have an equality operator */
4360  OpExpr *op = (OpExpr *) qual;
4361  Var *var;
4362 
4363  if (list_length(op->args) != 2)
4364  elog(ERROR, "unexpected unary operator in JOIN/USING qual");
4365  /* Arguments should be Vars with perhaps implicit coercions */
4366  var = (Var *) strip_implicit_coercions((Node *) linitial(op->args));
4367  if (!IsA(var, Var))
4368  elog(ERROR, "unexpected node type in JOIN/USING qual: %d",
4369  (int) nodeTag(var));
4370  *leftvars = lappend(*leftvars, var);
4371  var = (Var *) strip_implicit_coercions((Node *) lsecond(op->args));
4372  if (!IsA(var, Var))
4373  elog(ERROR, "unexpected node type in JOIN/USING qual: %d",
4374  (int) nodeTag(var));
4375  *rightvars = lappend(*rightvars, var);
4376  }
4377  else
4378  {
4379  /* Perhaps we have an implicit coercion to boolean? */
4380  Node *q = strip_implicit_coercions(qual);
4381 
4382  if (q != qual)
4383  flatten_join_using_qual(q, leftvars, rightvars);
4384  else
4385  elog(ERROR, "unexpected node type in JOIN/USING qual: %d",
4386  (int) nodeTag(qual));
4387  }
4388 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Definition: nodes.h:509
Definition: primnodes.h:163
#define lsecond(l)
Definition: pg_list.h:116
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
BoolExprType boolop
Definition: primnodes.h:562
List * lappend(List *list, void *datum)
Definition: list.c:128
static void flatten_join_using_qual(Node *qual, List **leftvars, List **rightvars)
Definition: ruleutils.c:4342
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
List * args
Definition: primnodes.h:563
#define nodeTag(nodeptr)
Definition: nodes.h:514
#define elog
Definition: elog.h:219
List * args
Definition: primnodes.h:502
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:612
static char * flatten_reloptions ( Oid  relid)
static

Definition at line 10733 of file ruleutils.c.

References Anum_pg_class_reloptions, appendStringInfo(), appendStringInfoString(), buf, StringInfoData::data, DatumGetArrayTypeP, deconstruct_array(), elog, ERROR, HeapTupleIsValid, i, initStringInfo(), name, noptions, NULL, ObjectIdGetDatum, options, pfree(), quote_identifier(), ReleaseSysCache(), RELOID, result, SearchSysCache1, simple_quote_literal(), SysCacheGetAttr(), TextDatumGetCString, TEXTOID, and value.

Referenced by pg_get_constraintdef_worker(), and pg_get_indexdef_worker().

10734 {
10735  char *result = NULL;
10736  HeapTuple tuple;
10737  Datum reloptions;
10738  bool isnull;
10739 
10740  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
10741  if (!HeapTupleIsValid(tuple))
10742  elog(ERROR, "cache lookup failed for relation %u", relid);
10743 
10744  reloptions = SysCacheGetAttr(RELOID, tuple,
10745  Anum_pg_class_reloptions, &isnull);
10746  if (!isnull)
10747  {
10749  Datum *options;
10750  int noptions;
10751  int i;
10752 
10753  initStringInfo(&buf);
10754 
10756  TEXTOID, -1, false, 'i',
10757  &options, NULL, &noptions);
10758 
10759  for (i = 0; i < noptions; i++)
10760  {
10761  char *option = TextDatumGetCString(options[i]);
10762  char *name;
10763  char *separator;
10764  char *value;
10765 
10766  /*
10767  * Each array element should have the form name=value. If the "="
10768  * is missing for some reason, treat it like an empty value.
10769  */
10770  name = option;
10771  separator = strchr(option, '=');
10772  if (separator)
10773  {
10774  *separator = '\0';
10775  value = separator + 1;
10776  }
10777  else
10778  value = "";
10779 
10780  if (i > 0)
10781  appendStringInfoString(&buf, ", ");
10782  appendStringInfo(&buf, "%s=", quote_identifier(name));
10783 
10784  /*
10785  * In general we need to quote the value; but to avoid unnecessary
10786  * clutter, do not quote if it is an identifier that would not
10787  * need quoting. (We could also allow numbers, but that is a bit
10788  * trickier than it looks --- for example, are leading zeroes
10789  * significant? We don't want to assume very much here about what
10790  * custom reloptions might mean.)
10791  */
10792  if (quote_identifier(value) == value)
10793  appendStringInfoString(&buf, value);
10794  else
10795  simple_quote_literal(&buf, value);
10796 
10797  pfree(option);
10798  }
10799 
10800  result = buf.data;
10801  }
10802 
10803  ReleaseSysCache(tuple);
10804 
10805  return result;
10806 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10280
#define TEXTOID
Definition: pg_type.h:324
#define Anum_pg_class_reloptions
Definition: pg_class.h:134
return result
Definition: formatting.c:1633
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
void pfree(void *pointer)
Definition: mcxt.c:950
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
static void simple_quote_literal(StringInfo buf, const char *val)
Definition: ruleutils.c:9329
static struct @121 value
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
static char ** options
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define TextDatumGetCString(d)
Definition: builtins.h:92
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1279
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
const char * name
Definition: encode.c:521
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3475
int i
#define elog
Definition: elog.h:219
static size_t noptions
#define DatumGetArrayTypeP(X)
Definition: array.h:242
char* generate_collation_name ( Oid  collid)

Definition at line 10688 of file ruleutils.c.

References CollationIsVisible(), COLLOID, elog, ERROR, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, NameStr, NULL, ObjectIdGetDatum, quote_qualified_identifier(), ReleaseSysCache(), result, and SearchSysCache1.

Referenced by get_const_collation(), get_from_clause_coldeflist(), get_rule_expr(), pg_collation_for(), pg_get_indexdef_worker(), and pg_get_partkeydef_worker().

10689 {
10690  HeapTuple tp;
10691  Form_pg_collation colltup;
10692  char *collname;
10693  char *nspname;
10694  char *result;
10695 
10696  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
10697  if (!HeapTupleIsValid(tp))
10698  elog(ERROR, "cache lookup failed for collation %u", collid);
10699  colltup = (Form_pg_collation) GETSTRUCT(tp);
10700  collname = NameStr(colltup->collname);
10701 
10702  if (!CollationIsVisible(collid))
10703  nspname = get_namespace_name(colltup->collnamespace);
10704  else
10705  nspname = NULL;
10706 
10707  result = quote_qualified_identifier(nspname, collname);
10708 
10709  ReleaseSysCache(tp);
10710 
10711  return result;
10712 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
return result
Definition: formatting.c:1633
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
bool CollationIsVisible(Oid collid)
Definition: namespace.c:2008
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10366
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:52
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
static char * generate_function_name ( Oid  funcid,
int  nargs,
List argnames,
Oid argtypes,
bool  has_variadic,
bool use_variadic_p,
ParseExprKind  special_exprkind 
)
static

Definition at line 10508 of file ruleutils.c.

References Assert, elog, ERROR, EXPR_KIND_GROUP_BY, func_get_detail(), FUNCDETAIL_AGGREGATE, FUNCDETAIL_NORMAL, FUNCDETAIL_NOTFOUND, FUNCDETAIL_WINDOWFUNC, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, InvalidOid, list_make1, makeString(), NameStr, NIL, NULL, ObjectIdGetDatum, OidIsValid, PROCOID, quote_qualified_identifier(), ReleaseSysCache(), result, and SearchSysCache1.

Referenced by get_agg_expr(), get_func_expr(), get_tablesample_def(), get_windowfunc_expr(), and pg_get_triggerdef_worker().

10511 {
10512  char *result;
10513  HeapTuple proctup;
10514  Form_pg_proc procform;
10515  char *proname;
10516  bool use_variadic;
10517  char *nspname;
10518  FuncDetailCode p_result;
10519  Oid p_funcid;
10520  Oid p_rettype;
10521  bool p_retset;
10522  int p_nvargs;
10523  Oid p_vatype;
10524  Oid *p_true_typeids;
10525  bool force_qualify = false;
10526 
10527  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
10528  if (!HeapTupleIsValid(proctup))
10529  elog(ERROR, "cache lookup failed for function %u", funcid);
10530  procform = (Form_pg_proc) GETSTRUCT(proctup);
10531  proname = NameStr(procform->proname);
10532 
10533  /*
10534  * Due to parser hacks to avoid needing to reserve CUBE, we need to force
10535  * qualification in some special cases.
10536  */
10537  if (special_exprkind == EXPR_KIND_GROUP_BY)
10538  {
10539  if (strcmp(proname, "cube") == 0 || strcmp(proname, "rollup") == 0)
10540  force_qualify = true;
10541  }
10542 
10543  /*
10544  * Determine whether VARIADIC should be printed. We must do this first
10545  * since it affects the lookup rules in func_get_detail().
10546  *
10547  * Currently, we always print VARIADIC if the function has a merged
10548  * variadic-array argument. Note that this is always the case for
10549  * functions taking a VARIADIC argument type other than VARIADIC ANY.
10550  *
10551  * In principle, if VARIADIC wasn't originally specified and the array
10552  * actual argument is deconstructable, we could print the array elements
10553  * separately and not print VARIADIC, thus more nearly reproducing the
10554  * original input. For the moment that seems like too much complication
10555  * for the benefit, and anyway we do not know whether VARIADIC was
10556  * originally specified if it's a non-ANY type.
10557  */
10558  if (use_variadic_p)
10559  {
10560  /* Parser should not have set funcvariadic unless fn is variadic */
10561  Assert(!has_variadic || OidIsValid(procform->provariadic));
10562  use_variadic = has_variadic;
10563  *use_variadic_p = use_variadic;
10564  }
10565  else
10566  {
10567  Assert(!has_variadic);
10568  use_variadic = false;
10569  }
10570 
10571  /*
10572  * The idea here is to schema-qualify only if the parser would fail to
10573  * resolve the correct function given the unqualified func name with the
10574  * specified argtypes and VARIADIC flag. But if we already decided to
10575  * force qualification, then we can skip the lookup and pretend we didn't
10576  * find it.
10577  */
10578  if (!force_qualify)
10579  p_result = func_get_detail(list_make1(makeString(proname)),
10580  NIL, argnames, nargs, argtypes,
10581  !use_variadic, true,
10582  &p_funcid, &p_rettype,
10583  &p_retset, &p_nvargs, &p_vatype,
10584  &p_true_typeids, NULL);
10585  else
10586  {
10587  p_result = FUNCDETAIL_NOTFOUND;
10588  p_funcid = InvalidOid;
10589  }
10590 
10591  if ((p_result == FUNCDETAIL_NORMAL ||
10592  p_result == FUNCDETAIL_AGGREGATE ||
10593  p_result == FUNCDETAIL_WINDOWFUNC) &&
10594  p_funcid == funcid)
10595  nspname = NULL;
10596  else
10597  nspname = get_namespace_name(procform->pronamespace);
10598 
10599  result = quote_qualified_identifier(nspname, proname);
10600 
10601  ReleaseSysCache(proctup);
10602 
10603  return result;
10604 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
return result
Definition: formatting.c:1633
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
#define list_make1(x1)
Definition: pg_list.h:139
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
FuncDetailCode
Definition: parse_func.h:22
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10366
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
FuncDetailCode func_get_detail(List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, Oid *funcid, Oid *rettype, bool *retset, int *nvargs, Oid *vatype, Oid **true_typeids, List **argdefaults)
Definition: parse_func.c:1283
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
static char * generate_operator_name ( Oid  operid,
Oid  arg1,
Oid  arg2 
)
static

Definition at line 10618 of file ruleutils.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), buf, StringInfoData::data, elog, ERROR, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, initStringInfo(), left_oper(), list_make1, makeString(), NameStr, NULL, ObjectIdGetDatum, oper(), OPEROID, oprid(), quote_identifier(), ReleaseSysCache(), right_oper(), and SearchSysCache1.

Referenced by get_oper_expr(), get_rule_expr(), get_rule_orderby(), get_simple_binary_op_name(), get_sublink_expr(), and pg_get_indexdef_worker().

10619 {
10621  HeapTuple opertup;
10622  Form_pg_operator operform;
10623  char *oprname;
10624  char *nspname;
10625  Operator p_result;
10626 
10627  initStringInfo(&buf);
10628 
10629  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operid));
10630  if (!HeapTupleIsValid(opertup))
10631  elog(ERROR, "cache lookup failed for operator %u", operid);
10632  operform = (Form_pg_operator) GETSTRUCT(opertup);
10633  oprname = NameStr(operform->oprname);
10634 
10635  /*
10636  * The idea here is to schema-qualify only if the parser would fail to
10637  * resolve the correct operator given the unqualified op name with the
10638  * specified argtypes.
10639  */
10640  switch (operform->oprkind)
10641  {
10642  case 'b':
10643  p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
10644  true, -1);
10645  break;
10646  case 'l':
10647  p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
10648  true, -1);
10649  break;
10650  case 'r':
10651  p_result = right_oper(NULL, list_make1(makeString(oprname)), arg1,
10652  true, -1);
10653  break;
10654  default:
10655  elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
10656  p_result = NULL; /* keep compiler quiet */
10657  break;
10658  }
10659 
10660  if (p_result != NULL && oprid(p_result) == operid)
10661  nspname = NULL;
10662  else
10663  {
10664  nspname = get_namespace_name(operform->oprnamespace);
10665  appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
10666  }
10667 
10668  appendStringInfoString(&buf, oprname);
10669 
10670  if (nspname)
10671  appendStringInfoChar(&buf, ')');
10672 
10673  if (p_result != NULL)
10674  ReleaseSysCache(p_result);
10675 
10676  ReleaseSysCache(opertup);
10677 
10678  return buf.data;
10679 }
Value * makeString(char *str)
Definition: value.c:53
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10280
Oid oprid(Operator op)
Definition: parse_oper.c:245
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
#define list_make1(x1)
Definition: pg_list.h:139
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Operator left_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
Definition: parse_oper.c:604
Operator right_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
Definition: parse_oper.c:525
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
static char * buf
Definition: pg_test_fsync.c:66
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
FormData_pg_operator* Form_pg_operator
Definition: pg_operator.h:57
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:377
static char * generate_qualified_relation_name ( Oid  relid)
static

Definition at line 10466 of file ruleutils.c.

References elog, ERROR, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, quote_qualified_identifier(), ReleaseSysCache(), RELOID, result, and SearchSysCache1.

Referenced by pg_get_constraintdef_worker(), and pg_get_serial_sequence().

10467 {
10468  HeapTuple tp;
10469  Form_pg_class reltup;
10470  char *relname;
10471  char *nspname;
10472  char *result;
10473 
10474  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
10475  if (!HeapTupleIsValid(tp))
10476  elog(ERROR, "cache lookup failed for relation %u", relid);
10477  reltup = (Form_pg_class) GETSTRUCT(tp);
10478  relname = NameStr(reltup->relname);
10479 
10480  nspname = get_namespace_name(reltup->relnamespace);
10481  if (!nspname)
10482  elog(ERROR, "cache lookup failed for namespace %u",
10483  reltup->relnamespace);
10484 
10485  result = quote_qualified_identifier(nspname, relname);
10486 
10487  ReleaseSysCache(tp);
10488 
10489  return result;
10490 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
return result
Definition: formatting.c:1633
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10366
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
static char * generate_relation_name ( Oid  relid,
List namespaces 
)
static

Definition at line 10406 of file ruleutils.c.

References CommonTableExpr::ctename, deparse_namespace::ctes, elog, ERROR, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, lfirst, NameStr, NULL, ObjectIdGetDatum, quote_qualified_identifier(), RelationIsVisible(), ReleaseSysCache(), RELOID, result, and SearchSysCache1.

Referenced by get_delete_query_def(), get_from_clause_item(), get_insert_query_def(), get_update_query_def(), make_ruledef(), pg_get_constraintdef_worker(), pg_get_indexdef_worker(), pg_get_statisticsobj_worker(), and pg_get_triggerdef_worker().

10407 {
10408  HeapTuple tp;
10409  Form_pg_class reltup;
10410  bool need_qual;
10411  ListCell *nslist;
10412  char *relname;
10413  char *nspname;
10414  char *result;
10415 
10416  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
10417  if (!HeapTupleIsValid(tp))
10418  elog(ERROR, "cache lookup failed for relation %u", relid);
10419  reltup = (Form_pg_class) GETSTRUCT(tp);
10420  relname = NameStr(reltup->relname);
10421 
10422  /* Check for conflicting CTE name */
10423  need_qual = false;
10424  foreach(nslist, namespaces)
10425  {
10426  deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
10427  ListCell *ctlist;
10428 
10429  foreach(ctlist, dpns->ctes)
10430  {
10431  CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
10432 
10433  if (strcmp(cte->ctename, relname) == 0)
10434  {
10435  need_qual = true;
10436  break;
10437  }
10438  }
10439  if (need_qual)
10440  break;
10441  }
10442 
10443  /* Otherwise, qualify the name if not visible in search path */
10444  if (!need_qual)
10445  need_qual = !RelationIsVisible(relid);
10446 
10447  if (need_qual)
10448  nspname = get_namespace_name(reltup->relnamespace);
10449  else
10450  nspname = NULL;
10451 
10452  result = quote_qualified_identifier(nspname, relname);
10453 
10454  ReleaseSysCache(tp);
10455 
10456  return result;
10457 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
return result
Definition: formatting.c:1633
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10366
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
bool RelationIsVisible(Oid relid)
Definition: namespace.c:682
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
static void get_agg_combine_expr ( Node node,
deparse_context context,
void *  private 
)
static

Definition at line 9025 of file ruleutils.c.

References elog, ERROR, get_agg_expr(), and IsA.

Referenced by get_agg_expr().

9026 {
9027  Aggref *aggref;
9028  Aggref *original_aggref = private;
9029 
9030  if (!IsA(node, Aggref))
9031  elog(ERROR, "combining Aggref does not point to an Aggref");
9032 
9033  aggref = (Aggref *) node;
9034  get_agg_expr(aggref, context, original_aggref);
9035 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define ERROR
Definition: elog.h:43
static void get_agg_expr(Aggref *aggref, deparse_context *context, Aggref *original_aggref)
Definition: ruleutils.c:8919
#define elog
Definition: elog.h:219
static void get_agg_expr ( Aggref aggref,
deparse_context context,
Aggref original_aggref 
)
static

Definition at line 8919 of file ruleutils.c.

References Aggref::aggdirectargs, Aggref::aggdistinct, Aggref::aggfilter, Aggref::aggfnoid, Aggref::aggkind, AGGKIND_IS_ORDERED_SET, Aggref::aggorder, Aggref::aggsplit, Aggref::aggstar, Aggref::aggvariadic, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), arg, Aggref::args, Assert, buf, deparse_context::buf, DO_AGGSPLIT_COMBINE, DO_AGGSPLIT_SKIPFINAL, TargetEntry::expr, FUNC_MAX_ARGS, generate_function_name(), get_agg_combine_expr(), get_aggregate_argtypes(), get_rule_expr(), get_rule_orderby(), i, IsA, lfirst, linitial_node, list_length(), NIL, NULL, TargetEntry::resjunk, resolve_special_varno(), and deparse_context::special_exprkind.

Referenced by get_agg_combine_expr(), and get_rule_expr().

8921 {
8922  StringInfo buf = context->buf;
8923  Oid argtypes[FUNC_MAX_ARGS];
8924  int nargs;
8925  bool use_variadic;
8926 
8927  /*
8928  * For a combining aggregate, we look up and deparse the corresponding
8929  * partial aggregate instead. This is necessary because our input
8930  * argument list has been replaced; the new argument list always has just
8931  * one element, which will point to a partial Aggref that supplies us with
8932  * transition states to combine.
8933  */
8934  if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
8935  {
8936  TargetEntry *tle = linitial_node(TargetEntry, aggref->args);
8937 
8938  Assert(list_length(aggref->args) == 1);
8939  resolve_special_varno((Node *) tle->expr, context, original_aggref,
8941  return;
8942  }
8943 
8944  /*
8945  * Mark as PARTIAL, if appropriate. We look to the original aggref so as
8946  * to avoid printing this when recursing from the code just above.
8947  */
8948  if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
8949  appendStringInfoString(buf, "PARTIAL ");
8950 
8951  /* Extract the argument types as seen by the parser */
8952  nargs = get_aggregate_argtypes(aggref, argtypes);
8953 
8954  /* Print the aggregate name, schema-qualified if needed */
8955  appendStringInfo(buf, "%s(%s",
8956  generate_function_name(aggref->aggfnoid, nargs,
8957  NIL, argtypes,
8958  aggref->aggvariadic,
8959  &use_variadic,
8960  context->special_exprkind),
8961  (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
8962 
8963  if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
8964  {
8965  /*
8966  * Ordered-set aggregates do not use "*" syntax. Also, we needn't
8967  * worry about inserting VARIADIC. So we can just dump the direct
8968  * args as-is.
8969  */
8970  Assert(!aggref->aggvariadic);
8971  get_rule_expr((Node *) aggref->aggdirectargs, context, true);
8972  Assert(aggref->aggorder != NIL);
8973  appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
8974  get_rule_orderby(aggref->aggorder, aggref->args, false, context);
8975  }
8976  else
8977  {
8978  /* aggstar can be set only in zero-argument aggregates */
8979  if (aggref->aggstar)
8980  appendStringInfoChar(buf, '*');
8981  else
8982  {
8983  ListCell *l;
8984  int i;
8985 
8986  i = 0;
8987  foreach(l, aggref->args)
8988  {
8989  TargetEntry *tle = (TargetEntry *) lfirst(l);
8990  Node *arg = (Node *) tle->expr;
8991 
8992  Assert(!IsA(arg, NamedArgExpr));
8993  if (tle->resjunk)
8994  continue;
8995  if (i++ > 0)
8996  appendStringInfoString(buf, ", ");
8997  if (use_variadic && i == nargs)
8998  appendStringInfoString(buf, "VARIADIC ");
8999  get_rule_expr(arg, context, true);
9000  }
9001  }
9002 
9003  if (aggref->aggorder != NIL)
9004  {
9005  appendStringInfoString(buf, " ORDER BY ");
9006  get_rule_orderby(aggref->aggorder, aggref->args, false, context);
9007  }
9008  }
9009 
9010  if (aggref->aggfilter != NULL)
9011  {
9012  appendStringInfoString(buf, ") FILTER (WHERE ");
9013  get_rule_expr((Node *) aggref->aggfilter, context, false);
9014  }
9015 
9016  appendStringInfoChar(buf, ')');
9017 }
List * aggdistinct
Definition: primnodes.h:303
#define NIL
Definition: pg_list.h:69
static char * generate_function_name(Oid funcid, int nargs, List *argnames, Oid *argtypes, bool has_variadic, bool *use_variadic_p, ParseExprKind special_exprkind)
Definition: ruleutils.c:10508
bool aggvariadic
Definition: primnodes.h:306
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
static void resolve_special_varno(Node *node, deparse_context *context, void *private, void(*callback)(Node *, deparse_context *, void *))
Definition: ruleutils.c:6566
static void get_rule_orderby(List *orderList, List *targetList, bool force_colno, deparse_context *context)
Definition: ruleutils.c:5689
Definition: nodes.h:509
List * args
Definition: primnodes.h:301
bool aggstar
Definition: primnodes.h:305
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:114
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:768
#define FUNC_MAX_ARGS
#define AGGKIND_IS_ORDERED_SET(kind)
Definition: pg_aggregate.h:129
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
bool resjunk
Definition: primnodes.h:1375
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
List * aggorder
Definition: primnodes.h:302
List * aggdirectargs
Definition: primnodes.h:300
ParseExprKind special_exprkind
Definition: ruleutils.c:116
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
Oid aggfnoid
Definition: primnodes.h:294
static void get_agg_combine_expr(Node *node, deparse_context *context, void *private)
Definition: ruleutils.c:9025
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7563
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1368
AggSplit aggsplit
Definition: primnodes.h:310
static int list_length(const List *l)
Definition: pg_list.h:89
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:769
Expr * aggfilter
Definition: primnodes.h:304
StringInfo buf
Definition: ruleutils.c:108
int i
void * arg
char aggkind
Definition: primnodes.h:308
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:1801
static void get_basic_select_query ( Query query,
deparse_context context,
TupleDesc  resultDesc 
)
static

Definition at line 5182 of file ruleutils.c.

References appendContextKeyword(), appendStringInfoChar(), appendStringInfoString(), buf, deparse_context::buf, Query::distinctClause, EXPR_KIND_GROUP_BY, get_from_clause(), get_rule_expr(), get_rule_groupingset(), get_rule_sortgroupclause(), get_rule_windowclause(), get_simple_values_rte(), get_target_list(), get_values_def(), Query::groupClause, Query::groupingSets, Query::hasDistinctOn, Query::havingQual, deparse_context::indentLevel, Query::jointree, lfirst, NIL, NULL, PRETTY_INDENT, PRETTYINDENT_STD, FromExpr::quals, deparse_context::special_exprkind, Query::targetList, SortGroupClause::tleSortGroupRef, RangeTblEntry::values_lists, and Query::windowClause.

Referenced by get_select_query_def().

5184 {
5185  StringInfo buf = context->buf;
5186  RangeTblEntry *values_rte;
5187  char *sep;
5188  ListCell *l;
5189 
5190  if (PRETTY_INDENT(context))
5191  {
5192  context->indentLevel += PRETTYINDENT_STD;
5193  appendStringInfoChar(buf, ' ');
5194  }
5195 
5196  /*
5197  * If the query looks like SELECT * FROM (VALUES ...), then print just the
5198  * VALUES part. This reverses what transformValuesClause() did at parse
5199  * time.
5200  */
5201  values_rte = get_simple_values_rte(query);
5202  if (values_rte)
5203  {
5204  get_values_def(values_rte->values_lists, context);
5205  return;
5206  }
5207 
5208  /*
5209  * Build up the query string - first we say SELECT
5210  */
5211  appendStringInfoString(buf, "SELECT");
5212 
5213  /* Add the DISTINCT clause if given */
5214  if (query->distinctClause != NIL)
5215  {
5216  if (query->hasDistinctOn)
5217  {
5218  appendStringInfoString(buf, " DISTINCT ON (");
5219  sep = "";
5220  foreach(l, query->distinctClause)
5221  {
5222  SortGroupClause *srt = (SortGroupClause *) lfirst(l);
5223 
5224  appendStringInfoString(buf, sep);
5226  false, context);
5227  sep = ", ";
5228  }
5229  appendStringInfoChar(buf, ')');
5230  }
5231  else
5232  appendStringInfoString(buf, " DISTINCT");
5233  }
5234 
5235  /* Then we tell what to select (the targetlist) */
5236  get_target_list(query->targetList, context, resultDesc);
5237 
5238  /* Add the FROM clause if needed */
5239  get_from_clause(query, " FROM ", context);
5240 
5241  /* Add the WHERE clause if given */
5242  if (query->jointree->quals != NULL)
5243  {
5244  appendContextKeyword(context, " WHERE ",
5246  get_rule_expr(query->jointree->quals, context, false);
5247  }
5248 
5249  /* Add the GROUP BY clause if given */
5250  if (query->groupClause != NULL || query->groupingSets != NULL)
5251  {
5252  ParseExprKind save_exprkind;
5253 
5254  appendContextKeyword(context, " GROUP BY ",
5256 
5257  save_exprkind = context->special_exprkind;
5259 
5260  if (query->groupingSets == NIL)
5261  {
5262  sep = "";
5263  foreach(l, query->groupClause)
5264  {
5265  SortGroupClause *grp = (SortGroupClause *) lfirst(l);
5266 
5267  appendStringInfoString(buf, sep);
5269  false, context);
5270  sep = ", ";
5271  }
5272  }
5273  else
5274  {
5275  sep = "";
5276  foreach(l, query->groupingSets)
5277  {
5278  GroupingSet *grp = lfirst(l);
5279 
5280  appendStringInfoString(buf, sep);
5281  get_rule_groupingset(grp, query->targetList, true, context);
5282  sep = ", ";
5283  }
5284  }
5285 
5286  context->special_exprkind = save_exprkind;
5287  }
5288 
5289  /* Add the HAVING clause if given */
5290  if (query->havingQual != NULL)
5291  {
5292  appendContextKeyword(context, " HAVING ",
5294  get_rule_expr(query->havingQual, context, false);
5295  }
5296 
5297  /* Add the WINDOW clause if needed */
5298  if (query->windowClause != NIL)
5299  get_rule_windowclause(query, context);
5300 }
#define NIL
Definition: pg_list.h:69
FromExpr * jointree
Definition: parsenodes.h:136
static void get_target_list(List *targetList, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5309
static Node * get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno, deparse_context *context)
Definition: ruleutils.c:5573
Index tleSortGroupRef
Definition: parsenodes.h:1176
List * groupingSets
Definition: parsenodes.h:148
static void get_from_clause(Query *query, const char *prefix, deparse_context *context)
Definition: ruleutils.c:9599
static void get_rule_windowclause(Query *query, deparse_context *context)
Definition: ruleutils.c:5747
#define PRETTY_INDENT(context)
Definition: ruleutils.c:97
ParseExprKind
Definition: parse_node.h:33
List * values_lists
Definition: parsenodes.h:1001
Node * quals
Definition: primnodes.h:1472
bool hasDistinctOn
Definition: parsenodes.h:127
List * windowClause
Definition: parsenodes.h:152
List * targetList
Definition: parsenodes.h:138
List * distinctClause
Definition: parsenodes.h:154
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:7458
static void get_rule_groupingset(GroupingSet *gset, List *targetlist, bool omit_parens, deparse_context *context)
Definition: ruleutils.c:5629
#define PRETTYINDENT_STD
Definition: ruleutils.c:82
ParseExprKind special_exprkind
Definition: ruleutils.c:116
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
#define NULL
Definition: c.h:229
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7563
#define lfirst(lc)
Definition: pg_list.h:106
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:4898
List * groupClause
Definition: parsenodes.h:146
StringInfo buf
Definition: ruleutils.c:108
static RangeTblEntry * get_simple_values_rte(Query *query)
Definition: ruleutils.c:5126
Node * havingQual
Definition: parsenodes.h:150
static void get_coercion_expr ( Node arg,
deparse_context context,
Oid  resulttype,
int32  resulttypmod,
Node parentNode 
)
static

Definition at line 9118 of file ruleutils.c.

References appendStringInfo(), appendStringInfoChar(), buf, deparse_context::buf, format_type_with_typemod(), get_const_expr(), get_rule_expr_paren(), IsA, and PRETTY_PAREN.

Referenced by get_func_expr(), and get_rule_expr().

9121 {
9122  StringInfo buf = context->buf;
9123 
9124  /*
9125  * Since parse_coerce.c doesn't immediately collapse application of
9126  * length-coercion functions to constants, what we'll typically see in
9127  * such cases is a Const with typmod -1 and a length-coercion function
9128  * right above it. Avoid generating redundant output. However, beware of
9129  * suppressing casts when the user actually wrote something like
9130  * 'foo'::text::char(3).
9131  *
9132  * Note: it might seem that we are missing the possibility of needing to
9133  * print a COLLATE clause for such a Const. However, a Const could only
9134  * have nondefault collation in a post-constant-folding tree, in which the
9135  * length coercion would have been folded too. See also the special
9136  * handling of CollateExpr in coerce_to_target_type(): any collation
9137  * marking will be above the coercion node, not below it.
9138  */
9139  if (arg && IsA(arg, Const) &&
9140  ((Const *) arg)->consttype == resulttype &&
9141  ((Const *) arg)->consttypmod == -1)
9142  {
9143  /* Show the constant without normal ::typename decoration */
9144  get_const_expr((Const *) arg, context, -1);
9145  }
9146  else
9147  {
9148  if (!PRETTY_PAREN(context))
9149  appendStringInfoChar(buf, '(');
9150  get_rule_expr_paren(arg, context, false, parentNode);
9151  if (!PRETTY_PAREN(context))
9152  appendStringInfoChar(buf, ')');
9153  }
9154  appendStringInfo(buf, "::%s",
9155  format_type_with_typemod(resulttype, resulttypmod));
9156 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
static void get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
Definition: ruleutils.c:7531
static void get_const_expr(Const *constval, deparse_context *context, int showtype)
Definition: ruleutils.c:9174
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
static char * buf
Definition: pg_test_fsync.c:66
#define PRETTY_PAREN(context)
Definition: ruleutils.c:96
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:113
StringInfo buf
Definition: ruleutils.c:108
static void get_column_alias_list ( deparse_columns colinfo,
deparse_context context 
)
static

Definition at line 10015 of file ruleutils.c.

References appendStringInfoChar(), appendStringInfoString(), buf, deparse_context::buf, i, deparse_columns::new_colnames, deparse_columns::num_new_cols, deparse_columns::printaliases, and quote_identifier().

Referenced by get_from_clause_item().

10016 {
10017  StringInfo buf = context->buf;
10018  int i;
10019  bool first = true;
10020 
10021  /* Don't print aliases if not needed */
10022  if (!colinfo->printaliases)
10023  return;
10024 
10025  for (i = 0; i < colinfo->num_new_cols; i++)
10026  {
10027  char *colname = colinfo->new_colnames[i];
10028 
10029  if (first)
10030  {
10031  appendStringInfoChar(buf, '(');
10032  first = false;
10033  }
10034  else
10035  appendStringInfoString(buf, ", ");
10037  }
10038  if (!first)
10039  appendStringInfoChar(buf, ')');
10040 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10280
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
StringInfo buf
Definition: ruleutils.c:108
int i
char ** new_colnames
Definition: ruleutils.c:242
static void get_const_collation ( Const constval,
deparse_context context 
)
static

Definition at line 9309 of file ruleutils.c.

References appendStringInfo(), buf, deparse_context::buf, Const::constcollid, Const::consttype, generate_collation_name(), get_typcollation(), and OidIsValid.

Referenced by get_const_expr().

9310 {
9311  StringInfo buf = context->buf;
9312 
9313  if (OidIsValid(constval->constcollid))
9314  {
9315  Oid typcollation = get_typcollation(constval->consttype);
9316 
9317  if (constval->constcollid != typcollation)
9318  {
9319  appendStringInfo(buf, " COLLATE %s",
9321  }
9322  }
9323 }
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:10688
Oid consttype
Definition: primnodes.h:192
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
Oid constcollid
Definition: primnodes.h:194
static char * buf
Definition: pg_test_fsync.c:66
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2781
StringInfo buf
Definition: ruleutils.c:108
static void get_const_expr ( Const constval,
deparse_context context,
int  showtype 
)
static

Definition at line 9174 of file ruleutils.c.

References appendStringInfo(), appendStringInfoString(), BITOID, BOOLOID, buf, deparse_context::buf, Const::constisnull, Const::consttype, Const::consttypmod, Const::constvalue, format_type_with_typemod(), get_const_collation(), getTypeOutputInfo(), INT4OID, NUMERICOID, OidOutputFunctionCall(), pfree(), simple_quote_literal(), UNKNOWNOID, and VARBITOID.

Referenced by get_coercion_expr(), get_rule_expr(), and get_rule_sortgroupclause().

9175 {
9176  StringInfo buf = context->buf;
9177  Oid typoutput;
9178  bool typIsVarlena;
9179  char *extval;
9180  bool needlabel = false;
9181 
9182  if (constval->constisnull)
9183  {
9184  /*
9185  * Always label the type of a NULL constant to prevent misdecisions
9186  * about type when reparsing.
9187  */
9188  appendStringInfoString(buf, "NULL");
9189  if (showtype >= 0)
9190  {
9191  appendStringInfo(buf, "::%s",
9193  constval->consttypmod));
9194  get_const_collation(constval, context);
9195  }
9196  return;
9197  }
9198 
9199  getTypeOutputInfo(constval->consttype,
9200  &typoutput, &typIsVarlena);
9201 
9202  extval = OidOutputFunctionCall(typoutput, constval->constvalue);
9203 
9204  switch (constval->consttype)
9205  {
9206  case INT4OID:
9207 
9208  /*
9209  * INT4 can be printed without any decoration, unless it is
9210  * negative; in that case print it as '-nnn'::integer to ensure
9211  * that the output will re-parse as a constant, not as a constant
9212  * plus operator. In most cases we could get away with printing
9213  * (-nnn) instead, because of the way that gram.y handles negative
9214  * literals; but that doesn't work for INT_MIN, and it doesn't
9215  * seem that much prettier anyway.
9216  */
9217  if (extval[0] != '-')
9218  appendStringInfoString(buf, extval);
9219  else
9220  {
9221  appendStringInfo(buf, "'%s'", extval);
9222  needlabel = true; /* we must attach a cast */
9223  }
9224  break;
9225 
9226  case NUMERICOID:
9227 
9228  /*
9229  * NUMERIC can be printed without quotes if it looks like a float
9230  * constant (not an integer, and not Infinity or NaN) and doesn't
9231  * have a leading sign (for the same reason as for INT4).
9232  */
9233  if (isdigit((unsigned char) extval[0]) &&
9234  strcspn(extval, "eE.") != strlen(extval))
9235  {
9236  appendStringInfoString(buf, extval);
9237  }
9238  else
9239  {
9240  appendStringInfo(buf, "'%s'", extval);
9241  needlabel = true; /* we must attach a cast */
9242  }
9243  break;
9244 
9245  case BITOID:
9246  case VARBITOID:
9247  appendStringInfo(buf, "B'%s'", extval);
9248  break;
9249 
9250  case BOOLOID:
9251  if (strcmp(extval, "t") == 0)
9252  appendStringInfoString(buf, "true");
9253  else
9254  appendStringInfoString(buf, "false");
9255  break;
9256 
9257  default:
9258  simple_quote_literal(buf, extval);
9259  break;
9260  }
9261 
9262  pfree(extval);
9263 
9264  if (showtype < 0)
9265  return;
9266 
9267  /*
9268  * For showtype == 0, append ::typename unless the constant will be
9269  * implicitly typed as the right type when it is read in.
9270  *
9271  * XXX this code has to be kept in sync with the behavior of the parser,
9272  * especially make_const.
9273  */
9274  switch (constval->consttype)
9275  {
9276  case BOOLOID:
9277  case UNKNOWNOID:
9278  /* These types can be left unlabeled */
9279  needlabel = false;
9280  break;
9281  case INT4OID:
9282  /* We determined above whether a label is needed */
9283  break;
9284  case NUMERICOID:
9285 
9286  /*
9287  * Float-looking constants will be typed as numeric, which we
9288  * checked above; but if there's a nondefault typmod we need to
9289  * show it.
9290  */
9291  needlabel |= (constval->consttypmod >= 0);
9292  break;
9293  default:
9294  needlabel = true;
9295  break;
9296  }
9297  if (needlabel || showtype > 0)
9298  appendStringInfo(buf, "::%s",
9300  constval->consttypmod));
9301 
9302  get_const_collation(constval, context);
9303 }
Datum constvalue
Definition: primnodes.h:196
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2632
#define NUMERICOID
Definition: pg_type.h:554
#define INT4OID
Definition: pg_type.h:316
#define VARBITOID
Definition: pg_type.h:546
unsigned int Oid
Definition: postgres_ext.h:31
Oid consttype
Definition: primnodes.h:192
void pfree(void *pointer)
Definition: mcxt.c:950
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
static void simple_quote_literal(StringInfo buf, const char *val)
Definition: ruleutils.c:9329
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static void get_const_collation(Const *constval, deparse_context *context)
Definition: ruleutils.c:9309
static char * buf
Definition: pg_test_fsync.c:66
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:113
#define BITOID
Definition: pg_type.h:542
#define BOOLOID
Definition: pg_type.h:288
#define UNKNOWNOID
Definition: pg_type.h:431
int32 consttypmod
Definition: primnodes.h:193
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1747
StringInfo buf
Definition: ruleutils.c:108
bool constisnull
Definition: primnodes.h:197
static void get_delete_query_def ( Query query,
deparse_context context 
)
static

Definition at line 6287 of file ruleutils.c.

References RangeTblEntry::alias, Alias::aliasname, appendContextKeyword(), appendStringInfo(), appendStringInfoChar(), Assert, buf, deparse_context::buf, generate_relation_name(), get_from_clause(), get_rule_expr(), get_target_list(), get_with_clause(), deparse_context::indentLevel, Query::jointree, NIL, NULL, only_marker, PRETTY_INDENT, PRETTYINDENT_STD, FromExpr::quals, quote_identifier(), RangeTblEntry::relid, Query::resultRelation, Query::returningList, rt_fetch, Query::rtable, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by get_query_def().

6288 {
6289  StringInfo buf = context->buf;
6290  RangeTblEntry *rte;
6291 
6292  /* Insert the WITH clause if given */
6293  get_with_clause(query, context);
6294 
6295  /*
6296  * Start the query with DELETE FROM relname
6297  */
6298  rte = rt_fetch(query->resultRelation, query->rtable);
6299  Assert(rte->rtekind == RTE_RELATION);
6300  if (PRETTY_INDENT(context))
6301  {
6302  appendStringInfoChar(buf, ' ');
6303  context->indentLevel += PRETTYINDENT_STD;
6304  }
6305  appendStringInfo(buf, "DELETE FROM %s%s",
6306  only_marker(rte),
6308  if (rte->alias != NULL)
6309  appendStringInfo(buf, " %s",
6311 
6312  /* Add the USING clause if given */
6313  get_from_clause(query, " USING ", context);
6314 
6315  /* Add a WHERE clause if given */
6316  if (query->jointree->quals != NULL)
6317  {
6318  appendContextKeyword(context, " WHERE ",
6320  get_rule_expr(query->jointree->quals, context, false);
6321  }
6322 
6323  /* Add RETURNING if present */
6324  if (query->returningList)
6325  {
6326  appendContextKeyword(context, " RETURNING",
6328  get_target_list(query->returningList, context, NULL);
6329  }
6330 }
#define NIL
Definition: pg_list.h:69
static void get_with_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:4941
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10280
Alias * alias
Definition: parsenodes.h:1034
FromExpr * jointree
Definition: parsenodes.h:136
int resultRelation
Definition: parsenodes.h:120
static void get_target_list(List *targetList, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5309
static void get_from_clause(Query *query, const char *prefix, deparse_context *context)
Definition: ruleutils.c:9599
#define PRETTY_INDENT(context)
Definition: ruleutils.c:97
Node * quals
Definition: primnodes.h:1472
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:10406
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
List * rtable
Definition: parsenodes.h:135
static char * buf
Definition: pg_test_fsync.c:66
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:7458
List * returningList
Definition: parsenodes.h:144
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define PRETTYINDENT_STD
Definition: ruleutils.c:82
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7563
char * aliasname
Definition: primnodes.h:42
#define only_marker(rte)
Definition: ruleutils.c:463
RTEKind rtekind
Definition: parsenodes.h:936
StringInfo buf
Definition: ruleutils.c:108
static void get_from_clause ( Query query,
const char *  prefix,
deparse_context context 
)
static

Definition at line 9599 of file ruleutils.c.

References appendContextKeyword(), appendStringInfoString(), buf, deparse_context::buf, StringInfoData::data, FromExpr::fromlist, get_from_clause_item(), RangeTblEntry::inFromCl, initStringInfo(), IsA, Query::jointree, StringInfoData::len, lfirst, NULL, pfree(), PRETTY_INDENT, PRETTYINDENT_STD, PRETTYINDENT_VAR, removeStringInfoSpaces(), rt_fetch, Query::rtable, and deparse_context::wrapColumn.

Referenced by get_basic_select_query(), get_delete_query_def(), and get_update_query_def().

9600 {
9601  StringInfo buf = context->buf;
9602  bool first = true;
9603  ListCell *l;
9604 
9605  /*
9606  * We use the query's jointree as a guide to what to print. However, we
9607  * must ignore auto-added RTEs that are marked not inFromCl. (These can
9608  * only appear at the top level of the jointree, so it's sufficient to
9609  * check here.) This check also ensures we ignore the rule pseudo-RTEs
9610  * for NEW and OLD.
9611  */
9612  foreach(l, query->jointree->fromlist)
9613  {
9614  Node *jtnode = (Node *) lfirst(l);
9615 
9616  if (IsA(jtnode, RangeTblRef))
9617  {
9618  int varno = ((RangeTblRef *) jtnode)->rtindex;
9619  RangeTblEntry *rte = rt_fetch(varno, query->rtable);
9620 
9621  if (!rte->inFromCl)
9622  continue;
9623  }
9624 
9625  if (first)
9626  {
9627  appendContextKeyword(context, prefix,
9629  first = false;
9630 
9631  get_from_clause_item(jtnode, query, context);
9632  }
9633  else
9634  {
9635  StringInfoData itembuf;
9636 
9637  appendStringInfoString(buf, ", ");
9638 
9639  /*
9640  * Put the new FROM item's text into itembuf so we can decide
9641  * after we've got it whether or not it needs to go on a new line.
9642  */
9643  initStringInfo(&itembuf);
9644  context->buf = &itembuf;
9645 
9646  get_from_clause_item(jtnode, query, context);
9647 
9648  /* Restore context's output buffer */
9649  context->buf = buf;
9650 
9651  /* Consider line-wrapping if enabled */
9652  if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
9653  {
9654  /* Does the new item start with a new line? */
9655  if (itembuf.len > 0 && itembuf.data[0] == '\n')
9656  {
9657  /* If so, we shouldn't add anything */
9658  /* instead, remove any trailing spaces currently in buf */
9660  }
9661  else
9662  {
9663  char *trailing_nl;
9664 
9665  /* Locate the start of the current line in the buffer */
9666  trailing_nl = strrchr(buf->data, '\n');
9667  if (trailing_nl == NULL)
9668  trailing_nl = buf->data;
9669  else
9670  trailing_nl++;
9671 
9672  /*
9673  * Add a newline, plus some indentation, if the new item
9674  * would cause an overflow.
9675  */
9676  if (strlen(trailing_nl) + itembuf.len > context->wrapColumn)
9677  appendContextKeyword(context, "", -PRETTYINDENT_STD,
9680  }
9681  }
9682 
9683  /* Add the new item */
9684  appendStringInfoString(buf, itembuf.data);
9685 
9686  /* clean up */
9687  pfree(itembuf.data);
9688  }
9689  }
9690 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
FromExpr * jointree
Definition: parsenodes.h:136
#define PRETTYINDENT_VAR
Definition: ruleutils.c:84
Definition: nodes.h:509
#define PRETTY_INDENT(context)
Definition: ruleutils.c:97
List * fromlist
Definition: primnodes.h:1471
void pfree(void *pointer)
Definition: mcxt.c:950
List * rtable
Definition: parsenodes.h:135
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:7458
static void removeStringInfoSpaces(StringInfo str)
Definition: ruleutils.c:7512
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define PRETTYINDENT_STD
Definition: ruleutils.c:82
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
StringInfo buf
Definition: ruleutils.c:108
static void get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
Definition: ruleutils.c:9693
static void get_from_clause_coldeflist ( RangeTblFunction rtfunc,
deparse_columns colinfo,
deparse_context context 
)
static

Definition at line 10055 of file ruleutils.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert, buf, deparse_context::buf, deparse_columns::colnames, format_type_with_typemod(), forthree, RangeTblFunction::funccolcollations, RangeTblFunction::funccolnames, RangeTblFunction::funccoltypes, RangeTblFunction::funccoltypmods, generate_collation_name(), get_typcollation(), i, lfirst, lfirst_int, lfirst_oid, list_head(), lnext, OidIsValid, quote_identifier(), and strVal.

Referenced by get_from_clause_item().

10058 {
10059  StringInfo buf = context->buf;
10060  ListCell *l1;
10061  ListCell *l2;
10062  ListCell *l3;
10063  ListCell *l4;
10064  int i;
10065 
10066  appendStringInfoChar(buf, '(');
10067 
10068  /* there's no forfour(), so must chase one list the hard way */
10069  i = 0;
10070  l4 = list_head(rtfunc->funccolnames);
10071  forthree(l1, rtfunc->funccoltypes,
10072  l2, rtfunc->funccoltypmods,
10073  l3, rtfunc->funccolcollations)
10074  {
10075  Oid atttypid = lfirst_oid(l1);
10076  int32 atttypmod = lfirst_int(l2);
10077  Oid attcollation = lfirst_oid(l3);
10078  char *attname;
10079 
10080  if (colinfo)
10081  attname = colinfo->colnames[i];
10082  else
10083  attname = strVal(lfirst(l4));
10084 
10085  Assert(attname); /* shouldn't be any dropped columns here */
10086 
10087  if (i > 0)
10088  appendStringInfoString(buf, ", ");
10089  appendStringInfo(buf, "%s %s",
10090  quote_identifier(attname),
10091  format_type_with_typemod(atttypid, atttypmod));
10092  if (OidIsValid(attcollation) &&
10093  attcollation != get_typcollation(atttypid))
10094  appendStringInfo(buf, " COLLATE %s",
10095  generate_collation_name(attcollation));
10096 
10097  l4 = lnext(l4);
10098  i++;
10099  }
10100 
10101  appendStringInfoChar(buf, ')');
10102 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10280
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:203
#define strVal(v)
Definition: value.h:54
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:10688
signed int int32
Definition: c.h:256
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define lfirst_int(lc)
Definition: pg_list.h:107
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:113
List * funccoltypmods
Definition: parsenodes.h:1072
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2781
List * funccolcollations
Definition: parsenodes.h:1073
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
StringInfo buf
Definition: ruleutils.c:108
int i
#define lfirst_oid(lc)
Definition: pg_list.h:108
char ** colnames
Definition: ruleutils.c:225
static void get_from_clause_item ( Node jtnode,
Query query,
deparse_context context 
)
static

Definition at line 9693 of file ruleutils.c.

References RangeTblEntry::alias, JoinExpr::alias, Alias::aliasname, appendContextKeyword(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), generate_unaccent_rules::args, buf, deparse_context::buf, RangeTblEntry::ctename, deparse_columns_fetch, elog, ERROR, RangeTblFunction::funccolnames, RangeTblFunction::funcexpr, RangeTblEntry::funcordinality, RangeTblEntry::functions, generate_relation_name(), get_column_alias_list(), get_from_clause_coldeflist(), get_query_def(), get_relation_name(), get_rtable_name(), get_rule_expr(), get_tablefunc(), get_tablesample_def(), get_values_def(), deparse_context::indentLevel, IsA, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, JoinExpr::jointype, JoinExpr::larg, RangeTblEntry::lateral, lfirst, linitial, list_concat(), list_copy(), list_length(), deparse_context::namespaces, NIL, nodeTag, NULL, only_marker, PRETTY_PAREN, deparse_context::prettyFlags, PRETTYINDENT_JOIN, PRETTYINDENT_STD, deparse_columns::printaliases, JoinExpr::quals, quote_identifier(), JoinExpr::rarg, RangeTblEntry::relid, rt_fetch, Query::rtable, RTE_CTE, RTE_FUNCTION, RTE_RELATION, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, JoinExpr::rtindex, RangeTblEntry::subquery, RangeTblEntry::tablefunc, RangeTblEntry::tablesample, JoinExpr::usingClause, deparse_columns::usingNames, RangeTblEntry::values_lists, and deparse_context::wrapColumn.

Referenced by get_from_clause().

9694 {
9695  StringInfo buf = context->buf;
9697 
9698  if (IsA(jtnode, RangeTblRef))
9699  {
9700  int varno = ((RangeTblRef *) jtnode)->rtindex;
9701  RangeTblEntry *rte = rt_fetch(varno, query->rtable);
9702  char *refname = get_rtable_name(varno, context);
9703  deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
9704  RangeTblFunction *rtfunc1 = NULL;
9705  bool printalias;
9706 
9707  if (rte->lateral)
9708  appendStringInfoString(buf, "LATERAL ");
9709 
9710  /* Print the FROM item proper */
9711  switch (rte->rtekind)
9712  {
9713  case RTE_RELATION:
9714  /* Normal relation RTE */
9715  appendStringInfo(buf, "%s%s",
9716  only_marker(rte),
9718  context->namespaces));
9719  break;
9720  case RTE_SUBQUERY:
9721  /* Subquery RTE */
9722  appendStringInfoChar(buf, '(');
9723  get_query_def(rte->subquery, buf, context->namespaces, NULL,
9724  context->prettyFlags, context->wrapColumn,
9725  context->indentLevel);
9726  appendStringInfoChar(buf, ')');
9727  break;
9728  case RTE_FUNCTION:
9729  /* Function RTE */
9730  rtfunc1 = (RangeTblFunction *) linitial(rte->functions);
9731 
9732  /*
9733  * Omit ROWS FROM() syntax for just one function, unless it
9734  * has both a coldeflist and WITH ORDINALITY. If it has both,
9735  * we must use ROWS FROM() syntax to avoid ambiguity about
9736  * whether the coldeflist includes the ordinality column.
9737  */
9738  if (list_length(rte->functions) == 1 &&
9739  (rtfunc1->funccolnames == NIL || !rte->funcordinality))
9740  {
9741  get_rule_expr(rtfunc1->funcexpr, context, true);
9742  /* we'll print the coldeflist below, if it has one */
9743  }
9744  else
9745  {
9746  bool all_unnest;
9747  ListCell *lc;
9748 
9749  /*
9750  * If all the function calls in the list are to unnest,
9751  * and none need a coldeflist, then collapse the list back
9752  * down to UNNEST(args). (If we had more than one
9753  * built-in unnest function, this would get more
9754  * difficult.)
9755  *
9756  * XXX This is pretty ugly, since it makes not-terribly-
9757  * future-proof assumptions about what the parser would do
9758  * with the output; but the alternative is to emit our
9759  * nonstandard ROWS FROM() notation for what might have
9760  * been a perfectly spec-compliant multi-argument
9761  * UNNEST().
9762  */
9763  all_unnest = true;
9764  foreach(lc, rte->functions)
9765  {
9766  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
9767 
9768  if (!IsA(rtfunc->funcexpr, FuncExpr) ||
9769  ((FuncExpr *) rtfunc->funcexpr)->funcid != F_ARRAY_UNNEST ||
9770  rtfunc->funccolnames != NIL)
9771  {
9772  all_unnest = false;
9773  break;
9774  }
9775  }
9776 
9777  if (all_unnest)
9778  {
9779  List *allargs = NIL;
9780 
9781  foreach(lc, rte->functions)
9782  {
9783  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
9784  List *args = ((FuncExpr *) rtfunc->funcexpr)->args;
9785 
9786  allargs = list_concat(allargs, list_copy(args));
9787  }
9788 
9789  appendStringInfoString(buf, "UNNEST(");
9790  get_rule_expr((Node *) allargs, context, true);
9791  appendStringInfoChar(buf, ')');
9792  }
9793  else
9794  {
9795  int funcno = 0;
9796 
9797  appendStringInfoString(buf, "ROWS FROM(");
9798  foreach(lc, rte->functions)
9799  {
9800  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
9801 
9802  if (funcno > 0)
9803  appendStringInfoString(buf, ", ");
9804  get_rule_expr(rtfunc->funcexpr, context, true);
9805  if (rtfunc->funccolnames != NIL)
9806  {
9807  /* Reconstruct the column definition list */
9808  appendStringInfoString(buf, " AS ");
9810  NULL,
9811  context);
9812  }
9813  funcno++;
9814  }
9815  appendStringInfoChar(buf, ')');
9816  }
9817  /* prevent printing duplicate coldeflist below */
9818  rtfunc1 = NULL;
9819  }
9820  if (rte->funcordinality)
9821  appendStringInfoString(buf, " WITH ORDINALITY");
9822  break;
9823  case RTE_TABLEFUNC:
9824  get_tablefunc(rte->tablefunc, context, true);
9825  break;
9826  case RTE_VALUES:
9827  /* Values list RTE */
9828  appendStringInfoChar(buf, '(');
9829  get_values_def(rte->values_lists, context);
9830  appendStringInfoChar(buf, ')');
9831  break;
9832  case RTE_CTE:
9834  break;
9835  default:
9836  elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
9837  break;
9838  }
9839 
9840  /* Print the relation alias, if needed */
9841  printalias = false;
9842  if (rte->alias != NULL)
9843  {
9844  /* Always print alias if user provided one */
9845  printalias = true;
9846  }
9847  else if (colinfo->printaliases)
9848  {
9849  /* Always print alias if we need to print column aliases */
9850  printalias = true;
9851  }
9852  else if (rte->rtekind == RTE_RELATION)
9853  {
9854  /*
9855  * No need to print alias if it's same as relation name (this
9856  * would normally be the case, but not if set_rtable_names had to
9857  * resolve a conflict).
9858  */
9859  if (strcmp(refname, get_relation_name(rte->relid)) != 0)
9860  printalias = true;
9861  }
9862  else if (rte->rtekind == RTE_FUNCTION)
9863  {
9864  /*
9865  * For a function RTE, always print alias. This covers possible
9866  * renaming of the function and/or instability of the
9867  * FigureColname rules for things that aren't simple functions.
9868  * Note we'd need to force it anyway for the columndef list case.
9869  */
9870  printalias = true;
9871  }
9872  else if (rte->rtekind == RTE_VALUES)
9873  {
9874  /* Alias is syntactically required for VALUES */
9875  printalias = true;
9876  }
9877  else if (rte->rtekind == RTE_CTE)
9878  {
9879  /*
9880  * No need to print alias if it's same as CTE name (this would
9881  * normally be the case, but not if set_rtable_names had to
9882  * resolve a conflict).
9883  */
9884  if (strcmp(refname, rte->ctename) != 0)
9885  printalias = true;
9886  }
9887  if (printalias)
9888  appendStringInfo(buf, " %s", quote_identifier(refname));
9889 
9890  /* Print the column definitions or aliases, if needed */
9891  if (rtfunc1 && rtfunc1->funccolnames != NIL)
9892  {
9893  /* Reconstruct the columndef list, which is also the aliases */
9894  get_from_clause_coldeflist(rtfunc1, colinfo, context);
9895  }
9896  else
9897  {
9898  /* Else print column aliases as needed */
9899  get_column_alias_list(colinfo, context);
9900  }
9901 
9902  /* Tablesample clause must go after any alias */
9903  if (rte->rtekind == RTE_RELATION && rte->tablesample)
9904  get_tablesample_def(rte->tablesample, context);
9905  }
9906  else if (IsA(jtnode, JoinExpr))
9907  {
9908  JoinExpr *j = (JoinExpr *) jtnode;
9909  deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
9910  bool need_paren_on_right;
9911 
9912  need_paren_on_right = PRETTY_PAREN(context) &&
9913  !IsA(j->rarg, RangeTblRef) &&
9914  !(IsA(j->rarg, JoinExpr) &&((JoinExpr *) j->rarg)->alias != NULL);
9915 
9916  if (!PRETTY_PAREN(context) || j->alias != NULL)
9917  appendStringInfoChar(buf, '(');
9918 
9919  get_from_clause_item(j->larg, query, context);
9920 
9921  switch (j->jointype)
9922  {
9923  case JOIN_INNER:
9924  if (j->quals)
9925  appendContextKeyword(context, " JOIN ",
9929  else
9930  appendContextKeyword(context, " CROSS JOIN ",
9934  break;
9935  case JOIN_LEFT:
9936  appendContextKeyword(context, " LEFT JOIN ",
9940  break;
9941  case JOIN_FULL:
9942  appendContextKeyword(context, " FULL JOIN ",
9946  break;
9947  case JOIN_RIGHT:
9948  appendContextKeyword(context, " RIGHT JOIN ",
9952  break;
9953  default:
9954  elog(ERROR, "unrecognized join type: %d",
9955  (int) j->jointype);
9956  }
9957 
9958  if (need_paren_on_right)
9959  appendStringInfoChar(buf, '(');
9960  get_from_clause_item(j->rarg, query, context);
9961  if (need_paren_on_right)
9962  appendStringInfoChar(buf, ')');
9963 
9964  if (j->usingClause)
9965  {
9966  ListCell *lc;
9967  bool first = true;
9968 
9969  appendStringInfoString(buf, " USING (");
9970  /* Use the assigned names, not what's in usingClause */
9971  foreach(lc, colinfo->usingNames)
9972  {
9973  char *colname = (char *) lfirst(lc);
9974 
9975  if (first)
9976  first = false;
9977  else
9978  appendStringInfoString(buf, ", ");
9980  }
9981  appendStringInfoChar(buf, ')');
9982  }
9983  else if (j->quals)
9984  {
9985  appendStringInfoString(buf, " ON ");
9986  if (!PRETTY_PAREN(context))
9987  appendStringInfoChar(buf, '(');
9988  get_rule_expr(j->quals, context, false);
9989  if (!PRETTY_PAREN(context))
9990  appendStringInfoChar(buf, ')');
9991  }
9992 
9993  if (!PRETTY_PAREN(context) || j->alias != NULL)
9994  appendStringInfoChar(buf, ')');
9995 
9996  /* Yes, it's correct to put alias after the right paren ... */
9997  if (j->alias != NULL)
9998  {
9999  appendStringInfo(buf, " %s",
10001  get_column_alias_list(colinfo, context);
10002  }
10003  }
10004  else
10005  elog(ERROR, "unrecognized node type: %d",
10006  (int) nodeTag(jtnode));
10007 }
List * namespaces
Definition: ruleutils.c:109
#define NIL
Definition: pg_list.h:69
static char * get_relation_name(Oid relid)
Definition: ruleutils.c:10386
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define PRETTYINDENT_JOIN
Definition: ruleutils.c:83
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10280
Alias * alias
Definition: parsenodes.h:1034
List * list_copy(const List *oldlist)
Definition: list.c:1160
Definition: nodes.h:509
List * list_concat(List *list1, List *list2)
Definition: list.c:321
bool funcordinality
Definition: parsenodes.h:991
List * values_lists
Definition: parsenodes.h:1001
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:10406
Node * larg
Definition: primnodes.h:1451
static void get_tablesample_def(TableSampleClause *tablesample, deparse_context *context)
Definition: ruleutils.c:10108
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define linitial(l)
Definition: pg_list.h:111
List * rtable
Definition: parsenodes.h:135
#define ERROR
Definition: elog.h:43
List * usingNames
Definition: ruleutils.c:271
TableFunc * tablefunc
Definition: parsenodes.h:996
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
#define PRETTY_PAREN(context)
Definition: ruleutils.c:96
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:7458
#define deparse_columns_fetch(rangetable_index, dpns)
Definition: ruleutils.c:275
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define PRETTYINDENT_STD
Definition: ruleutils.c:82
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
List * usingClause
Definition: primnodes.h:1453
Node * quals
Definition: primnodes.h:1454
static void get_tablefunc(TableFunc *tf, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:9481
Node * rarg
Definition: primnodes.h:1452
Alias * alias
Definition: primnodes.h:1455
#define NULL
Definition: c.h:229
JoinType jointype
Definition: primnodes.h:1449
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7563
#define lfirst(lc)
Definition: pg_list.h:106
char * aliasname
Definition: primnodes.h:42
List * functions
Definition: parsenodes.h:990
#define only_marker(rte)
Definition: ruleutils.c:463
static int list_length(const List *l)
Definition: pg_list.h:89
static void get_query_def(Query *query, StringInfo buf, List *parentnamespace, TupleDesc resultDesc, int prettyFlags, int wrapColumn, int startIndent)
Definition: ruleutils.c:4825
#define nodeTag(nodeptr)
Definition: nodes.h:514
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:4898
RTEKind rtekind
Definition: parsenodes.h:936
static void get_column_alias_list(deparse_columns *colinfo, deparse_context *context)
Definition: ruleutils.c:10015
char * ctename
Definition: parsenodes.h:1006
Query * subquery
Definition: parsenodes.h:959
StringInfo buf
Definition: ruleutils.c:108
#define elog
Definition: elog.h:219
static void get_from_clause_coldeflist(RangeTblFunction *rtfunc, deparse_columns *colinfo, deparse_context *context)
Definition: ruleutils.c:10055
int rtindex
Definition: primnodes.h:1456
Definition: pg_list.h:45
struct TableSampleClause * tablesample
Definition: parsenodes.h:954
static char * get_rtable_name(int rtindex, deparse_context *context)
Definition: ruleutils.c:4396
static void get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
Definition: ruleutils.c:9693
static void get_func_expr ( FuncExpr expr,
deparse_context context,
bool  showimplicit 
)
static

Definition at line 8834 of file ruleutils.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), arg, FuncExpr::args, buf, deparse_context::buf, COERCE_EXPLICIT_CAST, COERCE_IMPLICIT_CAST, ereport, errcode(), errmsg(), ERROR, exprIsLengthCoercion(), exprType(), FUNC_MAX_ARGS, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcvariadic, generate_function_name(), get_coercion_expr(), get_rule_expr(), get_rule_expr_paren(), IsA, lappend(), lfirst, linitial, list_length(), lnext, NIL, NULL, and deparse_context::special_exprkind.

Referenced by get_rule_expr().

8836 {
8837  StringInfo buf = context->buf;
8838  Oid funcoid = expr->funcid;
8839  Oid argtypes[FUNC_MAX_ARGS];
8840  int nargs;
8841  List *argnames;
8842  bool use_variadic;
8843  ListCell *l;
8844 
8845  /*
8846  * If the function call came from an implicit coercion, then just show the
8847  * first argument --- unless caller wants to see implicit coercions.
8848  */
8849  if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
8850  {
8851  get_rule_expr_paren((Node *) linitial(expr->args), context,
8852  false, (Node *) expr);
8853  return;
8854  }
8855 
8856  /*
8857  * If the function call came from a cast, then show the first argument
8858  * plus an explicit cast operation.
8859  */
8860  if (expr->funcformat == COERCE_EXPLICIT_CAST ||
8862  {
8863  Node *arg = linitial(expr->args);
8864  Oid rettype = expr->funcresulttype;
8865  int32 coercedTypmod;
8866 
8867  /* Get the typmod if this is a length-coercion function */
8868  (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
8869 
8870  get_coercion_expr(arg, context,
8871  rettype, coercedTypmod,
8872  (Node *) expr);
8873 
8874  return;
8875  }
8876 
8877  /*
8878  * Normal function: display as proname(args). First we need to extract
8879  * the argument datatypes.
8880  */
8881  if (list_length(expr->args) > FUNC_MAX_ARGS)
8882  ereport(ERROR,
8883  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
8884  errmsg("too many arguments")));
8885  nargs = 0;
8886  argnames = NIL;
8887  foreach(l, expr->args)
8888  {
8889  Node *arg = (Node *) lfirst(l);
8890 
8891  if (IsA(arg, NamedArgExpr))
8892  argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
8893  argtypes[nargs] = exprType(arg);
8894  nargs++;
8895  }
8896 
8897  appendStringInfo(buf, "%s(",
8898  generate_function_name(funcoid, nargs,
8899  argnames, argtypes,
8900  expr->funcvariadic,
8901  &use_variadic,
8902  context->special_exprkind));
8903  nargs = 0;
8904  foreach(l, expr->args)
8905  {
8906  if (nargs++ > 0)
8907  appendStringInfoString(buf, ", ");
8908  if (use_variadic && lnext(l) == NULL)
8909  appendStringInfoString(buf, "VARIADIC ");
8910  get_rule_expr((Node *) lfirst(l), context, true);
8911  }
8912  appendStringInfoChar(buf, ')');
8913 }
Oid funcresulttype
Definition: primnodes.h:450
#define NIL
Definition: pg_list.h:69
static char * generate_function_name(Oid funcid, int nargs, List *argnames, Oid *argtypes, bool has_variadic, bool *use_variadic_p, ParseExprKind special_exprkind)
Definition: ruleutils.c:10508
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
static void get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
Definition: ruleutils.c:7531
List * args
Definition: primnodes.h:457
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
bool exprIsLengthCoercion(const Node *expr, int32 *coercedTypmod)
Definition: nodeFuncs.c:513
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:256
#define FUNC_MAX_ARGS
CoercionForm funcformat
Definition: primnodes.h:454
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define linitial(l)
Definition: pg_list.h:111
Oid funcid
Definition: primnodes.h:449
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
static void get_coercion_expr(Node *arg, deparse_context *context, Oid resulttype, int32 resulttypmod, Node *parentNode)
Definition: ruleutils.c:9118
ParseExprKind special_exprkind
Definition: ruleutils.c:116
List * lappend(List *list, void *datum)
Definition: list.c:128
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
#define NULL
Definition: c.h:229
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7563
#define lfirst(lc)
Definition: pg_list.h:106
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
StringInfo buf
Definition: ruleutils.c:108
int errmsg(const char *fmt,...)
Definition: elog.c:797
void * arg
Definition: pg_list.h:45
bool funcvariadic
Definition: primnodes.h:452
static void get_insert_query_def ( Query query,
deparse_context context 
)
static

Definition at line 5880 of file ruleutils.c.

References OnConflictExpr::action, RangeTblEntry::alias, Alias::aliasname, appendContextKeyword(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), OnConflictExpr::arbiterElems, OnConflictExpr::arbiterWhere, Assert, buf, deparse_context::buf, OnConflictExpr::constraint, elog, ERROR, TargetEntry::expr, generate_relation_name(), get_constraint_name(), get_query_def(), get_relid_attribute_name(), get_rule_expr(), get_target_list(), get_update_query_targetlist_def(), get_values_def(), get_with_clause(), deparse_context::indentLevel, lappend(), lfirst, NIL, NULL, OidIsValid, Query::onConflict, ONCONFLICT_NOTHING, OnConflictExpr::onConflictSet, OnConflictExpr::onConflictWhere, Query::override, OVERRIDING_SYSTEM_VALUE, OVERRIDING_USER_VALUE, PRETTY_INDENT, deparse_context::prettyFlags, PRETTYINDENT_STD, processIndirection(), quote_identifier(), RangeTblEntry::relid, TargetEntry::resjunk, TargetEntry::resno, Query::resultRelation, Query::returningList, rt_fetch, Query::rtable, RTE_RELATION, RTE_SUBQUERY, RTE_VALUES, RangeTblEntry::rtekind, RangeTblEntry::subquery, Query::targetList, RangeTblEntry::values_lists, deparse_context::varprefix, and deparse_context::wrapColumn.

Referenced by get_query_def().

5881 {
5882  StringInfo buf = context->buf;
5883  RangeTblEntry *select_rte = NULL;
5884  RangeTblEntry *values_rte = NULL;
5885  RangeTblEntry *rte;
5886  char *sep;
5887  ListCell *l;
5888  List *strippedexprs;
5889 
5890  /* Insert the WITH clause if given */
5891  get_with_clause(query, context);
5892 
5893  /*
5894  * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
5895  * single RTE for the SELECT or VALUES. Plain VALUES has neither.
5896  */
5897  foreach(l, query->rtable)
5898  {
5899  rte = (RangeTblEntry *) lfirst(l);
5900 
5901  if (rte->rtekind == RTE_SUBQUERY)
5902  {
5903  if (select_rte)
5904  elog(ERROR, "too many subquery RTEs in INSERT");
5905  select_rte = rte;
5906  }
5907 
5908  if (rte->rtekind == RTE_VALUES)
5909  {
5910  if (values_rte)
5911  elog(ERROR, "too many values RTEs in INSERT");
5912  values_rte = rte;
5913  }
5914  }
5915  if (select_rte && values_rte)
5916  elog(ERROR, "both subquery and values RTEs in INSERT");
5917 
5918  /*
5919  * Start the query with INSERT INTO relname
5920  */
5921  rte = rt_fetch(query->resultRelation, query->rtable);
5922  Assert(rte->rtekind == RTE_RELATION);
5923 
5924  if (PRETTY_INDENT(context))
5925  {
5926  context->indentLevel += PRETTYINDENT_STD;
5927  appendStringInfoChar(buf, ' ');
5928  }
5929  appendStringInfo(buf, "INSERT INTO %s ",
5931  /* INSERT requires AS keyword for target alias */
5932  if (rte->alias != NULL)
5933  appendStringInfo(buf, "AS %s ",
5935 
5936  /*
5937  * Add the insert-column-names list. Any indirection decoration needed on
5938  * the column names can be inferred from the top targetlist.
5939  */
5940  strippedexprs = NIL;
5941  sep = "";
5942  if (query->targetList)
5943  appendStringInfoChar(buf, '(');
5944  foreach(l, query->targetList)
5945  {
5946  TargetEntry *tle = (TargetEntry *) lfirst(l);
5947 
5948  if (tle->resjunk)
5949  continue; /* ignore junk entries */
5950 
5951  appendStringInfoString(buf, sep);
5952  sep = ", ";
5953 
5954  /*
5955  * Put out name of target column; look in the catalogs, not at
5956  * tle->resname, since resname will fail to track RENAME.
5957  */
5960  tle->resno)));
5961 
5962  /*
5963  * Print any indirection needed (subfields or subscripts), and strip
5964  * off the top-level nodes representing the indirection assignments.
5965  * Add the stripped expressions to strippedexprs. (If it's a
5966  * single-VALUES statement, the stripped expressions are the VALUES to
5967  * print below. Otherwise they're just Vars and not really
5968  * interesting.)
5969  */
5970  strippedexprs = lappend(strippedexprs,
5971  processIndirection((Node *) tle->expr,
5972  context));
5973  }
5974  if (query->targetList)
5975  appendStringInfoString(buf, ") ");
5976 
5977  if (query->override)
5978  {
5979  if (query->override == OVERRIDING_SYSTEM_VALUE)
5980  appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
5981  else if (query->override == OVERRIDING_USER_VALUE)
5982  appendStringInfoString(buf, "OVERRIDING USER VALUE ");
5983  }
5984 
5985  if (select_rte)
5986  {
5987  /* Add the SELECT */
5988  get_query_def(select_rte->subquery, buf, NIL, NULL,
5989  context->prettyFlags, context->wrapColumn,
5990  context->indentLevel);
5991  }
5992  else if (values_rte)
5993  {
5994  /* Add the multi-VALUES expression lists */
5995  get_values_def(values_rte->values_lists, context);
5996  }
5997  else if (strippedexprs)
5998  {
5999  /* Add the single-VALUES expression list */
6000  appendContextKeyword(context, "VALUES (",
6002  get_rule_expr((Node *) strippedexprs, context, false);
6003  appendStringInfoChar(buf, ')');
6004  }
6005  else
6006  {
6007  /* No expressions, so it must be DEFAULT VALUES */
6008  appendStringInfoString(buf, "DEFAULT VALUES");
6009  }
6010 
6011  /* Add ON CONFLICT if present */
6012  if (query->onConflict)
6013  {
6014  OnConflictExpr *confl = query->onConflict;
6015 
6016  appendStringInfoString(buf, " ON CONFLICT");
6017 
6018  if (confl->arbiterElems)
6019  {
6020  /* Add the single-VALUES expression list */
6021  appendStringInfoChar(buf, '(');
6022  get_rule_expr((Node *) confl->arbiterElems, context, false);
6023  appendStringInfoChar(buf, ')');
6024 
6025  /* Add a WHERE clause (for partial indexes) if given */
6026  if (confl->arbiterWhere != NULL)
6027  {
6028  bool save_varprefix;
6029 
6030  /*
6031  * Force non-prefixing of Vars, since parser assumes that they
6032  * belong to target relation. WHERE clause does not use
6033  * InferenceElem, so this is separately required.
6034  */
6035  save_varprefix = context->varprefix;
6036  context->varprefix = false;
6037 
6038  appendContextKeyword(context, " WHERE ",
6040  get_rule_expr(confl->arbiterWhere, context, false);
6041 
6042  context->varprefix = save_varprefix;
6043  }
6044  }
6045  else if (OidIsValid(confl->constraint))
6046  {
6047  char *constraint = get_constraint_name(confl->constraint);
6048 
6049  if (!constraint)
6050  elog(ERROR, "cache lookup failed for constraint %u",
6051  confl->constraint);
6052  appendStringInfo(buf, " ON CONSTRAINT %s",
6053  quote_identifier(constraint));
6054  }
6055 
6056  if (confl->action == ONCONFLICT_NOTHING)
6057  {
6058  appendStringInfoString(buf, " DO NOTHING");
6059  }
6060  else
6061  {
6062  appendStringInfoString(buf, " DO UPDATE SET ");
6063  /* Deparse targetlist */
6065  context, rte);
6066 
6067  /* Add a WHERE clause if given */
6068  if (confl->onConflictWhere != NULL)
6069  {
6070  appendContextKeyword(context, " WHERE ",
6072  get_rule_expr(confl->onConflictWhere, context, false);
6073  }
6074  }
6075  }
6076 
6077  /* Add RETURNING if present */
6078  if (query->returningList)
6079  {
6080  appendContextKeyword(context, " RETURNING",
6082  get_target_list(query->returningList, context, NULL);
6083  }
6084 }
#define NIL
Definition: pg_list.h:69
static void get_with_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:4941
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10280
Alias * alias
Definition: parsenodes.h:1034
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:997
OnConflictExpr * onConflict
Definition: parsenodes.h:142
static Node * processIndirection(Node *node, deparse_context *context)
Definition: ruleutils.c:10192
int resultRelation
Definition: parsenodes.h:120
static void get_target_list(List *targetList, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5309
Definition: nodes.h:509
#define PRETTY_INDENT(context)
Definition: ruleutils.c:97
static void get_update_query_targetlist_def(Query *query, List *targetList, deparse_context *context, RangeTblEntry *rte)
Definition: ruleutils.c:6147
#define OidIsValid(objectId)
Definition: c.h:538
List * values_lists
Definition: parsenodes.h:1001
List * targetList
Definition: parsenodes.h:138
List * arbiterElems
Definition: primnodes.h:1490
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:10406
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
bool resjunk
Definition: primnodes.h:1375
List * rtable
Definition: parsenodes.h:135
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:7458
AttrNumber resno
Definition: primnodes.h:1369
List * returningList
Definition: parsenodes.h:144
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define PRETTYINDENT_STD
Definition: ruleutils.c:82
List * lappend(List *list, void *datum)
Definition: list.c:128
OnConflictAction action
Definition: primnodes.h:1487
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
char * get_relid_attribute_name(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:801
OverridingKind override
Definition: parsenodes.h:140
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7563
#define lfirst(lc)
Definition: pg_list.h:106
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1368
static void get_query_def(Query *query, StringInfo buf, List *parentnamespace, TupleDesc resultDesc, int prettyFlags, int wrapColumn, int startIndent)
Definition: ruleutils.c:4825
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:4898
RTEKind rtekind
Definition: parsenodes.h:936
Node * arbiterWhere
Definition: primnodes.h:1492
Query * subquery
Definition: parsenodes.h:959
StringInfo buf
Definition: ruleutils.c:108
List * onConflictSet
Definition: primnodes.h:1496
#define elog
Definition: elog.h:219
Node * onConflictWhere
Definition: primnodes.h:1497
Definition: pg_list.h:45
static const char* get_name_for_var_field ( Var var,
int  fieldno,
int  levelsup,
deparse_context context 
)
static

Definition at line 6651 of file ruleutils.c.

References Alias::aliasname, Assert, tupleDesc::attrs, RowExpr::colnames, RangeTblEntry::ctelevelsup, RangeTblEntry::ctename, CommonTableExpr::ctename, CommonTableExpr::ctequery, deparse_namespace::ctes, elog, RangeTblEntry::eref, ERROR, TargetEntry::expr, exprType(), exprTypmod(), find_param_referent(), get_expr_result_type(), get_rte_attribute_name(), get_tle_by_resno(), GetCTETargetList, deparse_namespace::index_tlist, INDEX_VAR, deparse_namespace::inner_planstate, deparse_namespace::inner_tlist, INNER_VAR, InvalidAttrNumber, IsA, RangeTblEntry::joinaliasvars, lcons(), lfirst, list_copy_tail(), list_delete_first(), list_length(), list_nth(), lookup_rowtype_tupdesc_copy(), deparse_context::namespaces, NameStr, NIL, NULL, deparse_namespace::outer_planstate, deparse_namespace::outer_tlist, OUTER_VAR, pop_ancestor_plan(), pop_child_plan(), push_ancestor_plan(), push_child_plan(), RECORDOID, TargetEntry::resjunk, result, rt_fetch, deparse_namespace::rtable, RTE_CTE, RTE_FUNCTION, RTE_JOIN, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, set_deparse_for_query(), strVal, RangeTblEntry::subquery, Query::targetList, TYPEFUNC_COMPOSITE, Var::varattno, Var::varlevelsup, Var::varno, and Var::vartype.

Referenced by get_rule_expr().

6653 {
6654  RangeTblEntry *rte;
6655  AttrNumber attnum;
6656  int netlevelsup;
6657  deparse_namespace *dpns;
6659  Node *expr;
6660 
6661  /*
6662  * If it's a RowExpr that was expanded from a whole-row Var, use the
6663  * column names attached to it.
6664  */
6665  if (IsA(var, RowExpr))
6666  {
6667  RowExpr *r = (RowExpr *) var;
6668 
6669  if (fieldno > 0 && fieldno <= list_length(r->colnames))
6670  return strVal(list_nth(r->colnames, fieldno - 1));
6671  }
6672 
6673  /*
6674  * If it's a Param of type RECORD, try to find what the Param refers to.
6675  */
6676  if (IsA(var, Param))
6677  {
6678  Param *param = (Param *) var;
6679  ListCell *ancestor_cell;
6680 
6681  expr = find_param_referent(param, context, &dpns, &ancestor_cell);
6682  if (expr)
6683  {
6684  /* Found a match, so recurse to decipher the field name */
6685  deparse_namespace save_dpns;
6686  const char *result;
6687 
6688  push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
6689  result = get_name_for_var_field((Var *) expr, fieldno,
6690  0, context);
6691  pop_ancestor_plan(dpns, &save_dpns);
6692  return result;
6693  }
6694  }
6695 
6696  /*
6697  * If it's a Var of type RECORD, we have to find what the Var refers to;
6698  * if not, we can use get_expr_result_type. If that fails, we try
6699  * lookup_rowtype_tupdesc, which will probably fail too, but will ereport
6700  * an acceptable message.
6701  */
6702  if (!IsA(var, Var) ||
6703  var->vartype != RECORDOID)
6704  {
6705  if (get_expr_result_type((Node *) var, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
6706  tupleDesc = lookup_rowtype_tupdesc_copy(exprType((Node *) var),
6707  exprTypmod((Node *) var));
6708  Assert(tupleDesc);
6709  /* Got the tupdesc, so we can extract the field name */
6710  Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
6711  return NameStr(tupleDesc->attrs[fieldno - 1]->attname);
6712  }
6713 
6714  /* Find appropriate nesting depth */
6715  netlevelsup = var->varlevelsup + levelsup;
6716  if (netlevelsup >= list_length(context->namespaces))
6717  elog(ERROR, "bogus varlevelsup: %d offset %d",
6718  var->varlevelsup, levelsup);
6719  dpns = (deparse_namespace *) list_nth(context->namespaces,
6720  netlevelsup);
6721 
6722  /*
6723  * Try to find the relevant RTE in this rtable. In a plan tree, it's
6724  * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
6725  * down into the subplans, or INDEX_VAR, which is resolved similarly.
6726  */
6727  if (var->varno >= 1 && var->varno <= list_length(dpns->rtable))
6728  {
6729  rte = rt_fetch(var->varno, dpns->rtable);
6730  attnum = var->varattno;
6731  }
6732  else if (var->varno == OUTER_VAR && dpns->outer_tlist)
6733  {
6734  TargetEntry *tle;
6735  deparse_namespace save_dpns;
6736  const char *result;
6737 
6738  tle = get_tle_by_resno(dpns->outer_tlist, var->varattno);
6739  if (!tle)
6740  elog(ERROR, "bogus varattno for OUTER_VAR var: %d", var->varattno);
6741 
6742  Assert(netlevelsup == 0);
6743  push_child_plan(dpns, dpns->outer_planstate, &save_dpns);
6744 
6745  result = get_name_for_var_field((Var *) tle->expr, fieldno,
6746  levelsup, context);
6747 
6748  pop_child_plan(dpns, &save_dpns);
6749  return result;
6750  }
6751  else if (var->varno == INNER_VAR && dpns->inner_tlist)
6752  {
6753  TargetEntry *tle;
6754  deparse_namespace save_dpns;
6755  const char *result;
6756 
6757  tle = get_tle_by_resno(dpns->inner_tlist, var->varattno);
6758  if (!tle)
6759  elog(ERROR, "bogus varattno for INNER_VAR var: %d", var->varattno);
6760 
6761  Assert(netlevelsup == 0);
6762  push_child_plan(dpns, dpns->inner_planstate, &save_dpns);
6763 
6764  result = get_name_for_var_field((Var *) tle->expr, fieldno,
6765  levelsup, context);
6766 
6767  pop_child_plan(dpns, &save_dpns);
6768  return result;
6769  }
6770  else if (var->varno == INDEX_VAR && dpns->index_tlist)
6771  {
6772  TargetEntry *tle;
6773  const char *result;
6774 
6775  tle = get_tle_by_resno(dpns->index_tlist, var->varattno);
6776  if (!tle)
6777  elog(ERROR, "bogus varattno for INDEX_VAR var: %d", var->varattno);
6778 
6779  Assert(netlevelsup == 0);
6780 
6781  result = get_name_for_var_field((Var *) tle->expr, fieldno,
6782  levelsup, context);
6783 
6784  return result;
6785  }
6786  else
6787  {
6788  elog(ERROR, "bogus varno: %d", var->varno);
6789  return NULL; /* keep compiler quiet */
6790  }
6791 
6792  if (attnum == InvalidAttrNumber)
6793  {
6794  /* Var is whole-row reference to RTE, so select the right field */
6795  return get_rte_attribute_name(rte, fieldno);
6796  }
6797 
6798  /*
6799  * This part has essentially the same logic as the parser's
6800  * expandRecordVariable() function, but we are dealing with a different
6801  * representation of the input context, and we only need one field name
6802  * not a TupleDesc. Also, we need special cases for finding subquery and
6803  * CTE subplans when deparsing Plan trees.
6804  */
6805  expr = (Node *) var; /* default if we can't drill down */
6806 
6807  switch (rte->rtekind)
6808  {
6809  case RTE_RELATION:
6810  case RTE_VALUES:
6811  case RTE_NAMEDTUPLESTORE:
6812 
6813  /*
6814  * This case should not occur: a column of a table or values list
6815  * shouldn't have type RECORD. Fall through and fail (most
6816  * likely) at the bottom.
6817  */
6818  break;
6819  case RTE_SUBQUERY:
6820  /* Subselect-in-FROM: examine sub-select's output expr */
6821  {
6822  if (rte->subquery)
6823  {
6825  attnum);
6826 
6827  if (ste == NULL || ste->resjunk)
6828  elog(ERROR, "subquery %s does not have attribute %d",
6829  rte->eref->aliasname, attnum);
6830  expr = (Node *) ste->expr;
6831  if (IsA(expr, Var))
6832  {
6833  /*
6834  * Recurse into the sub-select to see what its Var
6835  * refers to. We have to build an additional level of
6836  * namespace to keep in step with varlevelsup in the
6837  * subselect.
6838  */
6839  deparse_namespace mydpns;
6840  const char *result;
6841 
6842  set_deparse_for_query(&mydpns, rte->subquery,
6843  context->namespaces);
6844 
6845  context->namespaces = lcons(&mydpns,
6846  context->namespaces);
6847 
6848  result = get_name_for_var_field((Var *) expr, fieldno,
6849  0, context);
6850 
6851  context->namespaces =
6852  list_delete_first(context->namespaces);
6853 
6854  return result;
6855  }
6856  /* else fall through to inspect the expression */
6857  }
6858  else
6859  {
6860  /*
6861  * We're deparsing a Plan tree so we don't have complete
6862  * RTE entries (in particular, rte->subquery is NULL). But
6863  * the only place we'd see a Var directly referencing a
6864  * SUBQUERY RTE is in a SubqueryScan plan node, and we can
6865  * look into the child plan's tlist instead.
6866  */
6867  TargetEntry *tle;
6868  deparse_namespace save_dpns;
6869  const char *result;
6870 
6871  if (!dpns->inner_planstate)
6872  elog(ERROR, "failed to find plan for subquery %s",
6873  rte->eref->aliasname);
6874  tle = get_tle_by_resno(dpns->inner_tlist, attnum);
6875  if (!tle)
6876  elog(ERROR, "bogus varattno for subquery var: %d",
6877  attnum);
6878  Assert(netlevelsup == 0);
6879  push_child_plan(dpns, dpns->inner_planstate, &save_dpns);
6880 
6881  result = get_name_for_var_field((Var *) tle->expr, fieldno,
6882  levelsup, context);
6883 
6884  pop_child_plan(dpns, &save_dpns);
6885  return result;
6886  }
6887  }
6888  break;
6889  case RTE_JOIN:
6890  /* Join RTE --- recursively inspect the alias variable */
6891  if (rte->joinaliasvars == NIL)
6892  elog(ERROR, "cannot decompile join alias var in plan tree");
6893  Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
6894  expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
6895  Assert(expr != NULL);
6896  /* we intentionally don't strip implicit coercions here */
6897  if (IsA(expr, Var))
6898  return get_name_for_var_field((Var *) expr, fieldno,
6899  var->varlevelsup + levelsup,
6900  context);
6901  /* else fall through to inspect the expression */
6902  break;
6903  case RTE_FUNCTION:
6904  case RTE_TABLEFUNC:
6905 
6906  /*
6907  * We couldn't get here unless a function is declared with one of
6908  * its result columns as RECORD, which is not allowed.
6909  */
6910  break;
6911  case RTE_CTE:
6912  /* CTE reference: examine subquery's output expr */
6913  {
6914  CommonTableExpr *cte = NULL;
6915  Index ctelevelsup;
6916  ListCell *lc;
6917 
6918  /*
6919  * Try to find the referenced CTE using the namespace stack.
6920  */
6921  ctelevelsup = rte->ctelevelsup + netlevelsup;
6922  if (ctelevelsup >= list_length(context->namespaces))
6923  lc = NULL;
6924  else
6925  {
6926  deparse_namespace *ctedpns;
6927 
6928  ctedpns = (deparse_namespace *)
6929  list_nth(context->namespaces, ctelevelsup);
6930  foreach(lc, ctedpns->ctes)
6931  {
6932  cte = (CommonTableExpr *) lfirst(lc);
6933  if (strcmp(cte->ctename, rte->ctename) == 0)
6934  break;
6935  }
6936  }
6937  if (lc != NULL)
6938  {
6939  Query *ctequery = (Query *) cte->ctequery;
6941  attnum);
6942 
6943  if (ste == NULL || ste->resjunk)
6944  elog(ERROR, "subquery %s does not have attribute %d",
6945  rte->eref->aliasname, attnum);
6946  expr = (Node *) ste->expr;
6947  if (IsA(expr, Var))
6948  {
6949  /*
6950  * Recurse into the CTE to see what its Var refers to.
6951  * We have to build an additional level of namespace
6952  * to keep in step with varlevelsup in the CTE.
6953  * Furthermore it could be an outer CTE, so we may
6954  * have to delete some levels of namespace.
6955  */
6956  List *save_nslist = context->namespaces;
6957  List *new_nslist;
6958  deparse_namespace mydpns;
6959  const char *result;
6960 
6961  set_deparse_for_query(&mydpns, ctequery,
6962  context->namespaces);
6963 
6964  new_nslist = list_copy_tail(context->namespaces,
6965  ctelevelsup);
6966  context->namespaces = lcons(&mydpns, new_nslist);
6967 
6968  result = get_name_for_var_field((Var *) expr, fieldno,
6969  0, context);
6970 
6971  context->namespaces = save_nslist;
6972 
6973  return result;
6974  }
6975  /* else fall through to inspect the expression */
6976  }
6977  else
6978  {
6979  /*
6980  * We're deparsing a Plan tree so we don't have a CTE
6981  * list. But the only place we'd see a Var directly
6982  * referencing a CTE RTE is in a CteScan plan node, and we
6983  * can look into the subplan's tlist instead.
6984  */
6985  TargetEntry *tle;
6986  deparse_namespace save_dpns;
6987  const char *result;
6988 
6989  if (!dpns->inner_planstate)
6990  elog(ERROR, "failed to find plan for CTE %s",
6991  rte->eref->aliasname);
6992  tle = get_tle_by_resno(dpns->inner_tlist, attnum);
6993  if (!tle)
6994  elog(ERROR, "bogus varattno for subquery var: %d",
6995  attnum);
6996  Assert(netlevelsup == 0);
6997  push_child_plan(dpns, dpns->inner_planstate, &save_dpns);
6998 
6999  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7000  levelsup, context);
7001 
7002  pop_child_plan(dpns, &save_dpns);
7003  return result;
7004  }
7005  }
7006  break;
7007  }
7008 
7009  /*
7010  * We now have an expression we can't expand any more, so see if
7011  * get_expr_result_type() can do anything with it. If not, pass to
7012  * lookup_rowtype_tupdesc() which will probably fail, but will give an
7013  * appropriate error message while failing.
7014  */
7015  if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
7016  tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
7017  exprTypmod(expr));
7018  Assert(tupleDesc);
7019  /* Got the tupdesc, so we can extract the field name */
7020  Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
7021  return NameStr(tupleDesc->attrs[fieldno - 1]->attname);
7022 }
List * namespaces
Definition: ruleutils.c:109
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
List * joinaliasvars
Definition: parsenodes.h:980
Index varlevelsup
Definition: primnodes.h:173
static Node * find_param_referent(Param *param, deparse_context *context, deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
Definition: ruleutils.c:7033
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Definition: nodes.h:509
#define strVal(v)
Definition: value.h:54
AttrNumber varattno
Definition: primnodes.h:168
return result
Definition: formatting.c:1633
static void pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:4560
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1203
PlanState * inner_planstate
Definition: ruleutils.c:160
Definition: primnodes.h:163
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:227
List * targetList
Definition: parsenodes.h:138
bool resjunk
Definition: primnodes.h:1375
#define ERROR
Definition: elog.h:43
List * colnames
Definition: primnodes.h:999
Oid vartype
Definition: primnodes.h:170
void * list_nth(const List *list, int n)
Definition: list.c:410
static void push_child_plan(deparse_namespace *dpns, PlanState *ps, deparse_namespace *save_dpns)
Definition: ruleutils.c:4490
#define RECORDOID
Definition: pg_type.h:680
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
Index varno
Definition: primnodes.h:166
List * outer_tlist
Definition: ruleutils.c:161
unsigned int Index
Definition: c.h:365
static const char * get_name_for_var_field(Var *var, int fieldno, int levelsup, deparse_context *context)
Definition: ruleutils.c:6651
#define INNER_VAR
Definition: primnodes.h:153
char * get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
List * lcons(void *datum, List *list)
Definition: list.c:259
static void pop_child_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:4507
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1368
PlanState * outer_planstate
Definition: ruleutils.c:159
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
Index ctelevelsup
Definition: parsenodes.h:1007
static void set_deparse_for_query(deparse_namespace *dpns, Query *query, List *parent_namespaces)
Definition: ruleutils.c:3330
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:936
char * ctename
Definition: parsenodes.h:1006
Query * subquery
Definition: parsenodes.h:959
List * index_tlist
Definition: ruleutils.c:163
List * inner_tlist
Definition: ruleutils.c:162
static void push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell, deparse_namespace *save_dpns)
Definition: ruleutils.c:4537
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
Alias * eref
Definition: parsenodes.h:1035
#define INDEX_VAR
Definition: primnodes.h:155
Definition: pg_list.h:45
#define GetCTETargetList(cte)
Definition: parsenodes.h:1370
int16 AttrNumber
Definition: attnum.h:21
#define OUTER_VAR
Definition: primnodes.h:154
List * list_delete_first(List *list)
Definition: list.c:666
TupleDesc lookup_rowtype_tupdesc_copy(Oid type_id, int32 typmod)
Definition: typcache.c:1291
static void get_opclass_name ( Oid  opclass,
Oid  actual_datatype,
StringInfo  buf 
)
static

Definition at line 10152 of file ruleutils.c.

References appendStringInfo(), CLAOID, elog, ERROR, get_namespace_name(), GetDefaultOpClass(), GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, OidIsValid, OpclassIsVisible(), quote_identifier(), ReleaseSysCache(), and SearchSysCache1.

Referenced by get_rule_expr(), pg_get_indexdef_worker(), and pg_get_partkeydef_worker().

10154 {
10155  HeapTuple ht_opc;
10156  Form_pg_opclass opcrec;
10157  char *opcname;
10158  char *nspname;
10159 
10160  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
10161  if (!HeapTupleIsValid(ht_opc))
10162  elog(ERROR, "cache lookup failed for opclass %u", opclass);
10163  opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
10164 
10165  if (!OidIsValid(actual_datatype) ||
10166  GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
10167  {
10168  /* Okay, we need the opclass name. Do we need to qualify it? */
10169  opcname = NameStr(opcrec->opcname);
10170  if (OpclassIsVisible(opclass))
10171  appendStringInfo(buf, " %s", quote_identifier(opcname));
10172  else
10173  {
10174  nspname = get_namespace_name(opcrec->opcnamespace);
10175  appendStringInfo(buf, " %s.%s",
10176  quote_identifier(nspname),
10177  quote_identifier(opcname));
10178  }
10179  }
10180  ReleaseSysCache(ht_opc);
10181 }
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1391
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10280
#define OidIsValid(objectId)
Definition: c.h:538
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
bool OpclassIsVisible(Oid opcid)
Definition: namespace.c:1793
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:68
static void get_oper_expr ( OpExpr expr,
deparse_context context 
)
static

Definition at line 8773 of file ruleutils.c.

References appendStringInfo(), appendStringInfoChar(), arg, generate_unaccent_rules::args, OpExpr::args, buf, deparse_context::buf, elog, ERROR, exprType(), generate_operator_name(), get_rule_expr_paren(), GETSTRUCT, HeapTupleIsValid, InvalidOid, linitial, list_length(), lsecond, ObjectIdGetDatum, OPEROID, OpExpr::opno, PRETTY_PAREN, ReleaseSysCache(), and SearchSysCache1.

Referenced by get_rule_expr().

8774 {
8775  StringInfo buf = context->buf;
8776  Oid opno = expr->opno;
8777  List *args = expr->args;
8778 
8779  if (!PRETTY_PAREN(context))
8780  appendStringInfoChar(buf, '(');
8781  if (list_length(args) == 2)
8782  {
8783  /* binary operator */
8784  Node *arg1 = (Node *) linitial(args);
8785  Node *arg2 = (Node *) lsecond(args);
8786 
8787  get_rule_expr_paren(arg1, context, true, (Node *) expr);
8788  appendStringInfo(buf, " %s ",
8790  exprType(arg1),
8791  exprType(arg2)));
8792  get_rule_expr_paren(arg2, context, true, (Node *) expr);
8793  }
8794  else
8795  {
8796  /* unary operator --- but which side? */
8797  Node *arg = (Node *) linitial(args);
8798  HeapTuple tp;
8799  Form_pg_operator optup;
8800 
8802  if (!HeapTupleIsValid(tp))
8803  elog(ERROR, "cache lookup failed for operator %u", opno);
8804  optup = (Form_pg_operator) GETSTRUCT(tp);
8805  switch (optup->oprkind)
8806  {
8807  case 'l':
8808  appendStringInfo(buf, "%s ",
8810  InvalidOid,
8811  exprType(arg)));
8812  get_rule_expr_paren(arg, context, true, (Node *) expr);
8813  break;
8814  case 'r':
8815  get_rule_expr_paren(arg, context, true, (Node *) expr);
8816  appendStringInfo(buf, " %s",
8818  exprType(arg),
8819  InvalidOid));
8820  break;
8821  default:
8822  elog(ERROR, "bogus oprkind: %d", optup->oprkind);
8823  }
8824  ReleaseSysCache(tp);
8825  }
8826  if (!PRETTY_PAREN(context))
8827  appendStringInfoChar(buf, ')');
8828 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
static void get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
Definition: ruleutils.c:7531
Definition: nodes.h:509
unsigned int Oid
Definition: postgres_ext.h:31
#define lsecond(l)
Definition: pg_list.h:116
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
static char * generate_operator_name(Oid operid, Oid arg1, Oid arg2)
Definition: ruleutils.c:10618
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define linitial(l)
Definition: pg_list.h:111
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:66
#define PRETTY_PAREN(context)
Definition: ruleutils.c:96
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
FormData_pg_operator* Form_pg_operator
Definition: pg_operator.h:57
StringInfo buf
Definition: ruleutils.c:108
void * arg
Oid opno
Definition: primnodes.h:496
#define elog
Definition: elog.h:219
List * args
Definition: primnodes.h:502
Definition: pg_list.h:45
static void get_parameter ( Param param,
deparse_context context 
)
static

Definition at line 7153 of file ruleutils.c.

References appendStringInfo(), appendStringInfoChar(), deparse_context::buf, find_param_referent(), get_rule_expr(), IsA, Param::paramid, pop_ancestor_plan(), push_ancestor_plan(), and deparse_context::varprefix.

Referenced by get_rule_expr().

7154 {
7155  Node *expr;
7156  deparse_namespace *dpns;
7157  ListCell *ancestor_cell;
7158 
7159  /*
7160  * If it's a PARAM_EXEC parameter, try to locate the expression from which
7161  * the parameter was computed. Note that failing to find a referent isn't
7162  * an error, since the Param might well be a subplan output rather than an
7163  * input.
7164  */
7165  expr = find_param_referent(param, context, &dpns, &ancestor_cell);
7166  if (expr)
7167  {
7168  /* Found a match, so print it */
7169  deparse_namespace save_dpns;
7170  bool save_varprefix;
7171  bool need_paren;
7172 
7173  /* Switch attention to the ancestor plan node */
7174  push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
7175 
7176  /*
7177  * Force prefixing of Vars, since they won't belong to the relation
7178  * being scanned in the original plan node.
7179  */
7180  save_varprefix = context->varprefix;
7181  context->varprefix = true;
7182 
7183  /*
7184  * A Param's expansion is typically a Var, Aggref, or upper-level
7185  * Param, which wouldn't need extra parentheses. Otherwise, insert
7186  * parens to ensure the expression looks atomic.
7187  */
7188  need_paren = !(IsA(expr, Var) ||
7189  IsA(expr, Aggref) ||
7190  IsA(expr, Param));
7191  if (need_paren)
7192  appendStringInfoChar(context->buf, '(');
7193 
7194  get_rule_expr(expr, context, false);
7195 
7196  if (need_paren)
7197  appendStringInfoChar(context->buf, ')');
7198 
7199  context->varprefix = save_varprefix;
7200 
7201  pop_ancestor_plan(dpns, &save_dpns);
7202 
7203  return;
7204  }
7205 
7206  /*
7207  * Not PARAM_EXEC, or couldn't find referent: just print $N.
7208  */
7209  appendStringInfo(context->buf, "$%d", param->paramid);
7210 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
static Node * find_param_referent(Param *param, deparse_context *context, deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
Definition: ruleutils.c:7033
Definition: nodes.h:509
static void pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:4560
Definition: primnodes.h:163
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7563
int paramid
Definition: primnodes.h:245
StringInfo buf
Definition: ruleutils.c:108
static void push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell, deparse_namespace *save_dpns)
Definition: ruleutils.c:4537
static void get_query_def ( Query query,
StringInfo  buf,
List parentnamespace,
TupleDesc  resultDesc,
int  prettyFlags,
int  wrapColumn,
int  startIndent 
)
static

Definition at line 4825 of file ruleutils.c.

References AcquireRewriteLocks(), appendStringInfoString(), buf, deparse_context::buf, CHECK_FOR_INTERRUPTS, check_stack_depth(), CMD_DELETE, CMD_INSERT, CMD_NOTHING, CMD_SELECT, CMD_UPDATE, CMD_UTILITY, Query::commandType, elog, ERROR, EXPR_KIND_NONE, get_delete_query_def(), get_insert_query_def(), get_select_query_def(), get_update_query_def(), get_utility_query_def(), deparse_context::indentLevel, lcons(), list_copy(), list_length(), deparse_context::namespaces, NIL, deparse_context::prettyFlags, Query::rtable, set_deparse_for_query(), deparse_context::special_exprkind, deparse_context::varprefix, deparse_context::windowClause, deparse_context::windowTList, and deparse_context::wrapColumn.

Referenced by get_from_clause_item(), get_insert_query_def(), get_setop_query(), get_sublink_expr(), get_with_clause(), make_ruledef(), and make_viewdef().

4828 {
4829  deparse_context context;
4830  deparse_namespace dpns;
4831 
4832  /* Guard against excessively long or deeply-nested queries */
4835 
4836  /*
4837  * Before we begin to examine the query, acquire locks on referenced
4838  * relations, and fix up deleted columns in JOIN RTEs. This ensures
4839  * consistent results. Note we assume it's OK to scribble on the passed
4840  * querytree!
4841  *
4842  * We are only deparsing the query (we are not about to execute it), so we
4843  * only need AccessShareLock on the relations it mentions.
4844  */
4845  AcquireRewriteLocks(query, false, false);
4846 
4847  context.buf = buf;
4848  context.namespaces = lcons(&dpns, list_copy(parentnamespace));
4849  context.windowClause = NIL;
4850  context.windowTList = NIL;
4851  context.varprefix = (parentnamespace != NIL ||
4852  list_length(query->rtable) != 1);
4853  context.prettyFlags = prettyFlags;
4854  context.wrapColumn = wrapColumn;
4855  context.indentLevel = startIndent;
4856  context.special_exprkind = EXPR_KIND_NONE;
4857 
4858  set_deparse_for_query(&dpns, query, parentnamespace);
4859 
4860  switch (query->commandType)
4861  {
4862  case CMD_SELECT:
4863  get_select_query_def(query, &context, resultDesc);
4864  break;
4865 
4866  case CMD_UPDATE:
4867  get_update_query_def(query, &context);
4868  break;
4869 
4870  case CMD_INSERT:
4871  get_insert_query_def(query, &context);
4872  break;
4873 
4874  case CMD_DELETE:
4875  get_delete_query_def(query, &context);
4876  break;
4877 
4878  case CMD_NOTHING:
4879  appendStringInfoString(buf, "NOTHING");
4880  break;
4881 
4882  case CMD_UTILITY:
4883  get_utility_query_def(query, &context);
4884  break;
4885 
4886  default:
4887  elog(ERROR, "unrecognized query command type: %d",
4888  query->commandType);
4889  break;
4890  }
4891 }
List * namespaces
Definition: ruleutils.c:109
#define NIL
Definition: pg_list.h:69
List * list_copy(const List *oldlist)
Definition: list.c:1160
static void get_insert_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:5880
static void get_update_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:6092
List * rtable
Definition: parsenodes.h:135
#define ERROR
Definition: elog.h:43
static void get_utility_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:6338
static void get_select_query_def(Query *query, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5009
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:66
void check_stack_depth(void)
Definition: postgres.c:3117
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
ParseExprKind special_exprkind
Definition: ruleutils.c:116
static void get_delete_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:6287
List * windowTList
Definition: ruleutils.c:111
CmdType commandType
Definition: parsenodes.h:110
List * lcons(void *datum, List *list)
Definition: list.c:259
List * windowClause
Definition: ruleutils.c:110
static int list_length(const List *l)
Definition: pg_list.h:89
static void set_deparse_for_query(deparse_namespace *dpns, Query *query, List *parent_namespaces)
Definition: ruleutils.c:3330
StringInfo buf
Definition: ruleutils.c:108
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
#define elog
Definition: elog.h:219
static char * get_relation_name ( Oid  relid)
static

Definition at line 10386 of file ruleutils.c.

References elog, ERROR, and get_rel_name().

Referenced by get_from_clause_item(), pg_get_constraintdef_worker(), pg_get_indexdef_worker(), pg_get_partition_constraintdef(), and pg_get_partkeydef_worker().

10387 {
10388  char *relname = get_rel_name(relid);
10389 
10390  if (!relname)
10391  elog(ERROR, "cache lookup failed for relation %u", relid);
10392  return relname;
10393 }
#define ERROR
Definition: elog.h:43
#define elog
Definition: elog.h:219
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
static char * get_rtable_name ( int  rtindex,
deparse_context context 
)
static

Definition at line 4396 of file ruleutils.c.

References Assert, linitial, list_length(), list_nth(), deparse_context::namespaces, and deparse_namespace::rtable_names.

Referenced by get_from_clause_item(), and get_select_query_def().

4397 {
4399 
4400  Assert(rtindex > 0 && rtindex <= list_length(dpns->rtable_names));
4401  return (char *) list_nth(dpns->rtable_names, rtindex - 1);
4402 }
List * namespaces
Definition: ruleutils.c:109
List * rtable_names
Definition: ruleutils.c:150
#define linitial(l)
Definition: pg_list.h:111
void * list_nth(const List *list, int n)
Definition: list.c:410
#define Assert(condition)
Definition: c.h:675
static int list_length(const List *l)
Definition: pg_list.h:89
static void get_rule_expr ( Node node,
deparse_context context,
bool  showimplicit 
)
static

Definition at line 7563 of file ruleutils.c.

References AND_EXPR, appendContextKeyword(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), arg, NamedArgExpr::arg, FieldSelect::arg, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, CaseExpr::arg, NullTest::arg, BooleanTest::arg, CoerceToDomain::arg, XmlExpr::arg_names, NullTest::argisrow, generate_unaccent_rules::args, GroupingFunc::args, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, CaseExpr::args, RowExpr::args, CoalesceExpr::args, MinMaxExpr::args, XmlExpr::args, ArrayExpr::array_typeid, Assert, tupleDesc::attrs, BoolExpr::boolop, BooleanTest::booltesttype, buf, deparse_context::buf, castNode, CHECK_FOR_INTERRUPTS, check_stack_depth(), COERCE_EXPLICIT_CALL, COERCE_EXPLICIT_CAST, COERCE_IMPLICIT_CAST, CoerceViaIO::coerceformat, ArrayCoerceExpr::coerceformat, CoerceToDomain::coercionformat, CollateExpr::collOid, Const::constisnull, Const::constvalue, convert(), ConvertRowtypeExpr::convertformat, CurrentOfExpr::cursor_name, CurrentOfExpr::cursor_param, DatumGetBool, DatumGetInt32, CaseExpr::defresult, ArrayExpr::elements, elog, ERROR, CaseWhen::expr, InferenceElem::expr, EXPR_SUBLINK, exprType(), exprTypmod(), FieldSelect::fieldnum, forboth, format_type_with_typemod(), generate_collation_name(), generate_operator_name(), get_agg_expr(), get_base_element_type(), get_coercion_expr(), get_const_expr(), get_func_expr(), get_name_for_var_field(), get_opclass_input_type(), get_opclass_name(), get_oper_expr(), get_parameter(), get_rule_expr_paren(), get_rule_expr_toplevel(), get_sublink_expr(), get_tablefunc(), get_variable(), get_windowfunc_expr(), i, InferenceElem::infercollid, InferenceElem::inferopclass, PartitionRangeDatum::infinite, IS_DOCUMENT, IS_FALSE, IS_GREATEST, IS_LEAST, IS_NOT_FALSE, IS_NOT_NULL, IS_NOT_TRUE, IS_NOT_UNKNOWN, IS_NULL, IS_TRUE, IS_UNKNOWN, IS_XMLCONCAT, IS_XMLELEMENT, IS_XMLFOREST, IS_XMLPARSE, IS_XMLPI, IS_XMLROOT, IS_XMLSERIALIZE, IsA, RowCompareExpr::largs, lfirst, lfirst_node, linitial, linitial_oid, list_head(), list_length(), PartitionBoundSpec::listdatums, lnext, lookup_rowtype_tupdesc(), PartitionBoundSpec::lowerdatums, lsecond, lsecond_node, lthird_node, map_xml_name_to_sql_identifier(), NamedArgExpr::name, XmlExpr::name, XmlExpr::named_args, tupleDesc::natts, FieldStore::newvals, NIL, nodeTag, NOT_EXPR, NULL, NullTest::nulltesttype, MinMaxExpr::op, SQLValueFunction::op, XmlExpr::op, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, OR_EXPR, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, SubPlan::plan_name, PRETTY_INDENT, PRETTY_PAREN, PRETTYINDENT_VAR, printSubscripts(), processIndirection(), quote_identifier(), RowCompareExpr::rargs, RECORDOID, ArrayRef::refassgnexpr, ArrayRef::refexpr, RelabelType::relabelformat, ReleaseTupleDesc, CaseWhen::result, RelabelType::resulttype, CoerceViaIO::resulttype, ArrayCoerceExpr::resulttype, ConvertRowtypeExpr::resulttype, CoerceToDomain::resulttype, RelabelType::resulttypmod, ArrayCoerceExpr::resulttypmod, CoerceToDomain::resulttypmod, RowExpr::row_format, RowExpr::row_typeid, splan, PartitionBoundSpec::strategy, strip_implicit_coercions(), strVal, AlternativeSubPlan::subplans, SVFOP_CURRENT_CATALOG, SVFOP_CURRENT_DATE, SVFOP_CURRENT_ROLE, SVFOP_CURRENT_SCHEMA, SVFOP_CURRENT_TIME, SVFOP_CURRENT_TIME_N, SVFOP_CURRENT_TIMESTAMP, SVFOP_CURRENT_TIMESTAMP_N, SVFOP_CURRENT_USER, SVFOP_LOCALTIME, SVFOP_LOCALTIME_N, SVFOP_LOCALTIMESTAMP, SVFOP_LOCALTIMESTAMP_N, SVFOP_SESSION_USER, SVFOP_USER, T_Aggref, T_AlternativeSubPlan, T_ArrayCoerceExpr, T_ArrayExpr, T_ArrayRef, T_BooleanTest, T_BoolExpr, T_CaseExpr, T_CaseTestExpr, T_CoalesceExpr, T_CoerceToDomain, T_CoerceToDomainValue, T_CoerceViaIO, T_CollateExpr, T_Const, T_ConvertRowtypeExpr, T_CurrentOfExpr, T_DistinctExpr, T_FieldSelect, T_FieldStore, T_FuncExpr, T_GroupingFunc, T_InferenceElem, T_List, T_MinMaxExpr, T_NamedArgExpr, T_NullIfExpr, T_NullTest, T_OpExpr, T_Param, T_PartitionBoundSpec, T_RelabelType, T_RowCompareExpr, T_RowExpr, T_ScalarArrayOpExpr, T_SetToDefault, T_SQLValueFunction, T_SubLink, T_SubPlan, T_TableFunc, T_Var, T_WindowFunc, T_XmlExpr, XmlExpr::type, type_is_rowtype(), SQLValueFunction::typmod, XmlExpr::typmod, PartitionBoundSpec::upperdatums, SubPlan::useHashTable, ScalarArrayOpExpr::useOr, val, PartitionRangeDatum::value, deparse_context::varprefix, XML_STANDALONE_NO, XML_STANDALONE_NO_VALUE, XML_STANDALONE_YES, XmlExpr::xmloption, and XMLOPTION_DOCUMENT.

Referenced by deparse_expression_pretty(), get_agg_expr(), get_basic_select_query(), get_delete_query_def(), get_from_clause_item(), get_func_expr(), get_insert_query_def(), get_parameter(), get_rule_expr_paren(), get_rule_expr_toplevel(), get_rule_sortgroupclause(), get_rule_windowspec(), get_select_query_def(), get_special_variable(), get_sublink_expr(), get_tablefunc(), get_tablesample_def(), get_target_list(), get_update_query_def(), get_update_query_targetlist_def(), get_variable(), get_windowfunc_expr(), make_ruledef(), pg_get_triggerdef_worker(), and printSubscripts().

7565 {
7566  StringInfo buf = context->buf;
7567 
7568  if (node == NULL)
7569  return;
7570 
7571  /* Guard against excessively long or deeply-nested queries */
7574 
7575  /*
7576  * Each level of get_rule_expr must emit an indivisible term
7577  * (parenthesized if necessary) to ensure result is reparsed into the same
7578  * expression tree. The only exception is that when the input is a List,
7579  * we emit the component items comma-separated with no surrounding
7580  * decoration; this is convenient for most callers.
7581  */
7582  switch (nodeTag(node))
7583  {
7584  case T_Var:
7585  (void) get_variable((Var *) node, 0, false, context);
7586  break;
7587 
7588  case T_Const:
7589  get_const_expr((Const *) node, context, 0);
7590  break;
7591 
7592  case T_Param:
7593  get_parameter((Param *) node, context);
7594  break;
7595 
7596  case T_Aggref:
7597  get_agg_expr((Aggref *) node, context, (Aggref *) node);
7598  break;
7599 
7600  case T_GroupingFunc:
7601  {
7602  GroupingFunc *gexpr = (GroupingFunc *) node;
7603 
7604  appendStringInfoString(buf, "GROUPING(");
7605  get_rule_expr((Node *) gexpr->args, context, true);
7606  appendStringInfoChar(buf, ')');
7607  }
7608  break;
7609 
7610  case T_WindowFunc:
7611  get_windowfunc_expr((WindowFunc *) node, context);
7612  break;
7613 
7614  case T_ArrayRef:
7615  {
7616  ArrayRef *aref = (ArrayRef *) node;
7617  bool need_parens;
7618 
7619  /*
7620  * If the argument is a CaseTestExpr, we must be inside a
7621  * FieldStore, ie, we are assigning to an element of an array
7622  * within a composite column. Since we already punted on
7623  * displaying the FieldStore's target information, just punt
7624  * here too, and display only the assignment source
7625  * expression.
7626  */
7627  if (IsA(aref->refexpr, CaseTestExpr))
7628  {
7629  Assert(aref->refassgnexpr);
7630  get_rule_expr((Node *) aref->refassgnexpr,
7631  context, showimplicit);
7632  break;
7633  }
7634 
7635  /*
7636  * Parenthesize the argument unless it's a simple Var or a
7637  * FieldSelect. (In particular, if it's another ArrayRef, we
7638  * *must* parenthesize to avoid confusion.)
7639  */
7640  need_parens = !IsA(aref->refexpr, Var) &&
7641  !IsA(aref->refexpr, FieldSelect);
7642  if (need_parens)
7643  appendStringInfoChar(buf, '(');
7644  get_rule_expr((Node *) aref->refexpr, context, showimplicit);
7645  if (need_parens)
7646  appendStringInfoChar(buf, ')');
7647 
7648  /*
7649  * If there's a refassgnexpr, we want to print the node in the
7650  * format "array[subscripts] := refassgnexpr". This is not
7651  * legal SQL, so decompilation of INSERT or UPDATE statements
7652  * should always use processIndirection as part of the
7653  * statement-level syntax. We should only see this when
7654  * EXPLAIN tries to print the targetlist of a plan resulting
7655  * from such a statement.
7656  */
7657  if (aref->refassgnexpr)
7658  {
7659  Node *refassgnexpr;
7660 
7661  /*
7662  * Use processIndirection to print this node's subscripts
7663  * as well as any additional field selections or
7664  * subscripting in immediate descendants. It returns the
7665  * RHS expr that is actually being "assigned".
7666  */
7667  refassgnexpr = processIndirection(node, context);
7668  appendStringInfoString(buf, " := ");
7669  get_rule_expr(refassgnexpr, context, showimplicit);
7670  }
7671  else
7672  {
7673  /* Just an ordinary array fetch, so print subscripts */
7674  printSubscripts(aref, context);
7675  }
7676  }
7677  break;
7678 
7679  case T_FuncExpr:
7680  get_func_expr((FuncExpr *) node, context, showimplicit);
7681  break;
7682 
7683  case T_NamedArgExpr:
7684  {
7685  NamedArgExpr *na = (NamedArgExpr *) node;
7686 
7687  appendStringInfo(buf, "%s => ", quote_identifier(na->name));
7688  get_rule_expr((Node *) na->arg, context, showimplicit);
7689  }
7690  break;
7691 
7692  case T_OpExpr:
7693  get_oper_expr((OpExpr *) node, context);
7694  break;
7695 
7696  case T_DistinctExpr:
7697  {
7698  DistinctExpr *expr = (DistinctExpr *) node;
7699  List *<