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/dependency.h"
#include "catalog/indexing.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 missing_ok)
 
static char * pg_get_partkeydef_worker (Oid relid, int prettyFlags, bool attrsOnly, bool missing_ok)
 
static char * pg_get_constraintdef_worker (Oid constraintId, bool fullCommand, int prettyFlags, bool missing_ok)
 
static textpg_get_expr_worker (text *expr, Oid relid, const char *relname, int prettyFlags)
 
static int print_function_arguments (StringInfo buf, HeapTuple proctup, bool print_table_args, bool print_defaults)
 
static void print_function_rettype (StringInfo buf, HeapTuple proctup)
 
static void print_function_trftypes (StringInfo buf, HeapTuple proctup)
 
static void set_rtable_names (deparse_namespace *dpns, List *parent_namespaces, Bitmapset *rels_used)
 
static void set_deparse_for_query (deparse_namespace *dpns, Query *query, List *parent_namespaces)
 
static void set_simple_column_names (deparse_namespace *dpns)
 
static bool has_dangerous_join_using (deparse_namespace *dpns, Node *jtnode)
 
static void set_using_names (deparse_namespace *dpns, Node *jtnode, List *parentUsing)
 
static void set_relation_column_names (deparse_namespace *dpns, RangeTblEntry *rte, deparse_columns *colinfo)
 
static void set_join_column_names (deparse_namespace *dpns, RangeTblEntry *rte, deparse_columns *colinfo)
 
static bool colname_is_unique (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 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)
 
Datum pg_get_ruledef (PG_FUNCTION_ARGS)
 
Datum pg_get_ruledef_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_wrap (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_name (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_name_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_triggerdef (PG_FUNCTION_ARGS)
 
Datum pg_get_triggerdef_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_indexdef (PG_FUNCTION_ARGS)
 
Datum pg_get_indexdef_ext (PG_FUNCTION_ARGS)
 
char * pg_get_indexdef_string (Oid indexrelid)
 
char * pg_get_indexdef_columns (Oid indexrelid, bool pretty)
 
Datum pg_get_statisticsobjdef (PG_FUNCTION_ARGS)
 
Datum pg_get_partkeydef (PG_FUNCTION_ARGS)
 
char * pg_get_partkeydef_columns (Oid relid, bool pretty)
 
Datum pg_get_partition_constraintdef (PG_FUNCTION_ARGS)
 
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)
 
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)
 
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 484 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 101 of file ruleutils.c.

◆ PRETTYFLAG_INDENT

◆ PRETTYFLAG_PAREN

◆ PRETTYFLAG_SCHEMA

◆ PRETTYINDENT_JOIN

#define PRETTYINDENT_JOIN   4

Definition at line 85 of file ruleutils.c.

Referenced by get_from_clause_item().

◆ PRETTYINDENT_LIMIT

#define PRETTYINDENT_LIMIT   40 /* wrap limit */

Definition at line 88 of file ruleutils.c.

Referenced by appendContextKeyword().

◆ PRETTYINDENT_STD

◆ PRETTYINDENT_VAR

#define PRETTYINDENT_VAR   4

Definition at line 86 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 302 of file ruleutils.c.

Function Documentation

◆ add_cast_to()

static void add_cast_to ( StringInfo  buf,
Oid  typid 
)
static

Definition at line 11149 of file ruleutils.c.

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

Referenced by generate_operator_clause().

11150 {
11151  HeapTuple typetup;
11152  Form_pg_type typform;
11153  char *typname;
11154  char *nspname;
11155 
11156  typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
11157  if (!HeapTupleIsValid(typetup))
11158  elog(ERROR, "cache lookup failed for type %u", typid);
11159  typform = (Form_pg_type) GETSTRUCT(typetup);
11160 
11161  typname = NameStr(typform->typname);
11162  nspname = get_namespace_name(typform->typnamespace);
11163 
11164  appendStringInfo(buf, "::%s.%s",
11165  quote_identifier(nspname), quote_identifier(typname));
11166 
11167  ReleaseSysCache(typetup);
11168 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10697
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
NameData typname
Definition: pg_type.h:41
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_type * Form_pg_type
Definition: pg_type.h:250
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616

◆ appendContextKeyword()

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

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

7795 {
7796  StringInfo buf = context->buf;
7797 
7798  if (PRETTY_INDENT(context))
7799  {
7800  int indentAmount;
7801 
7802  context->indentLevel += indentBefore;
7803 
7804  /* remove any trailing spaces currently in the buffer ... */
7806  /* ... then add a newline and some spaces */
7807  appendStringInfoChar(buf, '\n');
7808 
7809  if (context->indentLevel < PRETTYINDENT_LIMIT)
7810  indentAmount = Max(context->indentLevel, 0) + indentPlus;
7811  else
7812  {
7813  /*
7814  * If we're indented more than PRETTYINDENT_LIMIT characters, try
7815  * to conserve horizontal space by reducing the per-level
7816  * indentation. For best results the scale factor here should
7817  * divide all the indent amounts that get added to indentLevel
7818  * (PRETTYINDENT_STD, etc). It's important that the indentation
7819  * not grow unboundedly, else deeply-nested trees use O(N^2)
7820  * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
7821  */
7822  indentAmount = PRETTYINDENT_LIMIT +
7823  (context->indentLevel - PRETTYINDENT_LIMIT) /
7824  (PRETTYINDENT_STD / 2);
7825  indentAmount %= PRETTYINDENT_LIMIT;
7826  /* scale/wrap logic affects indentLevel, but not indentPlus */
7827  indentAmount += indentPlus;
7828  }
7829  appendStringInfoSpaces(buf, indentAmount);
7830 
7832 
7833  context->indentLevel += indentAfter;
7834  if (context->indentLevel < 0)
7835  context->indentLevel = 0;
7836  }
7837  else
7839 }
#define PRETTY_INDENT(context)
Definition: ruleutils.c:100
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
static void removeStringInfoSpaces(StringInfo str)
Definition: ruleutils.c:7847
#define PRETTYINDENT_STD
Definition: ruleutils.c:84
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:88
#define Max(x, y)
Definition: c.h:905
StringInfo buf
Definition: ruleutils.c:112

◆ colname_is_unique()

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

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

4359 {
4360  int i;
4361  ListCell *lc;
4362 
4363  /* Check against already-assigned column aliases within RTE */
4364  for (i = 0; i < colinfo->num_cols; i++)
4365  {
4366  char *oldname = colinfo->colnames[i];
4367 
4368  if (oldname && strcmp(oldname, colname) == 0)
4369  return false;
4370  }
4371 
4372  /*
4373  * If we're building a new_colnames array, check that too (this will be
4374  * partially but not completely redundant with the previous checks)
4375  */
4376  for (i = 0; i < colinfo->num_new_cols; i++)
4377  {
4378  char *oldname = colinfo->new_colnames[i];
4379 
4380  if (oldname && strcmp(oldname, colname) == 0)
4381  return false;
4382  }
4383 
4384  /* Also check against USING-column names that must be globally unique */
4385  foreach(lc, dpns->using_names)
4386  {
4387  char *oldname = (char *) lfirst(lc);
4388 
4389  if (strcmp(oldname, colname) == 0)
4390  return false;
4391  }
4392 
4393  /* Also check against names already assigned for parent-join USING cols */
4394  foreach(lc, colinfo->parentUsing)
4395  {
4396  char *oldname = (char *) lfirst(lc);
4397 
4398  if (strcmp(oldname, colname) == 0)
4399  return false;
4400  }
4401 
4402  return true;
4403 }
List * using_names
Definition: ruleutils.c:168
#define lfirst(lc)
Definition: pg_list.h:190
int i
List * parentUsing
Definition: ruleutils.c:262
char ** new_colnames
Definition: ruleutils.c:255
char ** colnames
Definition: ruleutils.c:238

◆ decompile_column_index_array()

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

Definition at line 2329 of file ruleutils.c.

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

Referenced by pg_get_constraintdef_worker().

2331 {
2332  Datum *keys;
2333  int nKeys;
2334  int j;
2335 
2336  /* Extract data from array of int16 */
2337  deconstruct_array(DatumGetArrayTypeP(column_index_array),
2338  INT2OID, 2, true, 's',
2339  &keys, NULL, &nKeys);
2340 
2341  for (j = 0; j < nKeys; j++)
2342  {
2343  char *colName;
2344 
2345  colName = get_attname(relId, DatumGetInt16(keys[j]), false);
2346 
2347  if (j == 0)
2349  else
2350  appendStringInfo(buf, ", %s", quote_identifier(colName));
2351  }
2352 
2353  return nKeys;
2354 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10697
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:444
uintptr_t Datum
Definition: postgres.h:367
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3461
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ deparse_context_for()

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

Definition at line 3272 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(), transformPartitionBound(), and transformPartitionRangeBounds().

3273 {
3274  deparse_namespace *dpns;
3275  RangeTblEntry *rte;
3276 
3277  dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3278 
3279  /* Build a minimal RTE for the rel */
3280  rte = makeNode(RangeTblEntry);
3281  rte->rtekind = RTE_RELATION;
3282  rte->relid = relid;
3283  rte->relkind = RELKIND_RELATION; /* no need for exactness here */
3285  rte->alias = makeAlias(aliasname, NIL);
3286  rte->eref = rte->alias;
3287  rte->lateral = false;
3288  rte->inh = false;
3289  rte->inFromCl = true;
3290 
3291  /* Build one-element rtable */
3292  dpns->rtable = list_make1(rte);
3293  dpns->subplans = NIL;
3294  dpns->ctes = NIL;
3295  dpns->appendrels = NULL;
3296  set_rtable_names(dpns, NIL, NULL);
3298 
3299  /* Return a one-deep namespace stack */
3300  return list_make1(dpns);
3301 }
#define NIL
Definition: pg_list.h:65
Alias * alias
Definition: parsenodes.h:1112
#define AccessShareLock
Definition: lockdefs.h:36
AppendRelInfo ** appendrels
Definition: ruleutils.c:165
#define list_make1(x1)
Definition: pg_list.h:227
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:385
static void set_rtable_names(deparse_namespace *dpns, List *parent_namespaces, Bitmapset *rels_used)
Definition: ruleutils.c:3438
void * palloc0(Size size)
Definition: mcxt.c:980
#define makeNode(_type_)
Definition: nodes.h:573
static void set_simple_column_names(deparse_namespace *dpns)
Definition: ruleutils.c:3653
RTEKind rtekind
Definition: parsenodes.h:974
Alias * eref
Definition: parsenodes.h:1113

◆ deparse_context_for_plan_tree()

List* deparse_context_for_plan_tree ( PlannedStmt pstmt,
List rtable_names 
)

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

3318 {
3319  deparse_namespace *dpns;
3320 
3321  dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3322 
3323  /* Initialize fields that stay the same across the whole plan tree */
3324  dpns->rtable = pstmt->rtable;
3325  dpns->rtable_names = rtable_names;
3326  dpns->subplans = pstmt->subplans;
3327  dpns->ctes = NIL;
3328  if (pstmt->appendRelations)
3329  {
3330  /* Set up the array, indexed by child relid */
3331  int ntables = list_length(dpns->rtable);
3332  ListCell *lc;
3333 
3334  dpns->appendrels = (AppendRelInfo **)
3335  palloc0((ntables + 1) * sizeof(AppendRelInfo *));
3336  foreach(lc, pstmt->appendRelations)
3337  {
3338  AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
3339  Index crelid = appinfo->child_relid;
3340 
3341  Assert(crelid > 0 && crelid <= ntables);
3342  Assert(dpns->appendrels[crelid] == NULL);
3343  dpns->appendrels[crelid] = appinfo;
3344  }
3345  }
3346  else
3347  dpns->appendrels = NULL; /* don't need it */
3348 
3349  /*
3350  * Set up column name aliases. We will get rather bogus results for join
3351  * RTEs, but that doesn't matter because plan trees don't contain any join
3352  * alias Vars.
3353  */
3355 
3356  /* Return a one-deep namespace stack */
3357  return list_make1(dpns);
3358 }
#define NIL
Definition: pg_list.h:65
List * rtable_names
Definition: ruleutils.c:161
AppendRelInfo ** appendrels
Definition: ruleutils.c:165
#define list_make1(x1)
Definition: pg_list.h:227
#define lfirst_node(type, lc)
Definition: pg_list.h:193
void * palloc0(Size size)
Definition: mcxt.c:980
unsigned int Index
Definition: c.h:476
List * subplans
Definition: plannodes.h:79
#define Assert(condition)
Definition: c.h:739
static int list_length(const List *l)
Definition: pg_list.h:169
List * rtable
Definition: plannodes.h:66
static void set_simple_column_names(deparse_namespace *dpns)
Definition: ruleutils.c:3653
Index child_relid
Definition: pathnodes.h:2190
List * appendRelations
Definition: plannodes.h:77

◆ deparse_expression()

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

Definition at line 3212 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_plan_tlist(), show_sort_group_keys(), show_tablesample(), transformPartitionBound(), and transformPartitionRangeBounds().

3214 {
3215  return deparse_expression_pretty(expr, dpcontext, forceprefix,
3216  showimplicit, 0, 0);
3217 }
static char * deparse_expression_pretty(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit, int prettyFlags, int startIndent)
Definition: ruleutils.c:3239

◆ deparse_expression_pretty()

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

Definition at line 3239 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(), and pg_get_partkeydef_worker().

3242 {
3244  deparse_context context;
3245 
3246  initStringInfo(&buf);
3247  context.buf = &buf;
3248  context.namespaces = dpcontext;
3249  context.windowClause = NIL;
3250  context.windowTList = NIL;
3251  context.varprefix = forceprefix;
3252  context.prettyFlags = prettyFlags;
3253  context.wrapColumn = WRAP_COLUMN_DEFAULT;
3254  context.indentLevel = startIndent;
3255  context.special_exprkind = EXPR_KIND_NONE;
3256  context.appendparents = NULL;
3257 
3258  get_rule_expr(expr, &context, showimplicit);
3259 
3260  return buf.data;
3261 }
List * namespaces
Definition: ruleutils.c:113
#define NIL
Definition: pg_list.h:65
#define WRAP_COLUMN_DEFAULT
Definition: ruleutils.c:96
static char * buf
Definition: pg_test_fsync.c:67
ParseExprKind special_exprkind
Definition: ruleutils.c:120
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
List * windowTList
Definition: ruleutils.c:115
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7898
List * windowClause
Definition: ruleutils.c:114
Bitmapset * appendparents
Definition: ruleutils.c:122
StringInfo buf
Definition: ruleutils.c:112

◆ expand_colnames_array_to()

static void expand_colnames_array_to ( deparse_columns colinfo,
int  n 
)
static

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

4456 {
4457  if (n > colinfo->num_cols)
4458  {
4459  if (colinfo->colnames == NULL)
4460  colinfo->colnames = (char **) palloc0(n * sizeof(char *));
4461  else
4462  {
4463  colinfo->colnames = (char **) repalloc(colinfo->colnames,
4464  n * sizeof(char *));
4465  memset(colinfo->colnames + colinfo->num_cols, 0,
4466  (n - colinfo->num_cols) * sizeof(char *));
4467  }
4468  colinfo->num_cols = n;
4469  }
4470 }
void * palloc0(Size size)
Definition: mcxt.c:980
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
char ** colnames
Definition: ruleutils.c:238

◆ 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 7352 of file ruleutils.c.

References deparse_namespace::ancestors, arg, SubPlan::args, Assert, castNode, elog, ERROR, for_each_cell, forboth, innerPlan, IsA, lfirst, lfirst_int, 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().

7354 {
7355  /* Initialize output parameters to prevent compiler warnings */
7356  *dpns_p = NULL;
7357  *ancestor_cell_p = NULL;
7358 
7359  /*
7360  * If it's a PARAM_EXEC parameter, look for a matching NestLoopParam or
7361  * SubPlan argument. This will necessarily be in some ancestor of the
7362  * current expression's Plan node.
7363  */
7364  if (param->paramkind == PARAM_EXEC)
7365  {
7366  deparse_namespace *dpns;
7367  Plan *child_plan;
7368  bool in_same_plan_level;
7369  ListCell *lc;
7370 
7371  dpns = (deparse_namespace *) linitial(context->namespaces);
7372  child_plan = dpns->plan;
7373  in_same_plan_level = true;
7374 
7375  foreach(lc, dpns->ancestors)
7376  {
7377  Node *ancestor = (Node *) lfirst(lc);
7378  ListCell *lc2;
7379 
7380  /*
7381  * NestLoops transmit params to their inner child only; also, once
7382  * we've crawled up out of a subplan, this couldn't possibly be
7383  * the right match.
7384  */
7385  if (IsA(ancestor, NestLoop) &&
7386  child_plan == innerPlan(ancestor) &&
7387  in_same_plan_level)
7388  {
7389  NestLoop *nl = (NestLoop *) ancestor;
7390 
7391  foreach(lc2, nl->nestParams)
7392  {
7393  NestLoopParam *nlp = (NestLoopParam *) lfirst(lc2);
7394 
7395  if (nlp->paramno == param->paramid)
7396  {
7397  /* Found a match, so return it */
7398  *dpns_p = dpns;
7399  *ancestor_cell_p = lc;
7400  return (Node *) nlp->paramval;
7401  }
7402  }
7403  }
7404 
7405  /*
7406  * If ancestor is a SubPlan, check the arguments it provides.
7407  */
7408  if (IsA(ancestor, SubPlan))
7409  {
7410  SubPlan *subplan = (SubPlan *) ancestor;
7411  ListCell *lc3;
7412  ListCell *lc4;
7413 
7414  forboth(lc3, subplan->parParam, lc4, subplan->args)
7415  {
7416  int paramid = lfirst_int(lc3);
7417  Node *arg = (Node *) lfirst(lc4);
7418 
7419  if (paramid == param->paramid)
7420  {
7421  /*
7422  * Found a match, so return it. But, since Vars in
7423  * the arg are to be evaluated in the surrounding
7424  * context, we have to point to the next ancestor item
7425  * that is *not* a SubPlan.
7426  */
7427  ListCell *rest;
7428 
7429  for_each_cell(rest, dpns->ancestors,
7430  lnext(dpns->ancestors, lc))
7431  {
7432  Node *ancestor2 = (Node *) lfirst(rest);
7433 
7434  if (!IsA(ancestor2, SubPlan))
7435  {
7436  *dpns_p = dpns;
7437  *ancestor_cell_p = rest;
7438  return arg;
7439  }
7440  }
7441  elog(ERROR, "SubPlan cannot be outermost ancestor");
7442  }
7443  }
7444 
7445  /* We have emerged from a subplan. */
7446  in_same_plan_level = false;
7447 
7448  /* SubPlan isn't a kind of Plan, so skip the rest */
7449  continue;
7450  }
7451 
7452  /*
7453  * Check to see if we're emerging from an initplan of the current
7454  * ancestor plan. Initplans never have any parParams, so no need
7455  * to search that list, but we need to know if we should reset
7456  * in_same_plan_level.
7457  */
7458  foreach(lc2, ((Plan *) ancestor)->initPlan)
7459  {
7460  SubPlan *subplan = castNode(SubPlan, lfirst(lc2));
7461 
7462  if (child_plan != (Plan *) list_nth(dpns->subplans,
7463  subplan->plan_id - 1))
7464  continue;
7465 
7466  /* No parameters to be had here. */
7467  Assert(subplan->parParam == NIL);
7468 
7469  /* We have emerged from an initplan. */
7470  in_same_plan_level = false;
7471  break;
7472  }
7473 
7474  /* No luck, crawl up to next ancestor */
7475  child_plan = (Plan *) ancestor;
7476  }
7477  }
7478 
7479  /* No referent found */
7480  return NULL;
7481 }
List * namespaces
Definition: ruleutils.c:113
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
int plan_id
Definition: primnodes.h:709
List * nestParams
Definition: plannodes.h:703
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
ParamKind paramkind
Definition: primnodes.h:262
Definition: nodes.h:525
Var * paramval
Definition: plannodes.h:710
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:191
static void * list_nth(const List *list, int n)
Definition: pg_list.h:277
#define innerPlan(node)
Definition: plannodes.h:171
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
int paramid
Definition: primnodes.h:263
List * parParam
Definition: primnodes.h:729
#define elog(elevel,...)
Definition: elog.h:228
void * arg
List * args
Definition: primnodes.h:730

◆ flatten_reloptions()

static char * flatten_reloptions ( Oid  relid)
static

Definition at line 11258 of file ruleutils.c.

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

Referenced by pg_get_constraintdef_worker(), and pg_get_indexdef_worker().

11259 {
11260  char *result = NULL;
11261  HeapTuple tuple;
11262  Datum reloptions;
11263  bool isnull;
11264 
11265  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
11266  if (!HeapTupleIsValid(tuple))
11267  elog(ERROR, "cache lookup failed for relation %u", relid);
11268 
11269  reloptions = SysCacheGetAttr(RELOID, tuple,
11270  Anum_pg_class_reloptions, &isnull);
11271  if (!isnull)
11272  {
11274  Datum *options;
11275  int noptions;
11276  int i;
11277 
11278  initStringInfo(&buf);
11279 
11281  TEXTOID, -1, false, 'i',
11282  &options, NULL, &noptions);
11283 
11284  for (i = 0; i < noptions; i++)
11285  {
11286  char *option = TextDatumGetCString(options[i]);
11287  char *name;
11288  char *separator;
11289  char *value;
11290 
11291  /*
11292  * Each array element should have the form name=value. If the "="
11293  * is missing for some reason, treat it like an empty value.
11294  */
11295  name = option;
11296  separator = strchr(option, '=');
11297  if (separator)
11298  {
11299  *separator = '\0';
11300  value = separator + 1;
11301  }
11302  else
11303  value = "";
11304 
11305  if (i > 0)
11306  appendStringInfoString(&buf, ", ");
11307  appendStringInfo(&buf, "%s=", quote_identifier(name));
11308 
11309  /*
11310  * In general we need to quote the value; but to avoid unnecessary
11311  * clutter, do not quote if it is an identifier that would not
11312  * need quoting. (We could also allow numbers, but that is a bit
11313  * trickier than it looks --- for example, are leading zeroes
11314  * significant? We don't want to assume very much here about what
11315  * custom reloptions might mean.)
11316  */
11317  if (quote_identifier(value) == value)
11318  appendStringInfoString(&buf, value);
11319  else
11320  simple_quote_literal(&buf, value);
11321 
11322  pfree(option);
11323  }
11324 
11325  result = buf.data;
11326  }
11327 
11328  ReleaseSysCache(tuple);
11329 
11330  return result;
11331 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10697
static struct @145 value
void pfree(void *pointer)
Definition: mcxt.c:1056
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
static void simple_quote_literal(StringInfo buf, const char *val)
Definition: ruleutils.c:9725
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
static char ** options
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define TextDatumGetCString(d)
Definition: builtins.h:84
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
const char * name
Definition: encode.c:521
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3461
#define elog(elevel,...)
Definition: elog.h:228
int i
static size_t noptions
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ generate_collation_name()

char* generate_collation_name ( Oid  collid)

Definition at line 11213 of file ruleutils.c.

References CollationIsVisible(), COLLOID, elog, ERROR, get_namespace_name(), 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().

11214 {
11215  HeapTuple tp;
11216  Form_pg_collation colltup;
11217  char *collname;
11218  char *nspname;
11219  char *result;
11220 
11221  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
11222  if (!HeapTupleIsValid(tp))
11223  elog(ERROR, "cache lookup failed for collation %u", collid);
11224  colltup = (Form_pg_collation) GETSTRUCT(tp);
11225  collname = NameStr(colltup->collname);
11226 
11227  if (!CollationIsVisible(collid))
11228  nspname = get_namespace_name(colltup->collnamespace);
11229  else
11230  nspname = NULL;
11231 
11232  result = quote_qualified_identifier(nspname, collname);
11233 
11234  ReleaseSysCache(tp);
11235 
11236  return result;
11237 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
bool CollationIsVisible(Oid collid)
Definition: namespace.c:2040
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10781
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:51
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616

◆ 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 10923 of file ruleutils.c.

References Assert, elog, ERROR, EXPR_KIND_GROUP_BY, func_get_detail(), FUNCDETAIL_AGGREGATE, FUNCDETAIL_NORMAL, FUNCDETAIL_NOTFOUND, FUNCDETAIL_WINDOWFUNC, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, InvalidOid, list_make1, makeString(), NameStr, NIL, 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().

10926 {
10927  char *result;
10928  HeapTuple proctup;
10929  Form_pg_proc procform;
10930  char *proname;
10931  bool use_variadic;
10932  char *nspname;
10933  FuncDetailCode p_result;
10934  Oid p_funcid;
10935  Oid p_rettype;
10936  bool p_retset;
10937  int p_nvargs;
10938  Oid p_vatype;
10939  Oid *p_true_typeids;
10940  bool force_qualify = false;
10941 
10942  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
10943  if (!HeapTupleIsValid(proctup))
10944  elog(ERROR, "cache lookup failed for function %u", funcid);
10945  procform = (Form_pg_proc) GETSTRUCT(proctup);
10946  proname = NameStr(procform->proname);
10947 
10948  /*
10949  * Due to parser hacks to avoid needing to reserve CUBE, we need to force
10950  * qualification in some special cases.
10951  */
10952  if (special_exprkind == EXPR_KIND_GROUP_BY)
10953  {
10954  if (strcmp(proname, "cube") == 0 || strcmp(proname, "rollup") == 0)
10955  force_qualify = true;
10956  }
10957 
10958  /*
10959  * Determine whether VARIADIC should be printed. We must do this first
10960  * since it affects the lookup rules in func_get_detail().
10961  *
10962  * We always print VARIADIC if the function has a merged variadic-array
10963  * argument. Note that this is always the case for functions taking a
10964  * VARIADIC argument type other than VARIADIC ANY. If we omitted VARIADIC
10965  * and printed the array elements as separate arguments, the call could
10966  * match a newer non-VARIADIC function.
10967  */
10968  if (use_variadic_p)
10969  {
10970  /* Parser should not have set funcvariadic unless fn is variadic */
10971  Assert(!has_variadic || OidIsValid(procform->provariadic));
10972  use_variadic = has_variadic;
10973  *use_variadic_p = use_variadic;
10974  }
10975  else
10976  {
10977  Assert(!has_variadic);
10978  use_variadic = false;
10979  }
10980 
10981  /*
10982  * The idea here is to schema-qualify only if the parser would fail to
10983  * resolve the correct function given the unqualified func name with the
10984  * specified argtypes and VARIADIC flag. But if we already decided to
10985  * force qualification, then we can skip the lookup and pretend we didn't
10986  * find it.
10987  */
10988  if (!force_qualify)
10989  p_result = func_get_detail(list_make1(makeString(proname)),
10990  NIL, argnames, nargs, argtypes,
10991  !use_variadic, true,
10992  &p_funcid, &p_rettype,
10993  &p_retset, &p_nvargs, &p_vatype,
10994  &p_true_typeids, NULL);
10995  else
10996  {
10997  p_result = FUNCDETAIL_NOTFOUND;
10998  p_funcid = InvalidOid;
10999  }
11000 
11001  if ((p_result == FUNCDETAIL_NORMAL ||
11002  p_result == FUNCDETAIL_AGGREGATE ||
11003  p_result == FUNCDETAIL_WINDOWFUNC) &&
11004  p_funcid == funcid)
11005  nspname = NULL;
11006  else
11007  nspname = get_namespace_name(procform->pronamespace);
11008 
11009  result = quote_qualified_identifier(nspname, proname);
11010 
11011  ReleaseSysCache(proctup);
11012 
11013  return result;
11014 }
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:655
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define list_make1(x1)
Definition: pg_list.h:227
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
FuncDetailCode
Definition: parse_func.h:22
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10781
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
FuncDetailCode func_get_detail(List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, Oid *funcid, Oid *rettype, bool *retset, int *nvargs, Oid *vatype, Oid **true_typeids, List **argdefaults)
Definition: parse_func.c:1382
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616

◆ generate_operator_clause()

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

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

11113 {
11114  HeapTuple opertup;
11115  Form_pg_operator operform;
11116  char *oprname;
11117  char *nspname;
11118 
11119  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
11120  if (!HeapTupleIsValid(opertup))
11121  elog(ERROR, "cache lookup failed for operator %u", opoid);
11122  operform = (Form_pg_operator) GETSTRUCT(opertup);
11123  Assert(operform->oprkind == 'b');
11124  oprname = NameStr(operform->oprname);
11125 
11126  nspname = get_namespace_name(operform->oprnamespace);
11127 
11128  appendStringInfoString(buf, leftop);
11129  if (leftoptype != operform->oprleft)
11130  add_cast_to(buf, operform->oprleft);
11131  appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
11132  appendStringInfoString(buf, oprname);
11133  appendStringInfo(buf, ") %s", rightop);
11134  if (rightoptype != operform->oprright)
11135  add_cast_to(buf, operform->oprright);
11136 
11137  ReleaseSysCache(opertup);
11138 }
static void add_cast_to(StringInfo buf, Oid typid)
Definition: ruleutils.c:11149
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10697
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616

◆ generate_operator_name()

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

Definition at line 11028 of file ruleutils.c.

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

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

11029 {
11031  HeapTuple opertup;
11032  Form_pg_operator operform;
11033  char *oprname;
11034  char *nspname;
11035  Operator p_result;
11036 
11037  initStringInfo(&buf);
11038 
11039  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operid));
11040  if (!HeapTupleIsValid(opertup))
11041  elog(ERROR, "cache lookup failed for operator %u", operid);
11042  operform = (Form_pg_operator) GETSTRUCT(opertup);
11043  oprname = NameStr(operform->oprname);
11044 
11045  /*
11046  * The idea here is to schema-qualify only if the parser would fail to
11047  * resolve the correct operator given the unqualified op name with the
11048  * specified argtypes.
11049  */
11050  switch (operform->oprkind)
11051  {
11052  case 'b':
11053  p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
11054  true, -1);
11055  break;
11056  case 'l':
11057  p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
11058  true, -1);
11059  break;
11060  case 'r':
11061  p_result = right_oper(NULL, list_make1(makeString(oprname)), arg1,
11062  true, -1);
11063  break;
11064  default:
11065  elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
11066  p_result = NULL; /* keep compiler quiet */
11067  break;
11068  }
11069 
11070  if (p_result != NULL && oprid(p_result) == operid)
11071  nspname = NULL;
11072  else
11073  {
11074  nspname = get_namespace_name(operform->oprnamespace);
11075  appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
11076  }
11077 
11078  appendStringInfoString(&buf, oprname);
11079 
11080  if (nspname)
11081  appendStringInfoChar(&buf, ')');
11082 
11083  if (p_result != NULL)
11084  ReleaseSysCache(p_result);
11085 
11086  ReleaseSysCache(opertup);
11087 
11088  return buf.data;
11089 }
Value * makeString(char *str)
Definition: value.c:53
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10697
Oid oprid(Operator op)
Definition: parse_oper.c:245
#define list_make1(x1)
Definition: pg_list.h:227
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Operator left_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
Definition: parse_oper.c:604
Operator right_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
Definition: parse_oper.c:525
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
static char * buf
Definition: pg_test_fsync.c:67
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:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:377

◆ generate_qualified_relation_name()

static char * generate_qualified_relation_name ( Oid  relid)
static

Definition at line 10881 of file ruleutils.c.

References elog, ERROR, get_namespace_name(), 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().

10882 {
10883  HeapTuple tp;
10884  Form_pg_class reltup;
10885  char *relname;
10886  char *nspname;
10887  char *result;
10888 
10889  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
10890  if (!HeapTupleIsValid(tp))
10891  elog(ERROR, "cache lookup failed for relation %u", relid);
10892  reltup = (Form_pg_class) GETSTRUCT(tp);
10893  relname = NameStr(reltup->relname);
10894 
10895  nspname = get_namespace_name(reltup->relnamespace);
10896  if (!nspname)
10897  elog(ERROR, "cache lookup failed for namespace %u",
10898  reltup->relnamespace);
10899 
10900  result = quote_qualified_identifier(nspname, relname);
10901 
10902  ReleaseSysCache(tp);
10903 
10904  return result;
10905 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
NameData relname
Definition: pg_class.h:35
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10781
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616

◆ generate_qualified_type_name()

static char * generate_qualified_type_name ( Oid  typid)
static

Definition at line 11180 of file ruleutils.c.

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

Referenced by pg_get_constraintdef_worker().

11181 {
11182  HeapTuple tp;
11183  Form_pg_type typtup;
11184  char *typname;
11185  char *nspname;
11186  char *result;
11187 
11189  if (!HeapTupleIsValid(tp))
11190  elog(ERROR, "cache lookup failed for type %u", typid);
11191  typtup = (Form_pg_type) GETSTRUCT(tp);
11192  typname = NameStr(typtup->typname);
11193 
11194  nspname = get_namespace_name(typtup->typnamespace);
11195  if (!nspname)
11196  elog(ERROR, "cache lookup failed for namespace %u",
11197  typtup->typnamespace);
11198 
11199  result = quote_qualified_identifier(nspname, typname);
11200 
11201  ReleaseSysCache(tp);
11202 
11203  return result;
11204 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
NameData typname
Definition: pg_type.h:41
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10781
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_type * Form_pg_type
Definition: pg_type.h:250
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616

◆ generate_relation_name()

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

Definition at line 10821 of file ruleutils.c.

References CommonTableExpr::ctename, deparse_namespace::ctes, elog, ERROR, get_namespace_name(), 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().

10822 {
10823  HeapTuple tp;
10824  Form_pg_class reltup;
10825  bool need_qual;
10826  ListCell *nslist;
10827  char *relname;
10828  char *nspname;
10829  char *result;
10830 
10831  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
10832  if (!HeapTupleIsValid(tp))
10833  elog(ERROR, "cache lookup failed for relation %u", relid);
10834  reltup = (Form_pg_class) GETSTRUCT(tp);
10835  relname = NameStr(reltup->relname);
10836 
10837  /* Check for conflicting CTE name */
10838  need_qual = false;
10839  foreach(nslist, namespaces)
10840  {
10841  deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
10842  ListCell *ctlist;
10843 
10844  foreach(ctlist, dpns->ctes)
10845  {
10846  CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
10847 
10848  if (strcmp(cte->ctename, relname) == 0)
10849  {
10850  need_qual = true;
10851  break;
10852  }
10853  }
10854  if (need_qual)
10855  break;
10856  }
10857 
10858  /* Otherwise, qualify the name if not visible in search path */
10859  if (!need_qual)
10860  need_qual = !RelationIsVisible(relid);
10861 
10862  if (need_qual)
10863  nspname = get_namespace_name(reltup->relnamespace);
10864  else
10865  nspname = NULL;
10866 
10867  result = quote_qualified_identifier(nspname, relname);
10868 
10869  ReleaseSysCache(tp);
10870 
10871  return result;
10872 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
NameData relname
Definition: pg_class.h:35
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10781
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:190
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
bool RelationIsVisible(Oid relid)
Definition: namespace.c:700
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616

◆ get_agg_combine_expr()

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

Definition at line 9418 of file ruleutils.c.

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

Referenced by get_agg_expr().

9419 {
9420  Aggref *aggref;
9421  Aggref *original_aggref = callback_arg;
9422 
9423  if (!IsA(node, Aggref))
9424  elog(ERROR, "combining Aggref does not point to an Aggref");
9425 
9426  aggref = (Aggref *) node;
9427  get_agg_expr(aggref, context, original_aggref);
9428 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define ERROR
Definition: elog.h:43
static void get_agg_expr(Aggref *aggref, deparse_context *context, Aggref *original_aggref)
Definition: ruleutils.c:9311
#define elog(elevel,...)
Definition: elog.h:228

◆ get_agg_expr()

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

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

9313 {
9314  StringInfo buf = context->buf;
9315  Oid argtypes[FUNC_MAX_ARGS];
9316  int nargs;
9317  bool use_variadic;
9318 
9319  /*
9320  * For a combining aggregate, we look up and deparse the corresponding
9321  * partial aggregate instead. This is necessary because our input
9322  * argument list has been replaced; the new argument list always has just
9323  * one element, which will point to a partial Aggref that supplies us with
9324  * transition states to combine.
9325  */
9326  if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
9327  {
9328  TargetEntry *tle;
9329 
9330  Assert(list_length(aggref->args) == 1);
9331  tle = linitial_node(TargetEntry, aggref->args);
9332  resolve_special_varno((Node *) tle->expr, context,
9333  get_agg_combine_expr, original_aggref);
9334  return;
9335  }
9336 
9337  /*
9338  * Mark as PARTIAL, if appropriate. We look to the original aggref so as
9339  * to avoid printing this when recursing from the code just above.
9340  */
9341  if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
9342  appendStringInfoString(buf, "PARTIAL ");
9343 
9344  /* Extract the argument types as seen by the parser */
9345  nargs = get_aggregate_argtypes(aggref, argtypes);
9346 
9347  /* Print the aggregate name, schema-qualified if needed */
9348  appendStringInfo(buf, "%s(%s",
9349  generate_function_name(aggref->aggfnoid, nargs,
9350  NIL, argtypes,
9351  aggref->aggvariadic,
9352  &use_variadic,
9353  context->special_exprkind),
9354  (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
9355 
9356  if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
9357  {
9358  /*
9359  * Ordered-set aggregates do not use "*" syntax. Also, we needn't
9360  * worry about inserting VARIADIC. So we can just dump the direct
9361  * args as-is.
9362  */
9363  Assert(!aggref->aggvariadic);
9364  get_rule_expr((Node *) aggref->aggdirectargs, context, true);
9365  Assert(aggref->aggorder != NIL);
9366  appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
9367  get_rule_orderby(aggref->aggorder, aggref->args, false, context);
9368  }
9369  else
9370  {
9371  /* aggstar can be set only in zero-argument aggregates */
9372  if (aggref->aggstar)
9373  appendStringInfoChar(buf, '*');
9374  else
9375  {
9376  ListCell *l;
9377  int i;
9378 
9379  i = 0;
9380  foreach(l, aggref->args)
9381  {
9382  TargetEntry *tle = (TargetEntry *) lfirst(l);
9383  Node *arg = (Node *) tle->expr;
9384 
9385  Assert(!IsA(arg, NamedArgExpr));
9386  if (tle->resjunk)
9387  continue;
9388  if (i++ > 0)
9389  appendStringInfoString(buf, ", ");
9390  if (use_variadic && i == nargs)
9391  appendStringInfoString(buf, "VARIADIC ");
9392  get_rule_expr(arg, context, true);
9393  }
9394  }
9395 
9396  if (aggref->aggorder != NIL)
9397  {
9398  appendStringInfoString(buf, " ORDER BY ");
9399  get_rule_orderby(aggref->aggorder, aggref->args, false, context);
9400  }
9401  }
9402 
9403  if (aggref->aggfilter != NULL)
9404  {
9405  appendStringInfoString(buf, ") FILTER (WHERE ");
9406  get_rule_expr((Node *) aggref->aggfilter, context, false);
9407  }
9408 
9409  appendStringInfoChar(buf, ')');
9410 }
static void resolve_special_varno(Node *node, deparse_context *context, rsv_callback callback, void *callback_arg)
Definition: ruleutils.c:6849
List * aggdistinct
Definition: primnodes.h:321
#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:10923
bool aggvariadic
Definition: primnodes.h:324
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static void get_rule_orderby(List *orderList, List *targetList, bool force_colno, deparse_context *context)
Definition: ruleutils.c:5885
Definition: nodes.h:525
List * args
Definition: primnodes.h:319
bool aggstar
Definition: primnodes.h:323
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:198
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:787
#define FUNC_MAX_ARGS
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
bool resjunk
Definition: primnodes.h:1414
static void get_agg_combine_expr(Node *node, deparse_context *context, void *callback_arg)
Definition: ruleutils.c:9418
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
List * aggorder
Definition: primnodes.h:320
List * aggdirectargs
Definition: primnodes.h:318
ParseExprKind special_exprkind
Definition: ruleutils.c:120
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
Oid aggfnoid
Definition: primnodes.h:312
#define Assert(condition)
Definition: c.h:739
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7898
#define lfirst(lc)
Definition: pg_list.h:190
Expr * expr
Definition: primnodes.h:1407
AggSplit aggsplit
Definition: primnodes.h:328
static int list_length(const List *l)
Definition: pg_list.h:169
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:788
Expr * aggfilter
Definition: primnodes.h:322
StringInfo buf
Definition: ruleutils.c:112
int i
void * arg
char aggkind
Definition: primnodes.h:326
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:1819

◆ get_basic_select_query()

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

Definition at line 5378 of file ruleutils.c.

References appendContextKeyword(), appendStringInfoChar(), appendStringInfoString(), buf, deparse_context::buf, Query::distinctClause, EXPR_KIND_GROUP_BY, get_from_clause(), get_rule_expr(), get_rule_groupingset(), get_rule_sortgroupclause(), get_rule_windowclause(), get_simple_values_rte(), get_target_list(), get_values_def(), Query::groupClause, Query::groupingSets, Query::hasDistinctOn, Query::havingQual, deparse_context::indentLevel, Query::jointree, lfirst, NIL, 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().

5380 {
5381  StringInfo buf = context->buf;
5382  RangeTblEntry *values_rte;
5383  char *sep;
5384  ListCell *l;
5385 
5386  if (PRETTY_INDENT(context))
5387  {
5388  context->indentLevel += PRETTYINDENT_STD;
5389  appendStringInfoChar(buf, ' ');
5390  }
5391 
5392  /*
5393  * If the query looks like SELECT * FROM (VALUES ...), then print just the
5394  * VALUES part. This reverses what transformValuesClause() did at parse
5395  * time.
5396  */
5397  values_rte = get_simple_values_rte(query, resultDesc);
5398  if (values_rte)
5399  {
5400  get_values_def(values_rte->values_lists, context);
5401  return;
5402  }
5403 
5404  /*
5405  * Build up the query string - first we say SELECT
5406  */
5407  appendStringInfoString(buf, "SELECT");
5408 
5409  /* Add the DISTINCT clause if given */
5410  if (query->distinctClause != NIL)
5411  {
5412  if (query->hasDistinctOn)
5413  {
5414  appendStringInfoString(buf, " DISTINCT ON (");
5415  sep = "";
5416  foreach(l, query->distinctClause)
5417  {
5418  SortGroupClause *srt = (SortGroupClause *) lfirst(l);
5419 
5420  appendStringInfoString(buf, sep);
5422  false, context);
5423  sep = ", ";
5424  }
5425  appendStringInfoChar(buf, ')');
5426  }
5427  else
5428  appendStringInfoString(buf, " DISTINCT");
5429  }
5430 
5431  /* Then we tell what to select (the targetlist) */
5432  get_target_list(query->targetList, context, resultDesc);
5433 
5434  /* Add the FROM clause if needed */
5435  get_from_clause(query, " FROM ", context);
5436 
5437  /* Add the WHERE clause if given */
5438  if (query->jointree->quals != NULL)
5439  {
5440  appendContextKeyword(context, " WHERE ",
5442  get_rule_expr(query->jointree->quals, context, false);
5443  }
5444 
5445  /* Add the GROUP BY clause if given */
5446  if (query->groupClause != NULL || query->groupingSets != NULL)
5447  {
5448  ParseExprKind save_exprkind;
5449 
5450  appendContextKeyword(context, " GROUP BY ",
5452 
5453  save_exprkind = context->special_exprkind;
5455 
5456  if (query->groupingSets == NIL)
5457  {
5458  sep = "";
5459  foreach(l, query->groupClause)
5460  {
5461  SortGroupClause *grp = (SortGroupClause *) lfirst(l);
5462 
5463  appendStringInfoString(buf, sep);
5465  false, context);
5466  sep = ", ";
5467  }
5468  }
5469  else
5470  {
5471  sep = "";
5472  foreach(l, query->groupingSets)
5473  {
5474  GroupingSet *grp = lfirst(l);
5475 
5476  appendStringInfoString(buf, sep);
5477  get_rule_groupingset(grp, query->targetList, true, context);
5478  sep = ", ";
5479  }
5480  }
5481 
5482  context->special_exprkind = save_exprkind;
5483  }
5484 
5485  /* Add the HAVING clause if given */
5486  if (query->havingQual != NULL)
5487  {
5488  appendContextKeyword(context, " HAVING ",
5490  get_rule_expr(query->havingQual, context, false);
5491  }
5492 
5493  /* Add the WINDOW clause if needed */
5494  if (query->windowClause != NIL)
5495  get_rule_windowclause(query, context);
5496 }
#define NIL
Definition: pg_list.h:65
FromExpr * jointree
Definition: parsenodes.h:138
static void get_target_list(List *targetList, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5505
static Node * get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno, deparse_context *context)
Definition: ruleutils.c:5769
Index tleSortGroupRef
Definition: parsenodes.h:1255
List * groupingSets
Definition: parsenodes.h:150
static void get_from_clause(Query *query, const char *prefix, deparse_context *context)
Definition: ruleutils.c:9982
static void get_rule_windowclause(Query *query, deparse_context *context)
Definition: ruleutils.c:5943
#define PRETTY_INDENT(context)
Definition: ruleutils.c:100
ParseExprKind
Definition: parse_node.h:38
List * values_lists
Definition: parsenodes.h:1072
Node * quals
Definition: primnodes.h:1511
bool hasDistinctOn
Definition: parsenodes.h:129
List * windowClause
Definition: parsenodes.h:154
List * targetList
Definition: parsenodes.h:140
List * distinctClause
Definition: parsenodes.h:156
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:7793
static RangeTblEntry * get_simple_values_rte(Query *query, TupleDesc resultDesc)
Definition: ruleutils.c:5309
static void get_rule_groupingset(GroupingSet *gset, List *targetlist, bool omit_parens, deparse_context *context)
Definition: ruleutils.c:5825
#define PRETTYINDENT_STD
Definition: ruleutils.c:84
ParseExprKind special_exprkind
Definition: ruleutils.c:120
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7898
#define lfirst(lc)
Definition: pg_list.h:190
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:5068
List * groupClause
Definition: parsenodes.h:148
StringInfo buf
Definition: ruleutils.c:112
Node * havingQual
Definition: parsenodes.h:152

◆ get_coercion_expr()

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

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

9514 {
9515  StringInfo buf = context->buf;
9516 
9517  /*
9518  * Since parse_coerce.c doesn't immediately collapse application of
9519  * length-coercion functions to constants, what we'll typically see in
9520  * such cases is a Const with typmod -1 and a length-coercion function
9521  * right above it. Avoid generating redundant output. However, beware of
9522  * suppressing casts when the user actually wrote something like
9523  * 'foo'::text::char(3).
9524  *
9525  * Note: it might seem that we are missing the possibility of needing to
9526  * print a COLLATE clause for such a Const. However, a Const could only
9527  * have nondefault collation in a post-constant-folding tree, in which the
9528  * length coercion would have been folded too. See also the special
9529  * handling of CollateExpr in coerce_to_target_type(): any collation
9530  * marking will be above the coercion node, not below it.
9531  */
9532  if (arg && IsA(arg, Const) &&
9533  ((Const *) arg)->consttype == resulttype &&
9534  ((Const *) arg)->consttypmod == -1)
9535  {
9536  /* Show the constant without normal ::typename decoration */
9537  get_const_expr((Const *) arg, context, -1);
9538  }
9539  else
9540  {
9541  if (!PRETTY_PAREN(context))
9542  appendStringInfoChar(buf, '(');
9543  get_rule_expr_paren(arg, context, false, parentNode);
9544  if (!PRETTY_PAREN(context))
9545  appendStringInfoChar(buf, ')');
9546  }
9547 
9548  /*
9549  * Never emit resulttype(arg) functional notation. A pg_proc entry could
9550  * take precedence, and a resulttype in pg_temp would require schema
9551  * qualification that format_type_with_typemod() would usually omit. We've
9552  * standardized on arg::resulttype, but CAST(arg AS resulttype) notation
9553  * would work fine.
9554  */
9555  appendStringInfo(buf, "::%s",
9556  format_type_with_typemod(resulttype, resulttypmod));
9557 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static void get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
Definition: ruleutils.c:7866
static void get_const_expr(Const *constval, deparse_context *context, int showtype)
Definition: ruleutils.c:9575
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
static char * buf
Definition: pg_test_fsync.c:67
#define PRETTY_PAREN(context)
Definition: ruleutils.c:99
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:345
StringInfo buf
Definition: ruleutils.c:112

◆ get_column_alias_list()

static void get_column_alias_list ( deparse_columns colinfo,
deparse_context context 
)
static

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

10412 {
10413  StringInfo buf = context->buf;
10414  int i;
10415  bool first = true;
10416 
10417  /* Don't print aliases if not needed */
10418  if (!colinfo->printaliases)
10419  return;
10420 
10421  for (i = 0; i < colinfo->num_new_cols; i++)
10422  {
10423  char *colname = colinfo->new_colnames[i];
10424 
10425  if (first)
10426  {
10427  appendStringInfoChar(buf, '(');
10428  first = false;
10429  }
10430  else
10431  appendStringInfoString(buf, ", ");
10433  }
10434  if (!first)
10435  appendStringInfoChar(buf, ')');
10436 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10697
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
StringInfo buf
Definition: ruleutils.c:112
int i
char ** new_colnames
Definition: ruleutils.c:255

◆ get_const_collation()

static void get_const_collation ( Const constval,
deparse_context context 
)
static

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

9706 {
9707  StringInfo buf = context->buf;
9708 
9709  if (OidIsValid(constval->constcollid))
9710  {
9711  Oid typcollation = get_typcollation(constval->consttype);
9712 
9713  if (constval->constcollid != typcollation)
9714  {
9715  appendStringInfo(buf, " COLLATE %s",
9717  }
9718  }
9719 }
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:11213
Oid consttype
Definition: primnodes.h:210
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
Oid constcollid
Definition: primnodes.h:212
static char * buf
Definition: pg_test_fsync.c:67
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2823
StringInfo buf
Definition: ruleutils.c:112

◆ get_const_expr()

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

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

9576 {
9577  StringInfo buf = context->buf;
9578  Oid typoutput;
9579  bool typIsVarlena;
9580  char *extval;
9581  bool needlabel = false;
9582 
9583  if (constval->constisnull)
9584  {
9585  /*
9586  * Always label the type of a NULL constant to prevent misdecisions
9587  * about type when reparsing.
9588  */
9589  appendStringInfoString(buf, "NULL");
9590  if (showtype >= 0)
9591  {
9592  appendStringInfo(buf, "::%s",
9594  constval->consttypmod));
9595  get_const_collation(constval, context);
9596  }
9597  return;
9598  }
9599 
9600  getTypeOutputInfo(constval->consttype,
9601  &typoutput, &typIsVarlena);
9602 
9603  extval = OidOutputFunctionCall(typoutput, constval->constvalue);
9604 
9605  switch (constval->consttype)
9606  {
9607  case INT4OID:
9608 
9609  /*
9610  * INT4 can be printed without any decoration, unless it is
9611  * negative; in that case print it as '-nnn'::integer to ensure
9612  * that the output will re-parse as a constant, not as a constant
9613  * plus operator. In most cases we could get away with printing
9614  * (-nnn) instead, because of the way that gram.y handles negative
9615  * literals; but that doesn't work for INT_MIN, and it doesn't
9616  * seem that much prettier anyway.
9617  */
9618  if (extval[0] != '-')
9619  appendStringInfoString(buf, extval);
9620  else
9621  {
9622  appendStringInfo(buf, "'%s'", extval);
9623  needlabel = true; /* we must attach a cast */
9624  }
9625  break;
9626 
9627  case NUMERICOID:
9628 
9629  /*
9630  * NUMERIC can be printed without quotes if it looks like a float
9631  * constant (not an integer, and not Infinity or NaN) and doesn't
9632  * have a leading sign (for the same reason as for INT4).
9633  */
9634  if (isdigit((unsigned char) extval[0]) &&
9635  strcspn(extval, "eE.") != strlen(extval))
9636  {
9637  appendStringInfoString(buf, extval);
9638  }
9639  else
9640  {
9641  appendStringInfo(buf, "'%s'", extval);
9642  needlabel = true; /* we must attach a cast */
9643  }
9644  break;
9645 
9646  case BOOLOID:
9647  if (strcmp(extval, "t") == 0)
9648  appendStringInfoString(buf, "true");
9649  else
9650  appendStringInfoString(buf, "false");
9651  break;
9652 
9653  default:
9654  simple_quote_literal(buf, extval);
9655  break;
9656  }
9657 
9658  pfree(extval);
9659 
9660  if (showtype < 0)
9661  return;
9662 
9663  /*
9664  * For showtype == 0, append ::typename unless the constant will be
9665  * implicitly typed as the right type when it is read in.
9666  *
9667  * XXX this code has to be kept in sync with the behavior of the parser,
9668  * especially make_const.
9669  */
9670  switch (constval->consttype)
9671  {
9672  case BOOLOID:
9673  case UNKNOWNOID:
9674  /* These types can be left unlabeled */
9675  needlabel = false;
9676  break;
9677  case INT4OID:
9678  /* We determined above whether a label is needed */
9679  break;
9680  case NUMERICOID:
9681 
9682  /*
9683  * Float-looking constants will be typed as numeric, which we
9684  * checked above; but if there's a nondefault typmod we need to
9685  * show it.
9686  */
9687  needlabel |= (constval->consttypmod >= 0);
9688  break;
9689  default:
9690  needlabel = true;
9691  break;
9692  }
9693  if (needlabel || showtype > 0)
9694  appendStringInfo(buf, "::%s",
9696  constval->consttypmod));
9697 
9698  get_const_collation(constval, context);
9699 }
Datum constvalue
Definition: primnodes.h:214
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2674
unsigned int Oid
Definition: postgres_ext.h:31
Oid consttype
Definition: primnodes.h:210
void pfree(void *pointer)
Definition: mcxt.c:1056
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
static void simple_quote_literal(StringInfo buf, const char *val)
Definition: ruleutils.c:9725
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static void get_const_collation(Const *constval, deparse_context *context)
Definition: ruleutils.c:9705
static char * buf
Definition: pg_test_fsync.c:67
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:345
int32 consttypmod
Definition: primnodes.h:211
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1655
StringInfo buf
Definition: ruleutils.c:112
bool constisnull
Definition: primnodes.h:215

◆ get_delete_query_def()

static void get_delete_query_def ( Query query,
deparse_context context 
)
static

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

6506 {
6507  StringInfo buf = context->buf;
6508  RangeTblEntry *rte;
6509 
6510  /* Insert the WITH clause if given */
6511  get_with_clause(query, context);
6512 
6513  /*
6514  * Start the query with DELETE FROM relname
6515  */
6516  rte = rt_fetch(query->resultRelation, query->rtable);
6517  Assert(rte->rtekind == RTE_RELATION);
6518  if (PRETTY_INDENT(context))
6519  {
6520  appendStringInfoChar(buf, ' ');
6521  context->indentLevel += PRETTYINDENT_STD;
6522  }
6523  appendStringInfo(buf, "DELETE FROM %s%s",
6524  only_marker(rte),
6526  if (rte->alias != NULL)
6527  appendStringInfo(buf, " %s",
6529 
6530  /* Add the USING clause if given */
6531  get_from_clause(query, " USING ", context);
6532 
6533  /* Add a WHERE clause if given */
6534  if (query->jointree->quals != NULL)
6535  {
6536  appendContextKeyword(context, " WHERE ",
6538  get_rule_expr(query->jointree->quals, context, false);
6539  }
6540 
6541  /* Add RETURNING if present */
6542  if (query->returningList)
6543  {
6544  appendContextKeyword(context, " RETURNING",
6546  get_target_list(query->returningList, context, NULL);
6547  }
6548 }
#define NIL
Definition: pg_list.h:65
static void get_with_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:5111
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10697
Alias * alias
Definition: parsenodes.h:1112
FromExpr * jointree
Definition: parsenodes.h:138
int resultRelation
Definition: parsenodes.h:122
static void get_target_list(List *targetList, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5505
static void get_from_clause(Query *query, const char *prefix, deparse_context *context)
Definition: ruleutils.c:9982
#define PRETTY_INDENT(context)
Definition: ruleutils.c:100
Node * quals
Definition: primnodes.h:1511
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:10821
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
List * rtable
Definition: parsenodes.h:137
static char * buf
Definition: pg_test_fsync.c:67
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:7793
List * returningList
Definition: parsenodes.h:146
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define PRETTYINDENT_STD
Definition: ruleutils.c:84
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
#define Assert(condition)
Definition: c.h:739
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7898
char * aliasname
Definition: primnodes.h:42
#define only_marker(rte)
Definition: ruleutils.c:484
RTEKind rtekind
Definition: parsenodes.h:974
StringInfo buf
Definition: ruleutils.c:112

◆ get_from_clause()

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

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

9983 {
9984  StringInfo buf = context->buf;
9985  bool first = true;
9986  ListCell *l;
9987 
9988  /*
9989  * We use the query's jointree as a guide to what to print. However, we
9990  * must ignore auto-added RTEs that are marked not inFromCl. (These can
9991  * only appear at the top level of the jointree, so it's sufficient to
9992  * check here.) This check also ensures we ignore the rule pseudo-RTEs
9993  * for NEW and OLD.
9994  */
9995  foreach(l, query->jointree->fromlist)
9996  {
9997  Node *jtnode = (Node *) lfirst(l);
9998 
9999  if (IsA(jtnode, RangeTblRef))
10000  {
10001  int varno = ((RangeTblRef *) jtnode)->rtindex;
10002  RangeTblEntry *rte = rt_fetch(varno, query->rtable);
10003 
10004  if (!rte->inFromCl)
10005  continue;
10006  }
10007 
10008  if (first)
10009  {
10010  appendContextKeyword(context, prefix,
10012  first = false;
10013 
10014  get_from_clause_item(jtnode, query, context);
10015  }
10016  else
10017  {
10018  StringInfoData itembuf;
10019 
10020  appendStringInfoString(buf, ", ");
10021 
10022  /*
10023  * Put the new FROM item's text into itembuf so we can decide
10024  * after we've got it whether or not it needs to go on a new line.
10025  */
10026  initStringInfo(&itembuf);
10027  context->buf = &itembuf;
10028 
10029  get_from_clause_item(jtnode, query, context);
10030 
10031  /* Restore context's output buffer */
10032  context->buf = buf;
10033 
10034  /* Consider line-wrapping if enabled */
10035  if (PRETTY_INDENT(context) && context->wrapColumn >= 0)
10036  {
10037  /* Does the new item start with a new line? */
10038  if (itembuf.len > 0 && itembuf.data[0] == '\n')
10039  {
10040  /* If so, we shouldn't add anything */
10041  /* instead, remove any trailing spaces currently in buf */
10043  }
10044  else
10045  {
10046  char *trailing_nl;
10047 
10048  /* Locate the start of the current line in the buffer */
10049  trailing_nl = strrchr(buf->data, '\n');
10050  if (trailing_nl == NULL)
10051  trailing_nl = buf->data;
10052  else
10053  trailing_nl++;
10054 
10055  /*
10056  * Add a newline, plus some indentation, if the new item
10057  * would cause an overflow.
10058  */
10059  if (strlen(trailing_nl) + itembuf.len > context->wrapColumn)
10060  appendContextKeyword(context, "", -PRETTYINDENT_STD,
10063  }
10064  }
10065 
10066  /* Add the new item */
10067  appendBinaryStringInfo(buf, itembuf.data, itembuf.len);
10068 
10069  /* clean up */
10070  pfree(itembuf.data);
10071  }
10072  }
10073 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
FromExpr * jointree
Definition: parsenodes.h:138
#define PRETTYINDENT_VAR
Definition: ruleutils.c:86
Definition: nodes.h:525
#define PRETTY_INDENT(context)
Definition: ruleutils.c:100
List * fromlist
Definition: primnodes.h:1510
void pfree(void *pointer)
Definition: mcxt.c:1056
List * rtable
Definition: parsenodes.h:137
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:7793
static void removeStringInfoSpaces(StringInfo str)
Definition: ruleutils.c:7847
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define PRETTYINDENT_STD
Definition: ruleutils.c:84
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define lfirst(lc)
Definition: pg_list.h:190
StringInfo buf
Definition: ruleutils.c:112
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:10076

◆ get_from_clause_coldeflist()

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

Definition at line 10451 of file ruleutils.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert, attcollation, attname, atttypid, 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().

10454 {
10455  StringInfo buf = context->buf;
10456  ListCell *l1;
10457  ListCell *l2;
10458  ListCell *l3;
10459  ListCell *l4;
10460  int i;
10461 
10462  appendStringInfoChar(buf, '(');
10463 
10464  i = 0;
10465  forfour(l1, rtfunc->funccoltypes,
10466  l2, rtfunc->funccoltypmods,
10467  l3, rtfunc->funccolcollations,
10468  l4, rtfunc->funccolnames)
10469  {
10470  Oid atttypid = lfirst_oid(l1);
10471  int32 atttypmod = lfirst_int(l2);
10472  Oid attcollation = lfirst_oid(l3);
10473  char *attname;
10474 
10475  if (colinfo)
10476  attname = colinfo->colnames[i];
10477  else
10478  attname = strVal(lfirst(l4));
10479 
10480  Assert(attname); /* shouldn't be any dropped columns here */
10481 
10482  if (i > 0)
10483  appendStringInfoString(buf, ", ");
10484  appendStringInfo(buf, "%s %s",
10485  quote_identifier(attname),
10486  format_type_with_typemod(atttypid, atttypmod));
10487  if (OidIsValid(attcollation) &&
10488  attcollation != get_typcollation(atttypid))
10489  appendStringInfo(buf, " COLLATE %s",
10490  generate_collation_name(attcollation));
10491 
10492  i++;
10493  }
10494 
10495  appendStringInfoChar(buf, ')');
10496 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10697
#define strVal(v)
Definition: value.h:54
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:11213
signed int int32
Definition: c.h:347
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
NameData attname
Definition: pg_attribute.h:40
#define lfirst_int(lc)
Definition: pg_list.h:191
Oid attcollation
Definition: pg_attribute.h:164
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
Oid atttypid
Definition: pg_attribute.h:49
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:345
List * funccoltypmods
Definition: parsenodes.h:1151
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2823
List * funccolcollations
Definition: parsenodes.h:1152
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
#define forfour(cell1, list1, cell2, list2, cell3, list3, cell4, list4)
Definition: pg_list.h:476
StringInfo buf
Definition: ruleutils.c:112
int i
#define lfirst_oid(lc)
Definition: pg_list.h:192
char ** colnames
Definition: ruleutils.c:238

◆ get_from_clause_item()

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

Definition at line 10076 of file ruleutils.c.

References RangeTblEntry::alias, JoinExpr::alias, appendContextKeyword(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), generate_unaccent_rules::args, buf, deparse_context::buf, RangeTblEntry::ctename, deparse_columns_fetch, elog, ERROR, RangeTblFunction::funccolnames, RangeTblFunction::funcexpr, RangeTblEntry::funcordinality, RangeTblEntry::functions, generate_relation_name(), get_column_alias_list(), get_from_clause_coldeflist(), get_query_def(), get_relation_name(), get_rtable_name(), get_rule_expr(), get_rule_expr_funccall(), get_tablefunc(), get_tablesample_def(), get_values_def(), deparse_context::indentLevel, IsA, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, JoinExpr::jointype, JoinExpr::larg, RangeTblEntry::lateral, lfirst, linitial, list_concat(), list_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().

10077 {
10078  StringInfo buf = context->buf;
10080 
10081  if (IsA(jtnode, RangeTblRef))
10082  {
10083  int varno = ((RangeTblRef *) jtnode)->rtindex;
10084  RangeTblEntry *rte = rt_fetch(varno, query->rtable);
10085  char *refname = get_rtable_name(varno, context);
10086  deparse_columns *colinfo = deparse_columns_fetch(varno, dpns);
10087  RangeTblFunction *rtfunc1 = NULL;
10088  bool printalias;
10089 
10090  if (rte->lateral)
10091  appendStringInfoString(buf, "LATERAL ");
10092 
10093  /* Print the FROM item proper */
10094  switch (rte->rtekind)
10095  {
10096  case RTE_RELATION:
10097  /* Normal relation RTE */
10098  appendStringInfo(buf, "%s%s",
10099  only_marker(rte),
10101  context->namespaces));
10102  break;
10103  case RTE_SUBQUERY:
10104  /* Subquery RTE */
10105  appendStringInfoChar(buf, '(');
10106  get_query_def(rte->subquery, buf, context->namespaces, NULL,
10107  context->prettyFlags, context->wrapColumn,
10108  context->indentLevel);
10109  appendStringInfoChar(buf, ')');
10110  break;
10111  case RTE_FUNCTION:
10112  /* Function RTE */
10113  rtfunc1 = (RangeTblFunction *) linitial(rte->functions);
10114 
10115  /*
10116  * Omit ROWS FROM() syntax for just one function, unless it
10117  * has both a coldeflist and WITH ORDINALITY. If it has both,
10118  * we must use ROWS FROM() syntax to avoid ambiguity about
10119  * whether the coldeflist includes the ordinality column.
10120  */
10121  if (list_length(rte->functions) == 1 &&
10122  (rtfunc1->funccolnames == NIL || !rte->funcordinality))
10123  {
10124  get_rule_expr_funccall(rtfunc1->funcexpr, context, true);
10125  /* we'll print the coldeflist below, if it has one */
10126  }
10127  else
10128  {
10129  bool all_unnest;
10130  ListCell *lc;
10131 
10132  /*
10133  * If all the function calls in the list are to unnest,
10134  * and none need a coldeflist, then collapse the list back
10135  * down to UNNEST(args). (If we had more than one
10136  * built-in unnest function, this would get more
10137  * difficult.)
10138  *
10139  * XXX This is pretty ugly, since it makes not-terribly-
10140  * future-proof assumptions about what the parser would do
10141  * with the output; but the alternative is to emit our
10142  * nonstandard ROWS FROM() notation for what might have
10143  * been a perfectly spec-compliant multi-argument
10144  * UNNEST().
10145  */
10146  all_unnest = true;
10147  foreach(lc, rte->functions)
10148  {
10149  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
10150 
10151  if (!IsA(rtfunc->funcexpr, FuncExpr) ||
10152  ((FuncExpr *) rtfunc->funcexpr)->funcid != F_ARRAY_UNNEST ||
10153  rtfunc->funccolnames != NIL)
10154  {
10155  all_unnest = false;
10156  break;
10157  }
10158  }
10159 
10160  if (all_unnest)
10161  {
10162  List *allargs = NIL;
10163 
10164  foreach(lc, rte->functions)
10165  {
10166  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
10167  List *args = ((FuncExpr *) rtfunc->funcexpr)->args;
10168 
10169  allargs = list_concat(allargs, args);
10170  }
10171 
10172  appendStringInfoString(buf, "UNNEST(");
10173  get_rule_expr((Node *) allargs, context, true);
10174  appendStringInfoChar(buf, ')');
10175  }
10176  else
10177  {
10178  int funcno = 0;
10179 
10180  appendStringInfoString(buf, "ROWS FROM(");
10181  foreach(lc, rte->functions)
10182  {
10183  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
10184 
10185  if (funcno > 0)
10186  appendStringInfoString(buf, ", ");
10187  get_rule_expr_funccall(rtfunc->funcexpr, context, true);
10188  if (rtfunc->funccolnames != NIL)
10189  {
10190  /* Reconstruct the column definition list */
10191  appendStringInfoString(buf, " AS ");
10193  NULL,
10194  context);
10195  }
10196  funcno++;
10197  }
10198  appendStringInfoChar(buf, ')');
10199  }
10200  /* prevent printing duplicate coldeflist below */
10201  rtfunc1 = NULL;
10202  }
10203  if (rte->funcordinality)
10204  appendStringInfoString(buf, " WITH ORDINALITY");
10205  break;
10206  case RTE_TABLEFUNC:
10207  get_tablefunc(rte->tablefunc, context, true);
10208  break;
10209  case RTE_VALUES:
10210  /* Values list RTE */
10211  appendStringInfoChar(buf, '(');
10212  get_values_def(rte->values_lists, context);
10213  appendStringInfoChar(buf, ')');
10214  break;
10215  case RTE_CTE:
10217  break;
10218  default:
10219  elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
10220  break;
10221  }
10222 
10223  /* Print the relation alias, if needed */
10224  printalias = false;
10225  if (rte->alias != NULL)
10226  {
10227  /* Always print alias if user provided one */
10228  printalias = true;
10229  }
10230  else if (colinfo->printaliases)
10231  {
10232  /* Always print alias if we need to print column aliases */
10233  printalias = true;
10234  }
10235  else if (rte->rtekind == RTE_RELATION)
10236  {
10237  /*
10238  * No need to print alias if it's same as relation name (this
10239  * would normally be the case, but not if set_rtable_names had to
10240  * resolve a conflict).
10241  */
10242  if (strcmp(refname, get_relation_name(rte->relid)) != 0)
10243  printalias = true;
10244  }
10245  else if (rte->rtekind == RTE_FUNCTION)
10246  {
10247  /*
10248  * For a function RTE, always print alias. This covers possible
10249  * renaming of the function and/or instability of the
10250  * FigureColname rules for things that aren't simple functions.
10251  * Note we'd need to force it anyway for the columndef list case.
10252  */
10253  printalias = true;
10254  }
10255  else if (rte->rtekind == RTE_VALUES)
10256  {
10257  /* Alias is syntactically required for VALUES */
10258  printalias = true;
10259  }
10260  else if (rte->rtekind == RTE_CTE)
10261  {
10262  /*
10263  * No need to print alias if it's same as CTE name (this would
10264  * normally be the case, but not if set_rtable_names had to
10265  * resolve a conflict).
10266  */
10267  if (strcmp(refname, rte->ctename) != 0)
10268  printalias = true;
10269  }
10270  if (printalias)
10271  appendStringInfo(buf, " %s", quote_identifier(refname));
10272 
10273  /* Print the column definitions or aliases, if needed */
10274  if (rtfunc1 && rtfunc1->funccolnames != NIL)
10275  {
10276  /* Reconstruct the columndef list, which is also the aliases */
10277  get_from_clause_coldeflist(rtfunc1, colinfo, context);
10278  }
10279  else
10280  {
10281  /* Else print column aliases as needed */
10282  get_column_alias_list(colinfo, context);
10283  }
10284 
10285  /* Tablesample clause must go after any alias */
10286  if (rte->rtekind == RTE_RELATION && rte->tablesample)
10287  get_tablesample_def(rte->tablesample, context);
10288  }
10289  else if (IsA(jtnode, JoinExpr))
10290  {
10291  JoinExpr *j = (JoinExpr *) jtnode;
10292  deparse_columns *colinfo = deparse_columns_fetch(j->rtindex, dpns);
10293  bool need_paren_on_right;
10294 
10295  need_paren_on_right = PRETTY_PAREN(context) &&
10296  !IsA(j->rarg, RangeTblRef) &&
10297  !(IsA(j->rarg, JoinExpr) &&((JoinExpr *) j->rarg)->alias != NULL);
10298 
10299  if (!PRETTY_PAREN(context) || j->alias != NULL)
10300  appendStringInfoChar(buf, '(');
10301 
10302  get_from_clause_item(j->larg, query, context);
10303 
10304  switch (j->jointype)
10305  {
10306  case JOIN_INNER:
10307  if (j->quals)
10308  appendContextKeyword(context, " JOIN ",
10312  else
10313  appendContextKeyword(context, " CROSS JOIN ",
10317  break;
10318  case JOIN_LEFT:
10319  appendContextKeyword(context, " LEFT JOIN ",
10323  break;
10324  case JOIN_FULL:
10325  appendContextKeyword(context, " FULL JOIN ",
10329  break;
10330  case JOIN_RIGHT:
10331  appendContextKeyword(context, " RIGHT JOIN ",
10335  break;
10336  default:
10337  elog(ERROR, "unrecognized join type: %d",
10338  (int) j->jointype);
10339  }
10340 
10341  if (need_paren_on_right)
10342  appendStringInfoChar(buf, '(');
10343  get_from_clause_item(j->rarg, query, context);
10344  if (need_paren_on_right)
10345  appendStringInfoChar(buf, ')');
10346 
10347  if (j->usingClause)
10348  {
10349  ListCell *lc;
10350  bool first = true;
10351 
10352  appendStringInfoString(buf, " USING (");
10353  /* Use the assigned names, not what's in usingClause */
10354  foreach(lc, colinfo->usingNames)
10355  {
10356  char *colname = (char *) lfirst(lc);
10357 
10358  if (first)
10359  first = false;
10360  else
10361  appendStringInfoString(buf, ", ");
10363  }
10364  appendStringInfoChar(buf, ')');
10365  }
10366  else if (j->quals)
10367  {
10368  appendStringInfoString(buf, " ON ");
10369  if (!PRETTY_PAREN(context))
10370  appendStringInfoChar(buf, '(');
10371  get_rule_expr(j->quals, context, false);
10372  if (!PRETTY_PAREN(context))
10373  appendStringInfoChar(buf, ')');
10374  }
10375  else if (j->jointype != JOIN_INNER)
10376  {
10377  /* If we didn't say CROSS JOIN above, we must provide an ON */
10378  appendStringInfoString(buf, " ON TRUE");
10379  }
10380 
10381  if (!PRETTY_PAREN(context) || j->alias != NULL)
10382  appendStringInfoChar(buf, ')');
10383 
10384  /* Yes, it's correct to put alias after the right paren ... */
10385  if (j->alias != NULL)
10386  {
10387  /*
10388  * Note that it's correct to emit an alias clause if and only if
10389  * there was one originally. Otherwise we'd be converting a named
10390  * join to unnamed or vice versa, which creates semantic
10391  * subtleties we don't want. However, we might print a different
10392  * alias name than was there originally.
10393  */
10394  appendStringInfo(buf, " %s",
10396  context)));
10397  get_column_alias_list(colinfo, context);
10398  }
10399  }
10400  else
10401  elog(ERROR, "unrecognized node type: %d",
10402  (int) nodeTag(jtnode));
10403 }
List * namespaces
Definition: ruleutils.c:113
#define NIL
Definition: pg_list.h:65
static char * get_relation_name(Oid relid)
Definition: ruleutils.c:10801
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define PRETTYINDENT_JOIN
Definition: ruleutils.c:85
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10697
Alias * alias
Definition: parsenodes.h:1112
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
bool funcordinality
Definition: parsenodes.h:1062
List * values_lists
Definition: parsenodes.h:1072
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:10821
Node * larg
Definition: primnodes.h:1490
static void get_tablesample_def(TableSampleClause *tablesample, deparse_context *context)
Definition: ruleutils.c:10502
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define linitial(l)
Definition: pg_list.h:195
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
List * usingNames
Definition: ruleutils.c:285
TableFunc * tablefunc
Definition: parsenodes.h:1067
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
#define PRETTY_PAREN(context)
Definition: ruleutils.c:99
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:7793
#define deparse_columns_fetch(rangetable_index, dpns)
Definition: ruleutils.c:289
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define PRETTYINDENT_STD
Definition: ruleutils.c:84
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
List * usingClause
Definition: primnodes.h:1492
Node * quals
Definition: primnodes.h:1493
static void get_tablefunc(TableFunc *tf, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:9877
Node * rarg
Definition: primnodes.h:1491
Alias * alias
Definition: primnodes.h:1494
JoinType jointype
Definition: primnodes.h:1488
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7898
#define lfirst(lc)
Definition: pg_list.h:190
List * functions
Definition: parsenodes.h:1061
#define only_marker(rte)
Definition: ruleutils.c:484
static int list_length(const List *l)
Definition: pg_list.h:169
static void get_query_def(Query *query, StringInfo buf, List *parentnamespace, TupleDesc resultDesc, int prettyFlags, int wrapColumn, int startIndent)
Definition: ruleutils.c:4994
#define nodeTag(nodeptr)
Definition: nodes.h:530
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:5068
RTEKind rtekind
Definition: parsenodes.h:974
static void get_column_alias_list(deparse_columns *colinfo, deparse_context *context)
Definition: ruleutils.c:10411
char * ctename
Definition: parsenodes.h:1077
Query * subquery
Definition: parsenodes.h:1009
StringInfo buf
Definition: ruleutils.c:112
#define elog(elevel,...)
Definition: elog.h:228
static void get_from_clause_coldeflist(RangeTblFunction *rtfunc, deparse_columns *colinfo, deparse_context *context)
Definition: ruleutils.c:10451
static void get_rule_expr_funccall(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:9115
int rtindex
Definition: primnodes.h:1495
Definition: pg_list.h:50
struct TableSampleClause * tablesample
Definition: parsenodes.h:1004
static char * get_rtable_name(int rtindex, deparse_context *context)
Definition: ruleutils.c:4547
static void get_from_clause_item(Node *jtnode, Query *query, deparse_context *context)
Definition: ruleutils.c:10076

◆ get_func_expr()

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

Definition at line 9226 of file ruleutils.c.

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

Referenced by get_rule_expr().

9228 {
9229  StringInfo buf = context->buf;
9230  Oid funcoid = expr->funcid;
9231  Oid argtypes[FUNC_MAX_ARGS];
9232  int nargs;
9233  List *argnames;
9234  bool use_variadic;
9235  ListCell *l;
9236 
9237  /*
9238  * If the function call came from an implicit coercion, then just show the
9239  * first argument --- unless caller wants to see implicit coercions.
9240  */
9241  if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
9242  {
9243  get_rule_expr_paren((Node *) linitial(expr->args), context,
9244  false, (Node *) expr);
9245  return;
9246  }
9247 
9248  /*
9249  * If the function call came from a cast, then show the first argument
9250  * plus an explicit cast operation.
9251  */
9252  if (expr->funcformat == COERCE_EXPLICIT_CAST ||
9254  {
9255  Node *arg = linitial(expr->args);
9256  Oid rettype = expr->funcresulttype;
9257  int32 coercedTypmod;
9258 
9259  /* Get the typmod if this is a length-coercion function */
9260  (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
9261 
9262  get_coercion_expr(arg, context,
9263  rettype, coercedTypmod,
9264  (Node *) expr);
9265 
9266  return;
9267  }
9268 
9269  /*
9270  * Normal function: display as proname(args). First we need to extract
9271  * the argument datatypes.
9272  */
9273  if (list_length(expr->args) > FUNC_MAX_ARGS)
9274  ereport(ERROR,
9275  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
9276  errmsg("too many arguments")));
9277  nargs = 0;
9278  argnames = NIL;
9279  foreach(l, expr->args)
9280  {
9281  Node *arg = (Node *) lfirst(l);
9282 
9283  if (IsA(arg, NamedArgExpr))
9284  argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
9285  argtypes[nargs] = exprType(arg);
9286  nargs++;
9287  }
9288 
9289  appendStringInfo(buf, "%s(",
9290  generate_function_name(funcoid, nargs,
9291  argnames, argtypes,
9292  expr->funcvariadic,
9293  &use_variadic,
9294  context->special_exprkind));
9295  nargs = 0;
9296  foreach(l, expr->args)
9297  {
9298  if (nargs++ > 0)
9299  appendStringInfoString(buf, ", ");
9300  if (use_variadic && lnext(expr->args, l) == NULL)
9301  appendStringInfoString(buf, "VARIADIC ");
9302  get_rule_expr((Node *) lfirst(l), context, true);
9303  }
9304  appendStringInfoChar(buf, ')');
9305 }
Oid funcresulttype
Definition: primnodes.h:470
#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:10923
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static void get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
Definition: ruleutils.c:7866
List * args
Definition: primnodes.h:477
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
bool exprIsLengthCoercion(const Node *expr, int32 *coercedTypmod)
Definition: nodeFuncs.c:512
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:347
#define FUNC_MAX_ARGS
CoercionForm funcformat
Definition: primnodes.h:474
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define linitial(l)
Definition: pg_list.h:195
Oid funcid
Definition: primnodes.h:469
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel, rest)
Definition: elog.h:141
static void get_coercion_expr(Node *arg, deparse_context *context, Oid resulttype, int32 resulttypmod, Node *parentNode)
Definition: ruleutils.c:9511
ParseExprKind special_exprkind
Definition: ruleutils.c:120
List * lappend(List *list, void *datum)
Definition: list.c:322
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7898
#define lfirst(lc)
Definition: pg_list.h:190
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:169
StringInfo buf
Definition: ruleutils.c:112
int errmsg(const char *fmt,...)
Definition: elog.c:822
void * arg
Definition: pg_list.h:50
bool funcvariadic
Definition: primnodes.h:472

◆ get_insert_query_def()

static void get_insert_query_def ( Query query,
deparse_context context 
)
static

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

6085 {
6086  StringInfo buf = context->buf;
6087  RangeTblEntry *select_rte = NULL;
6088  RangeTblEntry *values_rte = NULL;
6089  RangeTblEntry *rte;
6090  char *sep;
6091  ListCell *l;
6092  List *strippedexprs;
6093 
6094  /* Insert the WITH clause if given */
6095  get_with_clause(query, context);
6096 
6097  /*
6098  * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
6099  * single RTE for the SELECT or VALUES. Plain VALUES has neither.
6100  */
6101  foreach(l, query->rtable)
6102  {
6103  rte = (RangeTblEntry *) lfirst(l);
6104 
6105  if (rte->rtekind == RTE_SUBQUERY)
6106  {
6107  if (select_rte)
6108  elog(ERROR, "too many subquery RTEs in INSERT");
6109  select_rte = rte;
6110  }
6111 
6112  if (rte->rtekind == RTE_VALUES)
6113  {
6114  if (values_rte)
6115  elog(ERROR, "too many values RTEs in INSERT");
6116  values_rte = rte;
6117  }
6118  }
6119  if (select_rte && values_rte)
6120  elog(ERROR, "both subquery and values RTEs in INSERT");
6121 
6122  /*
6123  * Start the query with INSERT INTO relname
6124  */
6125  rte = rt_fetch(query->resultRelation, query->rtable);
6126  Assert(rte->rtekind == RTE_RELATION);
6127 
6128  if (PRETTY_INDENT(context))
6129  {
6130  context->indentLevel += PRETTYINDENT_STD;
6131  appendStringInfoChar(buf, ' ');
6132  }
6133  appendStringInfo(buf, "INSERT INTO %s ",
6135  /* INSERT requires AS keyword for target alias */
6136  if (rte->alias != NULL)
6137  appendStringInfo(buf, "AS %s ",
6139 
6140  /*
6141  * Add the insert-column-names list. Any indirection decoration needed on
6142  * the column names can be inferred from the top targetlist.
6143  */
6144  strippedexprs = NIL;
6145  sep = "";
6146  if (query->targetList)
6147  appendStringInfoChar(buf, '(');
6148  foreach(l, query->targetList)
6149  {
6150  TargetEntry *tle = (TargetEntry *) lfirst(l);
6151 
6152  if (tle->resjunk)
6153  continue; /* ignore junk entries */
6154 
6155  appendStringInfoString(buf, sep);
6156  sep = ", ";
6157 
6158  /*
6159  * Put out name of target column; look in the catalogs, not at
6160  * tle->resname, since resname will fail to track RENAME.
6161  */
6164  tle->resno,
6165  false)));
6166 
6167  /*
6168  * Print any indirection needed (subfields or subscripts), and strip
6169  * off the top-level nodes representing the indirection assignments.
6170  * Add the stripped expressions to strippedexprs. (If it's a
6171  * single-VALUES statement, the stripped expressions are the VALUES to
6172  * print below. Otherwise they're just Vars and not really
6173  * interesting.)
6174  */
6175  strippedexprs = lappend(strippedexprs,
6176  processIndirection((Node *) tle->expr,
6177  context));
6178  }
6179  if (query->targetList)
6180  appendStringInfoString(buf, ") ");
6181 
6182  if (query->override)
6183  {
6184  if (query->override == OVERRIDING_SYSTEM_VALUE)
6185  appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
6186  else if (query->override == OVERRIDING_USER_VALUE)
6187  appendStringInfoString(buf, "OVERRIDING USER VALUE ");
6188  }
6189 
6190  if (select_rte)
6191  {
6192  /* Add the SELECT */
6193  get_query_def(select_rte->subquery, buf, NIL, NULL,
6194  context->prettyFlags, context->wrapColumn,
6195  context->indentLevel);
6196  }
6197  else if (values_rte)
6198  {
6199  /* Add the multi-VALUES expression lists */
6200  get_values_def(values_rte->values_lists, context);
6201  }
6202  else if (strippedexprs)
6203  {
6204  /* Add the single-VALUES expression list */
6205  appendContextKeyword(context, "VALUES (",
6207  get_rule_expr((Node *) strippedexprs, context, false);
6208  appendStringInfoChar(buf, ')');
6209  }
6210  else
6211  {
6212  /* No expressions, so it must be DEFAULT VALUES */
6213  appendStringInfoString(buf, "DEFAULT VALUES");
6214  }
6215 
6216  /* Add ON CONFLICT if present */
6217  if (query->onConflict)
6218  {
6219  OnConflictExpr *confl = query->onConflict;
6220 
6221  appendStringInfoString(buf, " ON CONFLICT");
6222 
6223  if (confl->arbiterElems)
6224  {
6225  /* Add the single-VALUES expression list */
6226  appendStringInfoChar(buf, '(');
6227  get_rule_expr((Node *) confl->arbiterElems, context, false);
6228  appendStringInfoChar(buf, ')');
6229 
6230  /* Add a WHERE clause (for partial indexes) if given */
6231  if (confl->arbiterWhere != NULL)
6232  {
6233  bool save_varprefix;
6234 
6235  /*
6236  * Force non-prefixing of Vars, since parser assumes that they
6237  * belong to target relation. WHERE clause does not use
6238  * InferenceElem, so this is separately required.
6239  */
6240  save_varprefix = context->varprefix;
6241  context->varprefix = false;
6242 
6243  appendContextKeyword(context, " WHERE ",
6245  get_rule_expr(confl->arbiterWhere, context, false);
6246 
6247  context->varprefix = save_varprefix;
6248  }
6249  }
6250  else if (OidIsValid(confl->constraint))
6251  {
6252  char *constraint = get_constraint_name(confl->constraint);
6253 
6254  if (!constraint)
6255  elog(ERROR, "cache lookup failed for constraint %u",
6256  confl->constraint);
6257  appendStringInfo(buf, " ON CONSTRAINT %s",
6258  quote_identifier(constraint));
6259  }
6260 
6261  if (confl->action == ONCONFLICT_NOTHING)
6262  {
6263  appendStringInfoString(buf, " DO NOTHING");
6264  }
6265  else
6266  {
6267  appendStringInfoString(buf, " DO UPDATE SET ");
6268  /* Deparse targetlist */
6270  context, rte);
6271 
6272  /* Add a WHERE clause if given */
6273  if (confl->onConflictWhere != NULL)
6274  {
6275  appendContextKeyword(context, " WHERE ",
6277  get_rule_expr(confl->onConflictWhere, context, false);
6278  }
6279  }
6280  }
6281 
6282  /* Add RETURNING if present */
6283  if (query->returningList)
6284  {
6285  appendContextKeyword(context, " RETURNING",
6287  get_target_list(query->returningList, context, NULL);
6288  }
6289 }
#define NIL
Definition: pg_list.h:65
static void get_with_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:5111
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10697
Alias * alias
Definition: parsenodes.h:1112
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:969
OnConflictExpr * onConflict
Definition: parsenodes.h:144
static Node * processIndirection(Node *node, deparse_context *context)
Definition: ruleutils.c:10589
int resultRelation
Definition: parsenodes.h:122
static void get_target_list(List *targetList, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5505
Definition: nodes.h:525
#define PRETTY_INDENT(context)
Definition: ruleutils.c:100
static void get_update_query_targetlist_def(Query *query, List *targetList, deparse_context *context, RangeTblEntry *rte)
Definition: ruleutils.c:6352
#define OidIsValid(objectId)
Definition: c.h:645
List * values_lists
Definition: parsenodes.h:1072
List * targetList
Definition: parsenodes.h:140
List * arbiterElems
Definition: primnodes.h:1529
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:10821
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
bool resjunk
Definition: primnodes.h:1414
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
static void appendContextKeyword(deparse_context *context, const char *str, int indentBefore, int indentAfter, int indentPlus)
Definition: ruleutils.c:7793
AttrNumber resno
Definition: primnodes.h:1408
List * returningList
Definition: parsenodes.h:146
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define PRETTYINDENT_STD
Definition: ruleutils.c:84
List * lappend(List *list, void *datum)
Definition: list.c:322
OnConflictAction action
Definition: primnodes.h:1526
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
OverridingKind override
Definition: parsenodes.h:142
#define Assert(condition)
Definition: c.h:739
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7898
#define lfirst(lc)
Definition: pg_list.h:190
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1407
static void get_query_def(Query *query, StringInfo buf, List *parentnamespace, TupleDesc resultDesc, int prettyFlags, int wrapColumn, int startIndent)
Definition: ruleutils.c:4994
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:5068
RTEKind rtekind
Definition: parsenodes.h:974
Node * arbiterWhere
Definition: primnodes.h:1531
Query * subquery
Definition: parsenodes.h:1009
StringInfo buf
Definition: ruleutils.c:112
#define elog(elevel,...)
Definition: elog.h:228
List * onConflictSet
Definition: primnodes.h:1535
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
Node * onConflictWhere
Definition: primnodes.h:1536
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 6957 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().

6959 {
6960  RangeTblEntry *rte;
6962  int netlevelsup;
6963  deparse_namespace *dpns;
6964  Index varno;
6965  AttrNumber varattno;
6966  TupleDesc tupleDesc;
6967  Node *expr;
6968 
6969  /*
6970  * If it's a RowExpr that was expanded from a whole-row Var, use the
6971  * column names attached to it.
6972  */
6973  if (IsA(var, RowExpr))
6974  {
6975  RowExpr *r = (RowExpr *) var;
6976 
6977  if (fieldno > 0 && fieldno <= list_length(r->colnames))
6978  return strVal(list_nth(r->colnames, fieldno - 1));
6979  }
6980 
6981  /*
6982  * If it's a Param of type RECORD, try to find what the Param refers to.
6983  */
6984  if (IsA(var, Param))
6985  {
6986  Param *param = (Param *) var;
6987  ListCell *ancestor_cell;
6988 
6989  expr = find_param_referent(param, context, &dpns, &ancestor_cell);
6990  if (expr)
6991  {
6992  /* Found a match, so recurse to decipher the field name */
6993  deparse_namespace save_dpns;
6994  const char *result;
6995 
6996  push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
6997  result = get_name_for_var_field((Var *) expr, fieldno,
6998  0, context);
6999  pop_ancestor_plan(dpns, &save_dpns);
7000  return result;
7001  }
7002  }
7003 
7004  /*
7005  * If it's a Var of type RECORD, we have to find what the Var refers to;
7006  * if not, we can use get_expr_result_tupdesc().
7007  */
7008  if (!IsA(var, Var) ||
7009  var->vartype != RECORDOID)
7010  {
7011  tupleDesc = get_expr_result_tupdesc((Node *) var, false);
7012  /* Got the tupdesc, so we can extract the field name */
7013  Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
7014  return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
7015  }
7016 
7017  /* Find appropriate nesting depth */
7018  netlevelsup = var->varlevelsup + levelsup;
7019  if (netlevelsup >= list_length(context->namespaces))
7020  elog(ERROR, "bogus varlevelsup: %d offset %d",
7021  var->varlevelsup, levelsup);
7022  dpns = (deparse_namespace *) list_nth(context->namespaces,
7023  netlevelsup);
7024 
7025  /*
7026  * If we have a syntactic referent for the Var, and we're working from a
7027  * parse tree, prefer to use the syntactic referent. Otherwise, fall back
7028  * on the semantic referent. (See comments in get_variable().)
7029  */
7030  if (var->varnosyn > 0 && dpns->plan == NULL)
7031  {
7032  varno = var->varnosyn;
7033  varattno = var->varattnosyn;
7034  }
7035  else
7036  {
7037  varno = var->varno;
7038  varattno = var->varattno;
7039  }
7040 
7041  /*
7042  * Try to find the relevant RTE in this rtable. In a plan tree, it's
7043  * likely that varno is OUTER_VAR or INNER_VAR, in which case we must dig
7044  * down into the subplans, or INDEX_VAR, which is resolved similarly.
7045  *
7046  * Note: unlike get_variable and resolve_special_varno, we need not worry
7047  * about inheritance mapping: a child Var should have the same datatype as
7048  * its parent, and here we're really only interested in the Var's type.
7049  */
7050  if (varno >= 1 && varno <= list_length(dpns->rtable))
7051  {
7052  rte = rt_fetch(varno, dpns->rtable);
7053  attnum = varattno;
7054  }
7055  else if (varno == OUTER_VAR && dpns->outer_tlist)
7056  {
7057  TargetEntry *tle;
7058  deparse_namespace save_dpns;
7059  const char *result;
7060 
7061  tle = get_tle_by_resno(dpns->outer_tlist, varattno);
7062  if (!tle)
7063  elog(ERROR, "bogus varattno for OUTER_VAR var: %d", varattno);
7064 
7065  Assert(netlevelsup == 0);
7066  push_child_plan(dpns, dpns->outer_plan, &save_dpns);
7067 
7068  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7069  levelsup, context);
7070 
7071  pop_child_plan(dpns, &save_dpns);
7072  return result;
7073  }
7074  else if (varno == INNER_VAR && dpns->inner_tlist)
7075  {
7076  TargetEntry *tle;
7077  deparse_namespace save_dpns;
7078  const char *result;
7079 
7080  tle = get_tle_by_resno(dpns->inner_tlist, varattno);
7081  if (!tle)
7082  elog(ERROR, "bogus varattno for INNER_VAR var: %d", varattno);
7083 
7084  Assert(netlevelsup == 0);
7085  push_child_plan(dpns, dpns->inner_plan, &save_dpns);
7086 
7087  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7088  levelsup, context);
7089 
7090  pop_child_plan(dpns, &save_dpns);
7091  return result;
7092  }
7093  else if (varno == INDEX_VAR && dpns->index_tlist)
7094  {
7095  TargetEntry *tle;
7096  const char *result;
7097 
7098  tle = get_tle_by_resno(dpns->index_tlist, varattno);
7099  if (!tle)
7100  elog(ERROR, "bogus varattno for INDEX_VAR var: %d", varattno);
7101 
7102  Assert(netlevelsup == 0);
7103 
7104  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7105  levelsup, context);
7106 
7107  return result;
7108  }
7109  else
7110  {
7111  elog(ERROR, "bogus varno: %d", varno);
7112  return NULL; /* keep compiler quiet */
7113  }
7114 
7115  if (attnum == InvalidAttrNumber)
7116  {
7117  /* Var is whole-row reference to RTE, so select the right field */
7118  return get_rte_attribute_name(rte, fieldno);
7119  }
7120 
7121  /*
7122  * This part has essentially the same logic as the parser's
7123  * expandRecordVariable() function, but we are dealing with a different
7124  * representation of the input context, and we only need one field name
7125  * not a TupleDesc. Also, we need special cases for finding subquery and
7126  * CTE subplans when deparsing Plan trees.
7127  */
7128  expr = (Node *) var; /* default if we can't drill down */
7129 
7130  switch (rte->rtekind)
7131  {
7132  case RTE_RELATION:
7133  case RTE_VALUES:
7134  case RTE_NAMEDTUPLESTORE:
7135  case RTE_RESULT:
7136 
7137  /*
7138  * This case should not occur: a column of a table, values list,
7139  * or ENR shouldn't have type RECORD. Fall through and fail (most
7140  * likely) at the bottom.
7141  */
7142  break;
7143  case RTE_SUBQUERY:
7144  /* Subselect-in-FROM: examine sub-select's output expr */
7145  {
7146  if (rte->subquery)
7147  {
7149  attnum);
7150 
7151  if (ste == NULL || ste->resjunk)
7152  elog(ERROR, "subquery %s does not have attribute %d",
7153  rte->eref->aliasname, attnum);
7154  expr = (Node *) ste->expr;
7155  if (IsA(expr, Var))
7156  {
7157  /*
7158  * Recurse into the sub-select to see what its Var
7159  * refers to. We have to build an additional level of
7160  * namespace to keep in step with varlevelsup in the
7161  * subselect.
7162  */
7163  deparse_namespace mydpns;
7164  const char *result;
7165 
7166  set_deparse_for_query(&mydpns, rte->subquery,
7167  context->namespaces);
7168 
7169  context->namespaces = lcons(&mydpns,
7170  context->namespaces);
7171 
7172  result = get_name_for_var_field((Var *) expr, fieldno,
7173  0, context);
7174 
7175  context->namespaces =
7176  list_delete_first(context->namespaces);
7177 
7178  return result;
7179  }
7180  /* else fall through to inspect the expression */
7181  }
7182  else
7183  {
7184  /*
7185  * We're deparsing a Plan tree so we don't have complete
7186  * RTE entries (in particular, rte->subquery is NULL). But
7187  * the only place we'd see a Var directly referencing a
7188  * SUBQUERY RTE is in a SubqueryScan plan node, and we can
7189  * look into the child plan's tlist instead.
7190  */
7191  TargetEntry *tle;
7192  deparse_namespace save_dpns;
7193  const char *result;
7194 
7195  if (!dpns->inner_plan)
7196  elog(ERROR, "failed to find plan for subquery %s",
7197  rte->eref->aliasname);
7198  tle = get_tle_by_resno(dpns->inner_tlist, attnum);
7199  if (!tle)
7200  elog(ERROR, "bogus varattno for subquery var: %d",
7201  attnum);
7202  Assert(netlevelsup == 0);
7203  push_child_plan(dpns, dpns->inner_plan, &save_dpns);
7204 
7205  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7206  levelsup, context);
7207 
7208  pop_child_plan(dpns, &save_dpns);
7209  return result;
7210  }
7211  }
7212  break;
7213  case RTE_JOIN:
7214  /* Join RTE --- recursively inspect the alias variable */
7215  if (rte->joinaliasvars == NIL)
7216  elog(ERROR, "cannot decompile join alias var in plan tree");
7217  Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
7218  expr = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
7219  Assert(expr != NULL);
7220  /* we intentionally don't strip implicit coercions here */
7221  if (IsA(expr, Var))
7222  return get_name_for_var_field((Var *) expr, fieldno,
7223  var->varlevelsup + levelsup,
7224  context);
7225  /* else fall through to inspect the expression */
7226  break;
7227  case RTE_FUNCTION:
7228  case RTE_TABLEFUNC:
7229 
7230  /*
7231  * We couldn't get here unless a function is declared with one of
7232  * its result columns as RECORD, which is not allowed.
7233  */
7234  break;
7235  case RTE_CTE:
7236  /* CTE reference: examine subquery's output expr */
7237  {
7238  CommonTableExpr *cte = NULL;
7239  Index ctelevelsup;
7240  ListCell *lc;
7241 
7242  /*
7243  * Try to find the referenced CTE using the namespace stack.
7244  */
7245  ctelevelsup = rte->ctelevelsup + netlevelsup;
7246  if (ctelevelsup >= list_length(context->namespaces))
7247  lc = NULL;
7248  else
7249  {
7250  deparse_namespace *ctedpns;
7251 
7252  ctedpns = (deparse_namespace *)
7253  list_nth(context->namespaces, ctelevelsup);
7254  foreach(lc, ctedpns->ctes)
7255  {
7256  cte = (CommonTableExpr *) lfirst(lc);
7257  if (strcmp(cte->ctename, rte->ctename) == 0)
7258  break;
7259  }
7260  }
7261  if (lc != NULL)
7262  {
7263  Query *ctequery = (Query *) cte->ctequery;
7265  attnum);
7266 
7267  if (ste == NULL || ste->resjunk)
7268  elog(ERROR, "subquery %s does not have attribute %d",
7269  rte->eref->aliasname, attnum);
7270  expr = (Node *) ste->expr;
7271  if (IsA(expr, Var))
7272  {
7273  /*
7274  * Recurse into the CTE to see what its Var refers to.
7275  * We have to build an additional level of namespace
7276  * to keep in step with varlevelsup in the CTE.
7277  * Furthermore it could be an outer CTE, so we may
7278  * have to delete some levels of namespace.
7279  */
7280  List *save_nslist = context->namespaces;
7281  List *new_nslist;
7282  deparse_namespace mydpns;
7283  const char *result;
7284 
7285  set_deparse_for_query(&mydpns, ctequery,
7286  context->namespaces);
7287 
7288  new_nslist = list_copy_tail(context->namespaces,
7289  ctelevelsup);
7290  context->namespaces = lcons(&mydpns, new_nslist);
7291 
7292  result = get_name_for_var_field((Var *) expr, fieldno,
7293  0, context);
7294 
7295  context->namespaces = save_nslist;
7296 
7297  return result;
7298  }
7299  /* else fall through to inspect the expression */
7300  }
7301  else
7302  {
7303  /*
7304  * We're deparsing a Plan tree so we don't have a CTE
7305  * list. But the only place we'd see a Var directly
7306  * referencing a CTE RTE is in a CteScan plan node, and we
7307  * can look into the subplan's tlist instead.
7308  */
7309  TargetEntry *tle;
7310  deparse_namespace save_dpns;
7311  const char *result;
7312 
7313  if (!dpns->inner_plan)
7314  elog(ERROR, "failed to find plan for CTE %s",
7315  rte->eref->aliasname);
7316  tle = get_tle_by_resno(dpns->inner_tlist, attnum);
7317  if (!tle)
7318  elog(ERROR, "bogus varattno for subquery var: %d",
7319  attnum);
7320  Assert(netlevelsup == 0);
7321  push_child_plan(dpns, dpns->inner_plan, &save_dpns);
7322 
7323  result = get_name_for_var_field((Var *) tle->expr, fieldno,
7324  levelsup, context);
7325 
7326  pop_child_plan(dpns, &save_dpns);
7327  return result;
7328  }
7329  }
7330  break;
7331  }
7332 
7333  /*
7334  * We now have an expression we can't expand any more, so see if
7335  * get_expr_result_tupdesc() can do anything with it.
7336  */
7337  tupleDesc = get_expr_result_tupdesc(expr, false);
7338  /* Got the tupdesc, so we can extract the field name */
7339  Assert(fieldno >= 1 && fieldno <= tupleDesc->natts);
7340  return NameStr(TupleDescAttr(tupleDesc, fieldno - 1)->attname);
7341 }
List * namespaces
Definition: ruleutils.c:113
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
List * joinaliasvars
Definition: parsenodes.h:1049
Index varlevelsup
Definition: primnodes.h:191
static Node * find_param_referent(Param *param, deparse_context *context, deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
Definition: ruleutils.c:7352
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
AttrNumber varattno
Definition: primnodes.h:186
static void pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:4710
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1423
Definition: primnodes.h:181
List * targetList
Definition: parsenodes.h:140
bool resjunk
Definition: primnodes.h:1414
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
List * colnames
Definition: primnodes.h:1038
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:429
static void * list_nth(const List *list, int n)
Definition: pg_list.h:277
Oid vartype
Definition: primnodes.h:188
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
Index varnosyn
Definition: primnodes.h:194
Index varno
Definition: primnodes.h:184
AttrNumber varattnosyn
Definition: primnodes.h:195
List * outer_tlist
Definition: ruleutils.c:174
unsigned int Index
Definition: c.h:476
static const char * get_name_for_var_field(Var *var, int fieldno, int levelsup, deparse_context *context)
Definition: ruleutils.c:6957
int16 attnum
Definition: pg_attribute.h:79
#define INNER_VAR
Definition: primnodes.h:171
char * get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
List * lcons(void *datum, List *list)
Definition: list.c:454
static void pop_child_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:4659
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
char * aliasname
Definition: primnodes.h:42
static void push_child_plan(deparse_namespace *dpns, Plan *plan, deparse_namespace *save_dpns)
Definition: ruleutils.c:4642
Expr * expr
Definition: primnodes.h:1407
static int list_length(const List *l)
Definition: pg_list.h:169
Index ctelevelsup
Definition: parsenodes.h:1078
static void set_deparse_for_query(deparse_namespace *dpns, Query *query, List *parent_namespaces)
Definition: ruleutils.c:3588
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:974
char * ctename
Definition: parsenodes.h:1077
Query * subquery
Definition: parsenodes.h:1009
List * index_tlist
Definition: ruleutils.c:176
List * inner_tlist
Definition: ruleutils.c:175
static void push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell, deparse_namespace *save_dpns)
Definition: ruleutils.c:4689
#define elog(elevel,...)
Definition: elog.h:228
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
#define NameStr(name)
Definition: c.h:616
Alias * eref
Definition: parsenodes.h:1113
#define INDEX_VAR
Definition: primnodes.h:173
Definition: pg_list.h:50
#define GetCTETargetList(cte)
Definition: parsenodes.h:1465
int16 AttrNumber
Definition: attnum.h:21
#define OUTER_VAR
Definition: primnodes.h:172
List * list_delete_first(List *list)
Definition: list.c:861

◆ get_opclass_name()

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

Definition at line 10546 of file ruleutils.c.

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

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

10548 {
10549  HeapTuple ht_opc;
10550  Form_pg_opclass opcrec;
10551  char *opcname;
10552  char *nspname;
10553 
10554  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
10555  if (!HeapTupleIsValid(ht_opc))
10556  elog(ERROR, "cache lookup failed for opclass %u", opclass);
10557  opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
10558 
10559  if (!OidIsValid(actual_datatype) ||
10560  GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
10561  {
10562  /* Okay, we need the opclass name. Do we need to qualify it? */
10563  opcname = NameStr(opcrec->opcname);
10564  if (OpclassIsVisible(opclass))
10565  appendStringInfo(buf, " %s", quote_identifier(opcname));
10566  else
10567  {
10568  nspname = get_namespace_name(opcrec->opcnamespace);
10569  appendStringInfo(buf, " %s.%s",
10570  quote_identifier(nspname),
10571  quote_identifier(opcname));
10572  }
10573  }
10574  ReleaseSysCache(ht_opc);
10575 }
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1937
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10697
#define OidIsValid(objectId)
Definition: c.h:645
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
bool OpclassIsVisible(Oid opcid)
Definition: namespace.c:1825
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616
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 9165 of file ruleutils.c.

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

Referenced by get_rule_expr().

9166 {
9167  StringInfo buf = context->buf;
9168  Oid opno = expr->opno;
9169  List *args = expr->args;
9170 
9171  if (!PRETTY_PAREN(context))
9172  appendStringInfoChar(buf, '(');
9173  if (list_length(args) == 2)
9174  {
9175  /* binary operator */
9176  Node *arg1 = (Node *) linitial(args);
9177  Node *arg2 = (Node *) lsecond(args);
9178 
9179  get_rule_expr_paren(arg1, context, true, (Node *) expr);
9180  appendStringInfo(buf, " %s ",
9182  exprType(arg1),
9183  exprType(arg2)));
9184  get_rule_expr_paren(arg2, context, true, (Node *) expr);
9185  }
9186  else
9187  {
9188  /* unary operator --- but which side? */
9189  Node *arg = (Node *) linitial(args);
9190  HeapTuple tp;
9191  Form_pg_operator optup;
9192 
9194  if (!HeapTupleIsValid(tp))
9195  elog(ERROR, "cache lookup failed for operator %u", opno);
9196  optup = (Form_pg_operator) GETSTRUCT(tp);
9197  switch (optup->oprkind)
9198  {
9199  case 'l':
9200  appendStringInfo(buf, "%s ",
9202  InvalidOid,
9203  exprType(arg)));
9204  get_rule_expr_paren(arg, context, true, (Node *) expr);
9205  break;
9206  case 'r':
9207  get_rule_expr_paren(arg, context, true, (Node *) expr);
9208  appendStringInfo(buf, " %s",
9210  exprType(arg),
9211  InvalidOid));
9212  break;
9213  default:
9214  elog(ERROR, "bogus oprkind: %d", optup->oprkind);
9215  }
9216  ReleaseSysCache(tp);
9217  }
9218  if (!PRETTY_PAREN(context))
9219  appendStringInfoChar(buf, ')');
9220 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
static void get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
Definition: ruleutils.c:7866
Definition: nodes.h:525
unsigned int Oid
Definition: postgres_ext.h:31
#define lsecond(l)
Definition: pg_list.h:200
static char * generate_operator_name(Oid operid, Oid arg1, Oid arg2)
Definition: ruleutils.c:11028
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define linitial(l)
Definition: pg_list.h:195
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:67
#define PRETTY_PAREN(context)
Definition: ruleutils.c:99
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:169
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
StringInfo buf
Definition: ruleutils.c:112
#define elog(elevel,...)
Definition: elog.h:228
void * arg
Oid opno
Definition: primnodes.h:516
List * args
Definition: primnodes.h:522
Definition: pg_list.h:50

◆ get_parameter()

static void get_parameter ( Param param,
deparse_context context 
)
static

Definition at line 7487 of file ruleutils.c.

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

Referenced by get_rule_expr().

7488 {
7489  Node *expr;
7490  deparse_namespace *dpns;
7491  ListCell *ancestor_cell;
7492 
7493  /*
7494  * If it's a PARAM_EXEC parameter, try to locate the expression from which
7495  * the parameter was computed. Note that failing to find a referent isn't
7496  * an error, since the Param might well be a subplan output rather than an
7497  * input.
7498  */
7499  expr = find_param_referent(param, context, &dpns, &ancestor_cell);
7500  if (expr)
7501  {
7502  /* Found a match, so print it */
7503  deparse_namespace save_dpns;
7504  bool save_varprefix;
7505  bool need_paren;
7506 
7507  /* Switch attention to the ancestor plan node */
7508  push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
7509 
7510  /*
7511  * Force prefixing of Vars, since they won't belong to the relation
7512  * being scanned in the original plan node.
7513  */
7514  save_varprefix = context->varprefix;
7515  context->varprefix = true;
7516 
7517  /*
7518  * A Param's expansion is typically a Var, Aggref, or upper-level
7519  * Param, which wouldn't need extra parentheses. Otherwise, insert
7520  * parens to ensure the expression looks atomic.
7521  */
7522  need_paren = !(IsA(expr, Var) ||
7523  IsA(expr, Aggref) ||
7524  IsA(expr, Param));
7525  if (need_paren)
7526  appendStringInfoChar(context->buf, '(');
7527 
7528  get_rule_expr(expr, context, false);
7529 
7530  if (need_paren)
7531  appendStringInfoChar(context->buf, ')');
7532 
7533  context->varprefix = save_varprefix;
7534 
7535  pop_ancestor_plan(dpns, &save_dpns);
7536 
7537  return;
7538  }
7539 
7540  /*
7541  * Not PARAM_EXEC, or couldn't find referent: just print $N.
7542  */
7543  appendStringInfo(context->buf, "$%d", param->paramid);
7544 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static Node * find_param_referent(Param *param, deparse_context *context, deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
Definition: ruleutils.c:7352
Definition: nodes.h:525
static void pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:4710
Definition: primnodes.h:181
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7898
int paramid
Definition: primnodes.h:263
StringInfo buf
Definition: ruleutils.c:112
static void push_ancestor_plan(deparse_namespace *dpns, ListCell *ancestor_cell, deparse_namespace *save_dpns)
Definition: ruleutils.c:4689

◆ get_query_def()

static void get_query_def ( Query query,
StringInfo  buf,
List parentnamespace,
TupleDesc  resultDesc,
int  prettyFlags,
int  wrapColumn,
int  startIndent 
)
static

Definition at line 4994 of file ruleutils.c.

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

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

4997 {
4998  deparse_context context;
4999  deparse_namespace dpns;
5000 
5001  /* Guard against excessively long or deeply-nested queries */
5004 
5005  /*
5006  * Before we begin to examine the query, acquire locks on referenced
5007  * relations, and fix up deleted columns in JOIN RTEs. This ensures
5008  * consistent results. Note we assume it's OK to scribble on the passed
5009  * querytree!
5010  *
5011  * We are only deparsing the query (we are not about to execute it), so we
5012  * only need AccessShareLock on the relations it mentions.
5013  */
5014  AcquireRewriteLocks(query, false, false);
5015 
5016  context.buf = buf;
5017  context.namespaces = lcons(&dpns, list_copy(parentnamespace));
5018  context.windowClause = NIL;
5019  context.windowTList = NIL;
5020  context.varprefix = (parentnamespace != NIL ||
5021  list_length(query->rtable) != 1);
5022  context.prettyFlags = prettyFlags;
5023  context.wrapColumn = wrapColumn;
5024  context.indentLevel = startIndent;
5025  context.special_exprkind = EXPR_KIND_NONE;
5026  context.appendparents = NULL;
5027 
5028  set_deparse_for_query(&dpns, query, parentnamespace);
5029 
5030  switch (query->commandType)
5031  {
5032  case CMD_SELECT:
5033  get_select_query_def(query, &context, resultDesc);
5034  break;
5035 
5036  case CMD_UPDATE:
5037  get_update_query_def(query, &context);
5038  break;
5039 
5040  case CMD_INSERT:
5041  get_insert_query_def(query, &context);
5042  break;
5043 
5044  case CMD_DELETE:
5045  get_delete_query_def(query, &context);
5046  break;
5047 
5048  case CMD_NOTHING:
5049  appendStringInfoString(buf, "NOTHING");
5050  break;
5051 
5052  case CMD_UTILITY:
5053  get_utility_query_def(query, &context);
5054  break;
5055 
5056  default:
5057  elog(ERROR, "unrecognized query command type: %d",
5058  query->commandType);
5059  break;
5060  }
5061 }
List * namespaces
Definition: ruleutils.c:113
#define NIL
Definition: pg_list.h:65
List * list_copy(const List *oldlist)
Definition: list.c:1404
static void get_insert_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:6084
static void get_update_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:6297
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
static void get_utility_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:6556
static void get_select_query_def(Query *query, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5191
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
void check_stack_depth(void)
Definition: postgres.c:3288
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
ParseExprKind special_exprkind
Definition: ruleutils.c:120
static void get_delete_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:6505
List * windowTList
Definition: ruleutils.c:115
CmdType commandType
Definition: parsenodes.h:112
List * lcons(void *datum, List *list)
Definition: list.c:454
List * windowClause
Definition: ruleutils.c:114
static int list_length(const List *l)
Definition: pg_list.h:169
static void set_deparse_for_query(deparse_namespace *dpns, Query *query, List *parent_namespaces)
Definition: ruleutils.c:3588
Bitmapset * appendparents
Definition: ruleutils.c:122
StringInfo buf
Definition: ruleutils.c:112
#define elog(elevel,...)
Definition: elog.h:228
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99

◆ get_range_partbound_string()

char* get_range_partbound_string ( List bound_datums)

Definition at line 11338 of file ruleutils.c.

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

Referenced by check_new_partition_bound(), and get_rule_expr().

11339 {
11340  deparse_context context;
11342  ListCell *cell;
11343  char *sep;
11344 
11345  memset(&context, 0, sizeof(deparse_context));
11346  context.buf = buf;
11347 
11348  appendStringInfoString(buf, "(");
11349  sep = "";
11350  foreach(cell, bound_datums)
11351  {
11352  PartitionRangeDatum *datum =
11354 
11355  appendStringInfoString(buf, sep);
11356  if (datum->kind == PARTITION_RANGE_DATUM_MINVALUE)
11357  appendStringInfoString(buf, "MINVALUE");
11358  else if (datum->kind == PARTITION_RANGE_DATUM_MAXVALUE)
11359  appendStringInfoString(buf, "MAXVALUE");
11360  else
11361  {
11362  Const *val = castNode(Const, datum->value);
11363 
11364  get_const_expr(val, &context, -1);
11365  }
11366  sep = ", ";
11367  }
11368  appendStringInfoChar(buf, ')');
11369 
11370  return buf->data;
11371 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
PartitionRangeDatumKind kind
Definition: parsenodes.h:845
static void get_const_expr(Const *constval, deparse_context *context, int showtype)
Definition: ruleutils.c:9575
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:67
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
#define lfirst(lc)
Definition: pg_list.h:190
StringInfo buf
Definition: ruleutils.c:112
long val
Definition: informix.c:664

◆ get_relation_name()

static char * get_relation_name ( Oid  relid)
static

Definition at line 10801 of file ruleutils.c.

References elog, ERROR, get_rel_name(), and relname.

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

10802 {
10803  char *relname = get_rel_name(relid);
10804 
10805  if (!relname)
10806  elog(ERROR, "cache lookup failed for relation %u", relid);
10807  return relname;
10808 }
NameData relname
Definition: pg_class.h:35
#define ERROR
Definition: elog.h:43
#define elog(elevel,...)
Definition: elog.h:228
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730

◆ get_rtable_name()

static char * get_rtable_name ( int  rtindex,
deparse_context context 
)
static

Definition at line 4547 of file ruleutils.c.

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

Referenced by get_from_clause_item(), and get_select_query_def().

4548 {
4550 
4551  Assert(rtindex > 0 && rtindex <= list_length(dpns->rtable_names));
4552  return (char *) list_nth(dpns->rtable_names, rtindex - 1);
4553 }