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)
 
static void get_reloptions (StringInfo buf, Datum reloptions)
 
Datum pg_get_ruledef (PG_FUNCTION_ARGS)
 
Datum pg_get_ruledef_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_wrap (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_name (PG_FUNCTION_ARGS)
 
Datum pg_get_viewdef_name_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_triggerdef (PG_FUNCTION_ARGS)
 
Datum pg_get_triggerdef_ext (PG_FUNCTION_ARGS)
 
Datum pg_get_indexdef (PG_FUNCTION_ARGS)
 
Datum pg_get_indexdef_ext (PG_FUNCTION_ARGS)
 
char * pg_get_indexdef_string (Oid indexrelid)
 
char * pg_get_indexdef_columns (Oid indexrelid, bool pretty)
 
Datum pg_get_statisticsobjdef (PG_FUNCTION_ARGS)
 
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)
 
char * generate_opclass_name (Oid opclass)
 
const char * quote_identifier (const char *ident)
 
char * quote_qualified_identifier (const char *qualifier, const char *ident)
 
void generate_operator_clause (StringInfo buf, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
 
char * generate_collation_name (Oid collid)
 
char * get_range_partbound_string (List *bound_datums)
 

Variables

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

Macro Definition Documentation

◆ deparse_columns_fetch

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

◆ only_marker

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

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

11177 {
11178  HeapTuple typetup;
11179  Form_pg_type typform;
11180  char *typname;
11181  char *nspname;
11182 
11183  typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
11184  if (!HeapTupleIsValid(typetup))
11185  elog(ERROR, "cache lookup failed for type %u", typid);
11186  typform = (Form_pg_type) GETSTRUCT(typetup);
11187 
11188  typname = NameStr(typform->typname);
11189  nspname = get_namespace_name(typform->typnamespace);
11190 
11191  appendStringInfo(buf, "::%s.%s",
11192  quote_identifier(nspname), quote_identifier(typname));
11193 
11194  ReleaseSysCache(typetup);
11195 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10724
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:3155
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:255
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:615

◆ appendContextKeyword()

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

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

7805 {
7806  StringInfo buf = context->buf;
7807 
7808  if (PRETTY_INDENT(context))
7809  {
7810  int indentAmount;
7811 
7812  context->indentLevel += indentBefore;
7813 
7814  /* remove any trailing spaces currently in the buffer ... */
7816  /* ... then add a newline and some spaces */
7817  appendStringInfoChar(buf, '\n');
7818 
7819  if (context->indentLevel < PRETTYINDENT_LIMIT)
7820  indentAmount = Max(context->indentLevel, 0) + indentPlus;
7821  else
7822  {
7823  /*
7824  * If we're indented more than PRETTYINDENT_LIMIT characters, try
7825  * to conserve horizontal space by reducing the per-level
7826  * indentation. For best results the scale factor here should
7827  * divide all the indent amounts that get added to indentLevel
7828  * (PRETTYINDENT_STD, etc). It's important that the indentation
7829  * not grow unboundedly, else deeply-nested trees use O(N^2)
7830  * whitespace; so we also wrap modulo PRETTYINDENT_LIMIT.
7831  */
7832  indentAmount = PRETTYINDENT_LIMIT +
7833  (context->indentLevel - PRETTYINDENT_LIMIT) /
7834  (PRETTYINDENT_STD / 2);
7835  indentAmount %= PRETTYINDENT_LIMIT;
7836  /* scale/wrap logic affects indentLevel, but not indentPlus */
7837  indentAmount += indentPlus;
7838  }
7839  appendStringInfoSpaces(buf, indentAmount);
7840 
7842 
7843  context->indentLevel += indentAfter;
7844  if (context->indentLevel < 0)
7845  context->indentLevel = 0;
7846  }
7847  else
7849 }
#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:7857
#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:914
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 4368 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().

4370 {
4371  int i;
4372  ListCell *lc;
4373 
4374  /* Check against already-assigned column aliases within RTE */
4375  for (i = 0; i < colinfo->num_cols; i++)
4376  {
4377  char *oldname = colinfo->colnames[i];
4378 
4379  if (oldname && strcmp(oldname, colname) == 0)
4380  return false;
4381  }
4382 
4383  /*
4384  * If we're building a new_colnames array, check that too (this will be
4385  * partially but not completely redundant with the previous checks)
4386  */
4387  for (i = 0; i < colinfo->num_new_cols; i++)
4388  {
4389  char *oldname = colinfo->new_colnames[i];
4390 
4391  if (oldname && strcmp(oldname, colname) == 0)
4392  return false;
4393  }
4394 
4395  /* Also check against USING-column names that must be globally unique */
4396  foreach(lc, dpns->using_names)
4397  {
4398  char *oldname = (char *) lfirst(lc);
4399 
4400  if (strcmp(oldname, colname) == 0)
4401  return false;
4402  }
4403 
4404  /* Also check against names already assigned for parent-join USING cols */
4405  foreach(lc, colinfo->parentUsing)
4406  {
4407  char *oldname = (char *) lfirst(lc);
4408 
4409  if (strcmp(oldname, colname) == 0)
4410  return false;
4411  }
4412 
4413  return true;
4414 }
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 2340 of file ruleutils.c.

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

Referenced by pg_get_constraintdef_worker().

2342 {
2343  Datum *keys;
2344  int nKeys;
2345  int j;
2346 
2347  /* Extract data from array of int16 */
2348  deconstruct_array(DatumGetArrayTypeP(column_index_array),
2349  INT2OID, 2, true, TYPALIGN_SHORT,
2350  &keys, NULL, &nKeys);
2351 
2352  for (j = 0; j < nKeys; j++)
2353  {
2354  char *colName;
2355 
2356  colName = get_attname(relId, DatumGetInt16(keys[j]), false);
2357 
2358  if (j == 0)
2360  else
2361  appendStringInfo(buf, ", %s", quote_identifier(colName));
2362  }
2363 
2364  return nKeys;
2365 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10724
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:776
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ deparse_context_for()

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

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

3284 {
3285  deparse_namespace *dpns;
3286  RangeTblEntry *rte;
3287 
3288  dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3289 
3290  /* Build a minimal RTE for the rel */
3291  rte = makeNode(RangeTblEntry);
3292  rte->rtekind = RTE_RELATION;
3293  rte->relid = relid;
3294  rte->relkind = RELKIND_RELATION; /* no need for exactness here */
3296  rte->alias = makeAlias(aliasname, NIL);
3297  rte->eref = rte->alias;
3298  rte->lateral = false;
3299  rte->inh = false;
3300  rte->inFromCl = true;
3301 
3302  /* Build one-element rtable */
3303  dpns->rtable = list_make1(rte);
3304  dpns->subplans = NIL;
3305  dpns->ctes = NIL;
3306  dpns->appendrels = NULL;
3307  set_rtable_names(dpns, NIL, NULL);
3309 
3310  /* Return a one-deep namespace stack */
3311  return list_make1(dpns);
3312 }
#define NIL
Definition: pg_list.h:65
Alias * alias
Definition: parsenodes.h:1113
#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:3449
void * palloc0(Size size)
Definition: mcxt.c:980
#define makeNode(_type_)
Definition: nodes.h:574
static void set_simple_column_names(deparse_namespace *dpns)
Definition: ruleutils.c:3664
RTEKind rtekind
Definition: parsenodes.h:975
Alias * eref
Definition: parsenodes.h:1114

◆ deparse_context_for_plan_tree()

List* deparse_context_for_plan_tree ( PlannedStmt pstmt,
List rtable_names 
)

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

3329 {
3330  deparse_namespace *dpns;
3331 
3332  dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));
3333 
3334  /* Initialize fields that stay the same across the whole plan tree */
3335  dpns->rtable = pstmt->rtable;
3336  dpns->rtable_names = rtable_names;
3337  dpns->subplans = pstmt->subplans;
3338  dpns->ctes = NIL;
3339  if (pstmt->appendRelations)
3340  {
3341  /* Set up the array, indexed by child relid */
3342  int ntables = list_length(dpns->rtable);
3343  ListCell *lc;
3344 
3345  dpns->appendrels = (AppendRelInfo **)
3346  palloc0((ntables + 1) * sizeof(AppendRelInfo *));
3347  foreach(lc, pstmt->appendRelations)
3348  {
3349  AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
3350  Index crelid = appinfo->child_relid;
3351 
3352  Assert(crelid > 0 && crelid <= ntables);
3353  Assert(dpns->appendrels[crelid] == NULL);
3354  dpns->appendrels[crelid] = appinfo;
3355  }
3356  }
3357  else
3358  dpns->appendrels = NULL; /* don't need it */
3359 
3360  /*
3361  * Set up column name aliases. We will get rather bogus results for join
3362  * RTEs, but that doesn't matter because plan trees don't contain any join
3363  * alias Vars.
3364  */
3366 
3367  /* Return a one-deep namespace stack */
3368  return list_make1(dpns);
3369 }
#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:475
List * subplans
Definition: plannodes.h:79
#define Assert(condition)
Definition: c.h:738
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:3664
Index child_relid
Definition: pathnodes.h:2210
List * appendRelations
Definition: plannodes.h:77

◆ deparse_expression()

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

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

3225 {
3226  return deparse_expression_pretty(expr, dpcontext, forceprefix,
3227  showimplicit, 0, 0);
3228 }
static char * deparse_expression_pretty(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit, int prettyFlags, int startIndent)
Definition: ruleutils.c:3250

◆ deparse_expression_pretty()

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

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

3253 {
3255  deparse_context context;
3256 
3257  initStringInfo(&buf);
3258  context.buf = &buf;
3259  context.namespaces = dpcontext;
3260  context.windowClause = NIL;
3261  context.windowTList = NIL;
3262  context.varprefix = forceprefix;
3263  context.prettyFlags = prettyFlags;
3264  context.wrapColumn = WRAP_COLUMN_DEFAULT;
3265  context.indentLevel = startIndent;
3266  context.special_exprkind = EXPR_KIND_NONE;
3267  context.appendparents = NULL;
3268 
3269  get_rule_expr(expr, &context, showimplicit);
3270 
3271  return buf.data;
3272 }
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:7908
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 4466 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().

4467 {
4468  if (n > colinfo->num_cols)
4469  {
4470  if (colinfo->colnames == NULL)
4471  colinfo->colnames = (char **) palloc0(n * sizeof(char *));
4472  else
4473  {
4474  colinfo->colnames = (char **) repalloc(colinfo->colnames,
4475  n * sizeof(char *));
4476  memset(colinfo->colnames + colinfo->num_cols, 0,
4477  (n - colinfo->num_cols) * sizeof(char *));
4478  }
4479  colinfo->num_cols = n;
4480  }
4481 }
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 7362 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().

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

◆ flatten_reloptions()

static char * flatten_reloptions ( Oid  relid)
static

Definition at line 11341 of file ruleutils.c.

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

Referenced by pg_get_constraintdef_worker(), and pg_get_indexdef_worker().

11342 {
11343  char *result = NULL;
11344  HeapTuple tuple;
11345  Datum reloptions;
11346  bool isnull;
11347 
11348  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
11349  if (!HeapTupleIsValid(tuple))
11350  elog(ERROR, "cache lookup failed for relation %u", relid);
11351 
11352  reloptions = SysCacheGetAttr(RELOID, tuple,
11353  Anum_pg_class_reloptions, &isnull);
11354  if (!isnull)
11355  {
11357 
11358  initStringInfo(&buf);
11359  get_reloptions(&buf, reloptions);
11360 
11361  result = buf.data;
11362  }
11363 
11364  ReleaseSysCache(tuple);
11365 
11366  return result;
11367 }
static void get_reloptions(StringInfo buf, Datum reloptions)
Definition: ruleutils.c:11285
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:67
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
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
#define elog(elevel,...)
Definition: elog.h:214

◆ generate_collation_name()

char* generate_collation_name ( Oid  collid)

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

11241 {
11242  HeapTuple tp;
11243  Form_pg_collation colltup;
11244  char *collname;
11245  char *nspname;
11246  char *result;
11247 
11248  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
11249  if (!HeapTupleIsValid(tp))
11250  elog(ERROR, "cache lookup failed for collation %u", collid);
11251  colltup = (Form_pg_collation) GETSTRUCT(tp);
11252  collname = NameStr(colltup->collname);
11253 
11254  if (!CollationIsVisible(collid))
11255  nspname = get_namespace_name(colltup->collnamespace);
11256  else
11257  nspname = NULL;
11258 
11259  result = quote_qualified_identifier(nspname, collname);
11260 
11261  ReleaseSysCache(tp);
11262 
11263  return result;
11264 }
#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:3155
bool CollationIsVisible(Oid collid)
Definition: namespace.c:2048
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10808
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:214
#define NameStr(name)
Definition: c.h:615

◆ 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 10950 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().

10953 {
10954  char *result;
10955  HeapTuple proctup;
10956  Form_pg_proc procform;
10957  char *proname;
10958  bool use_variadic;
10959  char *nspname;
10960  FuncDetailCode p_result;
10961  Oid p_funcid;
10962  Oid p_rettype;
10963  bool p_retset;
10964  int p_nvargs;
10965  Oid p_vatype;
10966  Oid *p_true_typeids;
10967  bool force_qualify = false;
10968 
10969  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
10970  if (!HeapTupleIsValid(proctup))
10971  elog(ERROR, "cache lookup failed for function %u", funcid);
10972  procform = (Form_pg_proc) GETSTRUCT(proctup);
10973  proname = NameStr(procform->proname);
10974 
10975  /*
10976  * Due to parser hacks to avoid needing to reserve CUBE, we need to force
10977  * qualification in some special cases.
10978  */
10979  if (special_exprkind == EXPR_KIND_GROUP_BY)
10980  {
10981  if (strcmp(proname, "cube") == 0 || strcmp(proname, "rollup") == 0)
10982  force_qualify = true;
10983  }
10984 
10985  /*
10986  * Determine whether VARIADIC should be printed. We must do this first
10987  * since it affects the lookup rules in func_get_detail().
10988  *
10989  * We always print VARIADIC if the function has a merged variadic-array
10990  * argument. Note that this is always the case for functions taking a
10991  * VARIADIC argument type other than VARIADIC ANY. If we omitted VARIADIC
10992  * and printed the array elements as separate arguments, the call could
10993  * match a newer non-VARIADIC function.
10994  */
10995  if (use_variadic_p)
10996  {
10997  /* Parser should not have set funcvariadic unless fn is variadic */
10998  Assert(!has_variadic || OidIsValid(procform->provariadic));
10999  use_variadic = has_variadic;
11000  *use_variadic_p = use_variadic;
11001  }
11002  else
11003  {
11004  Assert(!has_variadic);
11005  use_variadic = false;
11006  }
11007 
11008  /*
11009  * The idea here is to schema-qualify only if the parser would fail to
11010  * resolve the correct function given the unqualified func name with the
11011  * specified argtypes and VARIADIC flag. But if we already decided to
11012  * force qualification, then we can skip the lookup and pretend we didn't
11013  * find it.
11014  */
11015  if (!force_qualify)
11016  p_result = func_get_detail(list_make1(makeString(proname)),
11017  NIL, argnames, nargs, argtypes,
11018  !use_variadic, true,
11019  &p_funcid, &p_rettype,
11020  &p_retset, &p_nvargs, &p_vatype,
11021  &p_true_typeids, NULL);
11022  else
11023  {
11024  p_result = FUNCDETAIL_NOTFOUND;
11025  p_funcid = InvalidOid;
11026  }
11027 
11028  if ((p_result == FUNCDETAIL_NORMAL ||
11029  p_result == FUNCDETAIL_AGGREGATE ||
11030  p_result == FUNCDETAIL_WINDOWFUNC) &&
11031  p_funcid == funcid)
11032  nspname = NULL;
11033  else
11034  nspname = get_namespace_name(procform->pronamespace);
11035 
11036  result = quote_qualified_identifier(nspname, proname);
11037 
11038  ReleaseSysCache(proctup);
11039 
11040  return result;
11041 }
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:644
#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:3155
FuncDetailCode
Definition: parse_func.h:22
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10808
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:738
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:214
#define NameStr(name)
Definition: c.h:615

◆ generate_opclass_name()

char* generate_opclass_name ( Oid  opclass)

Definition at line 10594 of file ruleutils.c.

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

Referenced by index_opclass_options().

10595 {
10597 
10598  initStringInfo(&buf);
10599  get_opclass_name(opclass, InvalidOid, &buf);
10600 
10601  return &buf.data[1]; /* get_opclass_name() prepends space */
10602 }
static char * buf
Definition: pg_test_fsync.c:67
static void get_opclass_name(Oid opclass, Oid actual_datatype, StringInfo buf)
Definition: ruleutils.c:10556
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define InvalidOid
Definition: postgres_ext.h:36

◆ generate_operator_clause()

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

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

11140 {
11141  HeapTuple opertup;
11142  Form_pg_operator operform;
11143  char *oprname;
11144  char *nspname;
11145 
11146  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opoid));
11147  if (!HeapTupleIsValid(opertup))
11148  elog(ERROR, "cache lookup failed for operator %u", opoid);
11149  operform = (Form_pg_operator) GETSTRUCT(opertup);
11150  Assert(operform->oprkind == 'b');
11151  oprname = NameStr(operform->oprname);
11152 
11153  nspname = get_namespace_name(operform->oprnamespace);
11154 
11155  appendStringInfoString(buf, leftop);
11156  if (leftoptype != operform->oprleft)
11157  add_cast_to(buf, operform->oprleft);
11158  appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
11159  appendStringInfoString(buf, oprname);
11160  appendStringInfo(buf, ") %s", rightop);
11161  if (rightoptype != operform->oprright)
11162  add_cast_to(buf, operform->oprright);
11163 
11164  ReleaseSysCache(opertup);
11165 }
static void add_cast_to(StringInfo buf, Oid typid)
Definition: ruleutils.c:11176
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10724
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:3155
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:738
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:615

◆ generate_operator_name()

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

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

11056 {
11058  HeapTuple opertup;
11059  Form_pg_operator operform;
11060  char *oprname;
11061  char *nspname;
11062  Operator p_result;
11063 
11064  initStringInfo(&buf);
11065 
11066  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operid));
11067  if (!HeapTupleIsValid(opertup))
11068  elog(ERROR, "cache lookup failed for operator %u", operid);
11069  operform = (Form_pg_operator) GETSTRUCT(opertup);
11070  oprname = NameStr(operform->oprname);
11071 
11072  /*
11073  * The idea here is to schema-qualify only if the parser would fail to
11074  * resolve the correct operator given the unqualified op name with the
11075  * specified argtypes.
11076  */
11077  switch (operform->oprkind)
11078  {
11079  case 'b':
11080  p_result = oper(NULL, list_make1(makeString(oprname)), arg1, arg2,
11081  true, -1);
11082  break;
11083  case 'l':
11084  p_result = left_oper(NULL, list_make1(makeString(oprname)), arg2,
11085  true, -1);
11086  break;
11087  case 'r':
11088  p_result = right_oper(NULL, list_make1(makeString(oprname)), arg1,
11089  true, -1);
11090  break;
11091  default:
11092  elog(ERROR, "unrecognized oprkind: %d", operform->oprkind);
11093  p_result = NULL; /* keep compiler quiet */
11094  break;
11095  }
11096 
11097  if (p_result != NULL && oprid(p_result) == operid)
11098  nspname = NULL;
11099  else
11100  {
11101  nspname = get_namespace_name(operform->oprnamespace);
11102  appendStringInfo(&buf, "OPERATOR(%s.", quote_identifier(nspname));
11103  }
11104 
11105  appendStringInfoString(&buf, oprname);
11106 
11107  if (nspname)
11108  appendStringInfoChar(&buf, ')');
11109 
11110  if (p_result != NULL)
11111  ReleaseSysCache(p_result);
11112 
11113  ReleaseSysCache(opertup);
11114 
11115  return buf.data;
11116 }
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:10724
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:3155
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:214
#define NameStr(name)
Definition: c.h:615
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 10908 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().

10909 {
10910  HeapTuple tp;
10911  Form_pg_class reltup;
10912  char *relname;
10913  char *nspname;
10914  char *result;
10915 
10916  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
10917  if (!HeapTupleIsValid(tp))
10918  elog(ERROR, "cache lookup failed for relation %u", relid);
10919  reltup = (Form_pg_class) GETSTRUCT(tp);
10920  relname = NameStr(reltup->relname);
10921 
10922  nspname = get_namespace_name(reltup->relnamespace);
10923  if (!nspname)
10924  elog(ERROR, "cache lookup failed for namespace %u",
10925  reltup->relnamespace);
10926 
10927  result = quote_qualified_identifier(nspname, relname);
10928 
10929  ReleaseSysCache(tp);
10930 
10931  return result;
10932 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
NameData relname
Definition: pg_class.h:38
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3155
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10808
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:153
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:615

◆ generate_qualified_type_name()

static char * generate_qualified_type_name ( Oid  typid)
static

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

11208 {
11209  HeapTuple tp;
11210  Form_pg_type typtup;
11211  char *typname;
11212  char *nspname;
11213  char *result;
11214 
11216  if (!HeapTupleIsValid(tp))
11217  elog(ERROR, "cache lookup failed for type %u", typid);
11218  typtup = (Form_pg_type) GETSTRUCT(tp);
11219  typname = NameStr(typtup->typname);
11220 
11221  nspname = get_namespace_name(typtup->typnamespace);
11222  if (!nspname)
11223  elog(ERROR, "cache lookup failed for namespace %u",
11224  typtup->typnamespace);
11225 
11226  result = quote_qualified_identifier(nspname, typname);
11227 
11228  ReleaseSysCache(tp);
11229 
11230  return result;
11231 }
#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:3155
NameData typname
Definition: pg_type.h:41
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10808
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:255
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:615

◆ generate_relation_name()

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

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

10849 {
10850  HeapTuple tp;
10851  Form_pg_class reltup;
10852  bool need_qual;
10853  ListCell *nslist;
10854  char *relname;
10855  char *nspname;
10856  char *result;
10857 
10858  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
10859  if (!HeapTupleIsValid(tp))
10860  elog(ERROR, "cache lookup failed for relation %u", relid);
10861  reltup = (Form_pg_class) GETSTRUCT(tp);
10862  relname = NameStr(reltup->relname);
10863 
10864  /* Check for conflicting CTE name */
10865  need_qual = false;
10866  foreach(nslist, namespaces)
10867  {
10868  deparse_namespace *dpns = (deparse_namespace *) lfirst(nslist);
10869  ListCell *ctlist;
10870 
10871  foreach(ctlist, dpns->ctes)
10872  {
10873  CommonTableExpr *cte = (CommonTableExpr *) lfirst(ctlist);
10874 
10875  if (strcmp(cte->ctename, relname) == 0)
10876  {
10877  need_qual = true;
10878  break;
10879  }
10880  }
10881  if (need_qual)
10882  break;
10883  }
10884 
10885  /* Otherwise, qualify the name if not visible in search path */
10886  if (!need_qual)
10887  need_qual = !RelationIsVisible(relid);
10888 
10889  if (need_qual)
10890  nspname = get_namespace_name(reltup->relnamespace);
10891  else
10892  nspname = NULL;
10893 
10894  result = quote_qualified_identifier(nspname, relname);
10895 
10896  ReleaseSysCache(tp);
10897 
10898  return result;
10899 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
NameData relname
Definition: pg_class.h:38
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3155
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10808
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:153
bool RelationIsVisible(Oid relid)
Definition: namespace.c:708
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:615

◆ get_agg_combine_expr()

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

Definition at line 9428 of file ruleutils.c.

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

Referenced by get_agg_expr().

9429 {
9430  Aggref *aggref;
9431  Aggref *original_aggref = callback_arg;
9432 
9433  if (!IsA(node, Aggref))
9434  elog(ERROR, "combining Aggref does not point to an Aggref");
9435 
9436  aggref = (Aggref *) node;
9437  get_agg_expr(aggref, context, original_aggref);
9438 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:577
#define ERROR
Definition: elog.h:43
static void get_agg_expr(Aggref *aggref, deparse_context *context, Aggref *original_aggref)
Definition: ruleutils.c:9321
#define elog(elevel,...)
Definition: elog.h:214

◆ get_agg_expr()

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

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

9323 {
9324  StringInfo buf = context->buf;
9325  Oid argtypes[FUNC_MAX_ARGS];
9326  int nargs;
9327  bool use_variadic;
9328 
9329  /*
9330  * For a combining aggregate, we look up and deparse the corresponding
9331  * partial aggregate instead. This is necessary because our input
9332  * argument list has been replaced; the new argument list always has just
9333  * one element, which will point to a partial Aggref that supplies us with
9334  * transition states to combine.
9335  */
9336  if (DO_AGGSPLIT_COMBINE(aggref->aggsplit))
9337  {
9338  TargetEntry *tle;
9339 
9340  Assert(list_length(aggref->args) == 1);
9341  tle = linitial_node(TargetEntry, aggref->args);
9342  resolve_special_varno((Node *) tle->expr, context,
9343  get_agg_combine_expr, original_aggref);
9344  return;
9345  }
9346 
9347  /*
9348  * Mark as PARTIAL, if appropriate. We look to the original aggref so as
9349  * to avoid printing this when recursing from the code just above.
9350  */
9351  if (DO_AGGSPLIT_SKIPFINAL(original_aggref->aggsplit))
9352  appendStringInfoString(buf, "PARTIAL ");
9353 
9354  /* Extract the argument types as seen by the parser */
9355  nargs = get_aggregate_argtypes(aggref, argtypes);
9356 
9357  /* Print the aggregate name, schema-qualified if needed */
9358  appendStringInfo(buf, "%s(%s",
9359  generate_function_name(aggref->aggfnoid, nargs,
9360  NIL, argtypes,
9361  aggref->aggvariadic,
9362  &use_variadic,
9363  context->special_exprkind),
9364  (aggref->aggdistinct != NIL) ? "DISTINCT " : "");
9365 
9366  if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
9367  {
9368  /*
9369  * Ordered-set aggregates do not use "*" syntax. Also, we needn't
9370  * worry about inserting VARIADIC. So we can just dump the direct
9371  * args as-is.
9372  */
9373  Assert(!aggref->aggvariadic);
9374  get_rule_expr((Node *) aggref->aggdirectargs, context, true);
9375  Assert(aggref->aggorder != NIL);
9376  appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
9377  get_rule_orderby(aggref->aggorder, aggref->args, false, context);
9378  }
9379  else
9380  {
9381  /* aggstar can be set only in zero-argument aggregates */
9382  if (aggref->aggstar)
9383  appendStringInfoChar(buf, '*');
9384  else
9385  {
9386  ListCell *l;
9387  int i;
9388 
9389  i = 0;
9390  foreach(l, aggref->args)
9391  {
9392  TargetEntry *tle = (TargetEntry *) lfirst(l);
9393  Node *arg = (Node *) tle->expr;
9394 
9395  Assert(!IsA(arg, NamedArgExpr));
9396  if (tle->resjunk)
9397  continue;
9398  if (i++ > 0)
9399  appendStringInfoString(buf, ", ");
9400  if (use_variadic && i == nargs)
9401  appendStringInfoString(buf, "VARIADIC ");
9402  get_rule_expr(arg, context, true);
9403  }
9404  }
9405 
9406  if (aggref->aggorder != NIL)
9407  {
9408  appendStringInfoString(buf, " ORDER BY ");
9409  get_rule_orderby(aggref->aggorder, aggref->args, false, context);
9410  }
9411  }
9412 
9413  if (aggref->aggfilter != NULL)
9414  {
9415  appendStringInfoString(buf, ") FILTER (WHERE ");
9416  get_rule_expr((Node *) aggref->aggfilter, context, false);
9417  }
9418 
9419  appendStringInfoChar(buf, ')');
9420 }
static void resolve_special_varno(Node *node, deparse_context *context, rsv_callback callback, void *callback_arg)
Definition: ruleutils.c:6859
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:10950
bool aggvariadic
Definition: primnodes.h:324
#define IsA(nodeptr, _type_)
Definition: nodes.h:577
static void get_rule_orderby(List *orderList, List *targetList, bool force_colno, deparse_context *context)
Definition: ruleutils.c:5896
Definition: nodes.h:526
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:788
#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:9428
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:738
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7908
#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:789
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 5389 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().

5391 {
5392  StringInfo buf = context->buf;
5393  RangeTblEntry *values_rte;
5394  char *sep;
5395  ListCell *l;
5396 
5397  if (PRETTY_INDENT(context))
5398  {
5399  context->indentLevel += PRETTYINDENT_STD;
5400  appendStringInfoChar(buf, ' ');
5401  }
5402 
5403  /*
5404  * If the query looks like SELECT * FROM (VALUES ...), then print just the
5405  * VALUES part. This reverses what transformValuesClause() did at parse
5406  * time.
5407  */
5408  values_rte = get_simple_values_rte(query, resultDesc);
5409  if (values_rte)
5410  {
5411  get_values_def(values_rte->values_lists, context);
5412  return;
5413  }
5414 
5415  /*
5416  * Build up the query string - first we say SELECT
5417  */
5418  appendStringInfoString(buf, "SELECT");
5419 
5420  /* Add the DISTINCT clause if given */
5421  if (query->distinctClause != NIL)
5422  {
5423  if (query->hasDistinctOn)
5424  {
5425  appendStringInfoString(buf, " DISTINCT ON (");
5426  sep = "";
5427  foreach(l, query->distinctClause)
5428  {
5429  SortGroupClause *srt = (SortGroupClause *) lfirst(l);
5430 
5431  appendStringInfoString(buf, sep);
5433  false, context);
5434  sep = ", ";
5435  }
5436  appendStringInfoChar(buf, ')');
5437  }
5438  else
5439  appendStringInfoString(buf, " DISTINCT");
5440  }
5441 
5442  /* Then we tell what to select (the targetlist) */
5443  get_target_list(query->targetList, context, resultDesc);
5444 
5445  /* Add the FROM clause if needed */
5446  get_from_clause(query, " FROM ", context);
5447 
5448  /* Add the WHERE clause if given */
5449  if (query->jointree->quals != NULL)
5450  {
5451  appendContextKeyword(context, " WHERE ",
5453  get_rule_expr(query->jointree->quals, context, false);
5454  }
5455 
5456  /* Add the GROUP BY clause if given */
5457  if (query->groupClause != NULL || query->groupingSets != NULL)
5458  {
5459  ParseExprKind save_exprkind;
5460 
5461  appendContextKeyword(context, " GROUP BY ",
5463 
5464  save_exprkind = context->special_exprkind;
5466 
5467  if (query->groupingSets == NIL)
5468  {
5469  sep = "";
5470  foreach(l, query->groupClause)
5471  {
5472  SortGroupClause *grp = (SortGroupClause *) lfirst(l);
5473 
5474  appendStringInfoString(buf, sep);
5476  false, context);
5477  sep = ", ";
5478  }
5479  }
5480  else
5481  {
5482  sep = "";
5483  foreach(l, query->groupingSets)
5484  {
5485  GroupingSet *grp = lfirst(l);
5486 
5487  appendStringInfoString(buf, sep);
5488  get_rule_groupingset(grp, query->targetList, true, context);
5489  sep = ", ";
5490  }
5491  }
5492 
5493  context->special_exprkind = save_exprkind;
5494  }
5495 
5496  /* Add the HAVING clause if given */
5497  if (query->havingQual != NULL)
5498  {
5499  appendContextKeyword(context, " HAVING ",
5501  get_rule_expr(query->havingQual, context, false);
5502  }
5503 
5504  /* Add the WINDOW clause if needed */
5505  if (query->windowClause != NIL)
5506  get_rule_windowclause(query, context);
5507 }
#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:5516
static Node * get_rule_sortgroupclause(Index ref, List *tlist, bool force_colno, deparse_context *context)
Definition: ruleutils.c:5780
Index tleSortGroupRef
Definition: parsenodes.h:1256
List * groupingSets
Definition: parsenodes.h:150
static void get_from_clause(Query *query, const char *prefix, deparse_context *context)
Definition: ruleutils.c:9992
static void get_rule_windowclause(Query *query, deparse_context *context)
Definition: ruleutils.c:5954
#define PRETTY_INDENT(context)
Definition: ruleutils.c:100
ParseExprKind
Definition: parse_node.h:38
List * values_lists
Definition: parsenodes.h:1073
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:7803
static RangeTblEntry * get_simple_values_rte(Query *query, TupleDesc resultDesc)
Definition: ruleutils.c:5320
static void get_rule_groupingset(GroupingSet *gset, List *targetlist, bool omit_parens, deparse_context *context)
Definition: ruleutils.c:5836
#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:7908
#define lfirst(lc)
Definition: pg_list.h:190
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:5079
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 9521 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().

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

10422 {
10423  StringInfo buf = context->buf;
10424  int i;
10425  bool first = true;
10426 
10427  /* Don't print aliases if not needed */
10428  if (!colinfo->printaliases)
10429  return;
10430 
10431  for (i = 0; i < colinfo->num_new_cols; i++)
10432  {
10433  char *colname = colinfo->new_colnames[i];
10434 
10435  if (first)
10436  {
10437  appendStringInfoChar(buf, '(');
10438  first = false;
10439  }
10440  else
10441  appendStringInfoString(buf, ", ");
10443  }
10444  if (!first)
10445  appendStringInfoChar(buf, ')');
10446 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10724
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 9715 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().

9716 {
9717  StringInfo buf = context->buf;
9718 
9719  if (OidIsValid(constval->constcollid))
9720  {
9721  Oid typcollation = get_typcollation(constval->consttype);
9722 
9723  if (constval->constcollid != typcollation)
9724  {
9725  appendStringInfo(buf, " COLLATE %s",
9727  }
9728  }
9729 }
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:11240
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:2884
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 9585 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().

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

6516 {
6517  StringInfo buf = context->buf;
6518  RangeTblEntry *rte;
6519 
6520  /* Insert the WITH clause if given */
6521  get_with_clause(query, context);
6522 
6523  /*
6524  * Start the query with DELETE FROM relname
6525  */
6526  rte = rt_fetch(query->resultRelation, query->rtable);
6527  Assert(rte->rtekind == RTE_RELATION);
6528  if (PRETTY_INDENT(context))
6529  {
6530  appendStringInfoChar(buf, ' ');
6531  context->indentLevel += PRETTYINDENT_STD;
6532  }
6533  appendStringInfo(buf, "DELETE FROM %s%s",
6534  only_marker(rte),
6536  if (rte->alias != NULL)
6537  appendStringInfo(buf, " %s",
6539 
6540  /* Add the USING clause if given */
6541  get_from_clause(query, " USING ", context);
6542 
6543  /* Add a WHERE clause if given */
6544  if (query->jointree->quals != NULL)
6545  {
6546  appendContextKeyword(context, " WHERE ",
6548  get_rule_expr(query->jointree->quals, context, false);
6549  }
6550 
6551  /* Add RETURNING if present */
6552  if (query->returningList)
6553  {
6554  appendContextKeyword(context, " RETURNING",
6556  get_target_list(query->returningList, context, NULL);
6557  }
6558 }
#define NIL
Definition: pg_list.h:65
static void get_with_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:5122
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10724
Alias * alias
Definition: parsenodes.h:1113
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:5516
static void get_from_clause(Query *query, const char *prefix, deparse_context *context)
Definition: ruleutils.c:9992
#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:10848
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:7803
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:738
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7908
char * aliasname
Definition: primnodes.h:42
#define only_marker(rte)
Definition: ruleutils.c:485
RTEKind rtekind
Definition: parsenodes.h:975
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 9992 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().

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

◆ get_from_clause_coldeflist()

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

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

10464 {
10465  StringInfo buf = context->buf;
10466  ListCell *l1;
10467  ListCell *l2;
10468  ListCell *l3;
10469  ListCell *l4;
10470  int i;
10471 
10472  appendStringInfoChar(buf, '(');
10473 
10474  i = 0;
10475  forfour(l1, rtfunc->funccoltypes,
10476  l2, rtfunc->funccoltypmods,
10477  l3, rtfunc->funccolcollations,
10478  l4, rtfunc->funccolnames)
10479  {
10480  Oid atttypid = lfirst_oid(l1);
10481  int32 atttypmod = lfirst_int(l2);
10482  Oid attcollation = lfirst_oid(l3);
10483  char *attname;
10484 
10485  if (colinfo)
10486  attname = colinfo->colnames[i];
10487  else
10488  attname = strVal(lfirst(l4));
10489 
10490  Assert(attname); /* shouldn't be any dropped columns here */
10491 
10492  if (i > 0)
10493  appendStringInfoString(buf, ", ");
10494  appendStringInfo(buf, "%s %s",
10495  quote_identifier(attname),
10496  format_type_with_typemod(atttypid, atttypmod));
10497  if (OidIsValid(attcollation) &&
10498  attcollation != get_typcollation(atttypid))
10499  appendStringInfo(buf, " COLLATE %s",
10500  generate_collation_name(attcollation));
10501 
10502  i++;
10503  }
10504 
10505  appendStringInfoChar(buf, ')');
10506 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10724
#define strVal(v)
Definition: value.h:54
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
char * generate_collation_name(Oid collid)
Definition: ruleutils.c:11240
signed int int32
Definition: c.h:355
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:157
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:346
List * funccoltypmods
Definition: parsenodes.h:1152
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2884
List * funccolcollations
Definition: parsenodes.h:1153
#define Assert(condition)
Definition: c.h:738
#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 10086 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().

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

◆ get_func_expr()

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

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

9238 {
9239  StringInfo buf = context->buf;
9240  Oid funcoid = expr->funcid;
9241  Oid argtypes[FUNC_MAX_ARGS];
9242  int nargs;
9243  List *argnames;
9244  bool use_variadic;
9245  ListCell *l;
9246 
9247  /*
9248  * If the function call came from an implicit coercion, then just show the
9249  * first argument --- unless caller wants to see implicit coercions.
9250  */
9251  if (expr->funcformat == COERCE_IMPLICIT_CAST && !showimplicit)
9252  {
9253  get_rule_expr_paren((Node *) linitial(expr->args), context,
9254  false, (Node *) expr);
9255  return;
9256  }
9257 
9258  /*
9259  * If the function call came from a cast, then show the first argument
9260  * plus an explicit cast operation.
9261  */
9262  if (expr->funcformat == COERCE_EXPLICIT_CAST ||
9264  {
9265  Node *arg = linitial(expr->args);
9266  Oid rettype = expr->funcresulttype;
9267  int32 coercedTypmod;
9268 
9269  /* Get the typmod if this is a length-coercion function */
9270  (void) exprIsLengthCoercion((Node *) expr, &coercedTypmod);
9271 
9272  get_coercion_expr(arg, context,
9273  rettype, coercedTypmod,
9274  (Node *) expr);
9275 
9276  return;
9277  }
9278 
9279  /*
9280  * Normal function: display as proname(args). First we need to extract
9281  * the argument datatypes.
9282  */
9283  if (list_length(expr->args) > FUNC_MAX_ARGS)
9284  ereport(ERROR,
9285  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
9286  errmsg("too many arguments")));
9287  nargs = 0;
9288  argnames = NIL;
9289  foreach(l, expr->args)
9290  {
9291  Node *arg = (Node *) lfirst(l);
9292 
9293  if (IsA(arg, NamedArgExpr))
9294  argnames = lappend(argnames, ((NamedArgExpr *) arg)->name);
9295  argtypes[nargs] = exprType(arg);
9296  nargs++;
9297  }
9298 
9299  appendStringInfo(buf, "%s(",
9300  generate_function_name(funcoid, nargs,
9301  argnames, argtypes,
9302  expr->funcvariadic,
9303  &use_variadic,
9304  context->special_exprkind));
9305  nargs = 0;
9306  foreach(l, expr->args)
9307  {
9308  if (nargs++ > 0)
9309  appendStringInfoString(buf, ", ");
9310  if (use_variadic && lnext(expr->args, l) == NULL)
9311  appendStringInfoString(buf, "VARIADIC ");
9312  get_rule_expr((Node *) lfirst(l), context, true);
9313  }
9314  appendStringInfoChar(buf, ')');
9315 }
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:10950
#define IsA(nodeptr, _type_)
Definition: nodes.h:577
static void get_rule_expr_paren(Node *node, deparse_context *context, bool showimplicit, Node *parentNode)
Definition: ruleutils.c:7876
List * args
Definition: primnodes.h:477
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
Definition: nodes.h:526
int errcode(int sqlerrcode)
Definition: elog.c:610
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:355
#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
static void get_coercion_expr(Node *arg, deparse_context *context, Oid resulttype, int32 resulttypmod, Node *parentNode)
Definition: ruleutils.c:9521
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
#define ereport(elevel,...)
Definition: elog.h:144
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7908
#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:824
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 6095 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().

6096 {
6097  StringInfo buf = context->buf;
6098  RangeTblEntry *select_rte = NULL;
6099  RangeTblEntry *values_rte = NULL;
6100  RangeTblEntry *rte;
6101  char *sep;
6102  ListCell *l;
6103  List *strippedexprs;
6104 
6105  /* Insert the WITH clause if given */
6106  get_with_clause(query, context);
6107 
6108  /*
6109  * If it's an INSERT ... SELECT or multi-row VALUES, there will be a
6110  * single RTE for the SELECT or VALUES. Plain VALUES has neither.
6111  */
6112  foreach(l, query->rtable)
6113  {
6114  rte = (RangeTblEntry *) lfirst(l);
6115 
6116  if (rte->rtekind == RTE_SUBQUERY)
6117  {
6118  if (select_rte)
6119  elog(ERROR, "too many subquery RTEs in INSERT");
6120  select_rte = rte;
6121  }
6122 
6123  if (rte->rtekind == RTE_VALUES)
6124  {
6125  if (values_rte)
6126  elog(ERROR, "too many values RTEs in INSERT");
6127  values_rte = rte;
6128  }
6129  }
6130  if (select_rte && values_rte)
6131  elog(ERROR, "both subquery and values RTEs in INSERT");
6132 
6133  /*
6134  * Start the query with INSERT INTO relname
6135  */
6136  rte = rt_fetch(query->resultRelation, query->rtable);
6137  Assert(rte->rtekind == RTE_RELATION);
6138 
6139  if (PRETTY_INDENT(context))
6140  {
6141  context->indentLevel += PRETTYINDENT_STD;
6142  appendStringInfoChar(buf, ' ');
6143  }
6144  appendStringInfo(buf, "INSERT INTO %s ",
6146  /* INSERT requires AS keyword for target alias */
6147  if (rte->alias != NULL)
6148  appendStringInfo(buf, "AS %s ",
6150 
6151  /*
6152  * Add the insert-column-names list. Any indirection decoration needed on
6153  * the column names can be inferred from the top targetlist.
6154  */
6155  strippedexprs = NIL;
6156  sep = "";
6157  if (query->targetList)
6158  appendStringInfoChar(buf, '(');
6159  foreach(l, query->targetList)
6160  {
6161  TargetEntry *tle = (TargetEntry *) lfirst(l);
6162 
6163  if (tle->resjunk)
6164  continue; /* ignore junk entries */
6165 
6166  appendStringInfoString(buf, sep);
6167  sep = ", ";
6168 
6169  /*
6170  * Put out name of target column; look in the catalogs, not at
6171  * tle->resname, since resname will fail to track RENAME.
6172  */
6175  tle->resno,
6176  false)));
6177 
6178  /*
6179  * Print any indirection needed (subfields or subscripts), and strip
6180  * off the top-level nodes representing the indirection assignments.
6181  * Add the stripped expressions to strippedexprs. (If it's a
6182  * single-VALUES statement, the stripped expressions are the VALUES to
6183  * print below. Otherwise they're just Vars and not really
6184  * interesting.)
6185  */
6186  strippedexprs = lappend(strippedexprs,
6187  processIndirection((Node *) tle->expr,
6188  context));
6189  }
6190  if (query->targetList)
6191  appendStringInfoString(buf, ") ");
6192 
6193  if (query->override)
6194  {
6195  if (query->override == OVERRIDING_SYSTEM_VALUE)
6196  appendStringInfoString(buf, "OVERRIDING SYSTEM VALUE ");
6197  else if (query->override == OVERRIDING_USER_VALUE)
6198  appendStringInfoString(buf, "OVERRIDING USER VALUE ");
6199  }
6200 
6201  if (select_rte)
6202  {
6203  /* Add the SELECT */
6204  get_query_def(select_rte->subquery, buf, NIL, NULL,
6205  context->prettyFlags, context->wrapColumn,
6206  context->indentLevel);
6207  }
6208  else if (values_rte)
6209  {
6210  /* Add the multi-VALUES expression lists */
6211  get_values_def(values_rte->values_lists, context);
6212  }
6213  else if (strippedexprs)
6214  {
6215  /* Add the single-VALUES expression list */
6216  appendContextKeyword(context, "VALUES (",
6218  get_rule_expr((Node *) strippedexprs, context, false);
6219  appendStringInfoChar(buf, ')');
6220  }
6221  else
6222  {
6223  /* No expressions, so it must be DEFAULT VALUES */
6224  appendStringInfoString(buf, "DEFAULT VALUES");
6225  }
6226 
6227  /* Add ON CONFLICT if present */
6228  if (query->onConflict)
6229  {
6230  OnConflictExpr *confl = query->onConflict;
6231 
6232  appendStringInfoString(buf, " ON CONFLICT");
6233 
6234  if (confl->arbiterElems)
6235  {
6236  /* Add the single-VALUES expression list */
6237  appendStringInfoChar(buf, '(');
6238  get_rule_expr((Node *) confl->arbiterElems, context, false);
6239  appendStringInfoChar(buf, ')');
6240 
6241  /* Add a WHERE clause (for partial indexes) if given */
6242  if (confl->arbiterWhere != NULL)
6243  {
6244  bool save_varprefix;
6245 
6246  /*
6247  * Force non-prefixing of Vars, since parser assumes that they
6248  * belong to target relation. WHERE clause does not use
6249  * InferenceElem, so this is separately required.
6250  */
6251  save_varprefix = context->varprefix;
6252  context->varprefix = false;
6253 
6254  appendContextKeyword(context, " WHERE ",
6256  get_rule_expr(confl->arbiterWhere, context, false);
6257 
6258  context->varprefix = save_varprefix;
6259  }
6260  }
6261  else if (OidIsValid(confl->constraint))
6262  {
6263  char *constraint = get_constraint_name(confl->constraint);
6264 
6265  if (!constraint)
6266  elog(ERROR, "cache lookup failed for constraint %u",
6267  confl->constraint);
6268  appendStringInfo(buf, " ON CONSTRAINT %s",
6269  quote_identifier(constraint));
6270  }
6271 
6272  if (confl->action == ONCONFLICT_NOTHING)
6273  {
6274  appendStringInfoString(buf, " DO NOTHING");
6275  }
6276  else
6277  {
6278  appendStringInfoString(buf, " DO UPDATE SET ");
6279  /* Deparse targetlist */
6281  context, rte);
6282 
6283  /* Add a WHERE clause if given */
6284  if (confl->onConflictWhere != NULL)
6285  {
6286  appendContextKeyword(context, " WHERE ",
6288  get_rule_expr(confl->onConflictWhere, context, false);
6289  }
6290  }
6291  }
6292 
6293  /* Add RETURNING if present */
6294  if (query->returningList)
6295  {
6296  appendContextKeyword(context, " RETURNING",
6298  get_target_list(query->returningList, context, NULL);
6299  }
6300 }
#define NIL
Definition: pg_list.h:65
static void get_with_clause(Query *query, deparse_context *context)
Definition: ruleutils.c:5122
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10724
Alias * alias
Definition: parsenodes.h:1113
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:1030
OnConflictExpr * onConflict
Definition: parsenodes.h:144
static Node * processIndirection(Node *node, deparse_context *context)
Definition: ruleutils.c:10616
int resultRelation
Definition: parsenodes.h:122
static void get_target_list(List *targetList, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5516
Definition: nodes.h:526
#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:6363
#define OidIsValid(objectId)
Definition: c.h:644
List * values_lists
Definition: parsenodes.h:1073
List * targetList
Definition: parsenodes.h:140
List * arbiterElems
Definition: primnodes.h:1529
static char * generate_relation_name(Oid relid, List *namespaces)
Definition: ruleutils.c:10848
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:7803
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:738
static void get_rule_expr(Node *node, deparse_context *context, bool showimplicit)
Definition: ruleutils.c:7908
#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:5005
static void get_values_def(List *values_lists, deparse_context *context)
Definition: ruleutils.c:5079
RTEKind rtekind
Definition: parsenodes.h:975
Node * arbiterWhere
Definition: primnodes.h:1531
Query * subquery
Definition: parsenodes.h:1010
StringInfo buf
Definition: ruleutils.c:112
#define elog(elevel,...)
Definition: elog.h:214
List * onConflictSet
Definition: primnodes.h:1535
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:776
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 6967 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().

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

10558 {
10559  HeapTuple ht_opc;
10560  Form_pg_opclass opcrec;
10561  char *opcname;
10562  char *nspname;
10563 
10564  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
10565  if (!HeapTupleIsValid(ht_opc))
10566  elog(ERROR, "cache lookup failed for opclass %u", opclass);
10567  opcrec = (Form_pg_opclass) GETSTRUCT(ht_opc);
10568 
10569  if (!OidIsValid(actual_datatype) ||
10570  GetDefaultOpClass(actual_datatype, opcrec->opcmethod) != opclass)
10571  {
10572  /* Okay, we need the opclass name. Do we need to qualify it? */
10573  opcname = NameStr(opcrec->opcname);
10574  if (OpclassIsVisible(opclass))
10575  appendStringInfo(buf, " %s", quote_identifier(opcname));
10576  else
10577  {
10578  nspname = get_namespace_name(opcrec->opcnamespace);
10579  appendStringInfo(buf, " %s.%s",
10580  quote_identifier(nspname),
10581  quote_identifier(opcname));
10582  }
10583  }
10584  ReleaseSysCache(ht_opc);
10585 }
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2045
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10724
#define OidIsValid(objectId)
Definition: c.h:644
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:3155
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:1833
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:615
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 9175 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().

9176 {
9177  StringInfo buf = context->buf;
9178  Oid opno = expr->opno;
9179  List *args = expr->args;
9180 
9181  if (!PRETTY_PAREN(context))
9182  appendStringInfoChar(buf, '(');
9183  if (list_length(args) == 2)
9184  {
9185  /* binary operator */
9186  Node *arg1 = (Node *) linitial(args);
9187  Node *arg2 = (Node *) lsecond(args);
9188 
9189  get_rule_expr_paren(arg1, context, true, (Node *) expr);
9190  appendStringInfo(buf, " %s ",
9192  exprType(arg1),
9193  exprType(arg2)));
9194  get_rule_expr_paren(arg2, context, true, (Node *) expr);
9195  }
9196  else
9197  {
9198  /* unary operator --- but which side? */
9199  Node *arg = (Node *) linitial(args);
9200  HeapTuple tp;
9201  Form_pg_operator optup;
9202 
9204  if (!HeapTupleIsValid(tp))
9205  elog(ERROR, "cache lookup failed for operator %u", opno);
9206  optup = (Form_pg_operator) GETSTRUCT(tp);
9207  switch (optup->oprkind)
9208  {
9209  case 'l':
9210  appendStringInfo(buf, "%s ",
9212  InvalidOid,
9213  exprType(arg)));
9214  get_rule_expr_paren(arg, context, true, (Node *) expr);
9215  break;
9216  case 'r':
9217  get_rule_expr_paren(arg, context, true, (Node *) expr);
9218  appendStringInfo(buf, " %s",
9220  exprType(arg),
9221  InvalidOid));
9222  break;
9223  default:
9224  elog(ERROR, "bogus oprkind: %d", optup->oprkind);
9225  }
9226  ReleaseSysCache(tp);
9227  }
9228  if (!PRETTY_PAREN(context))
9229  appendStringInfoChar(buf, ')');
9230 }
#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:7876
Definition: nodes.h:526
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:11055
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:214
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 7497 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().

7498 {
7499  Node *expr;
7500  deparse_namespace *dpns;
7501  ListCell *ancestor_cell;
7502 
7503  /*
7504  * If it's a PARAM_EXEC parameter, try to locate the expression from which
7505  * the parameter was computed. Note that failing to find a referent isn't
7506  * an error, since the Param might well be a subplan output rather than an
7507  * input.
7508  */
7509  expr = find_param_referent(param, context, &dpns, &ancestor_cell);
7510  if (expr)
7511  {
7512  /* Found a match, so print it */
7513  deparse_namespace save_dpns;
7514  bool save_varprefix;
7515  bool need_paren;
7516 
7517  /* Switch attention to the ancestor plan node */
7518  push_ancestor_plan(dpns, ancestor_cell, &save_dpns);
7519 
7520  /*
7521  * Force prefixing of Vars, since they won't belong to the relation
7522  * being scanned in the original plan node.
7523  */
7524  save_varprefix = context->varprefix;
7525  context->varprefix = true;
7526 
7527  /*
7528  * A Param's expansion is typically a Var, Aggref, or upper-level
7529  * Param, which wouldn't need extra parentheses. Otherwise, insert
7530  * parens to ensure the expression looks atomic.
7531  */
7532  need_paren = !(IsA(expr, Var) ||
7533  IsA(expr, Aggref) ||
7534  IsA(expr, Param));
7535  if (need_paren)
7536  appendStringInfoChar(context->buf, '(');
7537 
7538  get_rule_expr(expr, context, false);
7539 
7540  if (need_paren)
7541  appendStringInfoChar(context->buf, ')');
7542 
7543  context->varprefix = save_varprefix;
7544 
7545  pop_ancestor_plan(dpns, &save_dpns);
7546 
7547  return;
7548  }
7549 
7550  /*
7551  * Not PARAM_EXEC, or couldn't find referent: just print $N.
7552  */
7553  appendStringInfo(context->buf, "$%d", param->paramid);
7554 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:577
static Node * find_param_referent(Param *param, deparse_context *context, deparse_namespace **dpns_p, ListCell **ancestor_cell_p)
Definition: ruleutils.c:7362
Definition: nodes.h:526
static void pop_ancestor_plan(deparse_namespace *dpns, deparse_namespace *save_dpns)
Definition: ruleutils.c:4721
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:7908
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:4700

◆ 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 5005 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().

5008 {
5009  deparse_context context;
5010  deparse_namespace dpns;
5011 
5012  /* Guard against excessively long or deeply-nested queries */
5015 
5016  /*
5017  * Before we begin to examine the query, acquire locks on referenced
5018  * relations, and fix up deleted columns in JOIN RTEs. This ensures
5019  * consistent results. Note we assume it's OK to scribble on the passed
5020  * querytree!
5021  *
5022  * We are only deparsing the query (we are not about to execute it), so we
5023  * only need AccessShareLock on the relations it mentions.
5024  */
5025  AcquireRewriteLocks(query, false, false);
5026 
5027  context.buf = buf;
5028  context.namespaces = lcons(&dpns, list_copy(parentnamespace));
5029  context.windowClause = NIL;
5030  context.windowTList = NIL;
5031  context.varprefix = (parentnamespace != NIL ||
5032  list_length(query->rtable) != 1);
5033  context.prettyFlags = prettyFlags;
5034  context.wrapColumn = wrapColumn;
5035  context.indentLevel = startIndent;
5036  context.special_exprkind = EXPR_KIND_NONE;
5037  context.appendparents = NULL;
5038 
5039  set_deparse_for_query(&dpns, query, parentnamespace);
5040 
5041  switch (query->commandType)
5042  {
5043  case CMD_SELECT:
5044  get_select_query_def(query, &context, resultDesc);
5045  break;
5046 
5047  case CMD_UPDATE:
5048  get_update_query_def(query, &context);
5049  break;
5050 
5051  case CMD_INSERT:
5052  get_insert_query_def(query, &context);
5053  break;
5054 
5055  case CMD_DELETE:
5056  get_delete_query_def(query, &context);
5057  break;
5058 
5059  case CMD_NOTHING:
5060  appendStringInfoString(buf, "NOTHING");
5061  break;
5062 
5063  case CMD_UTILITY:
5064  get_utility_query_def(query, &context);
5065  break;
5066 
5067  default:
5068  elog(ERROR, "unrecognized query command type: %d",
5069  query->commandType);
5070  break;
5071  }
5072 }
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:6095
static void get_update_query_def(Query *query, deparse_context *context)
Definition: ruleutils.c:6308
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:6566
static void get_select_query_def(Query *query, deparse_context *context, TupleDesc resultDesc)
Definition: ruleutils.c:5202
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:3312
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:6515
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:3599
Bitmapset * appendparents
Definition: ruleutils.c:122
StringInfo buf
Definition: ruleutils.c:112
#define elog(elevel,...)
Definition: elog.h:214
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99

◆ get_range_partbound_string()

char* get_range_partbound_string ( List bound_datums)

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

11375 {
11376  deparse_context context;
11378  ListCell *cell;
11379  char *sep;
11380 
11381  memset(&context, 0, sizeof(deparse_context));
11382  context.buf = buf;
11383 
11384  appendStringInfoString(buf, "(");
11385  sep = "";
11386  foreach(cell, bound_datums)
11387  {
11388  PartitionRangeDatum *datum =
11390 
11391  appendStringInfoString(buf, sep);
11392  if (datum->kind == PARTITION_RANGE_DATUM_MINVALUE)
11393  appendStringInfoString(buf, "MINVALUE");
11394  else if (datum->kind == PARTITION_RANGE_DATUM_MAXVALUE)
11395  appendStringInfoString(buf, "MAXVALUE");
11396  else
11397  {
11398  Const *val = castNode(Const, datum->value);
11399 
11400  get_const_expr(val, &context, -1);
11401  }
11402  sep = ", ";
11403  }
11404  appendStringInfoChar(buf, ')');
11405 
11406  return buf->data;
11407 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:595
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
PartitionRangeDatumKind kind
Definition: parsenodes.h:846
static void get_const_expr(Const *constval, deparse_context *context, int showtype)
Definition: ruleutils.c:9585
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 10828 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().

10829 {
10830  char *relname = get_rel_name(relid);
10831 
10832  if (!relname)
10833  elog(ERROR, "cache lookup failed for relation %u", relid);
10834  return relname;
10835 }
NameData relname
Definition: pg_class.h:38
#define ERROR
Definition: elog.h:43
#define elog(elevel,...)
Definition: elog.h:214
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1791

◆ get_reloptions()

static void get_reloptions ( StringInfo  buf,
Datum  reloptions 
)
static

Definition at line 11285 of file ruleutils.c.

References appendStringInfo(), appendStringInfoString(), DatumGetArrayTypeP, deconstruct_array(), i, name, noptions, options, pfree(), quote_identifier(), simple_quote_literal(), TextDatumGetCString, and value.

Referenced by flatten_reloptions(), and pg_get_indexdef_worker().

11286 {
11287  Datum *options;
11288  int noptions;
11289  int i;
11290 
11292  TEXTOID, -1, false, TYPALIGN_INT,
11293  &options, NULL, &noptions);
11294 
11295  for (i = 0; i < noptions; i++)
11296  {
11297  char *option = TextDatumGetCString(options[i]);
11298  char *name;
11299  char *separator;
11300  char *value;
11301 
11302  /*
11303  * Each array element should have the form name=value. If the "="
11304  * is missing for some reason, treat it like an empty value.
11305  */
11306  name = option;
11307  separator = strchr(option, '=');
11308  if (separator)
11309  {
11310  *separator = '\0';
11311  value = separator + 1;
11312  }
11313  else
11314  value = "";
11315 
11316  if (i > 0)
11317  appendStringInfoString(buf, ", ");
11318  appendStringInfo(buf, "%s=", quote_identifier(name));
11319 
11320  /*
11321  * In general we need to quote the value; but to avoid unnecessary
11322  * clutter, do not quote if it is an identifier that would not
11323  * need quoting. (We could also allow numbers, but that is a bit
11324  * trickier than it looks --- for example, are leading zeroes
11325  * significant? We don't want to assume very much here about what
11326  * custom reloptions might mean.)
11327  */
11328  if (quote_identifier(value) == value)
11329  appendStringInfoString(buf, value);
11330  else
11331  simple_quote_literal(buf, value);
11332 
11333  pfree(option);
11334  }
11335 }