PostgreSQL Source Code  git master
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/relation.h"
#include "access/sysattr.h"
#include "access/table.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 "nodes/pathnodes.h"
#include "optimizer/optimizer.h"
#include "parser/parse_agg.h"
#include "parser/parse_func.h"
#include "parser/parse_node.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/guc.h"
#include "utils/hsearch.h"
#include "utils/lsyscache.h"
#include "utils/partcache.h"
#include "utils/rel.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.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   0x0001
 
#define PRETTYFLAG_INDENT   0x0002
 
#define PRETTYFLAG_SCHEMA   0x0004
 
#define WRAP_COLUMN_DEFAULT   0
 
#define PRETTY_PAREN(context)   ((context)->prettyFlags & PRETTYFLAG_PAREN)
 
#define PRETTY_INDENT(context)   ((context)->prettyFlags & PRETTYFLAG_INDENT)
 
#define PRETTY_SCHEMA(context)   ((context)->prettyFlags & PRETTYFLAG_SCHEMA)
 
#define deparse_columns_fetch(rangetable_index, dpns)   ((deparse_columns *) list_nth((dpns)->rtable_columns, (rangetable_index)-1))
 
#define only_marker(rte)   ((rte)->inh ? "" : "ONLY ")
 

Typedefs

typedef void(* rsv_callback) (Node *node, deparse_context *context, void *callback_arg)
 

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 int 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 keysOnly, bool showTblSpc, bool inherits, int prettyFlags, bool missing_ok)
 
static char * pg_get_statisticsobj_worker (Oid statextid, bool columns_only, 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 print_function_sqlbody (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 (const 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 char * get_rtable_name (int rtindex, deparse_context *context)
 
static void set_deparse_plan (deparse_namespace *dpns, Plan *plan)
 
static void push_child_plan (deparse_namespace *dpns, Plan *plan, 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 *callback_arg)
 
static void resolve_special_varno (Node *node, deparse_context *context, rsv_callback callback, void *callback_arg)
 
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 *callback_arg)
 
static void get_windowfunc_expr (WindowFunc *wfunc, deparse_context *context)
 
static bool get_func_sql_syntax (FuncExpr *expr, 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 (SubscriptingRef *sbsref, 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 void add_cast_to (StringInfo buf, Oid typid)
 
static char * generate_qualified_type_name (Oid typid)
 
static textstring_to_text (char *str)
 
static char * flatten_reloptions (Oid relid)
 
static void get_reloptions (StringInfo buf, Datum reloptions)
 
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)
 
char * pg_get_statisticsobjdef_string (Oid statextid)
 
Datum pg_get_statisticsobjdef_columns (PG_FUNCTION_ARGS)
 
Datum pg_get_statisticsobjdef_expressions (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)
 
char * pg_get_partconstrdef_string (Oid partitionId, char *aliasname)
 
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)
 
Datum pg_get_function_sqlbody (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_tree (PlannedStmt *pstmt, List *rtable_names)
 
Listset_deparse_context_plan (List *dpcontext, Plan *plan, List *ancestors)
 
Listselect_rtable_names_for_explain (List *rtable, Bitmapset *rels_used)
 
static RangeTblEntryget_simple_values_rte (Query *query, TupleDesc resultDesc)
 
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)
 
char * generate_opclass_name (Oid opclass)
 
const char * quote_identifier (const char *ident)
 
char * quote_qualified_identifier (const char *qualifier, const char *ident)
 
void generate_operator_clause (StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
 
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

◆ deparse_columns_fetch

#define deparse_columns_fetch (   rangetable_index,
  dpns 
)    ((deparse_columns *) list_nth((dpns)->rtable_columns, (rangetable_index)-1))

◆ only_marker

#define only_marker (   rte)    ((rte)->inh ? "" : "ONLY ")

Definition at line 490 of file ruleutils.c.

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

◆ PRETTY_INDENT

◆ PRETTY_PAREN

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

◆ PRETTY_SCHEMA

#define PRETTY_SCHEMA (   context)    ((context)->prettyFlags & PRETTYFLAG_SCHEMA)

Definition at line 99 of file ruleutils.c.

◆ PRETTYFLAG_INDENT

◆ PRETTYFLAG_PAREN

◆ PRETTYFLAG_SCHEMA

◆ PRETTYINDENT_JOIN

#define PRETTYINDENT_JOIN   4

Definition at line 83 of file ruleutils.c.

Referenced by get_from_clause_item().

◆ PRETTYINDENT_LIMIT

#define PRETTYINDENT_LIMIT   40 /* wrap limit */

Definition at line 86 of file ruleutils.c.

Referenced by appendContextKeyword().

◆ PRETTYINDENT_STD

◆ PRETTYINDENT_VAR

#define PRETTYINDENT_VAR   4

Definition at line 84 of file ruleutils.c.

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

◆ WRAP_COLUMN_DEFAULT

Typedef Documentation

◆ rsv_callback

typedef void(* rsv_callback) (Node *node, deparse_context *context, void *callback_arg)

Definition at line 304 of file ruleutils.c.

Function Documentation

◆ add_cast_to()

static void add_cast_to ( StringInfo  buf,
Oid  typid 
)
static

Definition at line 11780 of file ruleutils.c.

References appendStringInfo(), elog, ERROR, get_namespace_name_or_temp(), GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, quote_identifier(), ReleaseSysCache(), SearchSysCache1(), TYPEOID, and typname.

Referenced by generate_operator_clause().

11781 {
11782  HeapTuple typetup;
11783  Form_pg_type typform;
11784  char *typname;
11785  char *nspname;
11786 
11787  typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
11788  if (!HeapTupleIsValid(typetup))
11789  elog(ERROR, "cache lookup failed for type %u", typid);
11790  typform = (Form_pg_type) GETSTRUCT(typetup);
11791 
11792  typname = NameStr(typform->typname);
11793  nspname = get_namespace_name_or_temp(typform->typnamespace);
11794 
11795  appendStringInfo(buf, "::%s.%s",
11796  quote_identifier(nspname), quote_identifier(typname));
11797 
11798  ReleaseSysCache(typetup);
11799 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
NameData typname
Definition: pg_type.h:41
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3340
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681

◆ appendContextKeyword()

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

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

8175 {
8176  StringInfo buf = context->buf;
8177 
8178  if (PRETTY_INDENT(context))
8179  {
8180  int indentAmount;
8181 
8182  context->indentLevel += indentBefore;
8183 
8184  /* remove any trailing spaces currently in the buffer ... */
8186  /* ... then add a newline and some spaces */
8187  appendStringInfoChar(buf, '\n');
8188 
8189  if (context->indentLevel < PRETTYINDENT_LIMIT)
8190  indentAmount = Max(context->indentLevel, 0) + indentPlus;
8191  else
8192  {
8193  /*
8194  * If we're indented more than PRETTYINDENT_LIMIT characters, try
8195  * to conserve horizontal space by reducing the per-level
8196  * indentation. For best results the scale factor here should
8197  * divide all the indent amounts that get added to indentLevel
8198  * (PRETTYINDENT_STD, etc). It's important that the indentation
8199  * not grow unboundedly, else deeply-nested trees use O(N^2)
8200  * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
8201  */
8202  indentAmount = PRETTYINDENT_LIMIT +
8203  (context->indentLevel - PRETTYINDENT_LIMIT) /
8204  (PRETTYINDENT_STD / 2);
8205  indentAmount %= PRETTYINDENT_LIMIT;
8206  /* scale/wrap logic affects indentLevel, but not indentPlus */
8207  indentAmount += indentPlus;
8208  }
8209  appendStringInfoSpaces(buf, indentAmount);
8210 
8212 
8213  context->indentLevel += indentAfter;
8214  if (context->indentLevel < 0)
8215  context->indentLevel = 0;
8216  }
8217  else
8219 }
#define PRETTY_INDENT(context)
Definition: ruleutils.c:98
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
static void removeStringInfoSpaces(StringInfo str)
Definition: ruleutils.c:8227
#define PRETTYINDENT_STD
Definition: ruleutils.c:82
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void appendStringInfoSpaces(StringInfo str, int count)
Definition: stringinfo.c:206
#define PRETTYINDENT_LIMIT
Definition: ruleutils.c:86
#define Max(x, y)
Definition: c.h:980
StringInfo buf
Definition: ruleutils.c:110

◆ colname_is_unique()

static bool colname_is_unique ( const char *  colname,
deparse_namespace dpns,
deparse_columns colinfo 
)
static

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

4633 {
4634  int i;
4635  ListCell *lc;
4636 
4637  /* Check against already-assigned column aliases within RTE */
4638  for (i = 0; i < colinfo->num_cols; i++)
4639  {
4640  char *oldname = colinfo->colnames[i];
4641 
4642  if (oldname && strcmp(oldname, colname) == 0)
4643  return false;
4644  }
4645 
4646  /*
4647  * If we're building a new_colnames array, check that too (this will be
4648  * partially but not completely redundant with the previous checks)
4649  */
4650  for (i = 0; i < colinfo->num_new_cols; i++)
4651  {
4652  char *oldname = colinfo->new_colnames[i];
4653 
4654  if (oldname && strcmp(oldname, colname) == 0)
4655  return false;
4656  }
4657 
4658  /* Also check against USING-column names that must be globally unique */
4659  foreach(lc, dpns->using_names)
4660  {
4661  char *oldname = (char *) lfirst(lc);
4662 
4663  if (strcmp(oldname, colname) == 0)
4664  return false;
4665  }
4666 
4667  /* Also check against names already assigned for parent-join USING cols */
4668  foreach(lc, colinfo->parentUsing)
4669  {
4670  char *oldname = (char *) lfirst(lc);
4671 
4672  if (strcmp(oldname, colname) == 0)
4673  return false;
4674  }
4675 
4676  return true;
4677 }
List * using_names
Definition: ruleutils.c:166
#define lfirst(lc)
Definition: pg_list.h:169
int i
List * parentUsing
Definition: ruleutils.c:264
char ** new_colnames
Definition: ruleutils.c:257
char ** colnames
Definition: ruleutils.c:240

◆ decompile_column_index_array()

static int decompile_column_index_array ( Datum  column_index_array,
Oid  relId,
StringInfo  buf 
)
static

Definition at line 2513 of file ruleutils.c.

References appendStringInfo(), appendStringInfoString(), DatumGetArrayTypeP, DatumGetInt16, deconstruct_array(), get_attname(), and quote_identifier().

Referenced by pg_get_constraintdef_worker().

2515 {
2516  Datum *keys;
2517  int nKeys;
2518  int j;
2519 
2520  /* Extract data from array of int16 */
2521  deconstruct_array(DatumGetArrayTypeP(column_index_array),
2522  INT2OID, 2, true, TYPALIGN_SHORT,
2523  &keys, NULL, &nKeys);
2524 
2525  for (j = 0; j < nKeys; j++)
2526  {
2527  char *colName;
2528 
2529  colName = get_attname(relId, DatumGetInt16(keys[j]), false);
2530 
2531  if (j == 0)
2533  else
2534  appendStringInfo(buf, ", %s", quote_identifier(colName));
2535  }
2536 
2537  return nKeys;
2538 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
#define DatumGetInt16(X)
Definition: postgres.h:488
uintptr_t Datum
Definition: postgres.h:411
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3490
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
#define DatumGetArrayTypeP(X)
Definition: array.h:254

◆ deparse_context_for()

List* deparse_context_for ( const char *  aliasname,
Oid  relid 
)

Definition at line 3551 of file ruleutils.c.

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

Referenced by pg_get_constraintdef_worker(), pg_get_expr_worker(), pg_get_indexdef_worker(), pg_get_partconstrdef_string(), pg_get_partition_constraintdef(), pg_get_partkeydef_worker(), pg_get_statisticsobj_worker(), pg_get_statisticsobjdef_expressions(), transformPartitionBound(), and transformPartitionRangeBounds().

3552 {
3553  deparse_namespace *dpns;
3554  RangeTblEntry *rte;
3555 
3556  dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3557 
3558  /* Build a minimal RTE for the rel */
3559  rte = makeNode(RangeTblEntry);
3560  rte->rtekind = RTE_RELATION;
3561  rte->relid = relid;
3562  rte->relkind = RELKIND_RELATION; /* no need for exactness here */
3564  rte->alias = makeAlias(aliasname, NIL);
3565  rte->eref = rte->alias;
3566  rte->lateral = false;
3567  rte->inh = false;
3568  rte->inFromCl = true;
3569 
3570  /* Build one-element rtable */
3571  dpns->rtable = list_make1(rte);
3572  dpns->subplans = NIL;
3573  dpns->ctes = NIL;
3574  dpns->appendrels = NULL;
3575  set_rtable_names(dpns, NIL, NULL);
3577 
3578  /* Return a one-deep namespace stack */
3579  return list_make1(dpns);
3580 }
#define NIL
Definition: pg_list.h:65
Alias * alias
Definition: parsenodes.h:1140
#define AccessShareLock
Definition: lockdefs.h:36
AppendRelInfo ** appendrels
Definition: ruleutils.c:163
#define list_make1(x1)
Definition: pg_list.h:206
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:387
static void set_rtable_names(deparse_namespace *dpns, List *parent_namespaces, Bitmapset *rels_used)
Definition: ruleutils.c:3717
void * palloc0(Size size)
Definition: mcxt.c:1093
#define makeNode(_type_)
Definition: nodes.h:587
static void set_simple_column_names(deparse_namespace *dpns)
Definition: ruleutils.c:3927
RTEKind rtekind
Definition: parsenodes.h:995
Alias * eref
Definition: parsenodes.h:1141

◆ deparse_context_for_plan_tree()

List* deparse_context_for_plan_tree ( PlannedStmt pstmt,
List rtable_names 
)

Definition at line 3596 of file ruleutils.c.

References PlannedStmt::appendRelations, deparse_namespace::appendrels, Assert, AppendRelInfo::child_relid, deparse_namespace::ctes, lfirst_node, list_length(), list_make1, NIL, palloc0(), PlannedStmt::rtable, deparse_namespace::rtable, deparse_namespace::rtable_names, set_simple_column_names(), PlannedStmt::subplans, and deparse_namespace::subplans.

Referenced by ExplainPrintPlan().

3597 {
3598  deparse_namespace *dpns;
3599 
3600  dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3601 
3602  /* Initialize fields that stay the same across the whole plan tree */
3603  dpns->rtable = pstmt->rtable;
3604  dpns->rtable_names = rtable_names;
3605  dpns->subplans = pstmt->subplans;
3606  dpns->ctes = NIL;
3607  if (pstmt->appendRelations)
3608  {
3609  /* Set up the array, indexed by child relid */
3610  int ntables = list_length(dpns->rtable);
3611  ListCell *lc;
3612 
3613  dpns->appendrels = (AppendRelInfo **)
3614  palloc0((ntables + 1) * sizeof(AppendRelInfo *));
3615  foreach(lc, pstmt->appendRelations)
3616  {
3617  AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
3618  Index crelid = appinfo->child_relid;
3619 
3620  Assert(crelid > 0 && crelid <= ntables);
3621  Assert(dpns->appendrels[crelid] == NULL);
3622  dpns->appendrels[crelid] = appinfo;
3623  }
3624  }
3625  else
3626  dpns->appendrels = NULL; /* don't need it */
3627 
3628  /*
3629  * Set up column name aliases. We will get rather bogus results for join
3630  * RTEs, but that doesn't matter because plan trees don't contain any join
3631  * alias Vars.
3632  */
3634 
3635  /* Return a one-deep namespace stack */
3636  return list_make1(dpns);
3637 }
#define NIL
Definition: pg_list.h:65
List * rtable_names
Definition: ruleutils.c:159
AppendRelInfo ** appendrels
Definition: ruleutils.c:163
#define list_make1(x1)
Definition: pg_list.h:206
#define lfirst_node(type, lc)
Definition: pg_list.h:172
void * palloc0(Size size)
Definition: mcxt.c:1093
unsigned int Index
Definition: c.h:549
List * subplans
Definition: plannodes.h:73
#define Assert(condition)
Definition: c.h:804
static int list_length(const List *l)
Definition: pg_list.h:149
List * rtable
Definition: plannodes.h:66
static void set_simple_column_names(deparse_namespace *dpns)
Definition: ruleutils.c:3927
Index child_relid
Definition: pathnodes.h:2296
List * appendRelations
Definition: plannodes.h:71

◆ deparse_expression()

char* deparse_expression ( Node expr,
List dpcontext,
bool  forceprefix,
bool  showimplicit 
)

Definition at line 3491 of file ruleutils.c.

References deparse_expression_pretty().

Referenced by AlterDomainDefault(), DefineDomain(), pg_get_function_arg_default(), pg_get_partconstrdef_string(), print_function_arguments(), show_expression(), show_grouping_set_keys(), show_memoize_info(), show_plan_tlist(), show_sort_group_keys(), show_tablesample(), transformPartitionBound(), and transformPartitionRangeBounds().

3493 {
3494  return deparse_expression_pretty(expr, dpcontext, forceprefix,
3495  showimplicit, 0, 0);
3496 }
static char * deparse_expression_pretty(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit, int prettyFlags, int startIndent)
Definition: ruleutils.c:3518

◆ deparse_expression_pretty()

static char * deparse_expression_pretty ( Node expr,
List dpcontext,
bool  forceprefix,
bool  showimplicit,
int  prettyFlags,
int  startIndent 
)
static

Definition at line 3518 of file ruleutils.c.

References deparse_context::appendparents, 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(), pg_get_partkeydef_worker(), pg_get_statisticsobj_worker(), and pg_get_statisticsobjdef_expressions().

3521 {
3523  deparse_context context;
3524 
3525  initStringInfo(&buf);
3526  context.buf = &buf;
3527  context.namespaces = dpcontext;
3528  context.windowClause = NIL;
3529  context.windowTList = NIL;
3530  context.varprefix = forceprefix;
3531  context.prettyFlags = prettyFlags;
3532  context.wrapColumn = WRAP_COLUMN_DEFAULT;
3533  context.indentLevel = startIndent;
3534  context.special_exprkind = EXPR_KIND_NONE;
3535  context.appendparents = NULL;
3536 
3537  get_rule_expr(expr, &context, showimplicit);
3538 
3539  return buf.data;
3540 }
List * namespaces
Definition: ruleutils.c:111
#define NIL
Definition: pg_list.h:65
#define WRAP_COLUMN_DEFAULT
Definition: ruleutils.c:94
static char * buf
Definition: pg_test_fsync.c:68
ParseExprKind special_exprkind
Definition: ruleutils.c:118
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
List * windowTList
Definition: ruleutils.c:113
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:8278
List * windowClause
Definition: ruleutils.c:112
Bitmapset * appendparents
Definition: ruleutils.c:120
StringInfo buf
Definition: ruleutils.c:110

◆ expand_colnames_array_to()

static void expand_colnames_array_to ( deparse_columns colinfo,
int  n 
)
static

Definition at line 4724 of file ruleutils.c.

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

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

4725 {
4726  if (n > colinfo->num_cols)
4727  {
4728  if (colinfo->colnames == NULL)
4729  colinfo->colnames = (char **) palloc0(n * sizeof(char *));
4730  else
4731  {
4732  colinfo->colnames = (char **) repalloc(colinfo->colnames,
4733  n * sizeof(char *));
4734  memset(colinfo->colnames + colinfo->num_cols, 0,
4735  (n - colinfo->num_cols) * sizeof(char *));
4736  }
4737  colinfo->num_cols = n;
4738  }
4739 }
void * palloc0(Size size)
Definition: mcxt.c:1093
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
char ** colnames
Definition: ruleutils.c:240

◆ find_param_referent()

static Node * find_param_referent ( Param param,
deparse_context context,
deparse_namespace **  dpns_p,
ListCell **  ancestor_cell_p 
)
static

Definition at line 7688 of file ruleutils.c.

References deparse_namespace::ancestors, arg, SubPlan::args, Assert, elog, ERROR, for_each_cell, forboth, innerPlan, IsA, lfirst, lfirst_int, lfirst_node, linitial, list_nth(), lnext(), deparse_context::namespaces, NestLoop::nestParams, NIL, PARAM_EXEC, Param::paramid, Param::paramkind, NestLoopParam::paramno, NestLoopParam::paramval, SubPlan::parParam, deparse_namespace::plan, SubPlan::plan_id, and deparse_namespace::subplans.

Referenced by get_name_for_var_field(), and get_parameter().

7690 {
7691  /* Initialize output parameters to prevent compiler warnings */
7692  *dpns_p = NULL;
7693  *ancestor_cell_p = NULL;
7694 
7695  /*
7696  * If it's a PARAM_EXEC parameter, look for a matching NestLoopParam or
7697  * SubPlan argument. This will necessarily be in some ancestor of the
7698  * current expression's Plan node.
7699  */
7700  if (param->paramkind == PARAM_EXEC)
7701  {
7702  deparse_namespace *dpns;
7703  Plan *child_plan;
7704  bool in_same_plan_level;
7705  ListCell *lc;
7706 
7707  dpns = (deparse_namespace *) linitial(context->namespaces);
7708  child_plan = dpns->plan;
7709  in_same_plan_level = true;
7710 
7711  foreach(lc, dpns->ancestors)
7712  {
7713  Node *ancestor = (Node *) lfirst(lc);
7714  ListCell *lc2;
7715 
7716  /*
7717  * NestLoops transmit params to their inner child only; also, once
7718  * we've crawled up out of a subplan, this couldn't possibly be
7719  * the right match.
7720  */
7721  if (IsA(ancestor, NestLoop) &&
7722  child_plan == innerPlan(ancestor) &&
7723  in_same_plan_level)
7724  {
7725  NestLoop *nl = (NestLoop *) ancestor;
7726 
7727  foreach(lc2, nl->nestParams)
7728  {
7729  NestLoopParam *nlp = (NestLoopParam *) lfirst(lc2);
7730 
7731  if (nlp->paramno == param->paramid)
7732  {
7733  /* Found a match, so return it */
7734  *dpns_p = dpns;
7735  *ancestor_cell_p = lc;
7736  return (Node *) nlp->paramval;
7737  }
7738  }
7739  }
7740 
7741  /*
7742  * If ancestor is a SubPlan, check the arguments it provides.
7743  */
7744  if (IsA(ancestor, SubPlan))
7745  {
7746  SubPlan *subplan = (SubPlan *) ancestor;
7747  ListCell *lc3;
7748  ListCell *lc4;
7749 
7750  forboth(lc3, subplan->parParam, lc4, subplan->args)
7751  {
7752  int paramid = lfirst_int(lc3);
7753  Node *arg = (Node *) lfirst(lc4);
7754 
7755  if (paramid == param->paramid)
7756  {
7757  /*
7758  * Found a match, so return it. But, since Vars in
7759  * the arg are to be evaluated in the surrounding
7760  * context, we have to point to the next ancestor item
7761  * that is *not* a SubPlan.
7762  */
7763  ListCell *rest;
7764 
7765  for_each_cell(rest, dpns->ancestors,
7766  lnext(dpns->ancestors, lc))
7767  {
7768  Node *ancestor2 = (Node *) lfirst(rest);
7769 
7770  if (!IsA(ancestor2, SubPlan))
7771  {
7772  *dpns_p = dpns;
7773  *ancestor_cell_p = rest;
7774  return arg;
7775  }
7776  }
7777  elog(ERROR, "SubPlan cannot be outermost ancestor");
7778  }
7779  }
7780 
7781  /* We have emerged from a subplan. */
7782  in_same_plan_level = false;
7783 
7784  /* SubPlan isn't a kind of Plan, so skip the rest */
7785  continue;
7786  }
7787 
7788  /*
7789  * Check to see if we're emerging from an initplan of the current
7790  * ancestor plan. Initplans never have any parParams, so no need
7791  * to search that list, but we need to know if we should reset
7792  * in_same_plan_level.
7793  */
7794  foreach(lc2, ((Plan *) ancestor)->initPlan)
7795  {
7796  SubPlan *subplan = lfirst_node(SubPlan, lc2);
7797 
7798  if (child_plan != (Plan *) list_nth(dpns->subplans,
7799  subplan->plan_id - 1))
7800  continue;
7801 
7802  /* No parameters to be had here. */
7803  Assert(subplan->parParam == NIL);
7804 
7805  /* We have emerged from an initplan. */
7806  in_same_plan_level = false;
7807  break;
7808  }
7809 
7810  /* No luck, crawl up to next ancestor */
7811  child_plan = (Plan *) ancestor;
7812  }
7813  }
7814 
7815  /* No referent found */
7816  return NULL;
7817 }
List * namespaces
Definition: ruleutils.c:111
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
int plan_id
Definition: primnodes.h:752
List * nestParams
Definition: plannodes.h:723
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:417
ParamKind paramkind
Definition: primnodes.h:267
Definition: nodes.h:539
Var * paramval
Definition: plannodes.h:730
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:46
#define lfirst_int(lc)
Definition: pg_list.h:170
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
#define lfirst_node(type, lc)
Definition: pg_list.h:172
#define innerPlan(node)
Definition: plannodes.h:170
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
int paramid
Definition: primnodes.h:268
List * parParam
Definition: primnodes.h:772
#define elog(elevel,...)
Definition: elog.h:232
void * arg
List * args
Definition: primnodes.h:773

◆ flatten_reloptions()

static char * flatten_reloptions ( Oid  relid)
static

Definition at line 11945 of file ruleutils.c.

References buf, StringInfoData::data, elog, ERROR, get_reloptions(), HeapTupleIsValid, initStringInfo(), ObjectIdGetDatum, ReleaseSysCache(), RELOID, SearchSysCache1(), and SysCacheGetAttr().

Referenced by pg_get_constraintdef_worker(), and pg_get_indexdef_worker().

11946 {
11947  char *result = NULL;
11948  HeapTuple tuple;
11949  Datum reloptions;
11950  bool isnull;
11951 
11952  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
11953  if (!HeapTupleIsValid(tuple))
11954  elog(ERROR, "cache lookup failed for relation %u", relid);
11955 
11956  reloptions = SysCacheGetAttr(RELOID, tuple,
11957  Anum_pg_class_reloptions, &isnull);
11958  if (!isnull)
11959  {
11961 
11962  initStringInfo(&buf);
11963  get_reloptions(&buf, reloptions);
11964 
11965  result = buf.data;
11966  }
11967 
11968  ReleaseSysCache(tuple);
11969 
11970  return result;
11971 }
static void get_reloptions(StringInfo buf, Datum reloptions)
Definition: ruleutils.c:11889
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
static char * buf
Definition: pg_test_fsync.c:68
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:232

◆ generate_collation_name()

char* generate_collation_name ( Oid  collid)

Definition at line 11844 of file ruleutils.c.

References CollationIsVisible(), COLLOID, elog, ERROR, get_namespace_name_or_temp(), GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, quote_qualified_identifier(), ReleaseSysCache(), 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().

11845 {
11846  HeapTuple tp;
11847  Form_pg_collation colltup;
11848  char *collname;
11849  char *nspname;
11850  char *result;
11851 
11852  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
11853  if (!HeapTupleIsValid(tp))
11854  elog(ERROR, "cache lookup failed for collation %u", collid);
11855  colltup = (Form_pg_collation) GETSTRUCT(tp);
11856  collname = NameStr(colltup->collname);
11857 
11858  if (!CollationIsVisible(collid))
11859  nspname = get_namespace_name_or_temp(colltup->collnamespace);
11860  else
11861  nspname = NULL;
11862 
11863  result = quote_qualified_identifier(nspname, collname);
11864 
11865  ReleaseSysCache(tp);
11866 
11867  return result;
11868 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
bool CollationIsVisible(Oid collid)
Definition: namespace.c:2093
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11416
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:56
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3340
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681

◆ generate_function_name()

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 11558 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_or_temp(), GETSTRUCT, HeapTupleIsValid, InvalidOid, list_make1, makeString(), NameStr, NIL, ObjectIdGetDatum, OidIsValid, PROCOID, proname, quote_qualified_identifier(), ReleaseSysCache(), and SearchSysCache1().

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

11561 {
11562  char *result;
11563  HeapTuple proctup;
11564  Form_pg_proc procform;
11565  char *proname;
11566  bool use_variadic;
11567  char *nspname;
11568  FuncDetailCode p_result;
11569  Oid p_funcid;
11570  Oid p_rettype;
11571  bool p_retset;
11572  int p_nvargs;
11573  Oid p_vatype;
11574  Oid *p_true_typeids;
11575  bool force_qualify = false;
11576 
11577  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
11578  if (!HeapTupleIsValid(proctup))
11579  elog(ERROR, "cache lookup failed for function %u", funcid);
11580  procform = (Form_pg_proc) GETSTRUCT(proctup);
11581  proname = NameStr(procform->proname);
11582 
11583  /*
11584  * Due to parser hacks to avoid needing to reserve CUBE, we need to force
11585  * qualification in some special cases.
11586  */
11587  if (special_exprkind == EXPR_KIND_GROUP_BY)
11588  {
11589  if (strcmp(proname, "cube") == 0 || strcmp(proname, "rollup") == 0)
11590  force_qualify = true;
11591  }
11592 
11593  /*
11594  * Determine whether VARIADIC should be printed. We must do this first
11595  * since it affects the lookup rules in func_get_detail().
11596  *
11597  * We always print VARIADIC if the function has a merged variadic-array
11598  * argument. Note that this is always the case for functions taking a
11599  * VARIADIC argument type other than VARIADIC ANY. If we omitted VARIADIC
11600  * and printed the array elements as separate arguments, the call could
11601  * match a newer non-VARIADIC function.
11602  */
11603  if (use_variadic_p)
11604  {
11605  /* Parser should not have set funcvariadic unless fn is variadic */
11606  Assert(!has_variadic || OidIsValid(procform->provariadic));
11607  use_variadic = has_variadic;
11608  *use_variadic_p = use_variadic;
11609  }
11610  else
11611  {
11612  Assert(!has_variadic);
11613  use_variadic = false;
11614  }
11615 
11616  /*
11617  * The idea here is to schema-qualify only if the parser would fail to
11618  * resolve the correct function given the unqualified func name with the
11619  * specified argtypes and VARIADIC flag. But if we already decided to
11620  * force qualification, then we can skip the lookup and pretend we didn't
11621  * find it.
11622  */
11623  if (!force_qualify)
11624  p_result = func_get_detail(list_make1(makeString(proname)),
11625  NIL, argnames, nargs, argtypes,
11626  !use_variadic, true, false,
11627  &p_funcid, &p_rettype,
11628  &p_retset, &p_nvargs, &p_vatype,
11629  &p_true_typeids, NULL);
11630  else
11631  {
11632  p_result = FUNCDETAIL_NOTFOUND;
11633  p_funcid = InvalidOid;
11634  }
11635 
11636  if ((p_result == FUNCDETAIL_NORMAL ||
11637  p_result == FUNCDETAIL_AGGREGATE ||
11638  p_result == FUNCDETAIL_WINDOWFUNC) &&
11639  p_funcid == funcid)
11640  nspname = NULL;
11641  else
11642  nspname = get_namespace_name_or_temp(procform->pronamespace);
11643 
11644  result = quote_qualified_identifier(nspname, proname);
11645 
11646  ReleaseSysCache(proctup);
11647 
11648  return result;
11649 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
NameData proname
Definition: pg_proc.h:35
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define list_make1(x1)
Definition: pg_list.h:206
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
FuncDetailCode
Definition: parse_func.h:22
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11416
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
FuncDetailCode func_get_detail(List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, bool include_out_arguments, Oid *funcid, Oid *rettype, bool *retset, int *nvargs, Oid *vatype, Oid **true_typeids, List **argdefaults)
Definition: parse_func.c:1393
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3340
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681

◆ generate_opclass_name()

char* generate_opclass_name ( Oid  opclass)

Definition at line 11202 of file ruleutils.c.

References buf, StringInfoData::data, get_opclass_name(), initStringInfo(), and InvalidOid.

Referenced by index_opclass_options().

11203 {
11205 
11206  initStringInfo(&buf);
11207  get_opclass_name(opclass, InvalidOid, &buf);
11208 
11209  return &buf.data[1]; /* get_opclass_name() prepends space */
11210 }
static char * buf
Definition: pg_test_fsync.c:68
static void get_opclass_name(Oid opclass, Oid actual_datatype, StringInfo buf)
Definition: ruleutils.c:11164
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define InvalidOid
Definition: postgres_ext.h:36

◆ generate_operator_clause()

void generate_operator_clause ( StringInfo  buf,
const char *  leftop,
Oid  leftoptype,
Oid  opoid,
const char *  rightop,
Oid  rightoptype 
)

Definition at line 11740 of file ruleutils.c.

References add_cast_to(), appendStringInfo(), appendStringInfoString(), Assert, elog, ERROR, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, OPEROID, quote_identifier(), ReleaseSysCache(), and SearchSysCache1().

Referenced by refresh_by_match_merge(), and ri_GenerateQual().

11744 {
11745  HeapTuple opertup;
11746  Form_pg_operator operform;
11747  char *oprname;
11748  char *nspname;
11749 
11750  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
11751  if (!HeapTupleIsValid(opertup))
11752  elog(ERROR, "cache lookup failed for operator %u", opoid);
11753  operform = (Form_pg_operator) GETSTRUCT(opertup);
11754  Assert(operform->oprkind == 'b');
11755  oprname = NameStr(operform->oprname);
11756 
11757  nspname = get_namespace_name(operform->oprnamespace);
11758 
11759  appendStringInfoString(buf, leftop);
11760  if (leftoptype != operform->oprleft)
11761  add_cast_to(buf, operform->oprleft);
11762  appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
11763  appendStringInfoString(buf, oprname);
11764  appendStringInfo(buf, ") %s", rightop);
11765  if (rightoptype != operform->oprright)
11766  add_cast_to(buf, operform->oprright);
11767 
11768  ReleaseSysCache(opertup);
11769 }
static void add_cast_to(StringInfo buf, Oid typid)
Definition: ruleutils.c:11780
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681

◆ generate_operator_name()

static char * generate_operator_name ( Oid  operid,
Oid  arg1,
Oid  arg2 
)
static

Definition at line 11663 of file ruleutils.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), buf, StringInfoData::data, elog, ERROR, get_namespace_name_or_temp(), GETSTRUCT, HeapTupleIsValid, initStringInfo(), left_oper(), list_make1, makeString(), NameStr, ObjectIdGetDatum, oper(), OPEROID, oprid(), quote_identifier(), ReleaseSysCache(), 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().

11664 {
11666  HeapTuple opertup;
11667  Form_pg_operator operform;
11668  char *oprname;
11669  char *nspname;
11670  Operator p_result;
11671 
11672  initStringInfo(&buf);
11673 
11674  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operid));
11675  if (!HeapTupleIsValid(opertup))
11676  elog(ERROR, "cache lookup failed for operator %u", operid);
11677  operform = (Form_pg_operator) GETSTRUCT(opertup);
11678  oprname = NameStr(operform->oprname);
11679 
11680  /*
11681  * The idea here is to schema-qualify only if the parser would fail to
11682  * resolve the correct operator given the unqualified op name with the
11683  * specified argtypes.
11684  */
11685  switch (operform->oprkind)
11686  {
11687  case 'b':
11688  p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
11689  true, -1);
11690  break;
11691  case 'l':
11692  p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
11693  true, -1);
11694  break;
11695  default:
11696  elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
11697  p_result = NULL; /* keep compiler quiet */
11698  break;
11699  }
11700 
11701  if (p_result != NULL && oprid(p_result) == operid)
11702  nspname = NULL;
11703  else
11704  {
11705  nspname = get_namespace_name_or_temp(operform->oprnamespace);
11706  appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
11707  }
11708 
11709  appendStringInfoString(&buf, oprname);
11710 
11711  if (nspname)
11712  appendStringInfoChar(&buf, ')');
11713 
11714  if (p_result != NULL)
11715  ReleaseSysCache(p_result);
11716 
11717  ReleaseSysCache(opertup);
11718 
11719  return buf.data;
11720 }
Value * makeString(char *str)
Definition: value.c:53
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
Oid oprid(Operator op)
Definition: parse_oper.c:250
#define list_make1(x1)
Definition: pg_list.h:206
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
Operator left_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
Definition: parse_oper.c:530
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3340
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:382

◆ generate_qualified_relation_name()

static char * generate_qualified_relation_name ( Oid  relid)
static

Definition at line 11516 of file ruleutils.c.

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

Referenced by make_ruledef(), pg_get_constraintdef_worker(), pg_get_indexdef_worker(), pg_get_serial_sequence(), and pg_get_triggerdef_worker().

11517 {
11518  HeapTuple tp;
11519  Form_pg_class reltup;
11520  char *relname;
11521  char *nspname;
11522  char *result;
11523 
11524  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
11525  if (!HeapTupleIsValid(tp))
11526  elog(ERROR, "cache lookup failed for relation %u", relid);
11527  reltup = (Form_pg_class) GETSTRUCT(tp);
11528  relname = NameStr(reltup->relname);
11529 
11530  nspname = get_namespace_name_or_temp(reltup->relnamespace);
11531  if (!nspname)
11532  elog(ERROR, "cache lookup failed for namespace %u",
11533  reltup->relnamespace);
11534 
11535  result = quote_qualified_identifier(nspname, relname);
11536 
11537  ReleaseSysCache(tp);
11538 
11539  return result;
11540 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
NameData relname
Definition: pg_class.h:38
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11416
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3340
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681

◆ generate_qualified_type_name()

static char * generate_qualified_type_name ( Oid  typid)
static

Definition at line 11811 of file ruleutils.c.

References elog, ERROR, get_namespace_name_or_temp(), GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, quote_qualified_identifier(), ReleaseSysCache(), SearchSysCache1(), TYPEOID, and typname.

Referenced by pg_get_constraintdef_worker().

11812 {
11813  HeapTuple tp;
11814  Form_pg_type typtup;
11815  char *typname;
11816  char *nspname;
11817  char *result;
11818 
11820  if (!HeapTupleIsValid(tp))
11821  elog(ERROR, "cache lookup failed for type %u", typid);
11822  typtup = (Form_pg_type) GETSTRUCT(tp);
11823  typname = NameStr(typtup->typname);
11824 
11825  nspname = get_namespace_name_or_temp(typtup->typnamespace);
11826  if (!nspname)
11827  elog(ERROR, "cache lookup failed for namespace %u",
11828  typtup->typnamespace);
11829 
11830  result = quote_qualified_identifier(nspname, typname);
11831 
11832  ReleaseSysCache(tp);
11833 
11834  return result;
11835 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
NameData typname
Definition: pg_type.h:41
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11416
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3340
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681

◆ generate_relation_name()

static char * generate_relation_name ( Oid  relid,
List namespaces 
)
static

Definition at line 11456 of file ruleutils.c.

References CommonTableExpr::ctename, deparse_namespace::ctes, elog, ERROR, get_namespace_name_or_temp(), GETSTRUCT, HeapTupleIsValid, lfirst, NameStr, ObjectIdGetDatum, quote_qualified_identifier(), RelationIsVisible(), ReleaseSysCache(), relname, RELOID, 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().

11457 {
11458  HeapTuple tp;
11459  Form_pg_class reltup;
11460  bool need_qual;
11461  ListCell *nslist;
11462  char *relname;
11463  char *nspname;
11464  char *result;
11465 
11466  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
11467  if (!HeapTupleIsValid(tp))
11468  elog(ERROR, "cache lookup failed for relation %u", relid);
11469  reltup = (Form_pg_class) GETSTRUCT(tp);
11470  relname = NameStr(reltup->relname);
11471 
11472  /* Check for conflicting CTE name */
11473  need_qual = false;
11474  foreach(nslist, namespaces)
11475  {
11476  deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
11477  ListCell *ctlist;
11478 
11479  foreach(ctlist, dpns->ctes)
11480  {
11481  CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
11482 
11483  if (strcmp(cte->ctename, relname) == 0)
11484  {
11485  need_qual = true;
11486  break;
11487  }
11488  }
11489  if (need_qual)
11490  break;
11491  }
11492 
11493  /* Otherwise, qualify the name if not visible in search path */
11494  if (!need_qual)
11495  need_qual = !RelationIsVisible(relid);
11496 
11497  if (need_qual)
11498  nspname = get_namespace_name_or_temp(reltup->relnamespace);
11499  else
11500  nspname = NULL;
11501 
11502  result = quote_qualified_identifier(nspname, relname);
11503 
11504  ReleaseSysCache(tp);
11505 
11506  return result;
11507 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
NameData relname
Definition: pg_class.h:38
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11416
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:169
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
bool RelationIsVisible(Oid relid)
Definition: namespace.c:709
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3340
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681

◆ get_agg_combine_expr()

static void get_agg_combine_expr ( Node node,
deparse_context context,
void *  callback_arg 
)
static

Definition at line 9792 of file ruleutils.c.

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

Referenced by get_agg_expr().

9793 {
9794  Aggref *aggref;
9795  Aggref *original_aggref = callback_arg;
9796 
9797  if (!IsA(node, Aggref))
9798  elog(ERROR, "combining Aggref does not point to an Aggref");
9799 
9800  aggref = (Aggref *) node;
9801  get_agg_expr(aggref, context, original_aggref);
9802 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define ERROR
Definition: elog.h:46
static void get_agg_expr(Aggref *aggref, deparse_context *context, Aggref *original_aggref)
Definition: ruleutils.c:9685
#define elog(elevel,...)
Definition: elog.h:232

◆ get_agg_expr()

static void get_agg_expr ( Aggref aggref,
deparse_context context,
Aggref original_aggref 
)
static

Definition at line 9685 of file ruleutils.c.

References Aggref::aggdirectargs, Aggref::aggdistinct, Aggref::aggfilter, Aggref::aggfnoid, Aggref::aggkind, 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, TargetEntry::resjunk, resolve_special_varno(), and deparse_context::special_exprkind.

Referenced by get_agg_combine_expr(), and get_rule_expr().

9687 {
9688  StringInfo buf = context->buf;
9689  Oid argtypes[FUNC_MAX_ARGS];
9690  int nargs;
9691  bool use_variadic;
9692 
9693  /*
9694  * For a combining aggregate, we look up and deparse the corresponding
9695  * partial aggregate instead. This is necessary because our input
9696  * argument list has been replaced; the new argument list always has just
9697  * one element, which will point to a partial Aggref that supplies us with
9698  * transition states to combine.
9699  */
9700  if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
9701  {
9702  TargetEntry *tle;
9703 
9704  Assert(list_length(aggref->args) == 1);
9705  tle = linitial_node(TargetEntry, aggref->args);
9706  resolve_special_varno((Node *) tle->expr, context,
9707  get_agg_combine_expr, original_aggref);
9708  return;
9709  }
9710 
9711  /*
9712  * Mark as PARTIAL, if appropriate. We look to the original aggref so as
9713  * to avoid printing this when recursing from the code just above.
9714  */
9715  if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
9716  appendStringInfoString(buf, "PARTIAL ");
9717 
9718  /* Extract the argument types as seen by the parser */
9719  nargs = get_aggregate_argtypes(aggref, argtypes);
9720 
9721  /* Print the aggregate name, schema-qualified if needed */
9722  appendStringInfo(buf, "%s(%s",
9723  generate_function_name(aggref->aggfnoid, nargs,
9724  NIL, argtypes,
9725  aggref->aggvariadic,
9726  &use_variadic,
9727  context->special_exprkind),
9728  (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
9729 
9730  if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
9731  {
9732  /*
9733  * Ordered-set aggregates do not use "*" syntax. Also, we needn't
9734  * worry about inserting VARIADIC. So we can just dump the direct
9735  * args as-is.
9736  */
9737  Assert(!aggref->aggvariadic);
9738  get_rule_expr((Node *) aggref->aggdirectargs, context, true);
9739  Assert(aggref->aggorder != NIL);
9740  appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
9741  get_rule_orderby(aggref->aggorder, aggref->args, false, context);
9742  }
9743  else
9744  {
9745  /* aggstar can be set only in zero-argument aggregates */
9746  if (aggref->aggstar)
9747  appendStringInfoChar(buf, '*');
9748  else
9749  {
9750  ListCell *l;
9751  int i;
9752 
9753  i = 0;
9754  foreach(l, aggref->args)
9755  {
9756  TargetEntry *tle = (TargetEntry *) lfirst(l);
9757  Node *arg = (Node *) tle->expr;
9758 
9759  Assert(!IsA(arg, NamedArgExpr));
9760  if (tle->resjunk)
9761  continue;
9762  if (i++ > 0)
9763  appendStringInfoString(buf, ", ");
9764  if (use_variadic && i == nargs)
9765  appendStringInfoString(buf, "VARIADIC ");
9766  get_rule_expr(arg, context, true);
9767  }
9768  }
9769 
9770  if (aggref->aggorder != NIL)
9771  {
9772  appendStringInfoString(buf, " ORDER BY ");
9773  get_rule_orderby(aggref->aggorder, aggref->args, false, context);
9774  }
9775  }
9776 
9777  if (aggref->aggfilter != NULL)
9778  {
9779  appendStringInfoString(buf, ") FILTER (WHERE ");
9780  get_rule_expr((Node *) aggref->aggfilter, context, false);
9781  }
9782 
9783  appendStringInfoChar(buf, ')');
9784 }
static void resolve_special_varno(Node *node, deparse_context *context, rsv_callback callback, void *callback_arg)
Definition: ruleutils.c:7185
List * aggdistinct
Definition: primnodes.h:332
#define NIL
Definition: pg_list.h:65
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:11558
bool aggvariadic
Definition: primnodes.h:335
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
static void get_rule_orderby(List *orderList, List *targetList, bool force_colno, deparse_context *context)
Definition: ruleutils.c:6222
Definition: nodes.h:539
List * args
Definition: primnodes.h:330
bool aggstar
Definition: primnodes.h:334
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:177
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:801
#define FUNC_MAX_ARGS
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
bool resjunk
Definition: primnodes.h:1461
static void get_agg_combine_expr(Node *node, deparse_context *context, void *callback_arg)
Definition: ruleutils.c:9792
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
List * aggorder
Definition: primnodes.h:331
List * aggdirectargs
Definition: primnodes.h:329
ParseExprKind special_exprkind
Definition: ruleutils.c:118
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
Oid aggfnoid
Definition: primnodes.h:323
#define Assert(condition)
Definition: c.h:804
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:8278
#define lfirst(lc)
Definition: pg_list.h:169
Expr * expr
Definition: primnodes.h:1454
AggSplit aggsplit
Definition: primnodes.h:339
static int list_length(const List *l)
Definition: pg_list.h:149
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:802
Expr * aggfilter
Definition: primnodes.h:333
StringInfo buf
Definition: ruleutils.c:110
int i
void * arg
char aggkind
Definition: primnodes.h:337
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:1887

◆ get_basic_select_query()

static void get_basic_select_query ( Query query,
deparse_context context,
TupleDesc  resultDesc 
)
static

Definition at line 5710 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::groupDistinct, Query::groupingSets, Query::hasDistinctOn, Query::havingQual, deparse_context::indentLevel, Query::isReturn, Query::jointree, lfirst, NIL, 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().

5712 {
5713  StringInfo buf = context->buf;
5714  RangeTblEntry *values_rte;
5715  char *sep;
5716  ListCell *l;
5717 
5718  if (PRETTY_INDENT(context))
5719  {
5720  context->indentLevel += PRETTYINDENT_STD;
5721  appendStringInfoChar(buf, ' ');
5722  }
5723 
5724  /*
5725  * If the query looks like SELECT * FROM (VALUES ...), then print just the
5726  * VALUES part. This reverses what transformValuesClause() did at parse
5727  * time.
5728  */
5729  values_rte = get_simple_values_rte(query, resultDesc);
5730  if (values_rte)
5731  {
5732  get_values_def(values_rte->values_lists, context);
5733  return;
5734  }
5735 
5736  /*
5737  * Build up the query string - first we say SELECT
5738  */
5739  if (query->isReturn)
5740  appendStringInfoString(buf, "RETURN");
5741  else
5742  appendStringInfoString(buf, "SELECT");
5743 
5744  /* Add the DISTINCT clause if given */
5745  if (query->distinctClause != NIL)
5746  {
5747  if (query->hasDistinctOn)
5748  {
5749  appendStringInfoString(buf, " DISTINCT ON (");
5750  sep = "";
5751  foreach(l, query->distinctClause)
5752  {
5753  SortGroupClause *srt = (SortGroupClause *) lfirst(l);
5754 
5755  appendStringInfoString(buf, sep);
5757  false, context);
5758  sep = ", ";
5759  }
5760  appendStringInfoChar(buf, ')');
5761  }
5762  else
5763  appendStringInfoString(buf, " DISTINCT");
5764  }
5765 
5766  /* Then we tell what to select (the targetlist) */
5767  get_target_list(query->targetList, context, resultDesc);
5768 
5769  /* Add the FROM clause if needed */
5770  get_from_clause(query, " FROM ", context);
5771 
5772  /* Add the WHERE clause if given */
5773  if (query->jointree->quals != NULL)
5774  {
5775  appendContextKeyword(context, " WHERE ",
5777  get_rule_expr(query->jointree->quals, context, false);
5778  }
5779 
5780  /* Add the GROUP BY clause if given */
5781  if (query->groupClause != NULL || query->groupingSets != NULL)
5782  {
5783  ParseExprKind save_exprkind;
5784 
5785  appendContextKeyword(context, " GROUP BY ",
5787  if (query->groupDistinct)
5788  appendStringInfoString(buf, "DISTINCT ");
5789 
5790  save_exprkind = context->special_exprkind;
5792 
5793  if (query->groupingSets == NIL)
5794  {
5795  sep = "";
5796  foreach(l, query->groupClause)
5797  {
5798  SortGroupClause *grp = (SortGroupClause *) lfirst(l);
5799 
5800  appendStringInfoString(buf, sep);
5802  false, context);
5803  sep = ", ";
5804  }
5805  }
5806  else
5807  {
5808  sep = "";
5809  foreach(l, query->groupingSets)
5810  {
5811  GroupingSet *grp = lfirst(l);
5812 
5813  appendStringInfoString(buf, sep);
5814  get_rule_groupingset(grp, query->targetList, true, context);
5815  sep = ", ";
5816  }
5817  }
5818 
5819  context->special_exprkind = save_exprkind;
5820  }
5821 
5822  /* Add the HAVING clause if given */
5823  if (query->havingQual != NULL)
5824  {
5825  appendContextKeyword(context, " HAVING ",
5827  get_rule_expr(query->havingQual, context, false);
5828  }
5829 
5830  /* Add the WINDOW clause if needed */
5831  if (query->windowClause != NIL)
5832  get_rule_windowclause(query, context);
5833 }
#define NIL
Definition: pg_list.h:65
FromExpr * jointree
Definition: parsenodes.h:148
bool groupDistinct
Definition: parsenodes.h:159
static void get_target_list(List *targetList, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5842
static Node * get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno, deparse_context *context)
Definition: ruleutils.c:6106
Index tleSortGroupRef
Definition: parsenodes.h:1283
List * groupingSets
Definition: parsenodes.h:161
static void get_from_clause(Query *query, const char *prefix, deparse_context *context)
Definition: ruleutils.c:10596
static void get_rule_windowclause(Query *query, deparse_context *context)
Definition: ruleutils.c:6280
#define PRETTY_INDENT(context)
Definition: ruleutils.c:98
ParseExprKind
Definition: parse_node.h:38
List * values_lists
Definition: parsenodes.h:1100
Node * quals
Definition: primnodes.h:1564
bool hasDistinctOn
Definition: parsenodes.h:137
List * windowClause
Definition: parsenodes.h:165
List * targetList
Definition: parsenodes.h:150
List * distinctClause
Definition: parsenodes.h:167
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:8173
static RangeTblEntry * get_simple_values_rte(Query *query, TupleDesc resultDesc)
Definition: ruleutils.c:5641
static void get_rule_groupingset(GroupingSet *gset, List *targetlist, bool omit_parens, deparse_context *context)
Definition: ruleutils.c:6162
#define PRETTYINDENT_STD
Definition: ruleutils.c:82
ParseExprKind special_exprkind
Definition: ruleutils.c:118
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
bool isReturn
Definition: parsenodes.h:143
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:8278
#define lfirst(lc)
Definition: pg_list.h:169
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:5329
List * groupClause
Definition: parsenodes.h:158
StringInfo buf
Definition: ruleutils.c:110
Node * havingQual
Definition: parsenodes.h:163

◆ get_coercion_expr()

static void get_coercion_expr ( Node arg,
deparse_context context,
Oid  resulttype,
int32  resulttypmod,
Node parentNode 
)
static

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

10128 {
10129  StringInfo buf = context->buf;
10130 
10131  /*
10132  * Since parse_coerce.c doesn't immediately collapse application of
10133  * length-coercion functions to constants, what we'll typically see in
10134  * such cases is a Const with typmod -1 and a length-coercion function
10135  * right above it. Avoid generating redundant output. However, beware of
10136  * suppressing casts when the user actually wrote something like
10137  * 'foo'::text::char(3).
10138  *
10139  * Note: it might seem that we are missing the possibility of needing to
10140  * print a COLLATE clause for such a Const. However, a Const could only
10141  * have nondefault collation in a post-constant-folding tree, in which the
10142  * length coercion would have been folded too. See also the special
10143  * handling of CollateExpr in coerce_to_target_type(): any collation
10144  * marking will be above the coercion node, not below it.
10145  */
10146  if (arg && IsA(arg, Const) &&
10147  ((Const *) arg)->consttype == resulttype &&
10148  ((Const *) arg)->consttypmod == -1)
10149  {
10150  /* Show the constant without normal ::typename decoration */
10151  get_const_expr((Const *) arg, context, -1);
10152  }
10153  else
10154  {
10155  if (!PRETTY_PAREN(context))
10156  appendStringInfoChar(buf, '(');
10157  get_rule_expr_paren(arg, context, false, parentNode);
10158  if (!PRETTY_PAREN(context))
10159  appendStringInfoChar(buf, ')');
10160  }
10161 
10162  /*
10163  * Never emit resulttype(arg) functional notation. A pg_proc entry could
10164  * take precedence, and a resulttype in pg_temp would require schema
10165  * qualification that format_type_with_typemod() would usually omit. We've
10166  * standardized on arg::resulttype, but CAST(arg AS resulttype) notation
10167  * would work fine.
10168  */
10169  appendStringInfo(buf, "::%s",
10170  format_type_with_typemod(resulttype, resulttypmod));
10171 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
static void get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
Definition: ruleutils.c:8246
static void get_const_expr(Const *constval, deparse_context *context, int showtype)
Definition: ruleutils.c:10189
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
static char * buf
Definition: pg_test_fsync.c:68
#define PRETTY_PAREN(context)
Definition: ruleutils.c:97
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:358
StringInfo buf
Definition: ruleutils.c:110

◆ get_column_alias_list()

static void get_column_alias_list ( deparse_columns colinfo,
deparse_context context 
)
static

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

11030 {
11031  StringInfo buf = context->buf;
11032  int i;
11033  bool first = true;
11034 
11035  /* Don't print aliases if not needed */
11036  if (!colinfo->printaliases)
11037  return;
11038 
11039  for (i = 0; i < colinfo->num_new_cols; i++)
11040  {
11041  char *colname = colinfo->new_colnames[i];
11042 
11043  if (first)
11044  {
11045  appendStringInfoChar(buf, '(');
11046  first = false;
11047  }
11048  else
11049  appendStringInfoString(buf, ", ");
11051  }
11052  if (!first)
11053  appendStringInfoChar(buf, ')');
11054 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
StringInfo buf
Definition: ruleutils.c:110
int i
char ** new_colnames
Definition: ruleutils.c:257

◆ get_const_collation()

static void get_const_collation ( Const constval,
deparse_context context 
)
static

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

10320 {
10321  StringInfo buf = context->buf;
10322 
10323  if (OidIsValid(constval->constcollid))
10324  {
10325  Oid typcollation = get_typcollation(constval->consttype);
10326 
10327  if (constval->constcollid != typcollation)
10328  {
10329  appendStringInfo(buf, " COLLATE %s",
10331  }
10332  }
10333 }
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:11844
Oid consttype
Definition: primnodes.h:215
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
Oid constcollid
Definition: primnodes.h:217
static char * buf
Definition: pg_test_fsync.c:68
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3003
StringInfo buf
Definition: ruleutils.c:110

◆ get_const_expr()

static void get_const_expr ( Const constval,
deparse_context context,
int  showtype 
)
static

Definition at line 10189 of file ruleutils.c.

References appendStringInfo(), appendStringInfoString(), buf, deparse_context::buf, Const::constisnull, Const::consttype, Const::consttypmod, Const::constvalue, format_type_with_typemod(), get_const_collation(), getTypeOutputInfo(), OidOutputFunctionCall(), pfree(), and simple_quote_literal().

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

10190 {
10191  StringInfo buf = context->buf;
10192  Oid typoutput;
10193  bool typIsVarlena;
10194  char *extval;
10195  bool needlabel = false;
10196 
10197  if (constval->constisnull)
10198  {
10199  /*
10200  * Always label the type of a NULL constant to prevent misdecisions
10201  * about type when reparsing.
10202  */
10203  appendStringInfoString(buf, "NULL");
10204  if (showtype >= 0)
10205  {
10206  appendStringInfo(buf, "::%s",
10208  constval->consttypmod));
10209  get_const_collation(constval, context);
10210  }
10211  return;
10212  }
10213 
10214  getTypeOutputInfo(constval->consttype,
10215  &typoutput, &typIsVarlena);
10216 
10217  extval = OidOutputFunctionCall(typoutput, constval->constvalue);
10218 
10219  switch (constval->consttype)
10220  {
10221  case INT4OID:
10222 
10223  /*
10224  * INT4 can be printed without any decoration, unless it is
10225  * negative; in that case print it as '-nnn'::integer to ensure
10226  * that the output will re-parse as a constant, not as a constant
10227  * plus operator. In most cases we could get away with printing
10228  * (-nnn) instead, because of the way that gram.y handles negative
10229  * literals; but that doesn't work for INT_MIN, and it doesn't
10230  * seem that much prettier anyway.
10231  */
10232  if (extval[0] != '-')
10233  appendStringInfoString(buf, extval);
10234  else
10235  {
10236  appendStringInfo(buf, "'%s'", extval);
10237  needlabel = true; /* we must attach a cast */
10238  }
10239  break;
10240 
10241  case NUMERICOID:
10242 
10243  /*
10244  * NUMERIC can be printed without quotes if it looks like a float
10245  * constant (not an integer, and not Infinity or NaN) and doesn't
10246  * have a leading sign (for the same reason as for INT4).
10247  */
10248  if (isdigit((unsigned char) extval[0]) &&
10249  strcspn(extval, "eE.") != strlen(extval))
10250  {
10251  appendStringInfoString(buf, extval);
10252  }
10253  else
10254  {
10255  appendStringInfo(buf, "'%s'", extval);
10256  needlabel = true; /* we must attach a cast */
10257  }
10258  break;
10259 
10260  case BOOLOID:
10261  if (strcmp(extval, "t") == 0)
10262  appendStringInfoString(buf, "true");
10263  else
10264  appendStringInfoString(buf, "false");
10265  break;
10266 
10267  default:
10268  simple_quote_literal(buf, extval);
10269  break;
10270  }
10271 
10272  pfree(extval);
10273 
10274  if (showtype < 0)
10275  return;
10276 
10277  /*
10278  * For showtype == 0, append ::typename unless the constant will be
10279  * implicitly typed as the right type when it is read in.
10280  *
10281  * XXX this code has to be kept in sync with the behavior of the parser,
10282  * especially make_const.
10283  */
10284  switch (constval->consttype)
10285  {
10286  case BOOLOID:
10287  case UNKNOWNOID:
10288  /* These types can be left unlabeled */
10289  needlabel = false;
10290  break;
10291  case INT4OID:
10292  /* We determined above whether a label is needed */
10293  break;
10294  case NUMERICOID:
10295 
10296  /*
10297  * Float-looking constants will be typed as numeric, which we
10298  * checked above; but if there's a nondefault typmod we need to
10299  * show it.
10300  */
10301  needlabel |= (constval->consttypmod >= 0);
10302  break;
10303  default:
10304  needlabel = true;
10305  break;
10306  }
10307  if (needlabel || showtype > 0)
10308  appendStringInfo(buf, "::%s",
10310  constval->consttypmod));
10311 
10312  get_const_collation(constval, context);
10313 }
Datum constvalue
Definition: primnodes.h:219
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2854
unsigned int Oid
Definition: postgres_ext.h:31
Oid consttype
Definition: primnodes.h:215
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
static void simple_quote_literal(StringInfo buf, const char *val)
Definition: ruleutils.c:10339
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static void get_const_collation(Const *constval, deparse_context *context)
Definition: ruleutils.c:10319
static char * buf
Definition: pg_test_fsync.c:68
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:358
int32 consttypmod
Definition: primnodes.h:216
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1653
StringInfo buf
Definition: ruleutils.c:110
bool constisnull
Definition: primnodes.h:220

◆ get_delete_query_def()

static void get_delete_query_def ( Query query,
deparse_context context 
)
static

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

6842 {
6843  StringInfo buf = context->buf;
6844  RangeTblEntry *rte;
6845 
6846  /* Insert the WITH clause if given */
6847  get_with_clause(query, context);
6848 
6849  /*
6850  * Start the query with DELETE FROM relname
6851  */
6852  rte = rt_fetch(query->resultRelation, query->rtable);
6853  Assert(rte->rtekind == RTE_RELATION);
6854  if (PRETTY_INDENT(context))
6855  {
6856  appendStringInfoChar(buf, ' ');
6857  context->indentLevel += PRETTYINDENT_STD;
6858  }
6859  appendStringInfo(buf, "DELETE FROM %s%s",
6860  only_marker(rte),
6862  if (rte->alias != NULL)
6863  appendStringInfo(buf, " %s",
6865 
6866  /* Add the USING clause if given */
6867  get_from_clause(query, " USING ", context);
6868 
6869  /* Add a WHERE clause if given */
6870  if (query->jointree->quals != NULL)
6871  {
6872  appendContextKeyword(context, " WHERE ",
6874  get_rule_expr(query->jointree->quals, context, false);
6875  }
6876 
6877  /* Add RETURNING if present */
6878  if (query->returningList)
6879  {
6880  appendContextKeyword(context, " RETURNING",
6882  get_target_list(query->returningList, context, NULL);
6883  }
6884 }
#define NIL
Definition: pg_list.h:65
static void get_with_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:5372
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
Alias * alias
Definition: parsenodes.h:1140
FromExpr * jointree
Definition: parsenodes.h:148
int resultRelation
Definition: parsenodes.h:130
static void get_target_list(List *targetList, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5842
static void get_from_clause(Query *query, const char *prefix, deparse_context *context)
Definition: ruleutils.c:10596
#define PRETTY_INDENT(context)
Definition: ruleutils.c:98
Node * quals
Definition: primnodes.h:1564
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:11456
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
List * rtable
Definition: parsenodes.h:147
static char * buf
Definition: pg_test_fsync.c:68
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:8173
List * returningList
Definition: parsenodes.h:156
#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:188
#define Assert(condition)
Definition: c.h:804
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:8278
char * aliasname
Definition: primnodes.h:42
#define only_marker(rte)
Definition: ruleutils.c:490
RTEKind rtekind
Definition: parsenodes.h:995
StringInfo buf
Definition: ruleutils.c:110

◆ get_from_clause()

static void get_from_clause ( Query query,
const char *  prefix,
deparse_context context 
)
static

Definition at line 10596 of file ruleutils.c.

References appendBinaryStringInfo(), appendContextKeyword(), appendStringInfoString(), buf, deparse_context::buf, StringInfoData::data, FromExpr::fromlist, get_from_clause_item(), RangeTblEntry::inFromCl, initStringInfo(), IsA, Query::jointree, StringInfoData::len, lfirst, 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().

10597 {
10598  StringInfo buf = context->buf;
10599  bool first = true;
10600  ListCell *l;
10601 
10602  /*
10603  * We use the query's jointree as a guide to what to print. However, we
10604  * must ignore auto-added RTEs that are marked not inFromCl. (These can
10605  * only appear at the top level of the jointree, so it's sufficient to
10606  * check here.) This check also ensures we ignore the rule pseudo-RTEs
10607  * for NEW and OLD.
10608  */
10609  foreach(l, query->jointree->fromlist)
10610  {
10611  Node *jtnode = (Node *) lfirst(l);
10612 
10613  if (IsA(jtnode, RangeTblRef))
10614  {
10615  int varno = ((RangeTblRef *) jtnode)->rtindex;
10616  RangeTblEntry *rte = rt_fetch(varno, query->rtable);
10617 
10618  if (!rte->inFromCl)
10619  continue;
10620  }
10621 
10622  if (first)
10623  {
10624  appendContextKeyword(context, prefix,
10626  first = false;
10627 
10628  get_from_clause_item(jtnode, query, context);
10629  }
10630  else
10631  {
10632  StringInfoData itembuf;
10633 
10634  appendStringInfoString(buf, ", ");
10635 
10636  /*
10637  * Put the new FROM item's text into itembuf so we can decide
10638  * after we've got it whether or not it needs to go on a new line.
10639  */
10640  initStringInfo(&itembuf);
10641  context->buf = &itembuf;
10642 
10643  get_from_clause_item(jtnode, query, context);
10644 
10645  /* Restore context's output buffer */
10646  context->buf = buf;
10647 
10648  /* Consider line-wrapping if enabled */
10649  if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
10650  {
10651  /* Does the new item start with a new line? */
10652  if (itembuf.len > 0 && itembuf.data[0] == '\n')
10653  {
10654  /* If so, we shouldn't add anything */
10655  /* instead, remove any trailing spaces currently in buf */
10657  }
10658  else
10659  {
10660  char *trailing_nl;
10661 
10662  /* Locate the start of the current line in the buffer */
10663  trailing_nl = strrchr(buf->data, '\n');
10664  if (trailing_nl == NULL)
10665  trailing_nl = buf->data;
10666  else
10667  trailing_nl++;
10668 
10669  /*
10670  * Add a newline, plus some indentation, if the new item
10671  * would cause an overflow.
10672  */
10673  if (strlen(trailing_nl) + itembuf.len > context->wrapColumn)
10674  appendContextKeyword(context, "", -PRETTYINDENT_STD,
10677  }
10678  }
10679 
10680  /* Add the new item */
10681  appendBinaryStringInfo(buf, itembuf.data, itembuf.len);
10682 
10683  /* clean up */
10684  pfree(itembuf.data);
10685  }
10686  }
10687 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
FromExpr * jointree
Definition: parsenodes.h:148
#define PRETTYINDENT_VAR
Definition: ruleutils.c:84
Definition: nodes.h:539
#define PRETTY_INDENT(context)
Definition: ruleutils.c:98
List * fromlist
Definition: primnodes.h:1563
void pfree(void *pointer)
Definition: mcxt.c:1169
List * rtable
Definition: parsenodes.h:147
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:8173
static void removeStringInfoSpaces(StringInfo str)
Definition: ruleutils.c:8227
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define PRETTYINDENT_STD
Definition: ruleutils.c:82
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define lfirst(lc)
Definition: pg_list.h:169
StringInfo buf
Definition: ruleutils.c:110
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
static void get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
Definition: ruleutils.c:10690

◆ get_from_clause_coldeflist()

static void get_from_clause_coldeflist ( RangeTblFunction rtfunc,
deparse_columns colinfo,
deparse_context context 
)
static

Definition at line 11069 of file ruleutils.c.

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

Referenced by get_from_clause_item().

11072 {
11073  StringInfo buf = context->buf;
11074  ListCell *l1;
11075  ListCell *l2;
11076  ListCell *l3;
11077  ListCell *l4;
11078  int i;
11079 
11080  appendStringInfoChar(buf, '(');
11081 
11082  i = 0;
11083  forfour(l1, rtfunc->funccoltypes,
11084  l2, rtfunc->funccoltypmods,
11085  l3, rtfunc->funccolcollations,
11086  l4, rtfunc->funccolnames)
11087  {
11088  Oid atttypid = lfirst_oid(l1);
11089  int32 atttypmod = lfirst_int(l2);
11090  Oid attcollation = lfirst_oid(l3);
11091  char *attname;
11092 
11093  if (colinfo)
11094  attname = colinfo->colnames[i];
11095  else
11096  attname = strVal(lfirst(l4));
11097 
11098  Assert(attname); /* shouldn't be any dropped columns here */
11099 
11100  if (i > 0)
11101  appendStringInfoString(buf, ", ");
11102  appendStringInfo(buf, "%s %s",
11103  quote_identifier(attname),
11104  format_type_with_typemod(atttypid, atttypmod));
11105  if (OidIsValid(attcollation) &&
11106  attcollation != get_typcollation(atttypid))
11107  appendStringInfo(buf, " COLLATE %s",
11108  generate_collation_name(attcollation));
11109 
11110  i++;
11111  }
11112 
11113  appendStringInfoChar(buf, ')');
11114 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
#define strVal(v)
Definition: value.h:54
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:11844
signed int int32
Definition: c.h:429
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
NameData attname
Definition: pg_attribute.h:41
#define lfirst_int(lc)
Definition: pg_list.h:170
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:358
List * funccoltypmods
Definition: parsenodes.h:1179
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3003
List * funccolcollations
Definition: parsenodes.h:1180
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
#define forfour(cell1, list1, cell2, list2, cell3, list3, cell4, list4)
Definition: pg_list.h:503
StringInfo buf
Definition: ruleutils.c:110
int i
#define lfirst_oid(lc)
Definition: pg_list.h:171
char ** colnames
Definition: ruleutils.c:240

◆ get_from_clause_item()

static void get_from_clause_item ( Node jtnode,
Query query,
deparse_context context 
)
static

Definition at line 10690 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::join_using_alias, JoinExpr::jointype, JoinExpr::larg, RangeTblEntry::lateral, lfirst, linitial, list_concat(), list_length(), deparse_context::namespaces, NIL, nodeTag, 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().

10691 {
10692  StringInfo buf = context->buf;
10694 
10695  if (IsA(jtnode, RangeTblRef))
10696  {
10697  int varno = ((RangeTblRef *) jtnode)->rtindex;
10698  RangeTblEntry *rte = rt_fetch(varno, query->rtable);
10699  char *refname = get_rtable_name(varno, context);
10700  deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
10701  RangeTblFunction *rtfunc1 = NULL;
10702  bool printalias;
10703 
10704  if (rte->lateral)
10705  appendStringInfoString(buf, "LATERAL ");
10706 
10707  /* Print the FROM item proper */
10708  switch (rte->rtekind)
10709  {
10710  case RTE_RELATION:
10711  /* Normal relation RTE */
10712  appendStringInfo(buf, "%s%s",
10713  only_marker(rte),
10715  context->namespaces));
10716  break;
10717  case RTE_SUBQUERY:
10718  /* Subquery RTE */
10719  appendStringInfoChar(buf, '(');
10720  get_query_def(rte->subquery, buf, context->namespaces, NULL,
10721  context->prettyFlags, context->wrapColumn,
10722  context->indentLevel);
10723  appendStringInfoChar(buf, ')');
10724  break;
10725  case RTE_FUNCTION:
10726  /* Function RTE */
10727  rtfunc1 = (RangeTblFunction *) linitial(rte->functions);
10728 
10729  /*
10730  * Omit ROWS FROM() syntax for just one function, unless it
10731  * has both a coldeflist and WITH ORDINALITY. If it has both,
10732  * we must use ROWS FROM() syntax to avoid ambiguity about
10733  * whether the coldeflist includes the ordinality column.
10734  */
10735  if (list_length(rte->functions) == 1 &&
10736  (rtfunc1->funccolnames == NIL || !rte->funcordinality))
10737  {
10738  get_rule_expr_funccall(rtfunc1->funcexpr, context, true);
10739  /* we'll print the coldeflist below, if it has one */
10740  }
10741  else
10742  {
10743  bool all_unnest;
10744  ListCell *lc;
10745 
10746  /*
10747  * If all the function calls in the list are to unnest,
10748  * and none need a coldeflist, then collapse the list back
10749  * down to UNNEST(args). (If we had more than one
10750  * built-in unnest function, this would get more
10751  * difficult.)
10752  *
10753  * XXX This is pretty ugly, since it makes not-terribly-
10754  * future-proof assumptions about what the parser would do
10755  * with the output; but the alternative is to emit our
10756  * nonstandard ROWS FROM() notation for what might have
10757  * been a perfectly spec-compliant multi-argument
10758  * UNNEST().
10759  */
10760  all_unnest = true;
10761  foreach(lc, rte->functions)
10762  {
10763  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
10764 
10765  if (!IsA(rtfunc->funcexpr, FuncExpr) ||
10766  ((FuncExpr *) rtfunc->funcexpr)->funcid != F_UNNEST_ANYARRAY ||
10767  rtfunc->funccolnames != NIL)
10768  {
10769  all_unnest = false;
10770  break;
10771  }
10772  }
10773 
10774  if (all_unnest)
10775  {
10776  List *allargs = NIL;
10777 
10778  foreach(lc, rte->functions)
10779  {
10780  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
10781  List *args = ((FuncExpr *) rtfunc->funcexpr)->args;
10782 
10783  allargs = list_concat(allargs, args);
10784  }
10785 
10786  appendStringInfoString(buf, "UNNEST(");
10787  get_rule_expr((Node *) allargs, context, true);
10788  appendStringInfoChar(buf, ')');
10789  }
10790  else
10791  {
10792  int funcno = 0;
10793 
10794  appendStringInfoString(buf, "ROWS FROM(");
10795  foreach(lc, rte->functions)
10796  {
10797  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
10798 
10799  if (funcno > 0)
10800  appendStringInfoString(buf, ", ");
10801  get_rule_expr_funccall(rtfunc->funcexpr, context, true);
10802  if (rtfunc->funccolnames != NIL)
10803  {
10804  /* Reconstruct the column definition list */
10805  appendStringInfoString(buf, " AS ");
10807  NULL,
10808  context);
10809  }
10810  funcno++;
10811  }
10812  appendStringInfoChar(buf, ')');
10813  }
10814  /* prevent printing duplicate coldeflist below */
10815  rtfunc1 = NULL;
10816  }
10817  if (rte->funcordinality)
10818  appendStringInfoString(buf, " WITH ORDINALITY");
10819  break;
10820  case RTE_TABLEFUNC:
10821  get_tablefunc(rte->tablefunc, context, true);
10822  break;
10823  case RTE_VALUES:
10824  /* Values list RTE */
10825  appendStringInfoChar(buf, '(');
10826  get_values_def(rte->values_lists, context);
10827  appendStringInfoChar(buf, ')');
10828  break;
10829  case RTE_CTE:
10831  break;
10832  default:
10833  elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
10834  break;
10835  }
10836 
10837  /* Print the relation alias, if needed */
10838  printalias = false;
10839  if (rte->alias != NULL)
10840  {
10841  /* Always print alias if user provided one */
10842  printalias = true;
10843  }
10844  else if (colinfo->printaliases)
10845  {
10846  /* Always print alias if we need to print column aliases */
10847  printalias = true;
10848  }
10849  else if (rte->rtekind == RTE_RELATION)
10850  {
10851  /*
10852  * No need to print alias if it's same as relation name (this
10853  * would normally be the case, but not if set_rtable_names had to
10854  * resolve a conflict).
10855  */
10856  if (strcmp(refname, get_relation_name(rte->relid)) != 0)
10857  printalias = true;
10858  }
10859  else if (rte->rtekind == RTE_FUNCTION)
10860  {
10861  /*
10862  * For a function RTE, always print alias. This covers possible
10863  * renaming of the function and/or instability of the
10864  * FigureColname rules for things that aren't simple functions.
10865  * Note we'd need to force it anyway for the columndef list case.
10866  */
10867  printalias = true;
10868  }
10869  else if (rte->rtekind == RTE_VALUES)
10870  {
10871  /* Alias is syntactically required for VALUES */
10872  printalias = true;
10873  }
10874  else if (rte->rtekind == RTE_CTE)
10875  {
10876  /*
10877  * No need to print alias if it's same as CTE name (this would
10878  * normally be the case, but not if set_rtable_names had to
10879  * resolve a conflict).
10880  */
10881  if (strcmp(refname, rte->ctename) != 0)
10882  printalias = true;
10883  }
10884  if (printalias)
10885  appendStringInfo(buf, " %s", quote_identifier(refname));
10886 
10887  /* Print the column definitions or aliases, if needed */
10888  if (rtfunc1 && rtfunc1->funccolnames != NIL)
10889  {
10890  /* Reconstruct the columndef list, which is also the aliases */
10891  get_from_clause_coldeflist(rtfunc1, colinfo, context);
10892  }
10893  else
10894  {
10895  /* Else print column aliases as needed */
10896  get_column_alias_list(colinfo, context);
10897  }
10898 
10899  /* Tablesample clause must go after any alias */
10900  if (rte->rtekind == RTE_RELATION && rte->tablesample)
10901  get_tablesample_def(rte->tablesample, context);
10902  }
10903  else if (IsA(jtnode, JoinExpr))
10904  {
10905  JoinExpr *j = (JoinExpr *) jtnode;
10906  deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
10907  bool need_paren_on_right;
10908 
10909  need_paren_on_right = PRETTY_PAREN(context) &&
10910  !IsA(j->rarg, RangeTblRef) &&
10911  !(IsA(j->rarg, JoinExpr) && ((JoinExpr *) j->rarg)->alias != NULL);
10912 
10913  if (!PRETTY_PAREN(context) || j->alias != NULL)
10914  appendStringInfoChar(buf, '(');
10915 
10916  get_from_clause_item(j->larg, query, context);
10917 
10918  switch (j->jointype)
10919  {
10920  case JOIN_INNER:
10921  if (j->quals)
10922  appendContextKeyword(context, " JOIN ",
10926  else
10927  appendContextKeyword(context, " CROSS JOIN ",
10931  break;
10932  case JOIN_LEFT:
10933  appendContextKeyword(context, " LEFT JOIN ",
10937  break;
10938  case JOIN_FULL:
10939  appendContextKeyword(context, " FULL JOIN ",
10943  break;
10944  case JOIN_RIGHT:
10945  appendContextKeyword(context, " RIGHT JOIN ",
10949  break;
10950  default:
10951  elog(ERROR, "unrecognized join type: %d",
10952  (int) j->jointype);
10953  }
10954 
10955  if (need_paren_on_right)
10956  appendStringInfoChar(buf, '(');
10957  get_from_clause_item(j->rarg, query, context);
10958  if (need_paren_on_right)
10959  appendStringInfoChar(buf, ')');
10960 
10961  if (j->usingClause)
10962  {
10963  ListCell *lc;
10964  bool first = true;
10965 
10966  appendStringInfoString(buf, " USING (");
10967  /* Use the assigned names, not what's in usingClause */
10968  foreach(lc, colinfo->usingNames)
10969  {
10970  char *colname = (char *) lfirst(lc);
10971 
10972  if (first)
10973  first = false;
10974  else
10975  appendStringInfoString(buf, ", ");
10977  }
10978  appendStringInfoChar(buf, ')');
10979 
10980  if (j->join_using_alias)
10981  appendStringInfo(buf, " AS %s",
10983  }
10984  else if (j->quals)
10985  {
10986  appendStringInfoString(buf, " ON ");
10987  if (!PRETTY_PAREN(context))
10988  appendStringInfoChar(buf, '(');
10989  get_rule_expr(j->quals, context, false);
10990  if (!PRETTY_PAREN(context))
10991  appendStringInfoChar(buf, ')');
10992  }
10993  else if (j->jointype != JOIN_INNER)
10994  {
10995  /* If we didn't say CROSS JOIN above, we must provide an ON */
10996  appendStringInfoString(buf, " ON TRUE");
10997  }
10998 
10999  if (!PRETTY_PAREN(context) || j->alias != NULL)
11000  appendStringInfoChar(buf, ')');
11001 
11002  /* Yes, it's correct to put alias after the right paren ... */
11003  if (j->alias != NULL)
11004  {
11005  /*
11006  * Note that it's correct to emit an alias clause if and only if
11007  * there was one originally. Otherwise we'd be converting a named
11008  * join to unnamed or vice versa, which creates semantic
11009  * subtleties we don't want. However, we might print a different
11010  * alias name than was there originally.
11011  */
11012  appendStringInfo(buf, " %s",
11014  context)));
11015  get_column_alias_list(colinfo, context);
11016  }
11017  }
11018  else
11019  elog(ERROR, "unrecognized node type: %d",
11020  (int) nodeTag(jtnode));
11021 }
List * namespaces
Definition: ruleutils.c:111
#define NIL
Definition: pg_list.h:65
static char * get_relation_name(Oid relid)
Definition: ruleutils.c:11436
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define PRETTYINDENT_JOIN
Definition: ruleutils.c:83
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
Alias * alias
Definition: parsenodes.h:1140
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
bool funcordinality
Definition: parsenodes.h:1090
List * values_lists
Definition: parsenodes.h:1100
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:11456
Node * larg
Definition: primnodes.h:1542
static void get_tablesample_def(TableSampleClause *tablesample, deparse_context *context)
Definition: ruleutils.c:11120
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define linitial(l)
Definition: pg_list.h:174
List * rtable
Definition: parsenodes.h:147
#define ERROR
Definition: elog.h:46
List * usingNames
Definition: ruleutils.c:287
TableFunc * tablefunc
Definition: parsenodes.h:1095
Alias * join_using_alias
Definition: primnodes.h:1545
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
#define PRETTY_PAREN(context)
Definition: ruleutils.c:97
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:8173
#define deparse_columns_fetch(rangetable_index, dpns)
Definition: ruleutils.c:291
#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:188
List * usingClause
Definition: primnodes.h:1544
Node * quals
Definition: primnodes.h:1546
static void get_tablefunc(TableFunc *tf, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:10491
Node * rarg
Definition: primnodes.h:1543
Alias * alias
Definition: primnodes.h:1547
JoinType jointype
Definition: primnodes.h:1540
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:8278
#define lfirst(lc)
Definition: pg_list.h:169
char * aliasname
Definition: primnodes.h:42
List * functions
Definition: parsenodes.h:1089
#define only_marker(rte)
Definition: ruleutils.c:490
static int list_length(const List *l)
Definition: pg_list.h:149
static void get_query_def(Query *query, StringInfo buf, List *parentnamespace, TupleDesc resultDesc, int prettyFlags, int wrapColumn, int startIndent)
Definition: ruleutils.c:5255
#define nodeTag(nodeptr)
Definition: nodes.h:544
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:5329
RTEKind rtekind
Definition: parsenodes.h:995
static void get_column_alias_list(deparse_columns *colinfo, deparse_context *context)
Definition: ruleutils.c:11029
char * ctename
Definition: parsenodes.h:1105
Query * subquery
Definition: parsenodes.h:1030
StringInfo buf
Definition: ruleutils.c:110
#define elog(elevel,...)
Definition: elog.h:232
static void get_from_clause_coldeflist(RangeTblFunction *rtfunc, deparse_columns *colinfo, deparse_context *context)
Definition: ruleutils.c:11069
static void get_rule_expr_funccall(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:9498
int rtindex
Definition: primnodes.h:1548
Definition: pg_list.h:50
struct TableSampleClause * tablesample
Definition: parsenodes.h:1025
static char * get_rtable_name(int rtindex, deparse_context *context)
Definition: ruleutils.c:4816
static void get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
Definition: ruleutils.c:10690

◆ get_func_expr()

static void get_func_expr ( FuncExpr expr,
deparse_context context,
bool  showimplicit 
)
static

Definition at line 9589 of file ruleutils.c.

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

Referenced by get_rule_expr().

9591 {
9592  StringInfo buf = context->buf;
9593  Oid funcoid = expr->funcid;
9594  Oid argtypes[FUNC_MAX_ARGS];
9595  int nargs;
9596  List *argnames;
9597  bool use_variadic;
9598  ListCell *l;
9599 
9600  /*
9601  * If the function call came from an implicit coercion, then just show the
9602  * first argument --- unless caller wants to see implicit coercions.
9603  */
9604  if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
9605  {
9606  get_rule_expr_paren((Node *) linitial(expr->args), context,
9607  false, (Node *) expr);
9608  return;
9609  }
9610 
9611  /*
9612  * If the function call came from a cast, then show the first argument
9613  * plus an explicit cast operation.
9614  */
9615  if (expr->funcformat == COERCE_EXPLICIT_CAST ||
9617  {
9618  Node *arg = linitial(expr->args);
9619  Oid rettype = expr->funcresulttype;
9620  int32 coercedTypmod;
9621 
9622  /* Get the typmod if this is a length-coercion function */
9623  (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
9624 
9625  get_coercion_expr(arg, context,
9626  rettype, coercedTypmod,
9627  (Node *) expr);
9628 
9629  return;
9630  }
9631 
9632  /*
9633  * If the function was called using one of the SQL spec's random special
9634  * syntaxes, try to reproduce that. If we don't recognize the function,
9635  * fall through.
9636  */
9637  if (expr->funcformat == COERCE_SQL_SYNTAX)
9638  {
9639  if (get_func_sql_syntax(expr, context))
9640  return;
9641  }
9642 
9643  /*
9644  * Normal function: display as proname(args). First we need to extract
9645  * the argument datatypes.
9646  */
9647  if (list_length(expr->args) > FUNC_MAX_ARGS)
9648  ereport(ERROR,
9649  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
9650  errmsg("too many arguments")));
9651  nargs = 0;
9652  argnames = NIL;
9653  foreach(l, expr->args)
9654  {
9655  Node *arg = (Node *) lfirst(l);
9656 
9657  if (IsA(arg, NamedArgExpr))
9658  argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
9659  argtypes[nargs] = exprType(arg);
9660  nargs++;
9661  }
9662 
9663  appendStringInfo(buf, "%s(",
9664  generate_function_name(funcoid, nargs,
9665  argnames, argtypes,
9666  expr->funcvariadic,
9667  &use_variadic,
9668  context->special_exprkind));
9669  nargs = 0;
9670  foreach(l, expr->args)
9671  {
9672  if (nargs++ > 0)
9673  appendStringInfoString(buf, ", ");
9674  if (use_variadic && lnext(expr->args, l) == NULL)
9675  appendStringInfoString(buf, "VARIADIC ");
9676  get_rule_expr((Node *) lfirst(l), context, true);
9677  }
9678  appendStringInfoChar(buf, ')');
9679 }
Oid funcresulttype
Definition: primnodes.h:496
#define NIL
Definition: pg_list.h:65
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:11558
static bool get_func_sql_syntax(FuncExpr *expr, deparse_context *context)
Definition: ruleutils.c:9885
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
static void get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
Definition: ruleutils.c:8246
List * args
Definition: primnodes.h:503
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
bool exprIsLengthCoercion(const Node *expr, int32 *coercedTypmod)
Definition: nodeFuncs.c:503
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:429
#define FUNC_MAX_ARGS
CoercionForm funcformat
Definition: primnodes.h:500
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define linitial(l)
Definition: pg_list.h:174
Oid funcid
Definition: primnodes.h:495
#define ERROR
Definition: elog.h:46
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
static void get_coercion_expr(Node *arg, deparse_context *context, Oid resulttype, int32 resulttypmod, Node *parentNode)
Definition: ruleutils.c:10125
ParseExprKind special_exprkind
Definition: ruleutils.c:118
List * lappend(List *list, void *datum)
Definition: list.c:336
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
#define ereport(elevel,...)
Definition: elog.h:157
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:8278
#define lfirst(lc)
Definition: pg_list.h:169
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
StringInfo buf
Definition: ruleutils.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:909
void * arg
Definition: pg_list.h:50
bool funcvariadic
Definition: primnodes.h:498

◆ get_func_sql_syntax()

static bool get_func_sql_syntax ( FuncExpr expr,
deparse_context context 
)
static

Definition at line 9885 of file ruleutils.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), FuncExpr::args, Assert, buf, deparse_context::buf, Const::constisnull, Const::consttype, Const::constvalue, FuncExpr::funcid, get_rule_expr(), IsA, lfourth, linitial, list_length(), lsecond, lthird, and TextDatumGetCString.

Referenced by get_func_expr().

9886 {
9887  StringInfo buf = context->buf;
9888  Oid funcoid = expr->funcid;
9889 
9890  switch (funcoid)
9891  {
9892  case F_TIMEZONE_INTERVAL_TIMESTAMP:
9893  case F_TIMEZONE_INTERVAL_TIMESTAMPTZ:
9894  case F_TIMEZONE_INTERVAL_TIMETZ:
9895  case F_TIMEZONE_TEXT_TIMESTAMP:
9896  case F_TIMEZONE_TEXT_TIMESTAMPTZ:
9897  case F_TIMEZONE_TEXT_TIMETZ:
9898  /* AT TIME ZONE ... note reversed argument order */
9899  appendStringInfoChar(buf, '(');
9900  get_rule_expr((Node *) lsecond(expr->args), context, false);
9901  appendStringInfoString(buf, " AT TIME ZONE ");
9902  get_rule_expr((Node *) linitial(expr->args), context, false);
9903  appendStringInfoChar(buf, ')');
9904  return true;
9905 
9906  case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_INTERVAL:
9907  case F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_TIMESTAMPTZ:
9908  case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL:
9909  case F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ:
9910  case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_INTERVAL:
9911  case F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_TIMESTAMP:
9912  case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_INTERVAL:
9913  case F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_TIMESTAMP:
9914  case F_OVERLAPS_TIMETZ_TIMETZ_TIMETZ_TIMETZ:
9915  case F_OVERLAPS_TIME_INTERVAL_TIME_INTERVAL:
9916  case F_OVERLAPS_TIME_INTERVAL_TIME_TIME:
9917  case F_OVERLAPS_TIME_TIME_TIME_INTERVAL:
9918  case F_OVERLAPS_TIME_TIME_TIME_TIME:
9919  /* (x1, x2) OVERLAPS (y1, y2) */
9920  appendStringInfoString(buf, "((");
9921  get_rule_expr((Node *) linitial(expr->args), context, false);
9922  appendStringInfoString(buf, ", ");
9923  get_rule_expr((Node *) lsecond(expr->args), context, false);
9924  appendStringInfoString(buf, ") OVERLAPS (");
9925  get_rule_expr((Node *) lthird(expr->args), context, false);
9926  appendStringInfoString(buf, ", ");
9927  get_rule_expr((Node *) lfourth(expr->args), context, false);
9928  appendStringInfoString(buf, "))");
9929  return true;
9930 
9931  case F_EXTRACT_TEXT_DATE:
9932  case F_EXTRACT_TEXT_TIME:
9933  case F_EXTRACT_TEXT_TIMETZ:
9934  case F_EXTRACT_TEXT_TIMESTAMP:
9935  case F_EXTRACT_TEXT_TIMESTAMPTZ:
9936  case F_EXTRACT_TEXT_INTERVAL:
9937  /* EXTRACT (x FROM y) */
9938  appendStringInfoString(buf, "EXTRACT(");
9939  {
9940  Const *con = (Const *) linitial(expr->args);
9941 
9942  Assert(IsA(con, Const) &&
9943  con->consttype == TEXTOID &&
9944  !con->constisnull);
9946  }
9947  appendStringInfoString(buf, " FROM ");
9948  get_rule_expr((Node *) lsecond(expr->args), context, false);
9949  appendStringInfoChar(buf, ')');
9950  return true;
9951 
9952  case F_IS_NORMALIZED:
9953  /* IS xxx NORMALIZED */
9954  appendStringInfoString(buf, "((");
9955  get_rule_expr((Node *) linitial(expr->args), context, false);
9956  appendStringInfoString(buf, ") IS");
9957  if (list_length(expr->args) == 2)
9958  {
9959  Const *con = (Const *) lsecond(expr->args);
9960 
9961  Assert(IsA(con, Const) &&
9962  con->consttype == TEXTOID &&
9963  !con->constisnull);
9964  appendStringInfo(buf, " %s",
9966  }
9967  appendStringInfoString(buf, " NORMALIZED)");
9968  return true;
9969 
9970  case F_PG_COLLATION_FOR:
9971  /* COLLATION FOR */
9972  appendStringInfoString(buf, "COLLATION FOR (");
9973  get_rule_expr((Node *) linitial(expr->args), context, false);
9974  appendStringInfoChar(buf, ')');
9975  return true;
9976 
9977  /*
9978  * XXX EXTRACT, a/k/a date_part(), is intentionally not covered
9979  * yet. Add it after we change the return type to numeric.
9980  */
9981 
9982  case F_NORMALIZE:
9983  /* NORMALIZE() */
9984  appendStringInfoString(buf, "NORMALIZE(");
9985  get_rule_expr((Node *) linitial(expr->args), context, false);
9986  if (list_length(expr->args) == 2)
9987  {
9988  Const *con = (Const *) lsecond(expr->args);
9989 
9990  Assert(IsA(con, Const) &&
9991  con->consttype == TEXTOID &&
9992  !con->constisnull);
9993  appendStringInfo(buf, ", %s",
9995  }
9996  appendStringInfoChar(buf, ')');
9997  return true;
9998 
9999  case F_OVERLAY_BIT_BIT_INT4:
10000  case F_OVERLAY_BIT_BIT_INT4_INT4:
10001  case F_OVERLAY_BYTEA_BYTEA_INT4:
10002  case F_OVERLAY_BYTEA_BYTEA_INT4_INT4:
10003  case F_OVERLAY_TEXT_TEXT_INT4:
10004  case F_OVERLAY_TEXT_TEXT_INT4_INT4:
10005  /* OVERLAY() */
10006  appendStringInfoString(buf, "OVERLAY(");
10007  get_rule_expr((Node *) linitial(expr->args), context, false);
10008  appendStringInfoString(buf, " PLACING ");
10009  get_rule_expr((Node *) lsecond(expr->args), context, false);
10010  appendStringInfoString(buf, " FROM ");
10011  get_rule_expr((Node *) lthird(expr->args), context, false);
10012  if (list_length(expr->args) == 4)
10013  {
10014  appendStringInfoString(buf, " FOR ");
10015  get_rule_expr((Node *) lfourth(expr->args), context, false);
10016  }
10017  appendStringInfoChar(buf, ')');
10018  return true;
10019 
10020  case F_POSITION_BIT_BIT:
10021  case F_POSITION_BYTEA_BYTEA:
10022  case F_POSITION_TEXT_TEXT:
10023  /* POSITION() ... extra parens since args are b_expr not a_expr */
10024  appendStringInfoString(buf, "POSITION((");
10025  get_rule_expr((Node *) lsecond(expr->args), context, false);
10026  appendStringInfoString(buf, ") IN (");
10027  get_rule_expr((Node *) linitial(expr->args), context, false);
10028  appendStringInfoString(buf, "))");
10029  return true;
10030 
10031  case F_SUBSTRING_BIT_INT4:
10032  case F_SUBSTRING_BIT_INT4_INT4:
10033  case F_SUBSTRING_BYTEA_INT4:
10034  case F_SUBSTRING_BYTEA_INT4_INT4:
10035  case F_SUBSTRING_TEXT_INT4:
10036  case F_SUBSTRING_TEXT_INT4_INT4:
10037  /* SUBSTRING FROM/FOR (i.e., integer-position variants) */
10038  appendStringInfoString(buf, "SUBSTRING(");
10039  get_rule_expr((Node *) linitial(expr->args), context, false);
10040  appendStringInfoString(buf, " FROM ");
10041  get_rule_expr((Node *) lsecond(expr->args), context, false);
10042  if (list_length(expr->args) == 3)
10043  {
10044  appendStringInfoString(buf, " FOR ");
10045  get_rule_expr((Node *) lthird(expr->args), context, false);
10046  }
10047  appendStringInfoChar(buf, ')');
10048  return true;
10049 
10050  case F_SUBSTRING_TEXT_TEXT_TEXT:
10051  /* SUBSTRING SIMILAR/ESCAPE */
10052  appendStringInfoString(buf, "SUBSTRING(");
10053  get_rule_expr((Node *) linitial(expr->args), context, false);
10054  appendStringInfoString(buf, " SIMILAR ");
10055  get_rule_expr((Node *) lsecond(expr->args), context, false);
10056  appendStringInfoString(buf, " ESCAPE ");
10057  get_rule_expr((Node *) lthird(expr->args), context, false);
10058  appendStringInfoChar(buf, ')');
10059  return true;
10060 
10061  case F_BTRIM_BYTEA_BYTEA:
10062  case F_BTRIM_TEXT:
10063  case F_BTRIM_TEXT_TEXT:
10064  /* TRIM() */
10065  appendStringInfoString(buf, "TRIM(BOTH");
10066  if (list_length(expr->args) == 2)
10067  {
10068  appendStringInfoChar(buf, ' ');
10069  get_rule_expr((Node *) lsecond(expr->args), context, false);
10070  }
10071  appendStringInfoString(buf, " FROM ");
10072  get_rule_expr((Node *) linitial(expr->args), context, false);
10073  appendStringInfoChar(buf, ')');
10074  return true;
10075 
10076  case F_LTRIM_BYTEA_BYTEA:
10077  case F_LTRIM_TEXT:
10078  case F_LTRIM_TEXT_TEXT:
10079  /* TRIM() */
10080  appendStringInfoString(buf, "TRIM(LEADING");
10081  if (list_length(expr->args) == 2)
10082  {
10083  appendStringInfoChar(buf, ' ');
10084  get_rule_expr((Node *) lsecond(expr->args), context, false);
10085  }
10086  appendStringInfoString(buf, " FROM ");
10087  get_rule_expr((Node *) linitial(expr->args), context, false);
10088  appendStringInfoChar(buf, ')');
10089  return true;
10090 
10091  case F_RTRIM_BYTEA_BYTEA:
10092  case F_RTRIM_TEXT:
10093  case F_RTRIM_TEXT_TEXT:
10094  /* TRIM() */
10095  appendStringInfoString(buf, "TRIM(TRAILING");
10096  if (list_length(expr->args) == 2)
10097  {
10098  appendStringInfoChar(buf, ' ');
10099  get_rule_expr((Node *) lsecond(expr->args), context, false);
10100  }
10101  appendStringInfoString(buf, " FROM ");
10102  get_rule_expr((Node *) linitial(expr->args), context, false);
10103  appendStringInfoChar(buf, ')');
10104  return true;
10105 
10106  case F_XMLEXISTS:
10107  /* XMLEXISTS ... extra parens because args are c_expr */
10108  appendStringInfoString(buf, "XMLEXISTS((");
10109  get_rule_expr((Node *) linitial(expr->args), context, false);
10110  appendStringInfoString(buf, ") PASSING (");
10111  get_rule_expr((Node *) lsecond(expr->args), context, false);
10112  appendStringInfoString(buf, "))");
10113  return true;
10114  }
10115  return false;
10116 }
Datum constvalue
Definition: primnodes.h:219
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
List * args
Definition: primnodes.h:503
Definition: nodes.h:539
unsigned int Oid
Definition: postgres_ext.h:31
#define lsecond(l)
Definition: pg_list.h:179
Oid consttype
Definition: primnodes.h:215
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define linitial(l)
Definition: pg_list.h:174
Oid funcid
Definition: primnodes.h:495
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
#define TextDatumGetCString(d)
Definition: builtins.h:83
#define Assert(condition)
Definition: c.h:804
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:8278
#define lfourth(l)
Definition: pg_list.h:189
static int list_length(const List *l)
Definition: pg_list.h:149
StringInfo buf
Definition: ruleutils.c:110
#define lthird(l)
Definition: pg_list.h:184
bool constisnull
Definition: primnodes.h:220

◆ get_insert_query_def()

static void get_insert_query_def ( Query query,
deparse_context context 
)
static

Definition at line 6421 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_attname(), get_constraint_name(), get_query_def(), get_rule_expr(), get_target_list(), get_update_query_targetlist_def(), get_values_def(), get_with_clause(), deparse_context::indentLevel, lappend(), lfirst, NIL, 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().

6422 {
6423  StringInfo buf = context->buf;
6424  RangeTblEntry *select_rte = NULL;
6425  RangeTblEntry *values_rte = NULL;
6426  RangeTblEntry *rte;
6427  char *sep;
6428  ListCell *l;
6429  List *strippedexprs;
6430 
6431  /* Insert the WITH clause if given */
6432  get_with_clause(query, context);
6433 
6434  /*
6435  * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
6436  * single RTE for the SELECT or VALUES. Plain VALUES has neither.
6437  */
6438  foreach(l, query->rtable)
6439  {
6440  rte = (RangeTblEntry *) lfirst(l);
6441 
6442  if (rte->rtekind == RTE_SUBQUERY)
6443  {
6444  if (select_rte)
6445  elog(ERROR, "too many subquery RTEs in INSERT");
6446  select_rte = rte;
6447  }
6448 
6449  if (rte->rtekind == RTE_VALUES)
6450  {
6451  if (values_rte)
6452  elog(ERROR, "too many values RTEs in INSERT");
6453  values_rte = rte;
6454  }
6455  }
6456  if (select_rte && values_rte)
6457  elog(ERROR, "both subquery and values RTEs in INSERT");
6458 
6459  /*
6460  * Start the query with INSERT INTO relname
6461  */
6462  rte = rt_fetch(query->resultRelation, query->rtable);
6463  Assert(rte->rtekind == RTE_RELATION);
6464 
6465  if (PRETTY_INDENT(context))
6466  {
6467  context->indentLevel += PRETTYINDENT_STD;
6468  appendStringInfoChar(buf, ' ');
6469  }
6470  appendStringInfo(buf, "INSERT INTO %s ",
6472  /* INSERT requires AS keyword for target alias */
6473  if (rte->alias != NULL)
6474  appendStringInfo(buf, "AS %s ",
6476 
6477  /*
6478  * Add the insert-column-names list. Any indirection decoration needed on
6479  * the column names can be inferred from the top targetlist.
6480  */
6481  strippedexprs = NIL;
6482  sep = "";
6483  if (query->targetList)
6484  appendStringInfoChar(buf, '(');
6485  foreach(l, query->targetList)
6486  {
6487  TargetEntry *tle = (TargetEntry *) lfirst(l);
6488 
6489  if (tle->resjunk)
6490  continue; /* ignore junk entries */
6491 
6492  appendStringInfoString(buf, sep);
6493  sep = ", ";
6494 
6495  /*
6496  * Put out name of target column; look in the catalogs, not at
6497  * tle->resname, since resname will fail to track RENAME.
6498  */
6501  tle->resno,
6502  false)));
6503 
6504  /*
6505  * Print any indirection needed (subfields or subscripts), and strip
6506  * off the top-level nodes representing the indirection assignments.
6507  * Add the stripped expressions to strippedexprs. (If it's a
6508  * single-VALUES statement, the stripped expressions are the VALUES to
6509  * print below. Otherwise they're just Vars and not really
6510  * interesting.)
6511  */
6512  strippedexprs = lappend(strippedexprs,
6513  processIndirection((Node *) tle->expr,
6514  context));
6515  }
6516  if (query->targetList)
6517  appendStringInfoString(buf, ") ");
6518 
6519  if (query->override)
6520  {
6521  if (query->override == OVERRIDING_SYSTEM_VALUE)
6522  appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
6523  else if (query->override == OVERRIDING_USER_VALUE)
6524  appendStringInfoString(buf, "OVERRIDING USER VALUE ");
6525  }
6526 
6527  if (select_rte)
6528  {
6529  /* Add the SELECT */
6530  get_query_def(select_rte->subquery, buf, NIL, NULL,
6531  context->prettyFlags, context->wrapColumn,
6532  context->indentLevel);
6533  }
6534  else if (values_rte)
6535  {
6536  /* Add the multi-VALUES expression lists */
6537  get_values_def(values_rte->values_lists, context);
6538  }
6539  else if (strippedexprs)
6540  {
6541  /* Add the single-VALUES expression list */
6542  appendContextKeyword(context, "VALUES (",
6544  get_rule_expr((Node *) strippedexprs, context, false);
6545  appendStringInfoChar(buf, ')');
6546  }
6547  else
6548  {
6549  /* No expressions, so it must be DEFAULT VALUES */
6550  appendStringInfoString(buf, "DEFAULT VALUES");
6551  }
6552 
6553  /* Add ON CONFLICT if present */
6554  if (query->onConflict)
6555  {
6556  OnConflictExpr *confl = query->onConflict;
6557 
6558  appendStringInfoString(buf, " ON CONFLICT");
6559 
6560  if (confl->arbiterElems)
6561  {
6562  /* Add the single-VALUES expression list */
6563  appendStringInfoChar(buf, '(');
6564  get_rule_expr((Node *) confl->arbiterElems, context, false);
6565  appendStringInfoChar(buf, ')');
6566 
6567  /* Add a WHERE clause (for partial indexes) if given */
6568  if (confl->arbiterWhere != NULL)
6569  {
6570  bool save_varprefix;
6571 
6572  /*
6573  * Force non-prefixing of Vars, since parser assumes that they
6574  * belong to target relation. WHERE clause does not use
6575  * InferenceElem, so this is separately required.
6576  */
6577  save_varprefix = context->varprefix;
6578  context->varprefix = false;
6579 
6580  appendContextKeyword(context, " WHERE ",
6582  get_rule_expr(confl->arbiterWhere, context, false);
6583 
6584  context->varprefix = save_varprefix;
6585  }
6586  }
6587  else if (OidIsValid(confl->constraint))
6588  {
6589  char *constraint = get_constraint_name(confl->constraint);
6590 
6591  if (!constraint)
6592  elog(ERROR, "cache lookup failed for constraint %u",
6593  confl->constraint);
6594  appendStringInfo(buf, " ON CONSTRAINT %s",
6595  quote_identifier(constraint));
6596  }
6597 
6598  if (confl->action == ONCONFLICT_NOTHING)
6599  {
6600  appendStringInfoString(buf, " DO NOTHING");
6601  }
6602  else
6603  {
6604  appendStringInfoString(buf, " DO UPDATE SET ");
6605  /* Deparse targetlist */
6607  context, rte);
6608 
6609  /* Add a WHERE clause if given */
6610  if (confl->onConflictWhere != NULL)
6611  {
6612  appendContextKeyword(context, " WHERE ",
6614  get_rule_expr(confl->onConflictWhere, context, false);
6615  }
6616  }
6617  }
6618 
6619  /* Add RETURNING if present */
6620  if (query->returningList)
6621  {
6622  appendContextKeyword(context, " RETURNING",
6624  get_target_list(query->returningList, context, NULL);
6625  }
6626 }
#define NIL
Definition: pg_list.h:65
static void get_with_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:5372
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
Alias * alias
Definition: parsenodes.h:1140
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:1106
OnConflictExpr * onConflict
Definition: parsenodes.h:154
static Node * processIndirection(Node *node, deparse_context *context)
Definition: ruleutils.c:11224
int resultRelation
Definition: parsenodes.h:130
static void get_target_list(List *targetList, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5842
Definition: nodes.h:539
#define PRETTY_INDENT(context)
Definition: ruleutils.c:98
static void get_update_query_targetlist_def(Query *query, List *targetList, deparse_context *context, RangeTblEntry *rte)
Definition: ruleutils.c:6689
#define OidIsValid(objectId)
Definition: c.h:710
List * values_lists
Definition: parsenodes.h:1100
List * targetList
Definition: parsenodes.h:150
List * arbiterElems
Definition: primnodes.h:1582
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:11456
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
bool resjunk
Definition: primnodes.h:1461
List * rtable
Definition: parsenodes.h:147
#define ERROR
Definition: elog.h:46
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:8173
AttrNumber resno
Definition: primnodes.h:1455
List * returningList
Definition: parsenodes.h:156
#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:336
OnConflictAction action
Definition: primnodes.h:1579
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
OverridingKind override
Definition: parsenodes.h:152
#define Assert(condition)
Definition: c.h:804
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:8278
#define lfirst(lc)
Definition: pg_list.h:169
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1454
static void get_query_def(Query *query, StringInfo buf, List *parentnamespace, TupleDesc resultDesc, int prettyFlags, int wrapColumn, int startIndent)
Definition: ruleutils.c:5255
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:5329
RTEKind rtekind
Definition: parsenodes.h:995
Node * arbiterWhere
Definition: primnodes.h:1584
Query * subquery
Definition: parsenodes.h:1030
StringInfo buf
Definition: ruleutils.c:110
#define elog(elevel,...)
Definition: elog.h:232
List * onConflictSet
Definition: primnodes.h:1588
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
Node * onConflictWhere
Definition: primnodes.h:1589
Definition: pg_list.h:50

◆ get_name_for_var_field()

static const char* get_name_for_var_field ( Var var,
int  fieldno,
int  levelsup,
deparse_context context 
)
static

Definition at line 7293 of file ruleutils.c.

References Alias::aliasname, Assert, attname, attnum, RowExpr::colnames, RangeTblEntry::ctelevelsup, RangeTblEntry::ctename, CommonTableExpr::ctename, CommonTableExpr::ctequery, deparse_namespace::ctes, elog, RangeTblEntry::eref, ERROR, TargetEntry::expr, find_param_referent(), get_expr_result_tupdesc(), get_rte_attribute_name(), get_tle_by_resno(), GetCTETargetList, deparse_namespace::index_tlist, INDEX_VAR, deparse_namespace::inner_plan, deparse_namespace::inner_tlist, INNER_VAR, InvalidAttrNumber, IsA, RangeTblEntry::joinaliasvars, lcons(), lfirst, list_copy_tail(), list_delete_first(), list_length(), list_nth(), deparse_context::namespaces, NameStr, NIL, deparse_namespace::outer_plan, deparse_namespace::outer_tlist, OUTER_VAR, deparse_namespace::plan, pop_ancestor_plan(), pop_child_plan(), push_ancestor_plan(), push_child_plan(), TargetEntry::resjunk, rt_fetch, deparse_namespace::rtable, RTE_CTE, RTE_FUNCTION, RTE_JOIN, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, set_deparse_for_query(), strVal, RangeTblEntry::subquery, Query::targetList, TupleDescAttr, Var::varattno, Var::varattnosyn, Var::varlevelsup, Var::varno, Var::varnosyn, and Var::vartype.

Referenced by get_rule_expr().

7295 {
7296  RangeTblEntry *rte;
7298  int netlevelsup;
7299  deparse_namespace *dpns;
7300  Index varno;
7301  AttrNumber varattno;
7302  TupleDesc tupleDesc;
7303  Node *expr;
7304 
7305  /*
7306  * If it's a RowExpr that was expanded from a whole-row Var, use the
7307  * column names attached to it.
7308  */
7309  if (IsA(var, RowExpr))
7310  {
7311  RowExpr *r = (RowExpr *) var;
7312 
7313  if (fieldno > 0 && fieldno <= list_length(r->colnames))
7314  return strVal(list_nth(r->colnames, fieldno - 1));
7315  }
7316 
7317  /*
7318  * If it's a Param of type RECORD, try to find what the Param refers to.
7319  */
7320  if (IsA(var, Param))
7321  {
7322  Param *param = (Param *) var;
7323  ListCell *ancestor_cell;
7324 
7325  expr = find_param_referent(param, context, &dpns, &ancestor_cell);
7326  if (expr)
7327  {
7328  /* Found a match, so recurse to decipher the field name */
7329  deparse_namespace save_dpns;
7330  const char *result;
7331 
7332  push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
7333  result = get_name_for_var_field((Var *) expr, fieldno,
7334  0, context);
7335  pop_ancestor_plan(dpns, &save_dpns);
7336  return result;
7337  }
7338  }
7339 
7340  /*
7341  * If it's a Var of type RECORD, we have to find what the Var refers to;
7342  * if not, we can use get_expr_result_tupdesc().
7343  */
7344  if (!IsA(var, Var) ||
7345  var->vartype != RECORDOID)
7346  {
7347  tupleDesc = get_expr_result_tupdesc((Node *) var, false);
7348  /* Got the tupdesc, so we can extract the field name */
7349  Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
7350  return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
7351  }
7352 
7353  /* Find appropriate nesting depth */
7354  netlevelsup = var->varlevelsup + levelsup;
7355  if (netlevelsup >= list_length(context->namespaces))
7356  elog(ERROR, "bogus varlevelsup: %d offset %d",
7357  var->varlevelsup, levelsup);
7358  dpns = (deparse_namespace *) list_nth(context->namespaces,
7359  netlevelsup);
7360 
7361  /*
7362  * If we have a syntactic referent for the Var, and we're working from a
7363  * parse tree, prefer to use the syntactic referent. Otherwise, fall back
7364  * on the semantic referent. (See comments in get_variable().)
7365  */
7366  if (var->varnosyn > 0 && dpns->plan == NULL)
7367  {
7368  varno = var->varnosyn;
7369  varattno = var->varattnosyn;
7370  }
7371  else
7372  {
7373  varno = var->varno;
7374  varattno = var->varattno;
7375  }
7376 
7377  /*
7378  * Try to find the relevant RTE in this rtable. In a plan tree, it's
7379  * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
7380  * down into the subplans, or INDEX_VAR, which is resolved similarly.
7381  *
7382  * Note: unlike get_variable and resolve_special_varno, we need not worry
7383  * about inheritance mapping: a child Var should have the same datatype as
7384  * its parent, and here we're really only interested in the Var's type.
7385  */
7386  if (varno >= 1 && varno <= list_length(dpns->rtable))
7387  {
7388  rte = rt_fetch(varno, dpns->rtable);
7389  attnum = varattno;
7390  }
7391  else if (varno == OUTER_VAR && dpns->outer_tlist)
7392  {
7393  TargetEntry *tle;
7394  deparse_namespace save_dpns;
7395  const char *result;
7396 
7397  tle = get_tle_by_resno(dpns->outer_tlist, varattno);
7398  if (!tle)
7399  elog(ERROR, "bogus varattno for OUTER_VAR var: %d", varattno);
7400 
7401  Assert(netlevelsup == 0);
7402  push_child_plan(dpns, dpns->outer_plan, &save_dpns);
7403 
7404  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7405  levelsup, context);
7406 
7407  pop_child_plan(dpns, &save_dpns);
7408  return result;
7409  }
7410  else if (varno == INNER_VAR && dpns->inner_tlist)
7411  {
7412  TargetEntry *tle;
7413  deparse_namespace save_dpns;
7414  const char *result;
7415 
7416  tle = get_tle_by_resno(dpns->inner_tlist, varattno);
7417  if (!tle)
7418  elog(ERROR, "bogus varattno for INNER_VAR var: %d", varattno);
7419 
7420  Assert(netlevelsup == 0);
7421  push_child_plan(dpns, dpns->inner_plan, &save_dpns);
7422 
7423  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7424  levelsup, context);
7425 
7426  pop_child_plan(dpns, &save_dpns);
7427  return result;
7428  }
7429  else if (varno == INDEX_VAR && dpns->index_tlist)
7430  {
7431  TargetEntry *tle;
7432  const char *result;
7433 
7434  tle = get_tle_by_resno(dpns->index_tlist, varattno);
7435  if (!tle)
7436  elog(ERROR, "bogus varattno for INDEX_VAR var: %d", varattno);
7437 
7438  Assert(netlevelsup == 0);
7439 
7440  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7441  levelsup, context);
7442 
7443  return result;
7444  }
7445  else
7446  {
7447  elog(ERROR, "bogus varno: %d", varno);
7448  return NULL; /* keep compiler quiet */
7449  }
7450 
7451  if (attnum == InvalidAttrNumber)
7452  {
7453  /* Var is whole-row reference to RTE, so select the right field */
7454  return get_rte_attribute_name(rte, fieldno);
7455  }
7456 
7457  /*
7458  * This part has essentially the same logic as the parser's
7459  * expandRecordVariable() function, but we are dealing with a different
7460  * representation of the input context, and we only need one field name
7461  * not a TupleDesc. Also, we need special cases for finding subquery and
7462  * CTE subplans when deparsing Plan trees.
7463  */
7464  expr = (Node *) var; /* default if we can't drill down */
7465 
7466  switch (rte->rtekind)
7467  {
7468  case RTE_RELATION:
7469  case RTE_VALUES:
7470  case RTE_NAMEDTUPLESTORE:
7471  case RTE_RESULT:
7472 
7473  /*
7474  * This case should not occur: a column of a table, values list,
7475  * or ENR shouldn't have type RECORD. Fall through and fail (most
7476  * likely) at the bottom.
7477  */
7478  break;
7479  case RTE_SUBQUERY:
7480  /* Subselect-in-FROM: examine sub-select's output expr */
7481  {
7482  if (rte->subquery)
7483  {
7485  attnum);
7486 
7487  if (ste == NULL || ste->resjunk)
7488  elog(ERROR, "subquery %s does not have attribute %d",
7489  rte->eref->aliasname, attnum);
7490  expr = (Node *) ste->expr;
7491  if (IsA(expr, Var))
7492  {
7493  /*
7494  * Recurse into the sub-select to see what its Var
7495  * refers to. We have to build an additional level of
7496  * namespace to keep in step with varlevelsup in the
7497  * subselect.
7498  */
7499  deparse_namespace mydpns;
7500  const char *result;
7501 
7502  set_deparse_for_query(&mydpns, rte->subquery,
7503  context->namespaces);
7504 
7505  context->namespaces = lcons(&mydpns,
7506  context->namespaces);
7507 
7508  result = get_name_for_var_field((Var *) expr, fieldno,
7509  0, context);
7510 
7511  context->namespaces =
7512  list_delete_first(context->namespaces);
7513 
7514  return result;
7515  }
7516  /* else fall through to inspect the expression */
7517  }
7518  else
7519  {
7520  /*
7521  * We're deparsing a Plan tree so we don't have complete
7522  * RTE entries (in particular, rte->subquery is NULL). But
7523  * the only place we'd see a Var directly referencing a
7524  * SUBQUERY RTE is in a SubqueryScan plan node, and we can
7525  * look into the child plan's tlist instead.
7526  */
7527  TargetEntry *tle;
7528  deparse_namespace save_dpns;
7529  const char *result;
7530 
7531  if (!dpns->inner_plan)
7532  elog(ERROR, "failed to find plan for subquery %s",
7533  rte->eref->aliasname);
7534  tle = get_tle_by_resno(dpns->inner_tlist, attnum);
7535  if (!tle)
7536  elog(ERROR, "bogus varattno for subquery var: %d",
7537  attnum);
7538  Assert(netlevelsup == 0);
7539  push_child_plan(dpns, dpns->inner_plan, &save_dpns);
7540 
7541  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7542  levelsup, context);
7543 
7544  pop_child_plan(dpns, &save_dpns);
7545  return result;
7546  }
7547  }
7548  break;
7549  case RTE_JOIN:
7550  /* Join RTE --- recursively inspect the alias variable */
7551  if (rte->joinaliasvars == NIL)
7552  elog(ERROR, "cannot decompile join alias var in plan tree");
7553  Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
7554  expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
7555  Assert(expr != NULL);
7556  /* we intentionally don't strip implicit coercions here */
7557  if (IsA(expr, Var))
7558  return get_name_for_var_field((Var *) expr, fieldno,
7559  var->varlevelsup + levelsup,
7560  context);
7561  /* else fall through to inspect the expression */
7562  break;
7563  case RTE_FUNCTION:
7564  case RTE_TABLEFUNC:
7565 
7566  /*
7567  * We couldn't get here unless a function is declared with one of
7568  * its result columns as RECORD, which is not allowed.
7569  */
7570  break;
7571  case RTE_CTE:
7572  /* CTE reference: examine subquery's output expr */
7573  {
7574  CommonTableExpr *cte = NULL;
7575  Index ctelevelsup;
7576  ListCell *lc;
7577 
7578  /*
7579  * Try to find the referenced CTE using the namespace stack.
7580  */
7581  ctelevelsup = rte->ctelevelsup + netlevelsup;
7582  if (ctelevelsup >= list_length(context->namespaces))
7583  lc = NULL;
7584  else
7585  {
7586  deparse_namespace *ctedpns;
7587 
7588  ctedpns = (deparse_namespace *)
7589  list_nth(context->namespaces, ctelevelsup);
7590  foreach(lc, ctedpns->ctes)
7591  {
7592  cte = (CommonTableExpr *) lfirst(lc);
7593  if (strcmp(cte->ctename, rte->ctename) == 0)
7594  break;
7595  }
7596  }
7597  if (lc != NULL)
7598  {
7599  Query *ctequery = (Query *) cte->ctequery;
7601  attnum);
7602 
7603  if (ste == NULL || ste->resjunk)
7604  elog(ERROR, "subquery %s does not have attribute %d",
7605  rte->eref->aliasname, attnum);
7606  expr = (Node *) ste->expr;
7607  if (IsA(expr, Var))
7608  {
7609  /*
7610  * Recurse into the CTE to see what its Var refers to.
7611  * We have to build an additional level of namespace
7612  * to keep in step with varlevelsup in the CTE.
7613  * Furthermore it could be an outer CTE, so we may
7614  * have to delete some levels of namespace.
7615  */
7616  List *save_nslist = context->namespaces;
7617  List *new_nslist;
7618  deparse_namespace mydpns;
7619  const char *result;
7620 
7621  set_deparse_for_query(&mydpns, ctequery,
7622  context->namespaces);
7623 
7624  new_nslist = list_copy_tail(context->namespaces,
7625  ctelevelsup);
7626  context->namespaces = lcons(&mydpns, new_nslist);
7627 
7628  result = get_name_for_var_field((Var *) expr, fieldno,
7629  0, context);
7630 
7631  context->namespaces = save_nslist;
7632 
7633  return result;
7634  }
7635  /* else fall through to inspect the expression */
7636  }
7637  else
7638  {
7639  /*
7640  * We're deparsing a Plan tree so we don't have a CTE
7641  * list. But the only place we'd see a Var directly
7642  * referencing a CTE RTE is in a CteScan plan node, and we
7643  * can look into the subplan's tlist instead.
7644  */
7645  TargetEntry *tle;
7646  deparse_namespace save_dpns;
7647  const char *result;
7648 
7649  if (!dpns->inner_plan)
7650  elog(ERROR, "failed to find plan for CTE %s",
7651  rte->eref->aliasname);
7652  tle = get_tle_by_resno(dpns->inner_tlist, attnum);
7653  if (!tle)
7654  elog(ERROR, "bogus varattno for subquery var: %d",
7655  attnum);
7656  Assert(netlevelsup == 0);
7657  push_child_plan(dpns, dpns->inner_plan, &save_dpns);
7658 
7659  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7660  levelsup, context);
7661 
7662  pop_child_plan(dpns, &save_dpns);
7663  return result;
7664  }
7665  }
7666  break;
7667  }
7668 
7669  /*
7670  * We now have an expression we can't expand any more, so see if
7671  * get_expr_result_tupdesc() can do anything with it.
7672  */
7673  tupleDesc = get_expr_result_tupdesc(expr, false);
7674  /* Got the tupdesc, so we can extract the field name */
7675  Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
7676  return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
7677 }
List * namespaces
Definition: ruleutils.c:111
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
List * joinaliasvars
Definition: parsenodes.h:1070
Index varlevelsup
Definition: primnodes.h:196
static Node * find_param_referent(Param *param, deparse_context *context, deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
Definition: ruleutils.c:7688
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Definition: nodes.h:539
#define strVal(v)
Definition: value.h:54
AttrNumber varattno
Definition: primnodes.h:191
static void pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:4975
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1437
Definition: primnodes.h:186
List * targetList
Definition: parsenodes.h:150
bool resjunk
Definition: primnodes.h:1461
#define ERROR
Definition: elog.h:46
NameData attname
Definition: pg_attribute.h:41
List * colnames
Definition: primnodes.h:1084
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:440
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
Oid vartype
Definition: primnodes.h:193
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
Index varnosyn
Definition: primnodes.h:199
Index varno
Definition: primnodes.h:189
AttrNumber varattnosyn
Definition: primnodes.h:200
List * outer_tlist
Definition: ruleutils.c:172
unsigned int Index
Definition: c.h:549
static const char * get_name_for_var_field(Var *var, int fieldno, int levelsup, deparse_context *context)
Definition: ruleutils.c:7293
int16 attnum
Definition: pg_attribute.h:83
#define INNER_VAR
Definition: primnodes.h:175
char * get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
List * lcons(void *datum, List *list)
Definition: list.c:468
static void pop_child_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:4924
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
char * aliasname
Definition: primnodes.h:42
static void push_child_plan(deparse_namespace *dpns, Plan *plan, deparse_namespace *save_dpns)
Definition: ruleutils.c:4907
Expr * expr
Definition: primnodes.h:1454
static int list_length(const List *l)
Definition: pg_list.h:149
Index ctelevelsup
Definition: parsenodes.h:1106
static void set_deparse_for_query(deparse_namespace *dpns, Query *query, List *parent_namespaces)
Definition: ruleutils.c:3862
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:995
char * ctename
Definition: parsenodes.h:1105
Query * subquery
Definition: parsenodes.h:1030
List * index_tlist
Definition: ruleutils.c:174
List * inner_tlist
Definition: ruleutils.c:173
static void push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell, deparse_namespace *save_dpns)
Definition: ruleutils.c:4954
#define elog(elevel,...)
Definition: elog.h:232
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
#define NameStr(name)
Definition: c.h:681
Alias * eref
Definition: parsenodes.h:1141
#define INDEX_VAR
Definition: primnodes.h:177
Definition: pg_list.h:50
#define GetCTETargetList(cte)
Definition: parsenodes.h:1519
int16 AttrNumber
Definition: attnum.h:21
#define OUTER_VAR
Definition: primnodes.h:176
List * list_delete_first(List *list)
Definition: list.c:875

◆ get_opclass_name()

static void get_opclass_name ( Oid  opclass,
Oid  actual_datatype,
StringInfo  buf 
)
static

Definition at line 11164 of file ruleutils.c.

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

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

11166 {
11167  HeapTuple ht_opc;
11168  Form_pg_opclass opcrec;
11169  char *opcname;
11170  char *nspname;
11171 
11172  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
11173  if (!HeapTupleIsValid(ht_opc))
11174  elog(ERROR, "cache lookup failed for opclass %u", opclass);
11175  opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
11176 
11177  if (!OidIsValid(actual_datatype) ||
11178  GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
11179  {
11180  /* Okay, we need the opclass name. Do we need to qualify it? */
11181  opcname = NameStr(opcrec->opcname);
11182  if (OpclassIsVisible(opclass))
11183  appendStringInfo(buf, " %s", quote_identifier(opcname));
11184  else
11185  {
11186  nspname = get_namespace_name_or_temp(opcrec->opcnamespace);
11187  appendStringInfo(buf, " %s.%s",
11188  quote_identifier(nspname),
11189  quote_identifier(opcname));
11190  }
11191  }
11192  ReleaseSysCache(ht_opc);
11193 }
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2089
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
#define OidIsValid(objectId)
Definition: c.h:710
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
bool OpclassIsVisible(Oid opcid)
Definition: namespace.c:1878
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3340
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83

◆ get_oper_expr()

static void get_oper_expr ( OpExpr expr,
deparse_context context 
)
static

Definition at line 9549 of file ruleutils.c.

References appendStringInfo(), appendStringInfoChar(), arg, generate_unaccent_rules::args, OpExpr::args, buf, deparse_context::buf, exprType(), generate_operator_name(), get_rule_expr_paren(), InvalidOid, linitial, list_length(), lsecond, OpExpr::opno, and PRETTY_PAREN.

Referenced by get_rule_expr().

9550 {
9551  StringInfo buf = context->buf;
9552  Oid opno = expr->opno;
9553  List *args = expr->args;
9554 
9555  if (!PRETTY_PAREN(context))
9556  appendStringInfoChar(buf, '(');
9557  if (list_length(args) == 2)
9558  {
9559  /* binary operator */
9560  Node *arg1 = (Node *) linitial(args);
9561  Node *arg2 = (Node *) lsecond(args);
9562 
9563  get_rule_expr_paren(arg1, context, true, (Node *) expr);
9564  appendStringInfo(buf, " %s ",
9566  exprType(arg1),
9567  exprType(arg2)));
9568  get_rule_expr_paren(arg2, context, true, (Node *) expr);
9569  }
9570  else
9571  {
9572  /* prefix operator */
9573  Node *arg = (Node *) linitial(args);
9574 
9575  appendStringInfo(buf, "%s ",
9577  InvalidOid,
9578  exprType(arg)));
9579  get_rule_expr_paren(arg, context, true, (Node *) expr);
9580  }
9581  if (!PRETTY_PAREN(context))
9582  appendStringInfoChar(buf, ')');
9583 }
static void get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
Definition: ruleutils.c:8246
Definition: nodes.h:539
unsigned int Oid
Definition: postgres_ext.h:31
#define lsecond(l)
Definition: pg_list.h:179
static char * generate_operator_name(Oid operid, Oid arg1, Oid arg2)
Definition: ruleutils.c:11663
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define linitial(l)
Definition: pg_list.h:174
static char * buf
Definition: pg_test_fsync.c:68
#define PRETTY_PAREN(context)
Definition: ruleutils.c:97
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
#define InvalidOid
Definition: postgres_ext.h:36
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
StringInfo buf
Definition: ruleutils.c:110
void * arg
Oid opno
Definition: primnodes.h:542
List * args
Definition: primnodes.h:548
Definition: pg_list.h:50

◆ get_parameter()

static void get_parameter ( Param param,
deparse_context context 
)
static

Definition at line 7823 of file ruleutils.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), deparse_namespace::argnames, deparse_context::buf, find_param_referent(), deparse_namespace::funcname, get_rule_expr(), IsA, lfirst, list_length(), list_tail(), deparse_context::namespaces, PARAM_EXTERN, Param::paramid, Param::paramkind, pop_ancestor_plan(), push_ancestor_plan(), quote_identifier(), deparse_namespace::rtable_names, and deparse_context::varprefix.

Referenced by get_rule_expr().

7824 {
7825  Node *expr;
7826  deparse_namespace *dpns;
7827  ListCell *ancestor_cell;
7828 
7829  /*
7830  * If it's a PARAM_EXEC parameter, try to locate the expression from which
7831  * the parameter was computed. Note that failing to find a referent isn't
7832  * an error, since the Param might well be a subplan output rather than an
7833  * input.
7834  */
7835  expr = find_param_referent(param, context, &dpns, &ancestor_cell);
7836  if (expr)
7837  {
7838  /* Found a match, so print it */
7839  deparse_namespace save_dpns;
7840  bool save_varprefix;
7841  bool need_paren;
7842 
7843  /* Switch attention to the ancestor plan node */
7844  push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
7845 
7846  /*
7847  * Force prefixing of Vars, since they won't belong to the relation
7848  * being scanned in the original plan node.
7849  */
7850  save_varprefix = context->varprefix;
7851  context->varprefix = true;
7852 
7853  /*
7854  * A Param's expansion is typically a Var, Aggref, or upper-level
7855  * Param, which wouldn't need extra parentheses. Otherwise, insert
7856  * parens to ensure the expression looks atomic.
7857  */
7858  need_paren = !(IsA(expr, Var) ||
7859  IsA(expr, Aggref) ||
7860  IsA(expr, Param));
7861  if (need_paren)
7862  appendStringInfoChar(context->buf, '(');
7863 
7864  get_rule_expr(expr, context, false);
7865 
7866  if (need_paren)
7867  appendStringInfoChar(context->buf, ')');
7868 
7869  context->varprefix = save_varprefix;
7870 
7871  pop_ancestor_plan(dpns, &save_dpns);
7872 
7873  return;
7874  }
7875 
7876  /*
7877  * If it's an external parameter, see if the outermost namespace provides
7878  * function argument names.
7879  */
7880  if (param->paramkind == PARAM_EXTERN)
7881  {
7882  dpns = lfirst(list_tail(context->namespaces));
7883  if (dpns->argnames)
7884  {
7885  char *argname = dpns->argnames[param->paramid - 1];
7886 
7887  if (argname)
7888  {
7889  bool should_qualify = false;
7890  ListCell *lc;
7891 
7892  /*
7893  * Qualify the parameter name if there are any other deparse
7894  * namespaces with range tables. This avoids qualifying in
7895  * trivial cases like "RETURN a + b", but makes it safe in all
7896  * other cases.