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_rule_expr_funccall (Node *node, deparse_context *context, bool showimplicit)
 
static bool looks_like_function (Node *node)
 
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)
 
char * get_range_partbound_string (List *bound_datums)
 

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 466 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 7492 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().

7494 {
7495  StringInfo buf = context->buf;
7496 
7497  if (PRETTY_INDENT(context))
7498  {
7499  int indentAmount;
7500 
7501  context->indentLevel += indentBefore;
7502 
7503  /* remove any trailing spaces currently in the buffer ... */
7505  /* ... then add a newline and some spaces */
7506  appendStringInfoChar(buf, '\n');
7507 
7508  if (context->indentLevel < PRETTYINDENT_LIMIT)
7509  indentAmount = Max(context->indentLevel, 0) + indentPlus;
7510  else
7511  {
7512  /*
7513  * If we're indented more than PRETTYINDENT_LIMIT characters, try
7514  * to conserve horizontal space by reducing the per-level
7515  * indentation. For best results the scale factor here should
7516  * divide all the indent amounts that get added to indentLevel
7517  * (PRETTYINDENT_STD, etc). It's important that the indentation
7518  * not grow unboundedly, else deeply-nested trees use O(N^2)
7519  * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
7520  */
7521  indentAmount = PRETTYINDENT_LIMIT +
7522  (context->indentLevel - PRETTYINDENT_LIMIT) /
7523  (PRETTYINDENT_STD / 2);
7524  indentAmount %= PRETTYINDENT_LIMIT;
7525  /* scale/wrap logic affects indentLevel, but not indentPlus */
7526  indentAmount += indentPlus;
7527  }
7528  appendStringInfoSpaces(buf, indentAmount);
7529 
7530  appendStringInfoString(buf, str);
7531 
7532  context->indentLevel += indentAfter;
7533  if (context->indentLevel < 0)
7534  context->indentLevel = 0;
7535  }
7536  else
7537  appendStringInfoString(buf, str);
7538 }
#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:7546
#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:801
StringInfo buf
Definition: ruleutils.c:108
static bool colname_is_unique ( char *  colname,
deparse_namespace dpns,
deparse_columns colinfo 
)
static

Definition at line 4100 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().

4102 {
4103  int i;
4104  ListCell *lc;
4105 
4106  /* Check against already-assigned column aliases within RTE */
4107  for (i = 0; i < colinfo->num_cols; i++)
4108  {
4109  char *oldname = colinfo->colnames[i];
4110 
4111  if (oldname && strcmp(oldname, colname) == 0)
4112  return false;
4113  }
4114 
4115  /*
4116  * If we're building a new_colnames array, check that too (this will be
4117  * partially but not completely redundant with the previous checks)
4118  */
4119  for (i = 0; i < colinfo->num_new_cols; i++)
4120  {
4121  char *oldname = colinfo->new_colnames[i];
4122 
4123  if (oldname && strcmp(oldname, colname) == 0)
4124  return false;
4125  }
4126 
4127  /* Also check against USING-column names that must be globally unique */
4128  foreach(lc, dpns->using_names)
4129  {
4130  char *oldname = (char *) lfirst(lc);
4131 
4132  if (strcmp(oldname, colname) == 0)
4133  return false;
4134  }
4135 
4136  /* Also check against names already assigned for parent-join USING cols */
4137  foreach(lc, colinfo->parentUsing)
4138  {
4139  char *oldname = (char *) lfirst(lc);
4140 
4141  if (strcmp(oldname, colname) == 0)
4142  return false;
4143  }
4144 
4145  return true;
4146 }
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 2163 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().

2165 {
2166  Datum *keys;
2167  int nKeys;
2168  int j;
2169 
2170  /* Extract data from array of int16 */
2171  deconstruct_array(DatumGetArrayTypeP(column_index_array),
2172  INT2OID, 2, true, 's',
2173  &keys, NULL, &nKeys);
2174 
2175  for (j = 0; j < nKeys; j++)
2176  {
2177  char *colName;
2178 
2179  colName = get_relid_attribute_name(relId, DatumGetInt16(keys[j]));
2180 
2181  if (j == 0)
2183  else
2184  appendStringInfo(buf, ", %s", quote_identifier(colName));
2185  }
2186 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10381
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 3043 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().

3044 {
3045  deparse_namespace *dpns;
3046  RangeTblEntry *rte;
3047 
3048  dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3049 
3050  /* Build a minimal RTE for the rel */
3051  rte = makeNode(RangeTblEntry);
3052  rte->rtekind = RTE_RELATION;
3053  rte->relid = relid;
3054  rte->relkind = RELKIND_RELATION; /* no need for exactness here */
3055  rte->alias = makeAlias(aliasname, NIL);
3056  rte->eref = rte->alias;
3057  rte->lateral = false;
3058  rte->inh = false;
3059  rte->inFromCl = true;
3060 
3061  /* Build one-element rtable */
3062  dpns->rtable = list_make1(rte);
3063  dpns->ctes = NIL;
3064  set_rtable_names(dpns, NIL, NULL);
3066 
3067  /* Return a one-deep namespace stack */
3068  return list_make1(dpns);
3069 }
#define NIL
Definition: pg_list.h:69
Alias * alias
Definition: parsenodes.h:1042
#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:3187
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:3400
RTEKind rtekind
Definition: parsenodes.h:944
Alias * eref
Definition: parsenodes.h:1043
#define RELKIND_RELATION
Definition: pg_class.h:160
List* deparse_context_for_plan_rtable ( List rtable,
List rtable_names 
)

Definition at line 3085 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().

3086 {
3087  deparse_namespace *dpns;
3088 
3089  dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3090 
3091  /* Initialize fields that stay the same across the whole plan tree */
3092  dpns->rtable = rtable;
3093  dpns->rtable_names = rtable_names;
3094  dpns->ctes = NIL;
3095 
3096  /*
3097  * Set up column name aliases. We will get rather bogus results for join
3098  * RTEs, but that doesn't matter because plan trees don't contain any join
3099  * alias Vars.
3100  */
3102 
3103  /* Return a one-deep namespace stack */
3104  return list_make1(dpns);
3105 }
#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:3400
char* deparse_expression ( Node expr,
List dpcontext,
bool  forceprefix,
bool  showimplicit 
)

Definition at line 2984 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().

2986 {
2987  return deparse_expression_pretty(expr, dpcontext, forceprefix,
2988  showimplicit, 0, 0);
2989 }
static char * deparse_expression_pretty(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit, int prettyFlags, int startIndent)
Definition: ruleutils.c:3011
static char * deparse_expression_pretty ( Node expr,
List dpcontext,
bool  forceprefix,
bool  showimplicit,
int  prettyFlags,
int  startIndent 
)
static

Definition at line 3011 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().

3014 {
3016  deparse_context context;
3017 
3018  initStringInfo(&buf);
3019  context.buf = &buf;
3020  context.namespaces = dpcontext;
3021  context.windowClause = NIL;
3022  context.windowTList = NIL;
3023  context.varprefix = forceprefix;
3024  context.prettyFlags = prettyFlags;
3025  context.wrapColumn = WRAP_COLUMN_DEFAULT;
3026  context.indentLevel = startIndent;
3027  context.special_exprkind = EXPR_KIND_NONE;
3028 
3029  get_rule_expr(expr, &context, showimplicit);
3030 
3031  return buf.data;
3032 }
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:7597
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 4198 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().

4199 {
4200  if (n > colinfo->num_cols)
4201  {
4202  if (colinfo->colnames == NULL)
4203  colinfo->colnames = (char **) palloc0(n * sizeof(char *));
4204  else
4205  {
4206  colinfo->colnames = (char **) repalloc(colinfo->colnames,
4207  n * sizeof(char *));
4208  memset(colinfo->colnames + colinfo->num_cols, 0,
4209  (n - colinfo->num_cols) * sizeof(char *));
4210  }
4211  colinfo->num_cols = n;
4212  }
4213 }
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 7066 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().

7068 {
7069  /* Initialize output parameters to prevent compiler warnings */
7070  *dpns_p = NULL;
7071  *ancestor_cell_p = NULL;
7072 
7073  /*
7074  * If it's a PARAM_EXEC parameter, look for a matching NestLoopParam or
7075  * SubPlan argument. This will necessarily be in some ancestor of the
7076  * current expression's PlanState.
7077  */
7078  if (param->paramkind == PARAM_EXEC)
7079  {
7080  deparse_namespace *dpns;
7081  PlanState *child_ps;
7082  bool in_same_plan_level;
7083  ListCell *lc;
7084 
7085  dpns = (deparse_namespace *) linitial(context->namespaces);
7086  child_ps = dpns->planstate;
7087  in_same_plan_level = true;
7088 
7089  foreach(lc, dpns->ancestors)
7090  {
7091  PlanState *ps = (PlanState *) lfirst(lc);
7092  ListCell *lc2;
7093 
7094  /*
7095  * NestLoops transmit params to their inner child only; also, once
7096  * we've crawled up out of a subplan, this couldn't possibly be
7097  * the right match.
7098  */
7099  if (IsA(ps, NestLoopState) &&
7100  child_ps == innerPlanState(ps) &&
7101  in_same_plan_level)
7102  {
7103  NestLoop *nl = (NestLoop *) ps->plan;
7104 
7105  foreach(lc2, nl->nestParams)
7106  {
7107  NestLoopParam *nlp = (NestLoopParam *) lfirst(lc2);
7108 
7109  if (nlp->paramno == param->paramid)
7110  {
7111  /* Found a match, so return it */
7112  *dpns_p = dpns;
7113  *ancestor_cell_p = lc;
7114  return (Node *) nlp->paramval;
7115  }
7116  }
7117  }
7118 
7119  /*
7120  * Check to see if we're crawling up from a subplan.
7121  */
7122  foreach(lc2, ps->subPlan)
7123  {
7124  SubPlanState *sstate = (SubPlanState *) lfirst(lc2);
7125  SubPlan *subplan = sstate->subplan;
7126  ListCell *lc3;
7127  ListCell *lc4;
7128 
7129  if (child_ps != sstate->planstate)
7130  continue;
7131 
7132  /* Matched subplan, so check its arguments */
7133  forboth(lc3, subplan->parParam, lc4, subplan->args)
7134  {
7135  int paramid = lfirst_int(lc3);
7136  Node *arg = (Node *) lfirst(lc4);
7137 
7138  if (paramid == param->paramid)
7139  {
7140  /* Found a match, so return it */
7141  *dpns_p = dpns;
7142  *ancestor_cell_p = lc;
7143  return arg;
7144  }
7145  }
7146 
7147  /* Keep looking, but we are emerging from a subplan. */
7148  in_same_plan_level = false;
7149  break;
7150  }
7151 
7152  /*
7153  * Likewise check to see if we're emerging from an initplan.
7154  * Initplans never have any parParams, so no need to search that
7155  * list, but we need to know if we should reset
7156  * in_same_plan_level.
7157  */
7158  foreach(lc2, ps->initPlan)
7159  {
7160  SubPlanState *sstate = (SubPlanState *) lfirst(lc2);
7161 
7162  if (child_ps != sstate->planstate)
7163  continue;
7164 
7165  /* No parameters to be had here. */
7166  Assert(sstate->subplan->parParam == NIL);
7167 
7168  /* Keep looking, but we are emerging from an initplan. */
7169  in_same_plan_level = false;
7170  break;
7171  }
7172 
7173  /* No luck, crawl up to next ancestor */
7174  child_ps = ps;
7175  }
7176  }
7177 
7178  /* No referent found */
7179  return NULL;
7180 }
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:868
List * subPlan
Definition: execnodes.h:870
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:758
SubPlan * subplan
Definition: execnodes.h:757
#define lfirst_int(lc)
Definition: pg_list.h:107
Plan * plan
Definition: execnodes.h:847
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#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:892
List * args
Definition: primnodes.h:710
static void flatten_join_using_qual ( Node qual,
List **  leftvars,
List **  rightvars 
)
static

Definition at line 4349 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().

4350 {
4351  if (IsA(qual, BoolExpr))
4352  {
4353  /* Handle AND nodes by recursion */
4354  BoolExpr *b = (BoolExpr *) qual;
4355  ListCell *lc;
4356 
4357  Assert(b->boolop == AND_EXPR);
4358  foreach(lc, b->args)
4359  {
4361  leftvars, rightvars);
4362  }
4363  }
4364  else if (IsA(qual, OpExpr))
4365  {
4366  /* Otherwise we should have an equality operator */
4367  OpExpr *op = (OpExpr *) qual;
4368  Var *var;
4369 
4370  if (list_length(op->args) != 2)
4371  elog(ERROR, "unexpected unary operator in JOIN/USING qual");
4372  /* Arguments should be Vars with perhaps implicit coercions */
4373  var = (Var *) strip_implicit_coercions((Node *) linitial(op->args));
4374  if (!IsA(var, Var))
4375  elog(ERROR, "unexpected node type in JOIN/USING qual: %d",
4376  (int) nodeTag(var));
4377  *leftvars = lappend(*leftvars, var);
4378  var = (Var *) strip_implicit_coercions((Node *) lsecond(op->args));
4379  if (!IsA(var, Var))
4380  elog(ERROR, "unexpected node type in JOIN/USING qual: %d",
4381  (int) nodeTag(var));
4382  *rightvars = lappend(*rightvars, var);
4383  }
4384  else
4385  {
4386  /* Perhaps we have an implicit coercion to boolean? */
4387  Node *q = strip_implicit_coercions(qual);
4388 
4389  if (q != qual)
4390  flatten_join_using_qual(q, leftvars, rightvars);
4391  else
4392  elog(ERROR, "unexpected node type in JOIN/USING qual: %d",
4393  (int) nodeTag(qual));
4394  }
4395 }
#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:4349
#define Assert(condition)
Definition: c.h:676
#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 10834 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().

10835 {
10836  char *result = NULL;
10837  HeapTuple tuple;
10838  Datum reloptions;
10839  bool isnull;
10840 
10841  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
10842  if (!HeapTupleIsValid(tuple))
10843  elog(ERROR, "cache lookup failed for relation %u", relid);
10844 
10845  reloptions = SysCacheGetAttr(RELOID, tuple,
10846  Anum_pg_class_reloptions, &isnull);
10847  if (!isnull)
10848  {
10850  Datum *options;
10851  int noptions;
10852  int i;
10853 
10854  initStringInfo(&buf);
10855 
10857  TEXTOID, -1, false, 'i',
10858  &options, NULL, &noptions);
10859 
10860  for (i = 0; i < noptions; i++)
10861  {
10862  char *option = TextDatumGetCString(options[i]);
10863  char *name;
10864  char *separator;
10865  char *value;
10866 
10867  /*
10868  * Each array element should have the form name=value. If the "="
10869  * is missing for some reason, treat it like an empty value.
10870  */
10871  name = option;
10872  separator = strchr(option, '=');
10873  if (separator)
10874  {
10875  *separator = '\0';
10876  value = separator + 1;
10877  }
10878  else
10879  value = "";
10880 
10881  if (i > 0)
10882  appendStringInfoString(&buf, ", ");
10883  appendStringInfo(&buf, "%s=", quote_identifier(name));
10884 
10885  /*
10886  * In general we need to quote the value; but to avoid unnecessary
10887  * clutter, do not quote if it is an identifier that would not
10888  * need quoting. (We could also allow numbers, but that is a bit
10889  * trickier than it looks --- for example, are leading zeroes
10890  * significant? We don't want to assume very much here about what
10891  * custom reloptions might mean.)
10892  */
10893  if (quote_identifier(value) == value)
10894  appendStringInfoString(&buf, value);
10895  else
10896  simple_quote_literal(&buf, value);
10897 
10898  pfree(option);
10899  }
10900 
10901  result = buf.data;
10902  }
10903 
10904  ReleaseSysCache(tuple);
10905 
10906  return result;
10907 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10381
#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:9403
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 10789 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().

10790 {
10791  HeapTuple tp;
10792  Form_pg_collation colltup;
10793  char *collname;
10794  char *nspname;
10795  char *result;
10796 
10797  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
10798  if (!HeapTupleIsValid(tp))
10799  elog(ERROR, "cache lookup failed for collation %u", collid);
10800  colltup = (Form_pg_collation) GETSTRUCT(tp);
10801  collname = NameStr(colltup->collname);
10802 
10803  if (!CollationIsVisible(collid))
10804  nspname = get_namespace_name(colltup->collnamespace);
10805  else
10806  nspname = NULL;
10807 
10808  result = quote_qualified_identifier(nspname, collname);
10809 
10810  ReleaseSysCache(tp);
10811 
10812  return result;
10813 }
#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:10467
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 10609 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().

10612 {
10613  char *result;
10614  HeapTuple proctup;
10615  Form_pg_proc procform;
10616  char *proname;
10617  bool use_variadic;
10618  char *nspname;
10619  FuncDetailCode p_result;
10620  Oid p_funcid;
10621  Oid p_rettype;
10622  bool p_retset;
10623  int p_nvargs;
10624  Oid p_vatype;
10625  Oid *p_true_typeids;
10626  bool force_qualify = false;
10627 
10628  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
10629  if (!HeapTupleIsValid(proctup))
10630  elog(ERROR, "cache lookup failed for function %u", funcid);
10631  procform = (Form_pg_proc) GETSTRUCT(proctup);
10632  proname = NameStr(procform->proname);
10633 
10634  /*
10635  * Due to parser hacks to avoid needing to reserve CUBE, we need to force
10636  * qualification in some special cases.
10637  */
10638  if (special_exprkind == EXPR_KIND_GROUP_BY)
10639  {
10640  if (strcmp(proname, "cube") == 0 || strcmp(proname, "rollup") == 0)
10641  force_qualify = true;
10642  }
10643 
10644  /*
10645  * Determine whether VARIADIC should be printed. We must do this first
10646  * since it affects the lookup rules in func_get_detail().
10647  *
10648  * Currently, we always print VARIADIC if the function has a merged
10649  * variadic-array argument. Note that this is always the case for
10650  * functions taking a VARIADIC argument type other than VARIADIC ANY.
10651  *
10652  * In principle, if VARIADIC wasn't originally specified and the array
10653  * actual argument is deconstructable, we could print the array elements
10654  * separately and not print VARIADIC, thus more nearly reproducing the
10655  * original input. For the moment that seems like too much complication
10656  * for the benefit, and anyway we do not know whether VARIADIC was
10657  * originally specified if it's a non-ANY type.
10658  */
10659  if (use_variadic_p)
10660  {
10661  /* Parser should not have set funcvariadic unless fn is variadic */
10662  Assert(!has_variadic || OidIsValid(procform->provariadic));
10663  use_variadic = has_variadic;
10664  *use_variadic_p = use_variadic;
10665  }
10666  else
10667  {
10668  Assert(!has_variadic);
10669  use_variadic = false;
10670  }
10671 
10672  /*
10673  * The idea here is to schema-qualify only if the parser would fail to
10674  * resolve the correct function given the unqualified func name with the
10675  * specified argtypes and VARIADIC flag. But if we already decided to
10676  * force qualification, then we can skip the lookup and pretend we didn't
10677  * find it.
10678  */
10679  if (!force_qualify)
10680  p_result = func_get_detail(list_make1(makeString(proname)),
10681  NIL, argnames, nargs, argtypes,
10682  !use_variadic, true,
10683  &p_funcid, &p_rettype,
10684  &p_retset, &p_nvargs, &p_vatype,
10685  &p_true_typeids, NULL);
10686  else
10687  {
10688  p_result = FUNCDETAIL_NOTFOUND;
10689  p_funcid = InvalidOid;
10690  }
10691 
10692  if ((p_result == FUNCDETAIL_NORMAL ||
10693  p_result == FUNCDETAIL_AGGREGATE ||
10694  p_result == FUNCDETAIL_WINDOWFUNC) &&
10695  p_funcid == funcid)
10696  nspname = NULL;
10697  else
10698  nspname = get_namespace_name(procform->pronamespace);
10699 
10700  result = quote_qualified_identifier(nspname, proname);
10701 
10702  ReleaseSysCache(proctup);
10703 
10704  return result;
10705 }
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:10467
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:676
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 10719 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().

10720 {
10722  HeapTuple opertup;
10723  Form_pg_operator operform;
10724  char *oprname;
10725  char *nspname;
10726  Operator p_result;
10727 
10728  initStringInfo(&buf);
10729 
10730  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operid));
10731  if (!HeapTupleIsValid(opertup))
10732  elog(ERROR, "cache lookup failed for operator %u", operid);
10733  operform = (Form_pg_operator) GETSTRUCT(opertup);
10734  oprname = NameStr(operform->oprname);
10735 
10736  /*
10737  * The idea here is to schema-qualify only if the parser would fail to
10738  * resolve the correct operator given the unqualified op name with the
10739  * specified argtypes.
10740  */
10741  switch (operform->oprkind)
10742  {
10743  case 'b':
10744  p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
10745  true, -1);
10746  break;
10747  case 'l':
10748  p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
10749  true, -1);
10750  break;
10751  case 'r':
10752  p_result = right_oper(NULL, list_make1(makeString(oprname)), arg1,
10753  true, -1);
10754  break;
10755  default:
10756  elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
10757  p_result = NULL; /* keep compiler quiet */
10758  break;
10759  }
10760 
10761  if (p_result != NULL && oprid(p_result) == operid)
10762  nspname = NULL;
10763  else
10764  {
10765  nspname = get_namespace_name(operform->oprnamespace);
10766  appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
10767  }
10768 
10769  appendStringInfoString(&buf, oprname);
10770 
10771  if (nspname)
10772  appendStringInfoChar(&buf, ')');
10773 
10774  if (p_result != NULL)
10775  ReleaseSysCache(p_result);
10776 
10777  ReleaseSysCache(opertup);
10778 
10779  return buf.data;
10780 }
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:10381
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 10567 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().

10568 {
10569  HeapTuple tp;
10570  Form_pg_class reltup;
10571  char *relname;
10572  char *nspname;
10573  char *result;
10574 
10575  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
10576  if (!HeapTupleIsValid(tp))
10577  elog(ERROR, "cache lookup failed for relation %u", relid);
10578  reltup = (Form_pg_class) GETSTRUCT(tp);
10579  relname = NameStr(reltup->relname);
10580 
10581  nspname = get_namespace_name(reltup->relnamespace);
10582  if (!nspname)
10583  elog(ERROR, "cache lookup failed for namespace %u",
10584  reltup->relnamespace);
10585 
10586  result = quote_qualified_identifier(nspname, relname);
10587 
10588  ReleaseSysCache(tp);
10589 
10590  return result;
10591 }
#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:10467
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 10507 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_rule_expr(), get_update_query_def(), make_ruledef(), pg_get_constraintdef_worker(), pg_get_indexdef_worker(), pg_get_statisticsobj_worker(), and pg_get_triggerdef_worker().

10508 {
10509  HeapTuple tp;
10510  Form_pg_class reltup;
10511  bool need_qual;
10512  ListCell *nslist;
10513  char *relname;
10514  char *nspname;
10515  char *result;
10516 
10517  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
10518  if (!HeapTupleIsValid(tp))
10519  elog(ERROR, "cache lookup failed for relation %u", relid);
10520  reltup = (Form_pg_class) GETSTRUCT(tp);
10521  relname = NameStr(reltup->relname);
10522 
10523  /* Check for conflicting CTE name */
10524  need_qual = false;
10525  foreach(nslist, namespaces)
10526  {
10527  deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
10528  ListCell *ctlist;
10529 
10530  foreach(ctlist, dpns->ctes)
10531  {
10532  CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
10533 
10534  if (strcmp(cte->ctename, relname) == 0)
10535  {
10536  need_qual = true;
10537  break;
10538  }
10539  }
10540  if (need_qual)
10541  break;
10542  }
10543 
10544  /* Otherwise, qualify the name if not visible in search path */
10545  if (!need_qual)
10546  need_qual = !RelationIsVisible(relid);
10547 
10548  if (need_qual)
10549  nspname = get_namespace_name(reltup->relnamespace);
10550  else
10551  nspname = NULL;
10552 
10553  result = quote_qualified_identifier(nspname, relname);
10554 
10555  ReleaseSysCache(tp);
10556 
10557  return result;
10558 }
#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:10467
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 9099 of file ruleutils.c.

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

Referenced by get_agg_expr().

9100 {
9101  Aggref *aggref;
9102  Aggref *original_aggref = private;
9103 
9104  if (!IsA(node, Aggref))
9105  elog(ERROR, "combining Aggref does not point to an Aggref");
9106 
9107  aggref = (Aggref *) node;
9108  get_agg_expr(aggref, context, original_aggref);
9109 }
#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:8993
#define elog
Definition: elog.h:219
static void get_agg_expr ( Aggref aggref,
deparse_context context,
Aggref original_aggref 
)
static

Definition at line 8993 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().

8995 {
8996  StringInfo buf = context->buf;
8997  Oid argtypes[FUNC_MAX_ARGS];
8998  int nargs;
8999  bool use_variadic;
9000 
9001  /*
9002  * For a combining aggregate, we look up and deparse the corresponding
9003  * partial aggregate instead. This is necessary because our input
9004  * argument list has been replaced; the new argument list always has just
9005  * one element, which will point to a partial Aggref that supplies us with
9006  * transition states to combine.
9007  */
9008  if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
9009  {
9010  TargetEntry *tle = linitial_node(TargetEntry, aggref->args);
9011 
9012  Assert(list_length(aggref->args) == 1);
9013  resolve_special_varno((Node *) tle->expr, context, original_aggref,
9015  return;
9016  }
9017 
9018  /*
9019  * Mark as PARTIAL, if appropriate. We look to the original aggref so as
9020  * to avoid printing this when recursing from the code just above.
9021  */
9022  if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
9023  appendStringInfoString(buf, "PARTIAL ");
9024 
9025  /* Extract the argument types as seen by the parser */
9026  nargs = get_aggregate_argtypes(aggref, argtypes);
9027 
9028  /* Print the aggregate name, schema-qualified if needed */
9029  appendStringInfo(buf, "%s(%s",
9030  generate_function_name(aggref->aggfnoid, nargs,
9031  NIL, argtypes,
9032  aggref->aggvariadic,
9033  &use_variadic,
9034  context->special_exprkind),
9035  (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
9036 
9037  if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
9038  {
9039  /*
9040  * Ordered-set aggregates do not use "*" syntax. Also, we needn't
9041  * worry about inserting VARIADIC. So we can just dump the direct
9042  * args as-is.
9043  */
9044  Assert(!aggref->aggvariadic);
9045  get_rule_expr((Node *) aggref->aggdirectargs, context, true);
9046  Assert(aggref->aggorder != NIL);
9047  appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
9048  get_rule_orderby(aggref->aggorder, aggref->args, false, context);
9049  }
9050  else
9051  {
9052  /* aggstar can be set only in zero-argument aggregates */
9053  if (aggref->aggstar)
9054  appendStringInfoChar(buf, '*');
9055  else
9056  {
9057  ListCell *l;
9058  int i;
9059 
9060  i = 0;
9061  foreach(l, aggref->args)
9062  {
9063  TargetEntry *tle = (TargetEntry *) lfirst(l);
9064  Node *arg = (Node *) tle->expr;
9065 
9066  Assert(!IsA(arg, NamedArgExpr));
9067  if (tle->resjunk)
9068  continue;
9069  if (i++ > 0)
9070  appendStringInfoString(buf, ", ");
9071  if (use_variadic && i == nargs)
9072  appendStringInfoString(buf, "VARIADIC ");
9073  get_rule_expr(arg, context, true);
9074  }
9075  }
9076 
9077  if (aggref->aggorder != NIL)
9078  {
9079  appendStringInfoString(buf, " ORDER BY ");
9080  get_rule_orderby(aggref->aggorder, aggref->args, false, context);
9081  }
9082  }
9083 
9084  if (aggref->aggfilter != NULL)
9085  {
9086  appendStringInfoString(buf, ") FILTER (WHERE ");
9087  get_rule_expr((Node *) aggref->aggfilter, context, false);
9088  }
9089 
9090  appendStringInfoChar(buf, ')');
9091 }
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:10609
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:6599
static void get_rule_orderby(List *orderList, List *targetList, bool force_colno, deparse_context *context)
Definition: ruleutils.c:5711
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:9099
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7597
#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 5204 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().

5206 {
5207  StringInfo buf = context->buf;
5208  RangeTblEntry *values_rte;
5209  char *sep;
5210  ListCell *l;
5211 
5212  if (PRETTY_INDENT(context))
5213  {
5214  context->indentLevel += PRETTYINDENT_STD;
5215  appendStringInfoChar(buf, ' ');
5216  }
5217 
5218  /*
5219  * If the query looks like SELECT * FROM (VALUES ...), then print just the
5220  * VALUES part. This reverses what transformValuesClause() did at parse
5221  * time.
5222  */
5223  values_rte = get_simple_values_rte(query);
5224  if (values_rte)
5225  {
5226  get_values_def(values_rte->values_lists, context);
5227  return;
5228  }
5229 
5230  /*
5231  * Build up the query string - first we say SELECT
5232  */
5233  appendStringInfoString(buf, "SELECT");
5234 
5235  /* Add the DISTINCT clause if given */
5236  if (query->distinctClause != NIL)
5237  {
5238  if (query->hasDistinctOn)
5239  {
5240  appendStringInfoString(buf, " DISTINCT ON (");
5241  sep = "";
5242  foreach(l, query->distinctClause)
5243  {
5244  SortGroupClause *srt = (SortGroupClause *) lfirst(l);
5245 
5246  appendStringInfoString(buf, sep);
5248  false, context);
5249  sep = ", ";
5250  }
5251  appendStringInfoChar(buf, ')');
5252  }
5253  else
5254  appendStringInfoString(buf, " DISTINCT");
5255  }
5256 
5257  /* Then we tell what to select (the targetlist) */
5258  get_target_list(query->targetList, context, resultDesc);
5259 
5260  /* Add the FROM clause if needed */
5261  get_from_clause(query, " FROM ", context);
5262 
5263  /* Add the WHERE clause if given */
5264  if (query->jointree->quals != NULL)
5265  {
5266  appendContextKeyword(context, " WHERE ",
5268  get_rule_expr(query->jointree->quals, context, false);
5269  }
5270 
5271  /* Add the GROUP BY clause if given */
5272  if (query->groupClause != NULL || query->groupingSets != NULL)
5273  {
5274  ParseExprKind save_exprkind;
5275 
5276  appendContextKeyword(context, " GROUP BY ",
5278 
5279  save_exprkind = context->special_exprkind;
5281 
5282  if (query->groupingSets == NIL)
5283  {
5284  sep = "";
5285  foreach(l, query->groupClause)
5286  {
5287  SortGroupClause *grp = (SortGroupClause *) lfirst(l);
5288 
5289  appendStringInfoString(buf, sep);
5291  false, context);
5292  sep = ", ";
5293  }
5294  }
5295  else
5296  {
5297  sep = "";
5298  foreach(l, query->groupingSets)
5299  {
5300  GroupingSet *grp = lfirst(l);
5301 
5302  appendStringInfoString(buf, sep);
5303  get_rule_groupingset(grp, query->targetList, true, context);
5304  sep = ", ";
5305  }
5306  }
5307 
5308  context->special_exprkind = save_exprkind;
5309  }
5310 
5311  /* Add the HAVING clause if given */
5312  if (query->havingQual != NULL)
5313  {
5314  appendContextKeyword(context, " HAVING ",
5316  get_rule_expr(query->havingQual, context, false);
5317  }
5318 
5319  /* Add the WINDOW clause if needed */
5320  if (query->windowClause != NIL)
5321  get_rule_windowclause(query, context);
5322 }
#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:5331
static Node * get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno, deparse_context *context)
Definition: ruleutils.c:5595
Index tleSortGroupRef
Definition: parsenodes.h:1184
List * groupingSets
Definition: parsenodes.h:148
static void get_from_clause(Query *query, const char *prefix, deparse_context *context)
Definition: ruleutils.c:9673
static void get_rule_windowclause(Query *query, deparse_context *context)
Definition: ruleutils.c:5769
#define PRETTY_INDENT(context)
Definition: ruleutils.c:97
ParseExprKind
Definition: parse_node.h:33
List * values_lists
Definition: parsenodes.h:1009
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:7492
static void get_rule_groupingset(GroupingSet *gset, List *targetlist, bool omit_parens, deparse_context *context)
Definition: ruleutils.c:5651
#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:7597
#define lfirst(lc)
Definition: pg_list.h:106
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:4920
List * groupClause
Definition: parsenodes.h:146
StringInfo buf
Definition: ruleutils.c:108
static RangeTblEntry * get_simple_values_rte(Query *query)
Definition: ruleutils.c:5148
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 9192 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().

9195 {
9196  StringInfo buf = context->buf;
9197 
9198  /*
9199  * Since parse_coerce.c doesn't immediately collapse application of
9200  * length-coercion functions to constants, what we'll typically see in
9201  * such cases is a Const with typmod -1 and a length-coercion function
9202  * right above it. Avoid generating redundant output. However, beware of
9203  * suppressing casts when the user actually wrote something like
9204  * 'foo'::text::char(3).
9205  *
9206  * Note: it might seem that we are missing the possibility of needing to
9207  * print a COLLATE clause for such a Const. However, a Const could only
9208  * have nondefault collation in a post-constant-folding tree, in which the
9209  * length coercion would have been folded too. See also the special
9210  * handling of CollateExpr in coerce_to_target_type(): any collation
9211  * marking will be above the coercion node, not below it.
9212  */
9213  if (arg && IsA(arg, Const) &&
9214  ((Const *) arg)->consttype == resulttype &&
9215  ((Const *) arg)->consttypmod == -1)
9216  {
9217  /* Show the constant without normal ::typename decoration */
9218  get_const_expr((Const *) arg, context, -1);
9219  }
9220  else
9221  {
9222  if (!PRETTY_PAREN(context))
9223  appendStringInfoChar(buf, '(');
9224  get_rule_expr_paren(arg, context, false, parentNode);
9225  if (!PRETTY_PAREN(context))
9226  appendStringInfoChar(buf, ')');
9227  }
9228  appendStringInfo(buf, "::%s",
9229  format_type_with_typemod(resulttype, resulttypmod));
9230 }
#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:7565
static void get_const_expr(Const *constval, deparse_context *context, int showtype)
Definition: ruleutils.c:9248
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 10094 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().

10095 {
10096  StringInfo buf = context->buf;
10097  int i;
10098  bool first = true;
10099 
10100  /* Don't print aliases if not needed */
10101  if (!colinfo->printaliases)
10102  return;
10103 
10104  for (i = 0; i < colinfo->num_new_cols; i++)
10105  {
10106  char *colname = colinfo->new_colnames[i];
10107 
10108  if (first)
10109  {
10110  appendStringInfoChar(buf, '(');
10111  first = false;
10112  }
10113  else
10114  appendStringInfoString(buf, ", ");
10116  }
10117  if (!first)
10118  appendStringInfoChar(buf, ')');
10119 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10381
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 9383 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().

9384 {
9385  StringInfo buf = context->buf;
9386 
9387  if (OidIsValid(constval->constcollid))
9388  {
9389  Oid typcollation = get_typcollation(constval->consttype);
9390 
9391  if (constval->constcollid != typcollation)
9392  {
9393  appendStringInfo(buf, " COLLATE %s",
9395  }
9396  }
9397 }
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:10789
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 9248 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_range_partbound_string(), get_rule_expr(), and get_rule_sortgroupclause().

9249 {
9250  StringInfo buf = context->buf;
9251  Oid typoutput;
9252  bool typIsVarlena;
9253  char *extval;
9254  bool needlabel = false;
9255 
9256  if (constval->constisnull)
9257  {
9258  /*
9259  * Always label the type of a NULL constant to prevent misdecisions
9260  * about type when reparsing.
9261  */
9262  appendStringInfoString(buf, "NULL");
9263  if (showtype >= 0)
9264  {
9265  appendStringInfo(buf, "::%s",
9267  constval->consttypmod));
9268  get_const_collation(constval, context);
9269  }
9270  return;
9271  }
9272 
9273  getTypeOutputInfo(constval->consttype,
9274  &typoutput, &typIsVarlena);
9275 
9276  extval = OidOutputFunctionCall(typoutput, constval->constvalue);
9277 
9278  switch (constval->consttype)
9279  {
9280  case INT4OID:
9281 
9282  /*
9283  * INT4 can be printed without any decoration, unless it is
9284  * negative; in that case print it as '-nnn'::integer to ensure
9285  * that the output will re-parse as a constant, not as a constant
9286  * plus operator. In most cases we could get away with printing
9287  * (-nnn) instead, because of the way that gram.y handles negative
9288  * literals; but that doesn't work for INT_MIN, and it doesn't
9289  * seem that much prettier anyway.
9290  */
9291  if (extval[0] != '-')
9292  appendStringInfoString(buf, extval);
9293  else
9294  {
9295  appendStringInfo(buf, "'%s'", extval);
9296  needlabel = true; /* we must attach a cast */
9297  }
9298  break;
9299 
9300  case NUMERICOID:
9301 
9302  /*
9303  * NUMERIC can be printed without quotes if it looks like a float
9304  * constant (not an integer, and not Infinity or NaN) and doesn't
9305  * have a leading sign (for the same reason as for INT4).
9306  */
9307  if (isdigit((unsigned char) extval[0]) &&
9308  strcspn(extval, "eE.") != strlen(extval))
9309  {
9310  appendStringInfoString(buf, extval);
9311  }
9312  else
9313  {
9314  appendStringInfo(buf, "'%s'", extval);
9315  needlabel = true; /* we must attach a cast */
9316  }
9317  break;
9318 
9319  case BITOID:
9320  case VARBITOID:
9321  appendStringInfo(buf, "B'%s'", extval);
9322  break;
9323 
9324  case BOOLOID:
9325  if (strcmp(extval, "t") == 0)
9326  appendStringInfoString(buf, "true");
9327  else
9328  appendStringInfoString(buf, "false");
9329  break;
9330 
9331  default:
9332  simple_quote_literal(buf, extval);
9333  break;
9334  }
9335 
9336  pfree(extval);
9337 
9338  if (showtype < 0)
9339  return;
9340 
9341  /*
9342  * For showtype == 0, append ::typename unless the constant will be
9343  * implicitly typed as the right type when it is read in.
9344  *
9345  * XXX this code has to be kept in sync with the behavior of the parser,
9346  * especially make_const.
9347  */
9348  switch (constval->consttype)
9349  {
9350  case BOOLOID:
9351  case UNKNOWNOID:
9352  /* These types can be left unlabeled */
9353  needlabel = false;
9354  break;
9355  case INT4OID:
9356  /* We determined above whether a label is needed */
9357  break;
9358  case NUMERICOID:
9359 
9360  /*
9361  * Float-looking constants will be typed as numeric, which we
9362  * checked above; but if there's a nondefault typmod we need to
9363  * show it.
9364  */
9365  needlabel |= (constval->consttypmod >= 0);
9366  break;
9367  default:
9368  needlabel = true;
9369  break;
9370  }
9371  if (needlabel || showtype > 0)
9372  appendStringInfo(buf, "::%s",
9374  constval->consttypmod));
9375 
9376  get_const_collation(constval, context);
9377 }
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:9403
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static void get_const_collation(Const *constval, deparse_context *context)
Definition: ruleutils.c:9383
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 6320 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().

6321 {
6322  StringInfo buf = context->buf;
6323  RangeTblEntry *rte;
6324 
6325  /* Insert the WITH clause if given */
6326  get_with_clause(query, context);
6327 
6328  /*
6329  * Start the query with DELETE FROM relname
6330  */
6331  rte = rt_fetch(query->resultRelation, query->rtable);
6332  Assert(rte->rtekind == RTE_RELATION);
6333  if (PRETTY_INDENT(context))
6334  {
6335  appendStringInfoChar(buf, ' ');
6336  context->indentLevel += PRETTYINDENT_STD;
6337  }
6338  appendStringInfo(buf, "DELETE FROM %s%s",
6339  only_marker(rte),
6341  if (rte->alias != NULL)
6342  appendStringInfo(buf, " %s",
6344 
6345  /* Add the USING clause if given */
6346  get_from_clause(query, " USING ", context);
6347 
6348  /* Add a WHERE clause if given */
6349  if (query->jointree->quals != NULL)
6350  {
6351  appendContextKeyword(context, " WHERE ",
6353  get_rule_expr(query->jointree->quals, context, false);
6354  }
6355 
6356  /* Add RETURNING if present */
6357  if (query->returningList)
6358  {
6359  appendContextKeyword(context, " RETURNING",
6361  get_target_list(query->returningList, context, NULL);
6362  }
6363 }
#define NIL
Definition: pg_list.h:69
static void get_with_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:4963
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10381
Alias * alias
Definition: parsenodes.h:1042
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:5331
static void get_from_clause(Query *query, const char *prefix, deparse_context *context)
Definition: ruleutils.c:9673
#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:10507
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:7492
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:676
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7597
char * aliasname
Definition: primnodes.h:42
#define only_marker(rte)
Definition: ruleutils.c:466
RTEKind rtekind
Definition: parsenodes.h:944
StringInfo buf
Definition: ruleutils.c:108
static void get_from_clause ( Query query,
const char *  prefix,
deparse_context context 
)
static

Definition at line 9673 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().

9674 {
9675  StringInfo buf = context->buf;
9676  bool first = true;
9677  ListCell *l;
9678 
9679  /*
9680  * We use the query's jointree as a guide to what to print. However, we
9681  * must ignore auto-added RTEs that are marked not inFromCl. (These can
9682  * only appear at the top level of the jointree, so it's sufficient to
9683  * check here.) This check also ensures we ignore the rule pseudo-RTEs
9684  * for NEW and OLD.
9685  */
9686  foreach(l, query->jointree->fromlist)
9687  {
9688  Node *jtnode = (Node *) lfirst(l);
9689 
9690  if (IsA(jtnode, RangeTblRef))
9691  {
9692  int varno = ((RangeTblRef *) jtnode)->rtindex;
9693  RangeTblEntry *rte = rt_fetch(varno, query->rtable);
9694 
9695  if (!rte->inFromCl)
9696  continue;
9697  }
9698 
9699  if (first)
9700  {
9701  appendContextKeyword(context, prefix,
9703  first = false;
9704 
9705  get_from_clause_item(jtnode, query, context);
9706  }
9707  else
9708  {
9709  StringInfoData itembuf;
9710 
9711  appendStringInfoString(buf, ", ");
9712 
9713  /*
9714  * Put the new FROM item's text into itembuf so we can decide
9715  * after we've got it whether or not it needs to go on a new line.
9716  */
9717  initStringInfo(&itembuf);
9718  context->buf = &itembuf;
9719 
9720  get_from_clause_item(jtnode, query, context);
9721 
9722  /* Restore context's output buffer */
9723  context->buf = buf;
9724 
9725  /* Consider line-wrapping if enabled */
9726  if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
9727  {
9728  /* Does the new item start with a new line? */
9729  if (itembuf.len > 0 && itembuf.data[0] == '\n')
9730  {
9731  /* If so, we shouldn't add anything */
9732  /* instead, remove any trailing spaces currently in buf */
9734  }
9735  else
9736  {
9737  char *trailing_nl;
9738 
9739  /* Locate the start of the current line in the buffer */
9740  trailing_nl = strrchr(buf->data, '\n');
9741  if (trailing_nl == NULL)
9742  trailing_nl = buf->data;
9743  else
9744  trailing_nl++;
9745 
9746  /*
9747  * Add a newline, plus some indentation, if the new item
9748  * would cause an overflow.
9749  */
9750  if (strlen(trailing_nl) + itembuf.len > context->wrapColumn)
9751  appendContextKeyword(context, "", -PRETTYINDENT_STD,
9754  }
9755  }
9756 
9757  /* Add the new item */
9758  appendStringInfoString(buf, itembuf.data);
9759 
9760  /* clean up */
9761  pfree(itembuf.data);
9762  }
9763  }
9764 }
#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:7492
static void removeStringInfoSpaces(StringInfo str)
Definition: ruleutils.c:7546
#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:9767
static void get_from_clause_coldeflist ( RangeTblFunction rtfunc,
deparse_columns colinfo,
deparse_context context 
)
static

Definition at line 10134 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().

10137 {
10138  StringInfo buf = context->buf;
10139  ListCell *l1;
10140  ListCell *l2;
10141  ListCell *l3;
10142  ListCell *l4;
10143  int i;
10144 
10145  appendStringInfoChar(buf, '(');
10146 
10147  /* there's no forfour(), so must chase one list the hard way */
10148  i = 0;
10149  l4 = list_head(rtfunc->funccolnames);
10150  forthree(l1, rtfunc->funccoltypes,
10151  l2, rtfunc->funccoltypmods,
10152  l3, rtfunc->funccolcollations)
10153  {
10154  Oid atttypid = lfirst_oid(l1);
10155  int32 atttypmod = lfirst_int(l2);
10156  Oid attcollation = lfirst_oid(l3);
10157  char *attname;
10158 
10159  if (colinfo)
10160  attname = colinfo->colnames[i];
10161  else
10162  attname = strVal(lfirst(l4));
10163 
10164  Assert(attname); /* shouldn't be any dropped columns here */
10165 
10166  if (i > 0)
10167  appendStringInfoString(buf, ", ");
10168  appendStringInfo(buf, "%s %s",
10169  quote_identifier(attname),
10170  format_type_with_typemod(atttypid, atttypmod));
10171  if (OidIsValid(attcollation) &&
10172  attcollation != get_typcollation(atttypid))
10173  appendStringInfo(buf, " COLLATE %s",
10174  generate_collation_name(attcollation));
10175 
10176  l4 = lnext(l4);
10177  i++;
10178  }
10179 
10180  appendStringInfoChar(buf, ')');
10181 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10381
#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:10789
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:1080
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2781
List * funccolcollations
Definition: parsenodes.h:1081
#define Assert(condition)
Definition: c.h:676
#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 9767 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_rule_expr_funccall(), 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().

9768 {
9769  StringInfo buf = context->buf;
9771 
9772  if (IsA(jtnode, RangeTblRef))
9773  {
9774  int varno = ((RangeTblRef *) jtnode)->rtindex;
9775  RangeTblEntry *rte = rt_fetch(varno, query->rtable);
9776  char *refname = get_rtable_name(varno, context);
9777  deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
9778  RangeTblFunction *rtfunc1 = NULL;
9779  bool printalias;
9780 
9781  if (rte->lateral)
9782  appendStringInfoString(buf, "LATERAL ");
9783 
9784  /* Print the FROM item proper */
9785  switch (rte->rtekind)
9786  {
9787  case RTE_RELATION:
9788  /* Normal relation RTE */
9789  appendStringInfo(buf, "%s%s",
9790  only_marker(rte),
9792  context->namespaces));
9793  break;
9794  case RTE_SUBQUERY:
9795  /* Subquery RTE */
9796  appendStringInfoChar(buf, '(');
9797  get_query_def(rte->subquery, buf, context->namespaces, NULL,
9798  context->prettyFlags, context->wrapColumn,
9799  context->indentLevel);
9800  appendStringInfoChar(buf, ')');
9801  break;
9802  case RTE_FUNCTION:
9803  /* Function RTE */
9804  rtfunc1 = (RangeTblFunction *) linitial(rte->functions);
9805 
9806  /*
9807  * Omit ROWS FROM() syntax for just one function, unless it
9808  * has both a coldeflist and WITH ORDINALITY. If it has both,
9809  * we must use ROWS FROM() syntax to avoid ambiguity about
9810  * whether the coldeflist includes the ordinality column.
9811  */
9812  if (list_length(rte->functions) == 1 &&
9813  (rtfunc1->funccolnames == NIL || !rte->funcordinality))
9814  {
9815  get_rule_expr_funccall(rtfunc1->funcexpr, context, true);
9816  /* we'll print the coldeflist below, if it has one */
9817  }
9818  else
9819  {
9820  bool all_unnest;
9821  ListCell *lc;
9822 
9823  /*
9824  * If all the function calls in the list are to unnest,
9825  * and none need a coldeflist, then collapse the list back
9826  * down to UNNEST(args). (If we had more than one
9827  * built-in unnest function, this would get more
9828  * difficult.)
9829  *
9830  * XXX This is pretty ugly, since it makes not-terribly-
9831  * future-proof assumptions about what the parser would do
9832  * with the output; but the alternative is to emit our
9833  * nonstandard ROWS FROM() notation for what might have
9834  * been a perfectly spec-compliant multi-argument
9835  * UNNEST().
9836  */
9837  all_unnest = true;
9838  foreach(lc, rte->functions)
9839  {
9840  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
9841 
9842  if (!IsA(rtfunc->funcexpr, FuncExpr) ||
9843  ((FuncExpr *) rtfunc->funcexpr)->funcid != F_ARRAY_UNNEST ||
9844  rtfunc->funccolnames != NIL)
9845  {
9846  all_unnest = false;
9847  break;
9848  }
9849  }
9850 
9851  if (all_unnest)
9852  {
9853  List *allargs = NIL;
9854 
9855  foreach(lc, rte->functions)
9856  {
9857  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
9858  List *args = ((FuncExpr *) rtfunc->funcexpr)->args;
9859 
9860  allargs = list_concat(allargs, list_copy(args));
9861  }
9862 
9863  appendStringInfoString(buf, "UNNEST(");
9864  get_rule_expr((Node *) allargs, context, true);
9865  appendStringInfoChar(buf, ')');
9866  }
9867  else
9868  {
9869  int funcno = 0;
9870 
9871  appendStringInfoString(buf, "ROWS FROM(");
9872  foreach(lc, rte->functions)
9873  {
9874  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
9875 
9876  if (funcno > 0)
9877  appendStringInfoString(buf, ", ");
9878  get_rule_expr_funccall(rtfunc->funcexpr, context, true);
9879  if (rtfunc->funccolnames != NIL)
9880  {
9881  /* Reconstruct the column definition list */
9882  appendStringInfoString(buf, " AS ");
9884  NULL,
9885  context);
9886  }
9887  funcno++;
9888  }
9889  appendStringInfoChar(buf, ')');
9890  }
9891  /* prevent printing duplicate coldeflist below */
9892  rtfunc1 = NULL;
9893  }
9894  if (rte->funcordinality)
9895  appendStringInfoString(buf, " WITH ORDINALITY");
9896  break;
9897  case RTE_TABLEFUNC:
9898  get_tablefunc(rte->tablefunc, context, true);
9899  break;
9900  case RTE_VALUES:
9901  /* Values list RTE */
9902  appendStringInfoChar(buf, '(');
9903  get_values_def(rte->values_lists, context);
9904  appendStringInfoChar(buf, ')');
9905  break;
9906  case RTE_CTE:
9908  break;
9909  default:
9910  elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
9911  break;
9912  }
9913 
9914  /* Print the relation alias, if needed */
9915  printalias = false;
9916  if (rte->alias != NULL)
9917  {
9918  /* Always print alias if user provided one */
9919  printalias = true;
9920  }
9921  else if (colinfo->printaliases)
9922  {
9923  /* Always print alias if we need to print column aliases */
9924  printalias = true;
9925  }
9926  else if (rte->rtekind == RTE_RELATION)
9927  {
9928  /*
9929  * No need to print alias if it's same as relation name (this
9930  * would normally be the case, but not if set_rtable_names had to
9931  * resolve a conflict).
9932  */
9933  if (strcmp(refname, get_relation_name(rte->relid)) != 0)
9934  printalias = true;
9935  }
9936  else if (rte->rtekind == RTE_FUNCTION)
9937  {
9938  /*
9939  * For a function RTE, always print alias. This covers possible
9940  * renaming of the function and/or instability of the
9941  * FigureColname rules for things that aren't simple functions.
9942  * Note we'd need to force it anyway for the columndef list case.
9943  */
9944  printalias = true;
9945  }
9946  else if (rte->rtekind == RTE_VALUES)
9947  {
9948  /* Alias is syntactically required for VALUES */
9949  printalias = true;
9950  }
9951  else if (rte->rtekind == RTE_CTE)
9952  {
9953  /*
9954  * No need to print alias if it's same as CTE name (this would
9955  * normally be the case, but not if set_rtable_names had to
9956  * resolve a conflict).
9957  */
9958  if (strcmp(refname, rte->ctename) != 0)
9959  printalias = true;
9960  }
9961  if (printalias)
9962  appendStringInfo(buf, " %s", quote_identifier(refname));
9963 
9964  /* Print the column definitions or aliases, if needed */
9965  if (rtfunc1 && rtfunc1->funccolnames != NIL)
9966  {
9967  /* Reconstruct the columndef list, which is also the aliases */
9968  get_from_clause_coldeflist(rtfunc1, colinfo, context);
9969  }
9970  else
9971  {
9972  /* Else print column aliases as needed */
9973  get_column_alias_list(colinfo, context);
9974  }
9975 
9976  /* Tablesample clause must go after any alias */
9977  if (rte->rtekind == RTE_RELATION && rte->tablesample)
9978  get_tablesample_def(rte->tablesample, context);
9979  }
9980  else if (IsA(jtnode, JoinExpr))
9981  {
9982  JoinExpr *j = (JoinExpr *) jtnode;
9983  deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
9984  bool need_paren_on_right;
9985 
9986  need_paren_on_right = PRETTY_PAREN(context) &&
9987  !IsA(j->rarg, RangeTblRef) &&
9988  !(IsA(j->rarg, JoinExpr) &&((JoinExpr *) j->rarg)->alias != NULL);
9989 
9990  if (!PRETTY_PAREN(context) || j->alias != NULL)
9991  appendStringInfoChar(buf, '(');
9992 
9993  get_from_clause_item(j->larg, query, context);
9994 
9995  switch (j->jointype)
9996  {
9997  case JOIN_INNER:
9998  if (j->quals)
9999  appendContextKeyword(context, " JOIN ",
10003  else
10004  appendContextKeyword(context, " CROSS JOIN ",
10008  break;
10009  case JOIN_LEFT:
10010  appendContextKeyword(context, " LEFT JOIN ",
10014  break;
10015  case JOIN_FULL:
10016  appendContextKeyword(context, " FULL JOIN ",
10020  break;
10021  case JOIN_RIGHT:
10022  appendContextKeyword(context, " RIGHT JOIN ",
10026  break;
10027  default:
10028  elog(ERROR, "unrecognized join type: %d",
10029  (int) j->jointype);
10030  }
10031 
10032  if (need_paren_on_right)
10033  appendStringInfoChar(buf, '(');
10034  get_from_clause_item(j->rarg, query, context);
10035  if (need_paren_on_right)
10036  appendStringInfoChar(buf, ')');
10037 
10038  if (j->usingClause)
10039  {
10040  ListCell *lc;
10041  bool first = true;
10042 
10043  appendStringInfoString(buf, " USING (");
10044  /* Use the assigned names, not what's in usingClause */
10045  foreach(lc, colinfo->usingNames)
10046  {
10047  char *colname = (char *) lfirst(lc);
10048 
10049  if (first)
10050  first = false;
10051  else
10052  appendStringInfoString(buf, ", ");
10054  }
10055  appendStringInfoChar(buf, ')');
10056  }
10057  else if (j->quals)
10058  {
10059  appendStringInfoString(buf, " ON ");
10060  if (!PRETTY_PAREN(context))
10061  appendStringInfoChar(buf, '(');
10062  get_rule_expr(j->quals, context, false);
10063  if (!PRETTY_PAREN(context))
10064  appendStringInfoChar(buf, ')');
10065  }
10066  else if (j->jointype != JOIN_INNER)
10067  {
10068  /* If we didn't say CROSS JOIN above, we must provide an ON */
10069  appendStringInfoString(buf, " ON TRUE");
10070  }
10071 
10072  if (!PRETTY_PAREN(context) || j->alias != NULL)
10073  appendStringInfoChar(buf, ')');
10074 
10075  /* Yes, it's correct to put alias after the right paren ... */
10076  if (j->alias != NULL)
10077  {
10078  appendStringInfo(buf, " %s",
10080  get_column_alias_list(colinfo, context);
10081  }
10082  }
10083  else
10084  elog(ERROR, "unrecognized node type: %d",
10085  (int) nodeTag(jtnode));
10086 }
List * namespaces
Definition: ruleutils.c:109
#define NIL
Definition: pg_list.h:69
static char * get_relation_name(Oid relid)
Definition: ruleutils.c:10487
#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:10381
Alias * alias
Definition: parsenodes.h:1042
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:999
List * values_lists
Definition: parsenodes.h:1009
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:10507
Node * larg
Definition: primnodes.h:1451
static void get_tablesample_def(TableSampleClause *tablesample, deparse_context *context)
Definition: ruleutils.c:10187
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:1004
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:7492
#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:9555
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:7597
#define lfirst(lc)
Definition: pg_list.h:106
char * aliasname
Definition: primnodes.h:42
List * functions
Definition: parsenodes.h:998
#define only_marker(rte)
Definition: ruleutils.c:466
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:4847
#define nodeTag(nodeptr)
Definition: nodes.h:514
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:4920
RTEKind rtekind
Definition: parsenodes.h:944
static void get_column_alias_list(deparse_columns *colinfo, deparse_context *context)
Definition: ruleutils.c:10094
char * ctename
Definition: parsenodes.h:1014
Query * subquery
Definition: parsenodes.h:967
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:10134
static void get_rule_expr_funccall(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:8797
int rtindex
Definition: primnodes.h:1456
Definition: pg_list.h:45
struct TableSampleClause * tablesample
Definition: parsenodes.h:962
static char * get_rtable_name(int rtindex, deparse_context *context)
Definition: ruleutils.c:4403
static void get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
Definition: ruleutils.c:9767
static void get_func_expr ( FuncExpr expr,
deparse_context context,
bool  showimplicit 
)
static

Definition at line 8908 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().

8910 {
8911  StringInfo buf = context->buf;
8912  Oid funcoid = expr->funcid;
8913  Oid argtypes[FUNC_MAX_ARGS];
8914  int nargs;
8915  List *argnames;
8916  bool use_variadic;
8917  ListCell *l;
8918 
8919  /*
8920  * If the function call came from an implicit coercion, then just show the
8921  * first argument --- unless caller wants to see implicit coercions.
8922  */
8923  if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
8924  {
8925  get_rule_expr_paren((Node *) linitial(expr->args), context,
8926  false, (Node *) expr);
8927  return;
8928  }
8929 
8930  /*
8931  * If the function call came from a cast, then show the first argument
8932  * plus an explicit cast operation.
8933  */
8934  if (expr->funcformat == COERCE_EXPLICIT_CAST ||
8936  {
8937  Node *arg = linitial(expr->args);
8938  Oid rettype = expr->funcresulttype;
8939  int32 coercedTypmod;
8940 
8941  /* Get the typmod if this is a length-coercion function */
8942  (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
8943 
8944  get_coercion_expr(arg, context,
8945  rettype, coercedTypmod,
8946  (Node *) expr);
8947 
8948  return;
8949  }
8950 
8951  /*
8952  * Normal function: display as proname(args). First we need to extract
8953  * the argument datatypes.
8954  */
8955  if (list_length(expr->args) > FUNC_MAX_ARGS)
8956  ereport(ERROR,
8957  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
8958  errmsg("too many arguments")));
8959  nargs = 0;
8960  argnames = NIL;
8961  foreach(l, expr->args)
8962  {
8963  Node *arg = (Node *) lfirst(l);
8964 
8965  if (IsA(arg, NamedArgExpr))
8966  argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
8967  argtypes[nargs] = exprType(arg);
8968  nargs++;
8969  }
8970 
8971  appendStringInfo(buf, "%s(",
8972  generate_function_name(funcoid, nargs,
8973  argnames, argtypes,
8974  expr->funcvariadic,
8975  &use_variadic,
8976  context->special_exprkind));
8977  nargs = 0;
8978  foreach(l, expr->args)
8979  {
8980  if (nargs++ > 0)
8981  appendStringInfoString(buf, ", ");
8982  if (use_variadic && lnext(l) == NULL)
8983  appendStringInfoString(buf, "VARIADIC ");
8984  get_rule_expr((Node *) lfirst(l), context, true);
8985  }
8986  appendStringInfoChar(buf, ')');
8987 }
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:10609
#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:7565
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:9192
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:7597
#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 5902 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().

5903 {
5904  StringInfo buf = context->buf;
5905  RangeTblEntry *select_rte = NULL;
5906  RangeTblEntry *values_rte = NULL;
5907  RangeTblEntry *rte;
5908  char *sep;
5909  ListCell *l;
5910  List *strippedexprs;
5911 
5912  /* Insert the WITH clause if given */
5913  get_with_clause(query, context);
5914 
5915  /*
5916  * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
5917  * single RTE for the SELECT or VALUES. Plain VALUES has neither.
5918  */
5919  foreach(l, query->rtable)
5920  {
5921  rte = (RangeTblEntry *) lfirst(l);
5922 
5923  if (rte->rtekind == RTE_SUBQUERY)
5924  {
5925  if (select_rte)
5926  elog(ERROR, "too many subquery RTEs in INSERT");
5927  select_rte = rte;
5928  }
5929 
5930  if (rte->rtekind == RTE_VALUES)
5931  {
5932  if (values_rte)
5933  elog(ERROR, "too many values RTEs in INSERT");
5934  values_rte = rte;
5935  }
5936  }
5937  if (select_rte && values_rte)
5938  elog(ERROR, "both subquery and values RTEs in INSERT");
5939 
5940  /*
5941  * Start the query with INSERT INTO relname
5942  */
5943  rte = rt_fetch(query->resultRelation, query->rtable);
5944  Assert(rte->rtekind == RTE_RELATION);
5945 
5946  if (PRETTY_INDENT(context))
5947  {
5948  context->indentLevel += PRETTYINDENT_STD;
5949  appendStringInfoChar(buf, ' ');
5950  }
5951  appendStringInfo(buf, "INSERT INTO %s ",
5953  /* INSERT requires AS keyword for target alias */
5954  if (rte->alias != NULL)
5955  appendStringInfo(buf, "AS %s ",
5957 
5958  /*
5959  * Add the insert-column-names list. Any indirection decoration needed on
5960  * the column names can be inferred from the top targetlist.
5961  */
5962  strippedexprs = NIL;
5963  sep = "";
5964  if (query->targetList)
5965  appendStringInfoChar(buf, '(');
5966  foreach(l, query->targetList)
5967  {
5968  TargetEntry *tle = (TargetEntry *) lfirst(l);
5969 
5970  if (tle->resjunk)
5971  continue; /* ignore junk entries */
5972 
5973  appendStringInfoString(buf, sep);
5974  sep = ", ";
5975 
5976  /*
5977  * Put out name of target column; look in the catalogs, not at
5978  * tle->resname, since resname will fail to track RENAME.
5979  */
5982  tle->resno)));
5983 
5984  /*
5985  * Print any indirection needed (subfields or subscripts), and strip
5986  * off the top-level nodes representing the indirection assignments.
5987  * Add the stripped expressions to strippedexprs. (If it's a
5988  * single-VALUES statement, the stripped expressions are the VALUES to
5989  * print below. Otherwise they're just Vars and not really
5990  * interesting.)
5991  */
5992  strippedexprs = lappend(strippedexprs,
5993  processIndirection((Node *) tle->expr,
5994  context));
5995  }
5996  if (query->targetList)
5997  appendStringInfoString(buf, ") ");
5998 
5999  if (query->override)
6000  {
6001  if (query->override == OVERRIDING_SYSTEM_VALUE)
6002  appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
6003  else if (query->override == OVERRIDING_USER_VALUE)
6004  appendStringInfoString(buf, "OVERRIDING USER VALUE ");
6005  }
6006 
6007  if (select_rte)
6008  {
6009  /* Add the SELECT */
6010  get_query_def(select_rte->subquery, buf, NIL, NULL,
6011  context->prettyFlags, context->wrapColumn,
6012  context->indentLevel);
6013  }
6014  else if (values_rte)
6015  {
6016  /* Add the multi-VALUES expression lists */
6017  get_values_def(values_rte->values_lists, context);
6018  }
6019  else if (strippedexprs)
6020  {
6021  /* Add the single-VALUES expression list */
6022  appendContextKeyword(context, "VALUES (",
6024  get_rule_expr((Node *) strippedexprs, context, false);
6025  appendStringInfoChar(buf, ')');
6026  }
6027  else
6028  {
6029  /* No expressions, so it must be DEFAULT VALUES */
6030  appendStringInfoString(buf, "DEFAULT VALUES");
6031  }
6032 
6033  /* Add ON CONFLICT if present */
6034  if (query->onConflict)
6035  {
6036  OnConflictExpr *confl = query->onConflict;
6037 
6038  appendStringInfoString(buf, " ON CONFLICT");
6039 
6040  if (confl->arbiterElems)
6041  {
6042  /* Add the single-VALUES expression list */
6043  appendStringInfoChar(buf, '(');
6044  get_rule_expr((Node *) confl->arbiterElems, context, false);
6045  appendStringInfoChar(buf, ')');
6046 
6047  /* Add a WHERE clause (for partial indexes) if given */
6048  if (confl->arbiterWhere != NULL)
6049  {
6050  bool save_varprefix;
6051 
6052  /*
6053  * Force non-prefixing of Vars, since parser assumes that they
6054  * belong to target relation. WHERE clause does not use
6055  * InferenceElem, so this is separately required.
6056  */
6057  save_varprefix = context->varprefix;
6058  context->varprefix = false;
6059 
6060  appendContextKeyword(context, " WHERE ",
6062  get_rule_expr(confl->arbiterWhere, context, false);
6063 
6064  context->varprefix = save_varprefix;
6065  }
6066  }
6067  else if (OidIsValid(confl->constraint))
6068  {
6069  char *constraint = get_constraint_name(confl->constraint);
6070 
6071  if (!constraint)
6072  elog(ERROR, "cache lookup failed for constraint %u",
6073  confl->constraint);
6074  appendStringInfo(buf, " ON CONSTRAINT %s",
6075  quote_identifier(constraint));
6076  }
6077 
6078  if (confl->action == ONCONFLICT_NOTHING)
6079  {
6080  appendStringInfoString(buf, " DO NOTHING");
6081  }
6082  else
6083  {
6084  appendStringInfoString(buf, " DO UPDATE SET ");
6085  /* Deparse targetlist */
6087  context, rte);
6088 
6089  /* Add a WHERE clause if given */
6090  if (confl->onConflictWhere != NULL)
6091  {
6092  appendContextKeyword(context, " WHERE ",
6094  get_rule_expr(confl->onConflictWhere, context, false);
6095  }
6096  }
6097  }
6098 
6099  /* Add RETURNING if present */
6100  if (query->returningList)
6101  {
6102  appendContextKeyword(context, " RETURNING",
6104  get_target_list(query->returningList, context, NULL);
6105  }
6106 }
#define NIL
Definition: pg_list.h:69
static void get_with_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:4963
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10381
Alias * alias
Definition: parsenodes.h:1042
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:10274
int resultRelation
Definition: parsenodes.h:120
static void get_target_list(List *targetList, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5331
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:6169
#define OidIsValid(objectId)
Definition: c.h:538
List * values_lists
Definition: parsenodes.h:1009
List * targetList
Definition: parsenodes.h:138
List * arbiterElems
Definition: primnodes.h:1490
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:10507
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:7492
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:676
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7597
#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:4847
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:4920
RTEKind rtekind
Definition: parsenodes.h:944
Node * arbiterWhere
Definition: primnodes.h:1492
Query * subquery
Definition: parsenodes.h:967
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 6684 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().

6686 {
6687  RangeTblEntry *rte;
6688  AttrNumber attnum;
6689  int netlevelsup;
6690  deparse_namespace *dpns;
6692  Node *expr;
6693 
6694  /*
6695  * If it's a RowExpr that was expanded from a whole-row Var, use the
6696  * column names attached to it.
6697  */
6698  if (IsA(var, RowExpr))
6699  {
6700  RowExpr *r = (RowExpr *) var;
6701 
6702  if (fieldno > 0 && fieldno <= list_length(r->colnames))
6703  return strVal(list_nth(r->colnames, fieldno - 1));
6704  }
6705 
6706  /*
6707  * If it's a Param of type RECORD, try to find what the Param refers to.
6708  */
6709  if (IsA(var, Param))
6710  {
6711  Param *param = (Param *) var;
6712  ListCell *ancestor_cell;
6713 
6714  expr = find_param_referent(param, context, &dpns, &ancestor_cell);
6715  if (expr)
6716  {
6717  /* Found a match, so recurse to decipher the field name */
6718  deparse_namespace save_dpns;
6719  const char *result;
6720 
6721  push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
6722  result = get_name_for_var_field((Var *) expr, fieldno,
6723  0, context);
6724  pop_ancestor_plan(dpns, &save_dpns);
6725  return result;
6726  }
6727  }
6728 
6729  /*
6730  * If it's a Var of type RECORD, we have to find what the Var refers to;
6731  * if not, we can use get_expr_result_type. If that fails, we try
6732  * lookup_rowtype_tupdesc, which will probably fail too, but will ereport
6733  * an acceptable message.
6734  */
6735  if (!IsA(var, Var) ||
6736  var->vartype != RECORDOID)
6737  {
6738  if (get_expr_result_type((Node *) var, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
6739  tupleDesc = lookup_rowtype_tupdesc_copy(exprType((Node *) var),
6740  exprTypmod((Node *) var));
6741  Assert(tupleDesc);
6742  /* Got the tupdesc, so we can extract the field name */
6743  Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
6744  return NameStr(tupleDesc->attrs[fieldno - 1]->attname);
6745  }
6746 
6747  /* Find appropriate nesting depth */
6748  netlevelsup = var->varlevelsup + levelsup;
6749  if (netlevelsup >= list_length(context->namespaces))
6750  elog(ERROR, "bogus varlevelsup: %d offset %d",
6751  var->varlevelsup, levelsup);
6752  dpns = (deparse_namespace *) list_nth(context->namespaces,
6753  netlevelsup);
6754 
6755  /*
6756  * Try to find the relevant RTE in this rtable. In a plan tree, it's
6757  * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
6758  * down into the subplans, or INDEX_VAR, which is resolved similarly.
6759  */
6760  if (var->varno >= 1 && var->varno <= list_length(dpns->rtable))
6761  {
6762  rte = rt_fetch(var->varno, dpns->rtable);
6763  attnum = var->varattno;
6764  }
6765  else if (var->varno == OUTER_VAR && dpns->outer_tlist)
6766  {
6767  TargetEntry *tle;
6768  deparse_namespace save_dpns;
6769  const char *result;
6770 
6771  tle = get_tle_by_resno(dpns->outer_tlist, var->varattno);
6772  if (!tle)
6773  elog(ERROR, "bogus varattno for OUTER_VAR var: %d", var->varattno);
6774 
6775  Assert(netlevelsup == 0);
6776  push_child_plan(dpns, dpns->outer_planstate, &save_dpns);
6777 
6778  result = get_name_for_var_field((Var *) tle->expr, fieldno,
6779  levelsup, context);
6780 
6781  pop_child_plan(dpns, &save_dpns);
6782  return result;
6783  }
6784  else if (var->varno == INNER_VAR && dpns->inner_tlist)
6785  {
6786  TargetEntry *tle;
6787  deparse_namespace save_dpns;
6788  const char *result;
6789 
6790  tle = get_tle_by_resno(dpns->inner_tlist, var->varattno);
6791  if (!tle)
6792  elog(ERROR, "bogus varattno for INNER_VAR var: %d", var->varattno);
6793 
6794  Assert(netlevelsup == 0);
6795  push_child_plan(dpns, dpns->inner_planstate, &save_dpns);
6796 
6797  result = get_name_for_var_field((Var *) tle->expr, fieldno,
6798  levelsup, context);
6799 
6800  pop_child_plan(dpns, &save_dpns);
6801  return result;
6802  }
6803  else if (var->varno == INDEX_VAR && dpns->index_tlist)
6804  {
6805  TargetEntry *tle;
6806  const char *result;
6807 
6808  tle = get_tle_by_resno(dpns->index_tlist, var->varattno);
6809  if (!tle)
6810  elog(ERROR, "bogus varattno for INDEX_VAR var: %d", var->varattno);
6811 
6812  Assert(netlevelsup == 0);
6813 
6814  result = get_name_for_var_field((Var *) tle->expr, fieldno,
6815  levelsup, context);
6816 
6817  return result;
6818  }
6819  else
6820  {
6821  elog(ERROR, "bogus varno: %d", var->varno);
6822  return NULL; /* keep compiler quiet */
6823  }
6824 
6825  if (attnum == InvalidAttrNumber)
6826  {
6827  /* Var is whole-row reference to RTE, so select the right field */
6828  return get_rte_attribute_name(rte, fieldno);
6829  }
6830 
6831  /*
6832  * This part has essentially the same logic as the parser's
6833  * expandRecordVariable() function, but we are dealing with a different
6834  * representation of the input context, and we only need one field name
6835  * not a TupleDesc. Also, we need special cases for finding subquery and
6836  * CTE subplans when deparsing Plan trees.
6837  */
6838  expr = (Node *) var; /* default if we can't drill down */
6839 
6840  switch (rte->rtekind)
6841  {
6842  case RTE_RELATION:
6843  case RTE_VALUES:
6844  case RTE_NAMEDTUPLESTORE:
6845 
6846  /*
6847  * This case should not occur: a column of a table or values list
6848  * shouldn't have type RECORD. Fall through and fail (most
6849  * likely) at the bottom.
6850  */
6851  break;
6852  case RTE_SUBQUERY:
6853  /* Subselect-in-FROM: examine sub-select's output expr */
6854  {
6855  if (rte->subquery)
6856  {
6858  attnum);
6859 
6860  if (ste == NULL || ste->resjunk)
6861  elog(ERROR, "subquery %s does not have attribute %d",
6862  rte->eref->aliasname, attnum);
6863  expr = (Node *) ste->expr;
6864  if (IsA(expr, Var))
6865  {
6866  /*
6867  * Recurse into the sub-select to see what its Var
6868  * refers to. We have to build an additional level of
6869  * namespace to keep in step with varlevelsup in the
6870  * subselect.
6871  */
6872  deparse_namespace mydpns;
6873  const char *result;
6874 
6875  set_deparse_for_query(&mydpns, rte->subquery,
6876  context->namespaces);
6877 
6878  context->namespaces = lcons(&mydpns,
6879  context->namespaces);
6880 
6881  result = get_name_for_var_field((Var *) expr, fieldno,
6882  0, context);
6883 
6884  context->namespaces =
6885  list_delete_first(context->namespaces);
6886 
6887  return result;
6888  }
6889  /* else fall through to inspect the expression */
6890  }
6891  else
6892  {
6893  /*
6894  * We're deparsing a Plan tree so we don't have complete
6895  * RTE entries (in particular, rte->subquery is NULL). But
6896  * the only place we'd see a Var directly referencing a
6897  * SUBQUERY RTE is in a SubqueryScan plan node, and we can
6898  * look into the child plan's tlist instead.
6899  */
6900  TargetEntry *tle;
6901  deparse_namespace save_dpns;
6902  const char *result;
6903 
6904  if (!dpns->inner_planstate)
6905  elog(ERROR, "failed to find plan for subquery %s",
6906  rte->eref->aliasname);
6907  tle = get_tle_by_resno(dpns->inner_tlist, attnum);
6908  if (!tle)
6909  elog(ERROR, "bogus varattno for subquery var: %d",
6910  attnum);
6911  Assert(netlevelsup == 0);
6912  push_child_plan(dpns, dpns->inner_planstate, &save_dpns);
6913 
6914  result = get_name_for_var_field((Var *) tle->expr, fieldno,
6915  levelsup, context);
6916 
6917  pop_child_plan(dpns, &save_dpns);
6918  return result;
6919  }
6920  }
6921  break;
6922  case RTE_JOIN:
6923  /* Join RTE --- recursively inspect the alias variable */
6924  if (rte->joinaliasvars == NIL)
6925  elog(ERROR, "cannot decompile join alias var in plan tree");
6926  Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
6927  expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
6928  Assert(expr != NULL);
6929  /* we intentionally don't strip implicit coercions here */
6930  if (IsA(expr, Var))
6931  return get_name_for_var_field((Var *) expr, fieldno,
6932  var->varlevelsup + levelsup,
6933  context);
6934  /* else fall through to inspect the expression */
6935  break;
6936  case RTE_FUNCTION:
6937  case RTE_TABLEFUNC:
6938 
6939  /*
6940  * We couldn't get here unless a function is declared with one of
6941  * its result columns as RECORD, which is not allowed.
6942  */
6943  break;
6944  case RTE_CTE:
6945  /* CTE reference: examine subquery's output expr */
6946  {
6947  CommonTableExpr *cte = NULL;
6948  Index ctelevelsup;
6949  ListCell *lc;
6950 
6951  /*
6952  * Try to find the referenced CTE using the namespace stack.
6953  */
6954  ctelevelsup = rte->ctelevelsup + netlevelsup;
6955  if (ctelevelsup >= list_length(context->namespaces))
6956  lc = NULL;
6957  else
6958  {
6959  deparse_namespace *ctedpns;
6960 
6961  ctedpns = (deparse_namespace *)
6962  list_nth(context->namespaces, ctelevelsup);
6963  foreach(lc, ctedpns->ctes)
6964  {
6965  cte = (CommonTableExpr *) lfirst(lc);
6966  if (strcmp(cte->ctename, rte->ctename) == 0)
6967  break;
6968  }
6969  }
6970  if (lc != NULL)
6971  {
6972  Query *ctequery = (Query *) cte->ctequery;
6974  attnum);
6975 
6976  if (ste == NULL || ste->resjunk)
6977  elog(ERROR, "subquery %s does not have attribute %d",
6978  rte->eref->aliasname, attnum);
6979  expr = (Node *) ste->expr;
6980  if (IsA(expr, Var))
6981  {
6982  /*
6983  * Recurse into the CTE to see what its Var refers to.
6984  * We have to build an additional level of namespace
6985  * to keep in step with varlevelsup in the CTE.
6986  * Furthermore it could be an outer CTE, so we may
6987  * have to delete some levels of namespace.
6988  */
6989  List *save_nslist = context->namespaces;
6990  List *new_nslist;
6991  deparse_namespace mydpns;
6992  const char *result;
6993 
6994  set_deparse_for_query(&mydpns, ctequery,
6995  context->namespaces);
6996 
6997  new_nslist = list_copy_tail(context->namespaces,
6998  ctelevelsup);
6999  context->namespaces = lcons(&mydpns, new_nslist);
7000 
7001  result = get_name_for_var_field((Var *) expr, fieldno,
7002  0, context);
7003 
7004  context->namespaces = save_nslist;
7005 
7006  return result;
7007  }
7008  /* else fall through to inspect the expression */
7009  }
7010  else
7011  {
7012  /*
7013  * We're deparsing a Plan tree so we don't have a CTE
7014  * list. But the only place we'd see a Var directly
7015  * referencing a CTE RTE is in a CteScan plan node, and we
7016  * can look into the subplan's tlist instead.
7017  */
7018  TargetEntry *tle;
7019  deparse_namespace save_dpns;
7020  const char *result;
7021 
7022  if (!dpns->inner_planstate)
7023  elog(ERROR, "failed to find plan for CTE %s",
7024  rte->eref->aliasname);
7025  tle = get_tle_by_resno(dpns->inner_tlist, attnum);
7026  if (!tle)
7027  elog(ERROR, "bogus varattno for subquery var: %d",
7028  attnum);
7029  Assert(netlevelsup == 0);
7030  push_child_plan(dpns, dpns->inner_planstate, &save_dpns);
7031 
7032  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7033  levelsup, context);
7034 
7035  pop_child_plan(dpns, &save_dpns);
7036  return result;
7037  }
7038  }
7039  break;
7040  }
7041 
7042  /*
7043  * We now have an expression we can't expand any more, so see if
7044  * get_expr_result_type() can do anything with it. If not, pass to
7045  * lookup_rowtype_tupdesc() which will probably fail, but will give an
7046  * appropriate error message while failing.
7047  */
7048  if (get_expr_result_type(expr, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
7049  tupleDesc = lookup_rowtype_tupdesc_copy(exprType(expr),
7050  exprTypmod(expr));
7051  Assert(tupleDesc);
7052  /* Got the tupdesc, so we can extract the field name */
7053  Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
7054  return NameStr(tupleDesc->attrs[fieldno - 1]->attname);
7055 }
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:988
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:7066
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:4567
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:4497
#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:6684
#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:4514
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#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:1015
static void set_deparse_for_query(deparse_namespace *dpns, Query *query, List *parent_namespaces)
Definition: ruleutils.c:3337
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:944
char * ctename
Definition: parsenodes.h:1014
Query * subquery
Definition: parsenodes.h:967
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:4544
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:1043
#define INDEX_VAR
Definition: primnodes.h:155
Definition: pg_list.h:45
#define GetCTETargetList(cte)
Definition: parsenodes.h:1378
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 10231 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().

10233 {
10234  HeapTuple ht_opc;
10235  Form_pg_opclass opcrec;
10236  char *opcname;
10237  char *nspname;
10238 
10239  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
10240  if (!HeapTupleIsValid(ht_opc))
10241  elog(ERROR, "cache lookup failed for opclass %u", opclass);
10242  opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
10243 
10244  if (!OidIsValid(actual_datatype) ||
10245  GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
10246  {
10247  /* Okay, we need the opclass name. Do we need to qualify it? */
10248  opcname = NameStr(opcrec->opcname);
10249  if (OpclassIsVisible(opclass))
10250  appendStringInfo(buf, " %s", quote_identifier(opcname));
10251  else
10252  {
10253  nspname = get_namespace_name(opcrec->opcnamespace);
10254  appendStringInfo(buf, " %s.%s",
10255  quote_identifier(nspname),
10256  quote_identifier(opcname));
10257  }
10258  }
10259  ReleaseSysCache(ht_opc);
10260 }
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:10381
#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 8847 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().

8848 {
8849  StringInfo buf = context->buf;
8850  Oid opno = expr->opno;
8851  List *args = expr->args;
8852 
8853  if (!PRETTY_PAREN(context))
8854  appendStringInfoChar(buf, '(');
8855  if (list_length(args) == 2)
8856  {
8857  /* binary operator */
8858  Node *arg1 = (Node *) linitial(args);
8859  Node *arg2 = (Node *) lsecond(args);
8860 
8861  get_rule_expr_paren(arg1, context, true, (Node *) expr);
8862  appendStringInfo(buf, " %s ",
8864  exprType(arg1),
8865  exprType(arg2)));
8866  get_rule_expr_paren(arg2, context, true, (Node *) expr);
8867  }
8868  else
8869  {
8870  /* unary operator --- but which side? */
8871  Node *arg = (Node *) linitial(args);
8872  HeapTuple tp;
8873  Form_pg_operator optup;
8874 
8876  if (!HeapTupleIsValid(tp))
8877  elog(ERROR, "cache lookup failed for operator %u", opno);
8878  optup = (Form_pg_operator) GETSTRUCT(tp);
8879  switch (optup->oprkind)
8880  {
8881  case 'l':
8882  appendStringInfo(buf, "%s ",
8884  InvalidOid,
8885  exprType(arg)));
8886  get_rule_expr_paren(arg, context, true, (Node *) expr);
8887  break;
8888  case 'r':
8889  get_rule_expr_paren(arg, context, true, (Node *) expr);
8890  appendStringInfo(buf, " %s",
8892  exprType(arg),
8893  InvalidOid));
8894  break;
8895  default:
8896  elog(ERROR, "bogus oprkind: %d", optup->oprkind);
8897  }
8898  ReleaseSysCache(tp);
8899  }
8900  if (!PRETTY_PAREN(context))
8901  appendStringInfoChar(buf, ')');
8902 }
#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:7565
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:10719
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 7186 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().

7187 {
7188  Node *expr;
7189  deparse_namespace *dpns;
7190  ListCell *ancestor_cell;
7191 
7192  /*
7193  * If it's a PARAM_EXEC parameter, try to locate the expression from which
7194  * the parameter was computed. Note that failing to find a referent isn't
7195  * an error, since the Param might well be a subplan output rather than an
7196  * input.
7197  */
7198  expr = find_param_referent(param, context, &dpns, &ancestor_cell);
7199  if (expr)
7200  {
7201  /* Found a match, so print it */
7202  deparse_namespace save_dpns;
7203  bool save_varprefix;
7204  bool need_paren;
7205 
7206  /* Switch attention to the ancestor plan node */
7207  push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
7208 
7209  /*
7210  * Force prefixing of Vars, since they won't belong to the relation
7211  * being scanned in the original plan node.
7212  */
7213  save_varprefix = context->varprefix;
7214  context->varprefix = true;
7215 
7216  /*
7217  * A Param's expansion is typically a Var, Aggref, or upper-level
7218  * Param, which wouldn't need extra parentheses. Otherwise, insert
7219  * parens to ensure the expression looks atomic.
7220  */
7221  need_paren = !(IsA(expr, Var) ||
7222  IsA(expr, Aggref) ||
7223  IsA(expr, Param));
7224  if (need_paren)
7225  appendStringInfoChar(context->buf, '(');
7226 
7227  get_rule_expr(expr, context, false);
7228 
7229  if (need_paren)
7230  appendStringInfoChar(context->buf, ')');
7231 
7232  context->varprefix = save_varprefix;
7233 
7234  pop_ancestor_plan(dpns, &save_dpns);
7235 
7236  return;
7237  }
7238 
7239  /*
7240  * Not PARAM_EXEC, or couldn't find referent: just print $N.
7241  */
7242  appendStringInfo(context->buf, "$%d", param->paramid);
7243 }
#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:7066
Definition: nodes.h:509
static void pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:4567
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:7597
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:4544
static void get_query_def ( Query query,
StringInfo  buf,
List parentnamespace,
TupleDesc  resultDesc,
int  prettyFlags,
int  wrapColumn,
int  startIndent 
)
static

Definition at line 4847 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().

4850 {
4851  deparse_context context;
4852  deparse_namespace dpns;
4853 
4854  /* Guard against excessively long or deeply-nested queries */
4857 
4858  /*
4859  * Before we begin to examine the query, acquire locks on referenced
4860  * relations, and fix up deleted columns in JOIN RTEs. This ensures
4861  * consistent results. Note we assume it's OK to scribble on the passed
4862  * querytree!
4863  *
4864  * We are only deparsing the query (we are not about to execute it), so we
4865  * only need AccessShareLock on the relations it mentions.
4866  */
4867  AcquireRewriteLocks(query, false, false);
4868 
4869  context.buf = buf;
4870  context.namespaces = lcons(&dpns, list_copy(parentnamespace));
4871  context.windowClause = NIL;
4872  context.windowTList = NIL;
4873  context.varprefix = (parentnamespace != NIL ||
4874  list_length(query->rtable) != 1);
4875  context.prettyFlags = prettyFlags;
4876  context.wrapColumn = wrapColumn;
4877  context.indentLevel = startIndent;
4878  context.special_exprkind = EXPR_KIND_NONE;
4879 
4880  set_deparse_for_query(&dpns, query, parentnamespace);
4881 
4882  switch (query->commandType)
4883  {
4884  case CMD_SELECT:
4885  get_select_query_def(query, &context, resultDesc);
4886  break;
4887 
4888  case CMD_UPDATE:
4889  get_update_query_def(query, &context);
4890  break;
4891 
4892  case CMD_INSERT:
4893  get_insert_query_def(query, &context);
4894  break;
4895 
4896  case CMD_DELETE:
4897  get_delete_query_def(query, &context);
4898  break;
4899 
4900  case CMD_NOTHING:
4901  appendStringInfoString(buf, "NOTHING");
4902  break;
4903 
4904  case CMD_UTILITY:
4905  get_utility_query_def(query, &context);
4906  break;
4907 
4908  default:
4909  elog(ERROR, "unrecognized query command type: %d",
4910  query->commandType);
4911  break;
4912  }
4913 }
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:5902
static void get_update_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:6114
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:6371
static void get_select_query_def(Query *query, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5031
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:6320
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:3337
StringInfo buf
Definition: ruleutils.c:108
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
#define elog
Definition: elog.h:219
char* get_range_partbound_string ( List bound_datums)

Definition at line 10914 of file ruleutils.c.

References appendStringInfoChar(), appendStringInfoString(), buf, deparse_context::buf, castNode, StringInfoData::data, get_const_expr(), PartitionRangeDatum::kind, lfirst, makeStringInfo(), PARTITION_RANGE_DATUM_MAXVALUE, PARTITION_RANGE_DATUM_MINVALUE, val, and PartitionRangeDatum::value.

Referenced by check_new_partition_bound(), and get_rule_expr().

10915 {
10916  deparse_context context;
10918  ListCell *cell;
10919  char *sep;
10920 
10921  memset(&context, 0, sizeof(deparse_context));
10922  context.buf = buf;
10923 
10924  appendStringInfoString(buf, "(");
10925  sep = "";
10926  foreach(cell, bound_datums)
10927  {
10928  PartitionRangeDatum *datum =
10930 
10931  appendStringInfoString(buf, sep);
10932  if (datum->kind == PARTITION_RANGE_DATUM_MINVALUE)
10933  appendStringInfoString(buf, "MINVALUE");
10934  else if (datum->kind == PARTITION_RANGE_DATUM_MAXVALUE)
10935  appendStringInfoString(buf, "MAXVALUE");
10936  else
10937  {
10938  Const *val = castNode(Const, datum->value);
10939 
10940  get_const_expr(val, &context, -1);
10941  }
10942  sep = ", ";
10943  }
10944  appendStringInfoChar(buf, ')');
10945 
10946  return buf->data;
10947 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
StringInfo makeStringInfo(void)
Definition: stringinfo.c:28
PartitionRangeDatumKind kind
Definition: parsenodes.h:827
static void get_const_expr(Const *constval, deparse_context *context, int showtype)
Definition: ruleutils.c:9248
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
#define lfirst(lc)
Definition: pg_list.h:106
StringInfo buf
Definition: ruleutils.c:108
long val
Definition: informix.c:689
static char * get_relation_name ( Oid  relid)
static

Definition at line 10487 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().

10488 {
10489  char *relname = get_rel_name(relid);
10490 
10491  if (!relname)
10492  elog(ERROR, "cache lookup failed for relation %u", relid);
10493  return relname;
10494 }
#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 4403 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().

4404 {
4406 
4407  Assert(rtindex > 0 && rtindex <= list_length(dpns->rtable_names));
4408  return (char *) list_nth(dpns->rtable_names, rtindex - 1);
4409 }
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:676
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 7597 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(), generate_relation_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_range_partbound_string(), get_rule_expr_paren(), get_rule_expr_toplevel(), get_sublink_expr(), get_tablefunc(), get_variable(), get_windowfunc_expr(), i, InferenceElem::infercollid, InferenceElem::inferopclass, 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, NextValueExpr::seqid, simple_quote_literal(), 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_NextValueExpr, 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, 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_funccall(), 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().

7599 {
7600  StringInfo buf = context->buf;
7601 
7602  if (node == NULL)
7603  return;
7604 
7605  /* Guard against excessively long or deeply-nested queries */
7608 
7609  /*
7610  * Each level of get_rule_expr must emit an indivisible term
7611  * (parenthesized if necessary) to ensure result is reparsed into the same
7612  * expression tree. The only exception is that when the input is a List,
7613  * we emit the component items comma-separated with no surrounding
7614  * decoration; this is convenient for most callers.
7615  */
7616  switch (nodeTag(node))
7617  {
7618  case T_Var:
7619  (void) get_variable((Var *) node, 0, false, context);
7620  break;
7621 
7622  case T_Const:
7623  get_const_expr((Const *) node, context, 0);
7624  break;
7625 
7626  case T_Param:
7627  get_parameter((Param *) node, context);
7628  break;
7629 
7630  case T_Aggref:
7631  get_agg_expr((Aggref *) node, context, (Aggref *) node);
7632  break;
7633 
7634  case T_GroupingFunc:<