PostgreSQL Source Code  git master
deparse.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_opfamily.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/plannodes.h"
#include "optimizer/optimizer.h"
#include "optimizer/prep.h"
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "postgres_fdw.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "commands/tablecmds.h"
Include dependency graph for deparse.c:

Go to the source code of this file.

Data Structures

struct  foreign_glob_cxt
 
struct  foreign_loc_cxt
 
struct  deparse_expr_cxt
 

Macros

#define REL_ALIAS_PREFIX   "r"
 
#define ADD_REL_QUALIFIER(buf, varno)    appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno))
 
#define SUBQUERY_REL_ALIAS_PREFIX   "s"
 
#define SUBQUERY_COL_ALIAS_PREFIX   "c"
 

Typedefs

typedef struct foreign_glob_cxt foreign_glob_cxt
 
typedef struct foreign_loc_cxt foreign_loc_cxt
 
typedef struct deparse_expr_cxt deparse_expr_cxt
 

Enumerations

enum  FDWCollateState { FDW_COLLATE_NONE , FDW_COLLATE_SAFE , FDW_COLLATE_UNSAFE }
 

Functions

static bool foreign_expr_walker (Node *node, foreign_glob_cxt *glob_cxt, foreign_loc_cxt *outer_cxt, foreign_loc_cxt *case_arg_cxt)
 
static char * deparse_type_name (Oid type_oid, int32 typemod)
 
static void deparseTargetList (StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, bool is_returning, Bitmapset *attrs_used, bool qualify_col, List **retrieved_attrs)
 
static void deparseExplicitTargetList (List *tlist, bool is_returning, List **retrieved_attrs, deparse_expr_cxt *context)
 
static void deparseSubqueryTargetList (deparse_expr_cxt *context)
 
static void deparseReturningList (StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, bool trig_after_row, List *withCheckOptionList, List *returningList, List **retrieved_attrs)
 
static void deparseColumnRef (StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col)
 
static void deparseRelation (StringInfo buf, Relation rel)
 
static void deparseExpr (Expr *expr, deparse_expr_cxt *context)
 
static void deparseVar (Var *node, deparse_expr_cxt *context)
 
static void deparseConst (Const *node, deparse_expr_cxt *context, int showtype)
 
static void deparseParam (Param *node, deparse_expr_cxt *context)
 
static void deparseSubscriptingRef (SubscriptingRef *node, deparse_expr_cxt *context)
 
static void deparseFuncExpr (FuncExpr *node, deparse_expr_cxt *context)
 
static void deparseOpExpr (OpExpr *node, deparse_expr_cxt *context)
 
static bool isPlainForeignVar (Expr *node, deparse_expr_cxt *context)
 
static void deparseOperatorName (StringInfo buf, Form_pg_operator opform)
 
static void deparseDistinctExpr (DistinctExpr *node, deparse_expr_cxt *context)
 
static void deparseScalarArrayOpExpr (ScalarArrayOpExpr *node, deparse_expr_cxt *context)
 
static void deparseRelabelType (RelabelType *node, deparse_expr_cxt *context)
 
static void deparseBoolExpr (BoolExpr *node, deparse_expr_cxt *context)
 
static void deparseNullTest (NullTest *node, deparse_expr_cxt *context)
 
static void deparseCaseExpr (CaseExpr *node, deparse_expr_cxt *context)
 
static void deparseArrayExpr (ArrayExpr *node, deparse_expr_cxt *context)
 
static void printRemoteParam (int paramindex, Oid paramtype, int32 paramtypmod, deparse_expr_cxt *context)
 
static void printRemotePlaceholder (Oid paramtype, int32 paramtypmod, deparse_expr_cxt *context)
 
static void deparseSelectSql (List *tlist, bool is_subquery, List **retrieved_attrs, deparse_expr_cxt *context)
 
static void deparseLockingClause (deparse_expr_cxt *context)
 
static void appendOrderByClause (List *pathkeys, bool has_final_sort, deparse_expr_cxt *context)
 
static void appendLimitClause (deparse_expr_cxt *context)
 
static void appendConditions (List *exprs, deparse_expr_cxt *context)
 
static void deparseFromExprForRel (StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool use_alias, Index ignore_rel, List **ignore_conds, List **params_list)
 
static void deparseFromExpr (List *quals, deparse_expr_cxt *context)
 
static void deparseRangeTblRef (StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **params_list)
 
static void deparseAggref (Aggref *node, deparse_expr_cxt *context)
 
static void appendGroupByClause (List *tlist, deparse_expr_cxt *context)
 
static void appendOrderBySuffix (Oid sortop, Oid sortcoltype, bool nulls_first, deparse_expr_cxt *context)
 
static void appendAggOrderBy (List *orderList, List *targetList, deparse_expr_cxt *context)
 
static void appendFunctionName (Oid funcid, deparse_expr_cxt *context)
 
static NodedeparseSortGroupClause (Index ref, List *tlist, bool force_colno, deparse_expr_cxt *context)
 
static bool is_subquery_var (Var *node, RelOptInfo *foreignrel, int *relno, int *colno)
 
static void get_relation_column_alias_ids (Var *node, RelOptInfo *foreignrel, int *relno, int *colno)
 
void classifyConditions (PlannerInfo *root, RelOptInfo *baserel, List *input_conds, List **remote_conds, List **local_conds)
 
bool is_foreign_expr (PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
 
bool is_foreign_param (PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
 
bool is_foreign_pathkey (PlannerInfo *root, RelOptInfo *baserel, PathKey *pathkey)
 
Listbuild_tlist_to_deparse (RelOptInfo *foreignrel)
 
void deparseSelectStmtForRel (StringInfo buf, PlannerInfo *root, RelOptInfo *rel, List *tlist, List *remote_conds, List *pathkeys, bool has_final_sort, bool has_limit, bool is_subquery, List **retrieved_attrs, List **params_list)
 
const char * get_jointype_name (JoinType jointype)
 
void deparseInsertSql (StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, List *targetAttrs, bool doNothing, List *withCheckOptionList, List *returningList, List **retrieved_attrs, int *values_end_len)
 
void rebuildInsertSql (StringInfo buf, Relation rel, char *orig_query, List *target_attrs, int values_end_len, int num_params, int num_rows)
 
void deparseUpdateSql (StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, List *targetAttrs, List *withCheckOptionList, List *returningList, List **retrieved_attrs)
 
void deparseDirectUpdateSql (StringInfo buf, PlannerInfo *root, Index rtindex, Relation rel, RelOptInfo *foreignrel, List *targetlist, List *targetAttrs, List *remote_conds, List **params_list, List *returningList, List **retrieved_attrs)
 
void deparseDeleteSql (StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, List *returningList, List **retrieved_attrs)
 
void deparseDirectDeleteSql (StringInfo buf, PlannerInfo *root, Index rtindex, Relation rel, RelOptInfo *foreignrel, List *remote_conds, List **params_list, List *returningList, List **retrieved_attrs)
 
void deparseAnalyzeSizeSql (StringInfo buf, Relation rel)
 
void deparseAnalyzeSql (StringInfo buf, Relation rel, List **retrieved_attrs)
 
void deparseTruncateSql (StringInfo buf, List *rels, DropBehavior behavior, bool restart_seqs)
 
void deparseStringLiteral (StringInfo buf, const char *val)
 

Macro Definition Documentation

◆ ADD_REL_QUALIFIER

#define ADD_REL_QUALIFIER (   buf,
  varno 
)     appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno))

Definition at line 109 of file deparse.c.

◆ REL_ALIAS_PREFIX

#define REL_ALIAS_PREFIX   "r"

Definition at line 107 of file deparse.c.

◆ SUBQUERY_COL_ALIAS_PREFIX

#define SUBQUERY_COL_ALIAS_PREFIX   "c"

Definition at line 112 of file deparse.c.

◆ SUBQUERY_REL_ALIAS_PREFIX

#define SUBQUERY_REL_ALIAS_PREFIX   "s"

Definition at line 111 of file deparse.c.

Typedef Documentation

◆ deparse_expr_cxt

◆ foreign_glob_cxt

◆ foreign_loc_cxt

Enumeration Type Documentation

◆ FDWCollateState

Enumerator
FDW_COLLATE_NONE 
FDW_COLLATE_SAFE 
FDW_COLLATE_UNSAFE 

Definition at line 77 of file deparse.c.

78 {
79  FDW_COLLATE_NONE, /* expression is of a noncollatable type, or
80  * it has default collation that is not
81  * traceable to a foreign Var */
82  FDW_COLLATE_SAFE, /* collation derives from a foreign Var */
83  FDW_COLLATE_UNSAFE /* collation is non-default and derives from
84  * something other than a foreign Var */
FDWCollateState
Definition: deparse.c:78
@ FDW_COLLATE_SAFE
Definition: deparse.c:82
@ FDW_COLLATE_UNSAFE
Definition: deparse.c:83
@ FDW_COLLATE_NONE
Definition: deparse.c:79

Function Documentation

◆ appendAggOrderBy()

static void appendAggOrderBy ( List orderList,
List targetList,
deparse_expr_cxt context 
)
static

Definition at line 3468 of file deparse.c.

3469 {
3470  StringInfo buf = context->buf;
3471  ListCell *lc;
3472  bool first = true;
3473 
3474  foreach(lc, orderList)
3475  {
3476  SortGroupClause *srt = (SortGroupClause *) lfirst(lc);
3477  Node *sortexpr;
3478 
3479  if (!first)
3480  appendStringInfoString(buf, ", ");
3481  first = false;
3482 
3483  /* Deparse the sort expression proper. */
3484  sortexpr = deparseSortGroupClause(srt->tleSortGroupRef, targetList,
3485  false, context);
3486  /* Add decoration as needed. */
3487  appendOrderBySuffix(srt->sortop, exprType(sortexpr), srt->nulls_first,
3488  context);
3489  }
3490 }
static Node * deparseSortGroupClause(Index ref, List *tlist, bool force_colno, deparse_expr_cxt *context)
Definition: deparse.c:3762
static void appendOrderBySuffix(Oid sortop, Oid sortcoltype, bool nulls_first, deparse_expr_cxt *context)
Definition: deparse.c:3497
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
#define lfirst(lc)
Definition: pg_list.h:170
static char * buf
Definition: pg_test_fsync.c:67
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
Definition: nodes.h:575
Index tleSortGroupRef
Definition: parsenodes.h:1306
StringInfo buf
Definition: deparse.c:103

References appendOrderBySuffix(), appendStringInfoString(), deparse_expr_cxt::buf, buf, deparseSortGroupClause(), exprType(), lfirst, SortGroupClause::nulls_first, SortGroupClause::sortop, and SortGroupClause::tleSortGroupRef.

Referenced by deparseAggref().

◆ appendConditions()

static void appendConditions ( List exprs,
deparse_expr_cxt context 
)
static

Definition at line 1499 of file deparse.c.

1500 {
1501  int nestlevel;
1502  ListCell *lc;
1503  bool is_first = true;
1504  StringInfo buf = context->buf;
1505 
1506  /* Make sure any constants in the exprs are printed portably */
1507  nestlevel = set_transmission_modes();
1508 
1509  foreach(lc, exprs)
1510  {
1511  Expr *expr = (Expr *) lfirst(lc);
1512 
1513  /* Extract clause from RestrictInfo, if required */
1514  if (IsA(expr, RestrictInfo))
1515  expr = ((RestrictInfo *) expr)->clause;
1516 
1517  /* Connect expressions with "AND" and parenthesize each condition. */
1518  if (!is_first)
1519  appendStringInfoString(buf, " AND ");
1520 
1521  appendStringInfoChar(buf, '(');
1522  deparseExpr(expr, context);
1523  appendStringInfoChar(buf, ')');
1524 
1525  is_first = false;
1526  }
1527 
1528  reset_transmission_modes(nestlevel);
1529 }
static void deparseExpr(Expr *expr, deparse_expr_cxt *context)
Definition: deparse.c:2603
#define IsA(nodeptr, _type_)
Definition: nodes.h:625
void reset_transmission_modes(int nestlevel)
int set_transmission_modes(void)
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188

References appendStringInfoChar(), appendStringInfoString(), deparse_expr_cxt::buf, buf, deparseExpr(), IsA, lfirst, reset_transmission_modes(), and set_transmission_modes().

Referenced by deparseDirectDeleteSql(), deparseDirectUpdateSql(), deparseFromExpr(), deparseFromExprForRel(), and deparseSelectStmtForRel().

◆ appendFunctionName()

static void appendFunctionName ( Oid  funcid,
deparse_expr_cxt context 
)
static

Definition at line 3727 of file deparse.c.

3728 {
3729  StringInfo buf = context->buf;
3730  HeapTuple proctup;
3731  Form_pg_proc procform;
3732  const char *proname;
3733 
3734  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3735  if (!HeapTupleIsValid(proctup))
3736  elog(ERROR, "cache lookup failed for function %u", funcid);
3737  procform = (Form_pg_proc) GETSTRUCT(proctup);
3738 
3739  /* Print schema name only if it's not pg_catalog */
3740  if (procform->pronamespace != PG_CATALOG_NAMESPACE)
3741  {
3742  const char *schemaname;
3743 
3744  schemaname = get_namespace_name(procform->pronamespace);
3745  appendStringInfo(buf, "%s.", quote_identifier(schemaname));
3746  }
3747 
3748  /* Always print the function name */
3749  proname = NameStr(procform->proname);
3751 
3752  ReleaseSysCache(proctup);
3753 }
#define NameStr(name)
Definition: c.h:692
#define ERROR
Definition: elog.h:33
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3326
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
NameData proname
Definition: pg_proc.h:35
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:12189
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ PROCOID
Definition: syscache.h:79

References appendStringInfo(), appendStringInfoString(), deparse_expr_cxt::buf, buf, elog(), ERROR, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, PROCOID, proname, quote_identifier(), ReleaseSysCache(), and SearchSysCache1().

Referenced by deparseAggref(), and deparseFuncExpr().

◆ appendGroupByClause()

static void appendGroupByClause ( List tlist,
deparse_expr_cxt context 
)
static

Definition at line 3581 of file deparse.c.

3582 {
3583  StringInfo buf = context->buf;
3584  Query *query = context->root->parse;
3585  ListCell *lc;
3586  bool first = true;
3587 
3588  /* Nothing to be done, if there's no GROUP BY clause in the query. */
3589  if (!query->groupClause)
3590  return;
3591 
3592  appendStringInfoString(buf, " GROUP BY ");
3593 
3594  /*
3595  * Queries with grouping sets are not pushed down, so we don't expect
3596  * grouping sets here.
3597  */
3598  Assert(!query->groupingSets);
3599 
3600  foreach(lc, query->groupClause)
3601  {
3602  SortGroupClause *grp = (SortGroupClause *) lfirst(lc);
3603 
3604  if (!first)
3605  appendStringInfoString(buf, ", ");
3606  first = false;
3607 
3608  deparseSortGroupClause(grp->tleSortGroupRef, tlist, true, context);
3609  }
3610 }
Assert(fmt[strlen(fmt) - 1] !='\n')
Query * parse
Definition: pathnodes.h:162
List * groupClause
Definition: parsenodes.h:164
List * groupingSets
Definition: parsenodes.h:167
PlannerInfo * root
Definition: deparse.c:98

References appendStringInfoString(), Assert(), deparse_expr_cxt::buf, buf, deparseSortGroupClause(), Query::groupClause, Query::groupingSets, lfirst, PlannerInfo::parse, deparse_expr_cxt::root, and SortGroupClause::tleSortGroupRef.

Referenced by deparseSelectStmtForRel().

◆ appendLimitClause()

static void appendLimitClause ( deparse_expr_cxt context)
static

Definition at line 3699 of file deparse.c.

3700 {
3701  PlannerInfo *root = context->root;
3702  StringInfo buf = context->buf;
3703  int nestlevel;
3704 
3705  /* Make sure any constants in the exprs are printed portably */
3706  nestlevel = set_transmission_modes();
3707 
3708  if (root->parse->limitCount)
3709  {
3710  appendStringInfoString(buf, " LIMIT ");
3711  deparseExpr((Expr *) root->parse->limitCount, context);
3712  }
3713  if (root->parse->limitOffset)
3714  {
3715  appendStringInfoString(buf, " OFFSET ");
3716  deparseExpr((Expr *) root->parse->limitOffset, context);
3717  }
3718 
3719  reset_transmission_modes(nestlevel);
3720 }
Node * limitCount
Definition: parsenodes.h:178
Node * limitOffset
Definition: parsenodes.h:177

References appendStringInfoString(), deparse_expr_cxt::buf, buf, deparseExpr(), Query::limitCount, Query::limitOffset, PlannerInfo::parse, reset_transmission_modes(), deparse_expr_cxt::root, and set_transmission_modes().

Referenced by deparseSelectStmtForRel().

◆ appendOrderByClause()

static void appendOrderByClause ( List pathkeys,
bool  has_final_sort,
deparse_expr_cxt context 
)
static

Definition at line 3622 of file deparse.c.

3624 {
3625  ListCell *lcell;
3626  int nestlevel;
3627  const char *delim = " ";
3628  StringInfo buf = context->buf;
3629 
3630  /* Make sure any constants in the exprs are printed portably */
3631  nestlevel = set_transmission_modes();
3632 
3633  appendStringInfoString(buf, " ORDER BY");
3634  foreach(lcell, pathkeys)
3635  {
3636  PathKey *pathkey = lfirst(lcell);
3637  EquivalenceMember *em;
3638  Expr *em_expr;
3639  Oid oprid;
3640 
3641  if (has_final_sort)
3642  {
3643  /*
3644  * By construction, context->foreignrel is the input relation to
3645  * the final sort.
3646  */
3647  em = find_em_for_rel_target(context->root,
3648  pathkey->pk_eclass,
3649  context->foreignrel);
3650  }
3651  else
3652  em = find_em_for_rel(context->root,
3653  pathkey->pk_eclass,
3654  context->scanrel);
3655 
3656  /*
3657  * We don't expect any error here; it would mean that shippability
3658  * wasn't verified earlier. For the same reason, we don't recheck
3659  * shippability of the sort operator.
3660  */
3661  if (em == NULL)
3662  elog(ERROR, "could not find pathkey item to sort");
3663 
3664  em_expr = em->em_expr;
3665 
3666  /*
3667  * Lookup the operator corresponding to the strategy in the opclass.
3668  * The datatype used by the opfamily is not necessarily the same as
3669  * the expression type (for array types for example).
3670  */
3672  em->em_datatype,
3673  em->em_datatype,
3674  pathkey->pk_strategy);
3675  if (!OidIsValid(oprid))
3676  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
3677  pathkey->pk_strategy, em->em_datatype, em->em_datatype,
3678  pathkey->pk_opfamily);
3679 
3680  appendStringInfoString(buf, delim);
3681  deparseExpr(em_expr, context);
3682 
3683  /*
3684  * Here we need to use the expression's actual type to discover
3685  * whether the desired operator will be the default or not.
3686  */
3687  appendOrderBySuffix(oprid, exprType((Node *) em_expr),
3688  pathkey->pk_nulls_first, context);
3689 
3690  delim = ", ";
3691  }
3692  reset_transmission_modes(nestlevel);
3693 }
#define OidIsValid(objectId)
Definition: c.h:721
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
Oid oprid(Operator op)
Definition: parse_oper.c:250
unsigned int Oid
Definition: postgres_ext.h:31
EquivalenceMember * find_em_for_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel)
EquivalenceMember * find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel)
bool pk_nulls_first
Definition: pathnodes.h:1212
int pk_strategy
Definition: pathnodes.h:1211
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1209
Oid pk_opfamily
Definition: pathnodes.h:1210
RelOptInfo * foreignrel
Definition: deparse.c:99
RelOptInfo * scanrel
Definition: deparse.c:100

References appendOrderBySuffix(), appendStringInfoString(), deparse_expr_cxt::buf, buf, deparseExpr(), elog(), EquivalenceMember::em_datatype, EquivalenceMember::em_expr, ERROR, exprType(), find_em_for_rel(), find_em_for_rel_target(), deparse_expr_cxt::foreignrel, get_opfamily_member(), lfirst, OidIsValid, oprid(), PathKey::pk_eclass, PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, reset_transmission_modes(), deparse_expr_cxt::root, deparse_expr_cxt::scanrel, and set_transmission_modes().

Referenced by deparseSelectStmtForRel().

◆ appendOrderBySuffix()

static void appendOrderBySuffix ( Oid  sortop,
Oid  sortcoltype,
bool  nulls_first,
deparse_expr_cxt context 
)
static

Definition at line 3497 of file deparse.c.

3499 {
3500  StringInfo buf = context->buf;
3501  TypeCacheEntry *typentry;
3502 
3503  /* See whether operator is default < or > for sort expr's datatype. */
3504  typentry = lookup_type_cache(sortcoltype,
3506 
3507  if (sortop == typentry->lt_opr)
3508  appendStringInfoString(buf, " ASC");
3509  else if (sortop == typentry->gt_opr)
3510  appendStringInfoString(buf, " DESC");
3511  else
3512  {
3513  HeapTuple opertup;
3514  Form_pg_operator operform;
3515 
3516  appendStringInfoString(buf, " USING ");
3517 
3518  /* Append operator name. */
3519  opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(sortop));
3520  if (!HeapTupleIsValid(opertup))
3521  elog(ERROR, "cache lookup failed for operator %u", sortop);
3522  operform = (Form_pg_operator) GETSTRUCT(opertup);
3523  deparseOperatorName(buf, operform);
3524  ReleaseSysCache(opertup);
3525  }
3526 
3527  if (nulls_first)
3528  appendStringInfoString(buf, " NULLS FIRST");
3529  else
3530  appendStringInfoString(buf, " NULLS LAST");
3531 }
static void deparseOperatorName(StringInfo buf, Form_pg_operator opform)
Definition: deparse.c:3125
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
@ OPEROID
Definition: syscache.h:72
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:339
#define TYPECACHE_GT_OPR
Definition: typcache.h:138
#define TYPECACHE_LT_OPR
Definition: typcache.h:137

References appendStringInfoString(), deparse_expr_cxt::buf, buf, deparseOperatorName(), elog(), ERROR, GETSTRUCT, TypeCacheEntry::gt_opr, HeapTupleIsValid, lookup_type_cache(), TypeCacheEntry::lt_opr, ObjectIdGetDatum, OPEROID, ReleaseSysCache(), SearchSysCache1(), TYPECACHE_GT_OPR, and TYPECACHE_LT_OPR.

Referenced by appendAggOrderBy(), and appendOrderByClause().

◆ build_tlist_to_deparse()

List* build_tlist_to_deparse ( RelOptInfo foreignrel)

Definition at line 1102 of file deparse.c.

1103 {
1104  List *tlist = NIL;
1105  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
1106  ListCell *lc;
1107 
1108  /*
1109  * For an upper relation, we have already built the target list while
1110  * checking shippability, so just return that.
1111  */
1112  if (IS_UPPER_REL(foreignrel))
1113  return fpinfo->grouped_tlist;
1114 
1115  /*
1116  * We require columns specified in foreignrel->reltarget->exprs and those
1117  * required for evaluating the local conditions.
1118  */
1119  tlist = add_to_flat_tlist(tlist,
1120  pull_var_clause((Node *) foreignrel->reltarget->exprs,
1122  foreach(lc, fpinfo->local_conds)
1123  {
1124  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
1125 
1126  tlist = add_to_flat_tlist(tlist,
1127  pull_var_clause((Node *) rinfo->clause,
1129  }
1130 
1131  return tlist;
1132 }
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define PVC_RECURSE_PLACEHOLDERS
Definition: optimizer.h:193
#define IS_UPPER_REL(rel)
Definition: pathnodes.h:673
#define lfirst_node(type, lc)
Definition: pg_list.h:174
#define NIL
Definition: pg_list.h:66
Definition: pg_list.h:52
List * exprs
Definition: pathnodes.h:1265
void * fdw_private
Definition: pathnodes.h:788
struct PathTarget * reltarget
Definition: pathnodes.h:715
Expr * clause
Definition: pathnodes.h:2234
List * add_to_flat_tlist(List *tlist, List *exprs)
Definition: tlist.c:121
List * pull_var_clause(Node *node, int flags)
Definition: var.c:604

References add_to_flat_tlist(), RestrictInfo::clause, PathTarget::exprs, RelOptInfo::fdw_private, PgFdwRelationInfo::grouped_tlist, if(), IS_UPPER_REL, lfirst_node, PgFdwRelationInfo::local_conds, NIL, pull_var_clause(), PVC_RECURSE_PLACEHOLDERS, and RelOptInfo::reltarget.

Referenced by estimate_path_cost_size(), and postgresGetForeignPlan().

◆ classifyConditions()

void classifyConditions ( PlannerInfo root,
RelOptInfo baserel,
List input_conds,
List **  remote_conds,
List **  local_conds 
)

Definition at line 211 of file deparse.c.

216 {
217  ListCell *lc;
218 
219  *remote_conds = NIL;
220  *local_conds = NIL;
221 
222  foreach(lc, input_conds)
223  {
225 
226  if (is_foreign_expr(root, baserel, ri->clause))
227  *remote_conds = lappend(*remote_conds, ri);
228  else
229  *local_conds = lappend(*local_conds, ri);
230  }
231 }
bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:237
List * lappend(List *list, void *datum)
Definition: list.c:338

References RestrictInfo::clause, is_foreign_expr(), lappend(), lfirst_node, and NIL.

Referenced by estimate_path_cost_size(), and postgresGetForeignRelSize().

◆ deparse_type_name()

static char * deparse_type_name ( Oid  type_oid,
int32  typemod 
)
static

Definition at line 1083 of file deparse.c.

1084 {
1086 
1087  if (!is_builtin(type_oid))
1088  flags |= FORMAT_TYPE_FORCE_QUALIFY;
1089 
1090  return format_type_extended(type_oid, typemod, flags);
1091 }
#define FORMAT_TYPE_TYPEMOD_GIVEN
Definition: builtins.h:112
#define FORMAT_TYPE_FORCE_QUALIFY
Definition: builtins.h:114
uint16 bits16
Definition: c.h:460
char * format_type_extended(Oid type_oid, int32 typemod, bits16 flags)
Definition: format_type.c:112
bool is_builtin(Oid objectId)
Definition: shippable.c:152

References format_type_extended(), FORMAT_TYPE_FORCE_QUALIFY, FORMAT_TYPE_TYPEMOD_GIVEN, and is_builtin().

Referenced by deparseArrayExpr(), deparseConst(), deparseFuncExpr(), deparseRelabelType(), printRemoteParam(), and printRemotePlaceholder().

◆ deparseAggref()

static void deparseAggref ( Aggref node,
deparse_expr_cxt context 
)
static

Definition at line 3376 of file deparse.c.

3377 {
3378  StringInfo buf = context->buf;
3379  bool use_variadic;
3380 
3381  /* Only basic, non-split aggregation accepted. */
3382  Assert(node->aggsplit == AGGSPLIT_SIMPLE);
3383 
3384  /* Check if need to print VARIADIC (cf. ruleutils.c) */
3385  use_variadic = node->aggvariadic;
3386 
3387  /* Find aggregate name from aggfnoid which is a pg_proc entry */
3388  appendFunctionName(node->aggfnoid, context);
3389  appendStringInfoChar(buf, '(');
3390 
3391  /* Add DISTINCT */
3392  appendStringInfoString(buf, (node->aggdistinct != NIL) ? "DISTINCT " : "");
3393 
3394  if (AGGKIND_IS_ORDERED_SET(node->aggkind))
3395  {
3396  /* Add WITHIN GROUP (ORDER BY ..) */
3397  ListCell *arg;
3398  bool first = true;
3399 
3400  Assert(!node->aggvariadic);
3401  Assert(node->aggorder != NIL);
3402 
3403  foreach(arg, node->aggdirectargs)
3404  {
3405  if (!first)
3406  appendStringInfoString(buf, ", ");
3407  first = false;
3408 
3409  deparseExpr((Expr *) lfirst(arg), context);
3410  }
3411 
3412  appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
3413  appendAggOrderBy(node->aggorder, node->args, context);
3414  }
3415  else
3416  {
3417  /* aggstar can be set only in zero-argument aggregates */
3418  if (node->aggstar)
3419  appendStringInfoChar(buf, '*');
3420  else
3421  {
3422  ListCell *arg;
3423  bool first = true;
3424 
3425  /* Add all the arguments */
3426  foreach(arg, node->args)
3427  {
3428  TargetEntry *tle = (TargetEntry *) lfirst(arg);
3429  Node *n = (Node *) tle->expr;
3430 
3431  if (tle->resjunk)
3432  continue;
3433 
3434  if (!first)
3435  appendStringInfoString(buf, ", ");
3436  first = false;
3437 
3438  /* Add VARIADIC */
3439  if (use_variadic && lnext(node->args, arg) == NULL)
3440  appendStringInfoString(buf, "VARIADIC ");
3441 
3442  deparseExpr((Expr *) n, context);
3443  }
3444  }
3445 
3446  /* Add ORDER BY */
3447  if (node->aggorder != NIL)
3448  {
3449  appendStringInfoString(buf, " ORDER BY ");
3450  appendAggOrderBy(node->aggorder, node->args, context);
3451  }
3452  }
3453 
3454  /* Add FILTER (WHERE ..) */
3455  if (node->aggfilter != NULL)
3456  {
3457  appendStringInfoString(buf, ") FILTER (WHERE ");
3458  deparseExpr((Expr *) node->aggfilter, context);
3459  }
3460 
3461  appendStringInfoChar(buf, ')');
3462 }
static void appendFunctionName(Oid funcid, deparse_expr_cxt *context)
Definition: deparse.c:3727
static void appendAggOrderBy(List *orderList, List *targetList, deparse_expr_cxt *context)
Definition: deparse.c:3468
@ AGGSPLIT_SIMPLE
Definition: nodes.h:831
void * arg
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341
bool aggstar
Definition: primnodes.h:399
Oid aggfnoid
Definition: primnodes.h:366
List * aggdistinct
Definition: primnodes.h:393
List * aggdirectargs
Definition: primnodes.h:384
bool aggvariadic
Definition: primnodes.h:405
char aggkind
Definition: primnodes.h:408
List * args
Definition: primnodes.h:387
Expr * aggfilter
Definition: primnodes.h:396
List * aggorder
Definition: primnodes.h:390
AggSplit aggsplit
Definition: primnodes.h:414
Expr * expr
Definition: primnodes.h:1828
bool resjunk
Definition: primnodes.h:1835

References Aggref::aggdirectargs, Aggref::aggdistinct, Aggref::aggfilter, Aggref::aggfnoid, Aggref::aggkind, Aggref::aggorder, Aggref::aggsplit, AGGSPLIT_SIMPLE, Aggref::aggstar, Aggref::aggvariadic, appendAggOrderBy(), appendFunctionName(), appendStringInfoChar(), appendStringInfoString(), arg, Aggref::args, Assert(), deparse_expr_cxt::buf, buf, deparseExpr(), TargetEntry::expr, if(), lfirst, lnext(), NIL, and TargetEntry::resjunk.

Referenced by deparseExpr().

◆ deparseAnalyzeSizeSql()

void deparseAnalyzeSizeSql ( StringInfo  buf,
Relation  rel 
)

Definition at line 2287 of file deparse.c.

2288 {
2290 
2291  /* We'll need the remote relation name as a literal. */
2293  deparseRelation(&relname, rel);
2294 
2295  appendStringInfoString(buf, "SELECT pg_catalog.pg_relation_size(");
2297  appendStringInfo(buf, "::pg_catalog.regclass) / %d", BLCKSZ);
2298 }
void deparseStringLiteral(StringInfo buf, const char *val)
Definition: deparse.c:2568
static void deparseRelation(StringInfo buf, Relation rel)
Definition: deparse.c:2528
NameData relname
Definition: pg_class.h:38
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
char data[NAMEDATALEN]
Definition: c.h:688

References appendStringInfo(), appendStringInfoString(), buf, nameData::data, deparseRelation(), deparseStringLiteral(), initStringInfo(), and relname.

Referenced by postgresAnalyzeForeignTable().

◆ deparseAnalyzeSql()

void deparseAnalyzeSql ( StringInfo  buf,
Relation  rel,
List **  retrieved_attrs 
)

Definition at line 2307 of file deparse.c.

2308 {
2309  Oid relid = RelationGetRelid(rel);
2310  TupleDesc tupdesc = RelationGetDescr(rel);
2311  int i;
2312  char *colname;
2313  List *options;
2314  ListCell *lc;
2315  bool first = true;
2316 
2317  *retrieved_attrs = NIL;
2318 
2319  appendStringInfoString(buf, "SELECT ");
2320  for (i = 0; i < tupdesc->natts; i++)
2321  {
2322  /* Ignore dropped columns. */
2323  if (TupleDescAttr(tupdesc, i)->attisdropped)
2324  continue;
2325 
2326  if (!first)
2327  appendStringInfoString(buf, ", ");
2328  first = false;
2329 
2330  /* Use attribute name or column_name option. */
2331  colname = NameStr(TupleDescAttr(tupdesc, i)->attname);
2332  options = GetForeignColumnOptions(relid, i + 1);
2333 
2334  foreach(lc, options)
2335  {
2336  DefElem *def = (DefElem *) lfirst(lc);
2337 
2338  if (strcmp(def->defname, "column_name") == 0)
2339  {
2340  colname = defGetString(def);
2341  break;
2342  }
2343  }
2344 
2346 
2347  *retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
2348  }
2349 
2350  /* Don't generate bad syntax for zero-column relation. */
2351  if (first)
2352  appendStringInfoString(buf, "NULL");
2353 
2354  /*
2355  * Construct FROM clause
2356  */
2357  appendStringInfoString(buf, " FROM ");
2358  deparseRelation(buf, rel);
2359 }
char * defGetString(DefElem *def)
Definition: define.c:49
List * GetForeignColumnOptions(Oid relid, AttrNumber attnum)
Definition: foreign.c:287
int i
Definition: isn.c:73
List * lappend_int(List *list, int datum)
Definition: list.c:356
NameData attname
Definition: pg_attribute.h:41
static char ** options
#define RelationGetRelid(relation)
Definition: rel.h:488
#define RelationGetDescr(relation)
Definition: rel.h:514
char * defname
Definition: parsenodes.h:766
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References appendStringInfoString(), attname, buf, defGetString(), DefElem::defname, deparseRelation(), GetForeignColumnOptions(), i, lappend_int(), lfirst, NameStr, TupleDescData::natts, NIL, options, quote_identifier(), RelationGetDescr, RelationGetRelid, and TupleDescAttr.

Referenced by postgresAcquireSampleRowsFunc().

◆ deparseArrayExpr()

static void deparseArrayExpr ( ArrayExpr node,
deparse_expr_cxt context 
)
static

Definition at line 3350 of file deparse.c.

3351 {
3352  StringInfo buf = context->buf;
3353  bool first = true;
3354  ListCell *lc;
3355 
3356  appendStringInfoString(buf, "ARRAY[");
3357  foreach(lc, node->elements)
3358  {
3359  if (!first)
3360  appendStringInfoString(buf, ", ");
3361  deparseExpr(lfirst(lc), context);
3362  first = false;
3363  }
3364  appendStringInfoChar(buf, ']');
3365 
3366  /* If the array is empty, we need an explicit cast to the array type. */
3367  if (node->elements == NIL)
3368  appendStringInfo(buf, "::%s",
3369  deparse_type_name(node->array_typeid, -1));
3370 }
static char * deparse_type_name(Oid type_oid, int32 typemod)
Definition: deparse.c:1083
Oid array_typeid
Definition: primnodes.h:1155
List * elements
Definition: primnodes.h:1158

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), ArrayExpr::array_typeid, deparse_expr_cxt::buf, buf, deparse_type_name(), deparseExpr(), ArrayExpr::elements, lfirst, and NIL.

Referenced by deparseExpr().

◆ deparseBoolExpr()

static void deparseBoolExpr ( BoolExpr node,
deparse_expr_cxt context 
)
static

Definition at line 3229 of file deparse.c.

3230 {
3231  StringInfo buf = context->buf;
3232  const char *op = NULL; /* keep compiler quiet */
3233  bool first;
3234  ListCell *lc;
3235 
3236  switch (node->boolop)
3237  {
3238  case AND_EXPR:
3239  op = "AND";
3240  break;
3241  case OR_EXPR:
3242  op = "OR";
3243  break;
3244  case NOT_EXPR:
3245  appendStringInfoString(buf, "(NOT ");
3246  deparseExpr(linitial(node->args), context);
3247  appendStringInfoChar(buf, ')');
3248  return;
3249  }
3250 
3251  appendStringInfoChar(buf, '(');
3252  first = true;
3253  foreach(lc, node->args)
3254  {
3255  if (!first)
3256  appendStringInfo(buf, " %s ", op);
3257  deparseExpr((Expr *) lfirst(lc), context);
3258  first = false;
3259  }
3260  appendStringInfoChar(buf, ')');
3261 }
#define linitial(l)
Definition: pg_list.h:176
@ AND_EXPR
Definition: primnodes.h:740
@ OR_EXPR
Definition: primnodes.h:740
@ NOT_EXPR
Definition: primnodes.h:740
BoolExprType boolop
Definition: primnodes.h:746
List * args
Definition: primnodes.h:747

References AND_EXPR, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), BoolExpr::args, BoolExpr::boolop, deparse_expr_cxt::buf, buf, deparseExpr(), lfirst, linitial, NOT_EXPR, and OR_EXPR.

Referenced by deparseExpr().

◆ deparseCaseExpr()

static void deparseCaseExpr ( CaseExpr node,
deparse_expr_cxt context 
)
static

Definition at line 3300 of file deparse.c.

3301 {
3302  StringInfo buf = context->buf;
3303  ListCell *lc;
3304 
3305  appendStringInfoString(buf, "(CASE");
3306 
3307  /* If this is a CASE arg WHEN then emit the arg expression */
3308  if (node->arg != NULL)
3309  {
3310  appendStringInfoChar(buf, ' ');
3311  deparseExpr(node->arg, context);
3312  }
3313 
3314  /* Add each condition/result of the CASE clause */
3315  foreach(lc, node->args)
3316  {
3317  CaseWhen *whenclause = (CaseWhen *) lfirst(lc);
3318 
3319  /* WHEN */
3320  appendStringInfoString(buf, " WHEN ");
3321  if (node->arg == NULL) /* CASE WHEN */
3322  deparseExpr(whenclause->expr, context);
3323  else /* CASE arg WHEN */
3324  {
3325  /* Ignore the CaseTestExpr and equality operator. */
3326  deparseExpr(lsecond(castNode(OpExpr, whenclause->expr)->args),
3327  context);
3328  }
3329 
3330  /* THEN */
3331  appendStringInfoString(buf, " THEN ");
3332  deparseExpr(whenclause->result, context);
3333  }
3334 
3335  /* add ELSE if present */
3336  if (node->defresult != NULL)
3337  {
3338  appendStringInfoString(buf, " ELSE ");
3339  deparseExpr(node->defresult, context);
3340  }
3341 
3342  /* append END */
3343  appendStringInfoString(buf, " END)");
3344 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:643
#define lsecond(l)
Definition: pg_list.h:181
Expr * arg
Definition: primnodes.h:1099
Expr * defresult
Definition: primnodes.h:1101
List * args
Definition: primnodes.h:1100
Expr * result
Definition: primnodes.h:1112
Expr * expr
Definition: primnodes.h:1111

References appendStringInfoChar(), appendStringInfoString(), CaseExpr::arg, CaseExpr::args, deparse_expr_cxt::buf, buf, castNode, CaseExpr::defresult, deparseExpr(), CaseWhen::expr, lfirst, lsecond, and CaseWhen::result.

Referenced by deparseExpr().

◆ deparseColumnRef()

static void deparseColumnRef ( StringInfo  buf,
int  varno,
int  varattno,
RangeTblEntry rte,
bool  qualify_col 
)
static

Definition at line 2400 of file deparse.c.

2402 {
2403  /* We support fetching the remote side's CTID and OID. */
2404  if (varattno == SelfItemPointerAttributeNumber)
2405  {
2406  if (qualify_col)
2407  ADD_REL_QUALIFIER(buf, varno);
2408  appendStringInfoString(buf, "ctid");
2409  }
2410  else if (varattno < 0)
2411  {
2412  /*
2413  * All other system attributes are fetched as 0, except for table OID,
2414  * which is fetched as the local table OID. However, we must be
2415  * careful; the table could be beneath an outer join, in which case it
2416  * must go to NULL whenever the rest of the row does.
2417  */
2418  Oid fetchval = 0;
2419 
2420  if (varattno == TableOidAttributeNumber)
2421  fetchval = rte->relid;
2422 
2423  if (qualify_col)
2424  {
2425  appendStringInfoString(buf, "CASE WHEN (");
2426  ADD_REL_QUALIFIER(buf, varno);
2427  appendStringInfo(buf, "*)::text IS NOT NULL THEN %u END", fetchval);
2428  }
2429  else
2430  appendStringInfo(buf, "%u", fetchval);
2431  }
2432  else if (varattno == 0)
2433  {
2434  /* Whole row reference */
2435  Relation rel;
2436  Bitmapset *attrs_used;
2437 
2438  /* Required only to be passed down to deparseTargetList(). */
2439  List *retrieved_attrs;
2440 
2441  /*
2442  * The lock on the relation will be held by upper callers, so it's
2443  * fine to open it with no lock here.
2444  */
2445  rel = table_open(rte->relid, NoLock);
2446 
2447  /*
2448  * The local name of the foreign table can not be recognized by the
2449  * foreign server and the table it references on foreign server might
2450  * have different column ordering or different columns than those
2451  * declared locally. Hence we have to deparse whole-row reference as
2452  * ROW(columns referenced locally). Construct this by deparsing a
2453  * "whole row" attribute.
2454  */
2455  attrs_used = bms_add_member(NULL,
2457 
2458  /*
2459  * In case the whole-row reference is under an outer join then it has
2460  * to go NULL whenever the rest of the row goes NULL. Deparsing a join
2461  * query would always involve multiple relations, thus qualify_col
2462  * would be true.
2463  */
2464  if (qualify_col)
2465  {
2466  appendStringInfoString(buf, "CASE WHEN (");
2467  ADD_REL_QUALIFIER(buf, varno);
2468  appendStringInfoString(buf, "*)::text IS NOT NULL THEN ");
2469  }
2470 
2471  appendStringInfoString(buf, "ROW(");
2472  deparseTargetList(buf, rte, varno, rel, false, attrs_used, qualify_col,
2473  &retrieved_attrs);
2474  appendStringInfoChar(buf, ')');
2475 
2476  /* Complete the CASE WHEN statement started above. */
2477  if (qualify_col)
2478  appendStringInfoString(buf, " END");
2479 
2480  table_close(rel, NoLock);
2481  bms_free(attrs_used);
2482  }
2483  else
2484  {
2485  char *colname = NULL;
2486  List *options;
2487  ListCell *lc;
2488 
2489  /* varno must not be any of OUTER_VAR, INNER_VAR and INDEX_VAR. */
2490  Assert(!IS_SPECIAL_VARNO(varno));
2491 
2492  /*
2493  * If it's a column of a foreign table, and it has the column_name FDW
2494  * option, use that value.
2495  */
2496  options = GetForeignColumnOptions(rte->relid, varattno);
2497  foreach(lc, options)
2498  {
2499  DefElem *def = (DefElem *) lfirst(lc);
2500 
2501  if (strcmp(def->defname, "column_name") == 0)
2502  {
2503  colname = defGetString(def);
2504  break;
2505  }
2506  }
2507 
2508  /*
2509  * If it's a column of a regular table or it doesn't have column_name
2510  * FDW option, use attribute name.
2511  */
2512  if (colname == NULL)
2513  colname = get_attname(rte->relid, varattno, false);
2514 
2515  if (qualify_col)
2516  ADD_REL_QUALIFIER(buf, varno);
2517 
2519  }
2520 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:738
static void deparseTargetList(StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, bool is_returning, Bitmapset *attrs_used, bool qualify_col, List **retrieved_attrs)
Definition: deparse.c:1333
#define ADD_REL_QUALIFIER(buf, varno)
Definition: deparse.c:109
#define NoLock
Definition: lockdefs.h:34
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
#define IS_SPECIAL_VARNO(varno)
Definition: primnodes.h:202
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
#define TableOidAttributeNumber
Definition: sysattr.h:26
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

References ADD_REL_QUALIFIER, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert(), bms_add_member(), bms_free(), buf, defGetString(), DefElem::defname, deparseTargetList(), FirstLowInvalidHeapAttributeNumber, get_attname(), GetForeignColumnOptions(), IS_SPECIAL_VARNO, lfirst, NoLock, options, quote_identifier(), RangeTblEntry::relid, SelfItemPointerAttributeNumber, table_close(), table_open(), and TableOidAttributeNumber.

Referenced by deparseDirectUpdateSql(), deparseInsertSql(), deparseTargetList(), deparseUpdateSql(), and deparseVar().

◆ deparseConst()

static void deparseConst ( Const node,
deparse_expr_cxt context,
int  showtype 
)
static

Definition at line 2739 of file deparse.c.

2740 {
2741  StringInfo buf = context->buf;
2742  Oid typoutput;
2743  bool typIsVarlena;
2744  char *extval;
2745  bool isfloat = false;
2746  bool isstring = false;
2747  bool needlabel;
2748 
2749  if (node->constisnull)
2750  {
2751  appendStringInfoString(buf, "NULL");
2752  if (showtype >= 0)
2753  appendStringInfo(buf, "::%s",
2755  node->consttypmod));
2756  return;
2757  }
2758 
2760  &typoutput, &typIsVarlena);
2761  extval = OidOutputFunctionCall(typoutput, node->constvalue);
2762 
2763  switch (node->consttype)
2764  {
2765  case INT2OID:
2766  case INT4OID:
2767  case INT8OID:
2768  case OIDOID:
2769  case FLOAT4OID:
2770  case FLOAT8OID:
2771  case NUMERICOID:
2772  {
2773  /*
2774  * No need to quote unless it's a special value such as 'NaN'.
2775  * See comments in get_const_expr().
2776  */
2777  if (strspn(extval, "0123456789+-eE.") == strlen(extval))
2778  {
2779  if (extval[0] == '+' || extval[0] == '-')
2780  appendStringInfo(buf, "(%s)", extval);
2781  else
2782  appendStringInfoString(buf, extval);
2783  if (strcspn(extval, "eE.") != strlen(extval))
2784  isfloat = true; /* it looks like a float */
2785  }
2786  else
2787  appendStringInfo(buf, "'%s'", extval);
2788  }
2789  break;
2790  case BITOID:
2791  case VARBITOID:
2792  appendStringInfo(buf, "B'%s'", extval);
2793  break;
2794  case BOOLOID:
2795  if (strcmp(extval, "t") == 0)
2796  appendStringInfoString(buf, "true");
2797  else
2798  appendStringInfoString(buf, "false");
2799  break;
2800  default:
2801  deparseStringLiteral(buf, extval);
2802  isstring = true;
2803  break;
2804  }
2805 
2806  pfree(extval);
2807 
2808  if (showtype == -1)
2809  return; /* never print type label */
2810 
2811  /*
2812  * For showtype == 0, append ::typename unless the constant will be
2813  * implicitly typed as the right type when it is read in.
2814  *
2815  * XXX this code has to be kept in sync with the behavior of the parser,
2816  * especially make_const.
2817  */
2818  switch (node->consttype)
2819  {
2820  case BOOLOID:
2821  case INT4OID:
2822  case UNKNOWNOID:
2823  needlabel = false;
2824  break;
2825  case NUMERICOID:
2826  needlabel = !isfloat || (node->consttypmod >= 0);
2827  break;
2828  default:
2829  if (showtype == -2)
2830  {
2831  /* label unless we printed it as an untyped string */
2832  needlabel = !isstring;
2833  }
2834  else
2835  needlabel = true;
2836  break;
2837  }
2838  if (needlabel || showtype > 0)
2839  appendStringInfo(buf, "::%s",
2841  node->consttypmod));
2842 }
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1639
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2864
void pfree(void *pointer)
Definition: mcxt.c:1175
Oid consttype
Definition: primnodes.h:256
Datum constvalue
Definition: primnodes.h:260
bool constisnull
Definition: primnodes.h:261
int32 consttypmod
Definition: primnodes.h:257

References appendStringInfo(), appendStringInfoString(), deparse_expr_cxt::buf, buf, Const::constisnull, Const::consttype, Const::consttypmod, Const::constvalue, deparse_type_name(), deparseStringLiteral(), getTypeOutputInfo(), OidOutputFunctionCall(), and pfree().

Referenced by deparseExpr(), deparseOpExpr(), and deparseSortGroupClause().

◆ deparseDeleteSql()

void deparseDeleteSql ( StringInfo  buf,
RangeTblEntry rte,
Index  rtindex,
Relation  rel,
List returningList,
List **  retrieved_attrs 
)

Definition at line 2150 of file deparse.c.

2154 {
2155  appendStringInfoString(buf, "DELETE FROM ");
2156  deparseRelation(buf, rel);
2157  appendStringInfoString(buf, " WHERE ctid = $1");
2158 
2159  deparseReturningList(buf, rte, rtindex, rel,
2160  rel->trigdesc && rel->trigdesc->trig_delete_after_row,
2161  NIL, returningList, retrieved_attrs);
2162 }
static void deparseReturningList(StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, bool trig_after_row, List *withCheckOptionList, List *returningList, List **retrieved_attrs)
Definition: deparse.c:2230
TriggerDesc * trigdesc
Definition: rel.h:115
bool trig_delete_after_row
Definition: reltrigger.h:67

References appendStringInfoString(), buf, deparseRelation(), deparseReturningList(), NIL, TriggerDesc::trig_delete_after_row, and RelationData::trigdesc.

Referenced by postgresPlanForeignModify().

◆ deparseDirectDeleteSql()

void deparseDirectDeleteSql ( StringInfo  buf,
PlannerInfo root,
Index  rtindex,
Relation  rel,
RelOptInfo foreignrel,
List remote_conds,
List **  params_list,
List returningList,
List **  retrieved_attrs 
)

Definition at line 2179 of file deparse.c.

2186 {
2187  deparse_expr_cxt context;
2188 
2189  /* Set up context struct for recursion */
2190  context.root = root;
2191  context.foreignrel = foreignrel;
2192  context.scanrel = foreignrel;
2193  context.buf = buf;
2194  context.params_list = params_list;
2195 
2196  appendStringInfoString(buf, "DELETE FROM ");
2197  deparseRelation(buf, rel);
2198  if (foreignrel->reloptkind == RELOPT_JOINREL)
2199  appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex);
2200 
2201  if (foreignrel->reloptkind == RELOPT_JOINREL)
2202  {
2203  List *ignore_conds = NIL;
2204 
2205  appendStringInfoString(buf, " USING ");
2206  deparseFromExprForRel(buf, root, foreignrel, true, rtindex,
2207  &ignore_conds, params_list);
2208  remote_conds = list_concat(remote_conds, ignore_conds);
2209  }
2210 
2211  if (remote_conds)
2212  {
2213  appendStringInfoString(buf, " WHERE ");
2214  appendConditions(remote_conds, &context);
2215  }
2216 
2217  if (foreignrel->reloptkind == RELOPT_JOINREL)
2218  deparseExplicitTargetList(returningList, true, retrieved_attrs,
2219  &context);
2220  else
2221  deparseReturningList(buf, planner_rt_fetch(rtindex, root),
2222  rtindex, rel, false,
2223  NIL, returningList, retrieved_attrs);
2224 }
#define REL_ALIAS_PREFIX
Definition: deparse.c:107
static void appendConditions(List *exprs, deparse_expr_cxt *context)
Definition: deparse.c:1499
static void deparseExplicitTargetList(List *tlist, bool is_returning, List **retrieved_attrs, deparse_expr_cxt *context)
Definition: deparse.c:1570
static void deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool use_alias, Index ignore_rel, List **ignore_conds, List **params_list)
Definition: deparse.c:1647
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:397
@ RELOPT_JOINREL
Definition: pathnodes.h:651
RelOptKind reloptkind
Definition: pathnodes.h:687
List ** params_list
Definition: deparse.c:104

References appendConditions(), appendStringInfo(), appendStringInfoString(), deparse_expr_cxt::buf, buf, deparseExplicitTargetList(), deparseFromExprForRel(), deparseRelation(), deparseReturningList(), deparse_expr_cxt::foreignrel, list_concat(), NIL, deparse_expr_cxt::params_list, planner_rt_fetch, REL_ALIAS_PREFIX, RELOPT_JOINREL, RelOptInfo::reloptkind, deparse_expr_cxt::root, and deparse_expr_cxt::scanrel.

Referenced by postgresPlanDirectModify().

◆ deparseDirectUpdateSql()

void deparseDirectUpdateSql ( StringInfo  buf,
PlannerInfo root,
Index  rtindex,
Relation  rel,
RelOptInfo foreignrel,
List targetlist,
List targetAttrs,
List remote_conds,
List **  params_list,
List returningList,
List **  retrieved_attrs 
)

Definition at line 2065 of file deparse.c.

2074 {
2075  deparse_expr_cxt context;
2076  int nestlevel;
2077  bool first;
2078  RangeTblEntry *rte = planner_rt_fetch(rtindex, root);
2079  ListCell *lc,
2080  *lc2;
2081 
2082  /* Set up context struct for recursion */
2083  context.root = root;
2084  context.foreignrel = foreignrel;
2085  context.scanrel = foreignrel;
2086  context.buf = buf;
2087  context.params_list = params_list;
2088 
2089  appendStringInfoString(buf, "UPDATE ");
2090  deparseRelation(buf, rel);
2091  if (foreignrel->reloptkind == RELOPT_JOINREL)
2092  appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex);
2093  appendStringInfoString(buf, " SET ");
2094 
2095  /* Make sure any constants in the exprs are printed portably */
2096  nestlevel = set_transmission_modes();
2097 
2098  first = true;
2099  forboth(lc, targetlist, lc2, targetAttrs)
2100  {
2101  TargetEntry *tle = lfirst_node(TargetEntry, lc);
2102  int attnum = lfirst_int(lc2);
2103 
2104  /* update's new-value expressions shouldn't be resjunk */
2105  Assert(!tle->resjunk);
2106 
2107  if (!first)
2108  appendStringInfoString(buf, ", ");
2109  first = false;
2110 
2111  deparseColumnRef(buf, rtindex, attnum, rte, false);
2112  appendStringInfoString(buf, " = ");
2113  deparseExpr((Expr *) tle->expr, &context);
2114  }
2115 
2116  reset_transmission_modes(nestlevel);
2117 
2118  if (foreignrel->reloptkind == RELOPT_JOINREL)
2119  {
2120  List *ignore_conds = NIL;
2121 
2122  appendStringInfoString(buf, " FROM ");
2123  deparseFromExprForRel(buf, root, foreignrel, true, rtindex,
2124  &ignore_conds, params_list);
2125  remote_conds = list_concat(remote_conds, ignore_conds);
2126  }
2127 
2128  if (remote_conds)
2129  {
2130  appendStringInfoString(buf, " WHERE ");
2131  appendConditions(remote_conds, &context);
2132  }
2133 
2134  if (foreignrel->reloptkind == RELOPT_JOINREL)
2135  deparseExplicitTargetList(returningList, true, retrieved_attrs,
2136  &context);
2137  else
2138  deparseReturningList(buf, rte, rtindex, rel, false,
2139  NIL, returningList, retrieved_attrs);
2140 }
static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col)
Definition: deparse.c:2400
int16 attnum
Definition: pg_attribute.h:83
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:465
#define lfirst_int(lc)
Definition: pg_list.h:171

References appendConditions(), appendStringInfo(), appendStringInfoString(), Assert(), attnum, deparse_expr_cxt::buf, buf, deparseColumnRef(), deparseExplicitTargetList(), deparseExpr(), deparseFromExprForRel(), deparseRelation(), deparseReturningList(), TargetEntry::expr, forboth, deparse_expr_cxt::foreignrel, lfirst_int, lfirst_node, list_concat(), NIL, deparse_expr_cxt::params_list, planner_rt_fetch, REL_ALIAS_PREFIX, RELOPT_JOINREL, RelOptInfo::reloptkind, reset_transmission_modes(), TargetEntry::resjunk, deparse_expr_cxt::root, deparse_expr_cxt::scanrel, and set_transmission_modes().

Referenced by postgresPlanDirectModify().

◆ deparseDistinctExpr()

static void deparseDistinctExpr ( DistinctExpr node,
deparse_expr_cxt context 
)
static

Definition at line 3153 of file deparse.c.

3154 {
3155  StringInfo buf = context->buf;
3156 
3157  Assert(list_length(node->args) == 2);
3158 
3159  appendStringInfoChar(buf, '(');
3160  deparseExpr(linitial(node->args), context);
3161  appendStringInfoString(buf, " IS DISTINCT FROM ");
3162  deparseExpr(lsecond(node->args), context);
3163  appendStringInfoChar(buf, ')');
3164 }
static int list_length(const List *l)
Definition: pg_list.h:150
List * args
Definition: primnodes.h:652

References appendStringInfoChar(), appendStringInfoString(), OpExpr::args, Assert(), deparse_expr_cxt::buf, buf, deparseExpr(), linitial, list_length(), and lsecond.

Referenced by deparseExpr().

◆ deparseExplicitTargetList()

static void deparseExplicitTargetList ( List tlist,
bool  is_returning,
List **  retrieved_attrs,
deparse_expr_cxt context 
)
static

Definition at line 1570 of file deparse.c.

1574 {
1575  ListCell *lc;
1576  StringInfo buf = context->buf;
1577  int i = 0;
1578 
1579  *retrieved_attrs = NIL;
1580 
1581  foreach(lc, tlist)
1582  {
1583  TargetEntry *tle = lfirst_node(TargetEntry, lc);
1584 
1585  if (i > 0)
1586  appendStringInfoString(buf, ", ");
1587  else if (is_returning)
1588  appendStringInfoString(buf, " RETURNING ");
1589 
1590  deparseExpr((Expr *) tle->expr, context);
1591 
1592  *retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
1593  i++;
1594  }
1595 
1596  if (i == 0 && !is_returning)
1597  appendStringInfoString(buf, "NULL");
1598 }

References appendStringInfoString(), deparse_expr_cxt::buf, buf, deparseExpr(), TargetEntry::expr, i, lappend_int(), lfirst_node, and NIL.

Referenced by deparseDirectDeleteSql(), deparseDirectUpdateSql(), and deparseSelectSql().

◆ deparseExpr()

static void deparseExpr ( Expr expr,
deparse_expr_cxt context 
)
static

Definition at line 2603 of file deparse.c.

2604 {
2605  if (node == NULL)
2606  return;
2607 
2608  switch (nodeTag(node))
2609  {
2610  case T_Var:
2611  deparseVar((Var *) node, context);
2612  break;
2613  case T_Const:
2614  deparseConst((Const *) node, context, 0);
2615  break;
2616  case T_Param:
2617  deparseParam((Param *) node, context);
2618  break;
2619  case T_SubscriptingRef:
2620  deparseSubscriptingRef((SubscriptingRef *) node, context);
2621  break;
2622  case T_FuncExpr:
2623  deparseFuncExpr((FuncExpr *) node, context);
2624  break;
2625  case T_OpExpr:
2626  deparseOpExpr((OpExpr *) node, context);
2627  break;
2628  case T_DistinctExpr:
2629  deparseDistinctExpr((DistinctExpr *) node, context);
2630  break;
2631  case T_ScalarArrayOpExpr:
2632  deparseScalarArrayOpExpr((ScalarArrayOpExpr *) node, context);
2633  break;
2634  case T_RelabelType:
2635  deparseRelabelType((RelabelType *) node, context);
2636  break;
2637  case T_BoolExpr:
2638  deparseBoolExpr((BoolExpr *) node, context);
2639  break;
2640  case T_NullTest:
2641  deparseNullTest((NullTest *) node, context);
2642  break;
2643  case T_CaseExpr:
2644  deparseCaseExpr((CaseExpr *) node, context);
2645  break;
2646  case T_ArrayExpr:
2647  deparseArrayExpr((ArrayExpr *) node, context);
2648  break;
2649  case T_Aggref:
2650  deparseAggref((Aggref *) node, context);
2651  break;
2652  default:
2653  elog(ERROR, "unsupported expression type for deparse: %d",
2654  (int) nodeTag(node));
2655  break;
2656  }
2657 }
static void deparseCaseExpr(CaseExpr *node, deparse_expr_cxt *context)
Definition: deparse.c:3300
static void deparseBoolExpr(BoolExpr *node, deparse_expr_cxt *context)
Definition: deparse.c:3229
static void deparseAggref(Aggref *node, deparse_expr_cxt *context)
Definition: deparse.c:3376
static void deparseRelabelType(RelabelType *node, deparse_expr_cxt *context)
Definition: deparse.c:3216
static void deparseNullTest(NullTest *node, deparse_expr_cxt *context)
Definition: deparse.c:3267
static void deparseOpExpr(OpExpr *node, deparse_expr_cxt *context)
Definition: deparse.c:2995
static void deparseConst(Const *node, deparse_expr_cxt *context, int showtype)
Definition: deparse.c:2739
static void deparseDistinctExpr(DistinctExpr *node, deparse_expr_cxt *context)
Definition: deparse.c:3153
static void deparseFuncExpr(FuncExpr *node, deparse_expr_cxt *context)
Definition: deparse.c:2932
static void deparseArrayExpr(ArrayExpr *node, deparse_expr_cxt *context)
Definition: deparse.c:3350
static void deparseVar(Var *node, deparse_expr_cxt *context)
Definition: deparse.c:2668
static void deparseSubscriptingRef(SubscriptingRef *node, deparse_expr_cxt *context)
Definition: deparse.c:2886
static void deparseScalarArrayOpExpr(ScalarArrayOpExpr *node, deparse_expr_cxt *context)
Definition: deparse.c:3171
static void deparseParam(Param *node, deparse_expr_cxt *context)
Definition: deparse.c:2853
#define nodeTag(nodeptr)
Definition: nodes.h:579
@ T_ArrayExpr
Definition: nodes.h:184
@ T_BoolExpr
Definition: nodes.h:170
@ T_OpExpr
Definition: nodes.h:166
@ T_ScalarArrayOpExpr
Definition: nodes.h:169
@ T_CaseExpr
Definition: nodes.h:181
@ T_RelabelType
Definition: nodes.h:176
@ T_Aggref
Definition: nodes.h:160
@ T_Const
Definition: nodes.h:158
@ T_Param
Definition: nodes.h:159
@ T_DistinctExpr
Definition: nodes.h:167
@ T_FuncExpr
Definition: nodes.h:164
@ T_Var
Definition: nodes.h:157
@ T_NullTest
Definition: nodes.h:191
@ T_SubscriptingRef
Definition: nodes.h:163
Definition: primnodes.h:209

References deparseAggref(), deparseArrayExpr(), deparseBoolExpr(), deparseCaseExpr(), deparseConst(), deparseDistinctExpr(), deparseFuncExpr(), deparseNullTest(), deparseOpExpr(), deparseParam(), deparseRelabelType(), deparseScalarArrayOpExpr(), deparseSubscriptingRef(), deparseVar(), elog(), ERROR, nodeTag, T_Aggref, T_ArrayExpr, T_BoolExpr, T_CaseExpr, T_Const, T_DistinctExpr, T_FuncExpr, T_NullTest, T_OpExpr, T_Param, T_RelabelType, T_ScalarArrayOpExpr, T_SubscriptingRef, and T_Var.

Referenced by appendConditions(), appendLimitClause(), appendOrderByClause(), deparseAggref(), deparseArrayExpr(), deparseBoolExpr(), deparseCaseExpr(), deparseDirectUpdateSql(), deparseDistinctExpr(), deparseExplicitTargetList(), deparseFuncExpr(), deparseNullTest(), deparseOpExpr(), deparseRelabelType(), deparseScalarArrayOpExpr(), deparseSortGroupClause(), deparseSubqueryTargetList(), and deparseSubscriptingRef().

◆ deparseFromExpr()

static void deparseFromExpr ( List quals,
deparse_expr_cxt context 
)
static

Definition at line 1299 of file deparse.c.

1300 {
1301  StringInfo buf = context->buf;
1302  RelOptInfo *scanrel = context->scanrel;
1303 
1304  /* For upper relations, scanrel must be either a joinrel or a baserel */
1305  Assert(!IS_UPPER_REL(context->foreignrel) ||
1306  IS_JOIN_REL(scanrel) || IS_SIMPLE_REL(scanrel));
1307 
1308  /* Construct FROM clause */
1309  appendStringInfoString(buf, " FROM ");
1310  deparseFromExprForRel(buf, context->root, scanrel,
1311  (bms_membership(scanrel->relids) == BMS_MULTIPLE),
1312  (Index) 0, NULL, context->params_list);
1313 
1314  /* Construct WHERE clause */
1315  if (quals != NIL)
1316  {
1317  appendStringInfoString(buf, " WHERE ");
1318  appendConditions(quals, context);
1319  }
1320 }
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:674
@ BMS_MULTIPLE
Definition: bitmapset.h:70
unsigned int Index
Definition: c.h:560
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:663
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:668
Relids relids
Definition: pathnodes.h:693

References appendConditions(), appendStringInfoString(), Assert(), bms_membership(), BMS_MULTIPLE, deparse_expr_cxt::buf, buf, deparseFromExprForRel(), deparse_expr_cxt::foreignrel, IS_JOIN_REL, IS_SIMPLE_REL, IS_UPPER_REL, NIL, deparse_expr_cxt::params_list, RelOptInfo::relids, deparse_expr_cxt::root, and deparse_expr_cxt::scanrel.

Referenced by deparseSelectStmtForRel().

◆ deparseFromExprForRel()

static void deparseFromExprForRel ( StringInfo  buf,
PlannerInfo root,
RelOptInfo foreignrel,
bool  use_alias,
Index  ignore_rel,
List **  ignore_conds,
List **  params_list 
)
static

Definition at line 1647 of file deparse.c.

1650 {
1651  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
1652 
1653  if (IS_JOIN_REL(foreignrel))
1654  {
1655  StringInfoData join_sql_o;
1656  StringInfoData join_sql_i;
1657  RelOptInfo *outerrel = fpinfo->outerrel;
1658  RelOptInfo *innerrel = fpinfo->innerrel;
1659  bool outerrel_is_target = false;
1660  bool innerrel_is_target = false;
1661 
1662  if (ignore_rel > 0 && bms_is_member(ignore_rel, foreignrel->relids))
1663  {
1664  /*
1665  * If this is an inner join, add joinclauses to *ignore_conds and
1666  * set it to empty so that those can be deparsed into the WHERE
1667  * clause. Note that since the target relation can never be
1668  * within the nullable side of an outer join, those could safely
1669  * be pulled up into the WHERE clause (see foreign_join_ok()).
1670  * Note also that since the target relation is only inner-joined
1671  * to any other relation in the query, all conditions in the join
1672  * tree mentioning the target relation could be deparsed into the
1673  * WHERE clause by doing this recursively.
1674  */
1675  if (fpinfo->jointype == JOIN_INNER)
1676  {
1677  *ignore_conds = list_concat(*ignore_conds,
1678  fpinfo->joinclauses);
1679  fpinfo->joinclauses = NIL;
1680  }
1681 
1682  /*
1683  * Check if either of the input relations is the target relation.
1684  */
1685  if (outerrel->relid == ignore_rel)
1686  outerrel_is_target = true;
1687  else if (innerrel->relid == ignore_rel)
1688  innerrel_is_target = true;
1689  }
1690 
1691  /* Deparse outer relation if not the target relation. */
1692  if (!outerrel_is_target)
1693  {
1694  initStringInfo(&join_sql_o);
1695  deparseRangeTblRef(&join_sql_o, root, outerrel,
1696  fpinfo->make_outerrel_subquery,
1697  ignore_rel, ignore_conds, params_list);
1698 
1699  /*
1700  * If inner relation is the target relation, skip deparsing it.
1701  * Note that since the join of the target relation with any other
1702  * relation in the query is an inner join and can never be within
1703  * the nullable side of an outer join, the join could be
1704  * interchanged with higher-level joins (cf. identity 1 on outer
1705  * join reordering shown in src/backend/optimizer/README), which
1706  * means it's safe to skip the target-relation deparsing here.
1707  */
1708  if (innerrel_is_target)
1709  {
1710  Assert(fpinfo->jointype == JOIN_INNER);
1711  Assert(fpinfo->joinclauses == NIL);
1712  appendBinaryStringInfo(buf, join_sql_o.data, join_sql_o.len);
1713  return;
1714  }
1715  }
1716 
1717  /* Deparse inner relation if not the target relation. */
1718  if (!innerrel_is_target)
1719  {
1720  initStringInfo(&join_sql_i);
1721  deparseRangeTblRef(&join_sql_i, root, innerrel,
1722  fpinfo->make_innerrel_subquery,
1723  ignore_rel, ignore_conds, params_list);
1724 
1725  /*
1726  * If outer relation is the target relation, skip deparsing it.
1727  * See the above note about safety.
1728  */
1729  if (outerrel_is_target)
1730  {
1731  Assert(fpinfo->jointype == JOIN_INNER);
1732  Assert(fpinfo->joinclauses == NIL);
1733  appendBinaryStringInfo(buf, join_sql_i.data, join_sql_i.len);
1734  return;
1735  }
1736  }
1737 
1738  /* Neither of the relations is the target relation. */
1739  Assert(!outerrel_is_target && !innerrel_is_target);
1740 
1741  /*
1742  * For a join relation FROM clause entry is deparsed as
1743  *
1744  * ((outer relation) <join type> (inner relation) ON (joinclauses))
1745  */
1746  appendStringInfo(buf, "(%s %s JOIN %s ON ", join_sql_o.data,
1747  get_jointype_name(fpinfo->jointype), join_sql_i.data);
1748 
1749  /* Append join clause; (TRUE) if no join clause */
1750  if (fpinfo->joinclauses)
1751  {
1752  deparse_expr_cxt context;
1753 
1754  context.buf = buf;
1755  context.foreignrel = foreignrel;
1756  context.scanrel = foreignrel;
1757  context.root = root;
1758  context.params_list = params_list;
1759 
1760  appendStringInfoChar(buf, '(');
1761  appendConditions(fpinfo->joinclauses, &context);
1762  appendStringInfoChar(buf, ')');
1763  }
1764  else
1765  appendStringInfoString(buf, "(TRUE)");
1766 
1767  /* End the FROM clause entry. */
1768  appendStringInfoChar(buf, ')');
1769  }
1770  else
1771  {
1772  RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root);
1773 
1774  /*
1775  * Core code already has some lock on each rel being planned, so we
1776  * can use NoLock here.
1777  */
1778  Relation rel = table_open(rte->relid, NoLock);
1779 
1780  deparseRelation(buf, rel);
1781 
1782  /*
1783  * Add a unique alias to avoid any conflict in relation names due to
1784  * pulled up subqueries in the query being built for a pushed down
1785  * join.
1786  */
1787  if (use_alias)
1788  appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, foreignrel->relid);
1789 
1790  table_close(rel, NoLock);
1791  }
1792 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
static void deparseRangeTblRef(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool make_subquery, Index ignore_rel, List **ignore_conds, List **params_list)
Definition: deparse.c:1798
const char * get_jointype_name(JoinType jointype)
Definition: deparse.c:1533
@ JOIN_INNER
Definition: nodes.h:750
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
RelOptInfo * outerrel
Definition: postgres_fdw.h:102
RelOptInfo * innerrel
Definition: postgres_fdw.h:103
Index relid
Definition: pathnodes.h:740

References appendBinaryStringInfo(), appendConditions(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert(), bms_is_member(), deparse_expr_cxt::buf, buf, StringInfoData::data, deparseRangeTblRef(), deparseRelation(), RelOptInfo::fdw_private, deparse_expr_cxt::foreignrel, get_jointype_name(), if(), initStringInfo(), PgFdwRelationInfo::innerrel, IS_JOIN_REL, JOIN_INNER, PgFdwRelationInfo::joinclauses, PgFdwRelationInfo::jointype, StringInfoData::len, list_concat(), PgFdwRelationInfo::make_innerrel_subquery, PgFdwRelationInfo::make_outerrel_subquery, NIL, NoLock, PgFdwRelationInfo::outerrel, deparse_expr_cxt::params_list, planner_rt_fetch, REL_ALIAS_PREFIX, RangeTblEntry::relid, RelOptInfo::relid, RelOptInfo::relids, deparse_expr_cxt::root, deparse_expr_cxt::scanrel, table_close(), and table_open().

Referenced by deparseDirectDeleteSql(), deparseDirectUpdateSql(), deparseFromExpr(), and deparseRangeTblRef().

◆ deparseFuncExpr()

static void deparseFuncExpr ( FuncExpr node,
deparse_expr_cxt context 
)
static

Definition at line 2932 of file deparse.c.

2933 {
2934  StringInfo buf = context->buf;
2935  bool use_variadic;
2936  bool first;
2937  ListCell *arg;
2938 
2939  /*
2940  * If the function call came from an implicit coercion, then just show the
2941  * first argument.
2942  */
2943  if (node->funcformat == COERCE_IMPLICIT_CAST)
2944  {
2945  deparseExpr((Expr *) linitial(node->args), context);
2946  return;
2947  }
2948 
2949  /*
2950  * If the function call came from a cast, then show the first argument
2951  * plus an explicit cast operation.
2952  */
2953  if (node->funcformat == COERCE_EXPLICIT_CAST)
2954  {
2955  Oid rettype = node->funcresulttype;
2956  int32 coercedTypmod;
2957 
2958  /* Get the typmod if this is a length-coercion function */
2959  (void) exprIsLengthCoercion((Node *) node, &coercedTypmod);
2960 
2961  deparseExpr((Expr *) linitial(node->args), context);
2962  appendStringInfo(buf, "::%s",
2963  deparse_type_name(rettype, coercedTypmod));
2964  return;
2965  }
2966 
2967  /* Check if need to print VARIADIC (cf. ruleutils.c) */
2968  use_variadic = node->funcvariadic;
2969 
2970  /*
2971  * Normal function: display as proname(args).
2972  */
2973  appendFunctionName(node->funcid, context);
2974  appendStringInfoChar(buf, '(');
2975 
2976  /* ... and all the arguments */
2977  first = true;
2978  foreach(arg, node->args)
2979  {
2980  if (!first)
2981  appendStringInfoString(buf, ", ");
2982  if (use_variadic && lnext(node->args, arg) == NULL)
2983  appendStringInfoString(buf, "VARIADIC ");
2984  deparseExpr((Expr *) lfirst(arg), context);
2985  first = false;
2986  }
2987  appendStringInfoChar(buf, ')');
2988 }
signed int int32
Definition: c.h:440
bool exprIsLengthCoercion(const Node *expr, int32 *coercedTypmod)
Definition: nodeFuncs.c:530
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:575
@ COERCE_EXPLICIT_CAST
Definition: primnodes.h:574
Oid funcid
Definition: primnodes.h:585
bool funcvariadic
Definition: primnodes.h:588
List * args
Definition: primnodes.h:593
CoercionForm funcformat
Definition: primnodes.h:590
Oid funcresulttype
Definition: primnodes.h:586

References appendFunctionName(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), arg, FuncExpr::args, deparse_expr_cxt::buf, buf, COERCE_EXPLICIT_CAST, COERCE_IMPLICIT_CAST, deparse_type_name(), deparseExpr(), exprIsLengthCoercion(), FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcvariadic, lfirst, linitial, and lnext().

Referenced by deparseExpr().

◆ deparseInsertSql()

void deparseInsertSql ( StringInfo  buf,
RangeTblEntry rte,
Index  rtindex,
Relation  rel,
List targetAttrs,
bool  doNothing,
List withCheckOptionList,
List returningList,
List **  retrieved_attrs,
int *  values_end_len 
)

Definition at line 1872 of file deparse.c.

1877 {
1878  TupleDesc tupdesc = RelationGetDescr(rel);
1879  AttrNumber pindex;
1880  bool first;
1881  ListCell *lc;
1882 
1883  appendStringInfoString(buf, "INSERT INTO ");
1884  deparseRelation(buf, rel);
1885 
1886  if (targetAttrs)
1887  {
1888  appendStringInfoChar(buf, '(');
1889 
1890  first = true;
1891  foreach(lc, targetAttrs)
1892  {
1893  int attnum = lfirst_int(lc);
1894 
1895  if (!first)
1896  appendStringInfoString(buf, ", ");
1897  first = false;
1898 
1899  deparseColumnRef(buf, rtindex, attnum, rte, false);
1900  }
1901 
1902  appendStringInfoString(buf, ") VALUES (");
1903 
1904  pindex = 1;
1905  first = true;
1906  foreach(lc, targetAttrs)
1907  {
1908  int attnum = lfirst_int(lc);
1909  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
1910 
1911  if (!first)
1912  appendStringInfoString(buf, ", ");
1913  first = false;
1914 
1915  if (attr->attgenerated)
1916  appendStringInfoString(buf, "DEFAULT");
1917  else
1918  {
1919  appendStringInfo(buf, "$%d", pindex);
1920  pindex++;
1921  }
1922  }
1923 
1924  appendStringInfoChar(buf, ')');
1925  }
1926  else
1927  appendStringInfoString(buf, " DEFAULT VALUES");
1928  *values_end_len = buf->len;
1929 
1930  if (doNothing)
1931  appendStringInfoString(buf, " ON CONFLICT DO NOTHING");
1932 
1933  deparseReturningList(buf, rte, rtindex, rel,
1934  rel->trigdesc && rel->trigdesc->trig_insert_after_row,
1935  withCheckOptionList, returningList, retrieved_attrs);
1936 }
int16 AttrNumber
Definition: attnum.h:21
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
bool trig_insert_after_row
Definition: reltrigger.h:57

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), attnum, buf, deparseColumnRef(), deparseRelation(), deparseReturningList(), lfirst_int, RelationGetDescr, TriggerDesc::trig_insert_after_row, RelationData::trigdesc, and TupleDescAttr.

Referenced by postgresBeginForeignInsert(), and postgresPlanForeignModify().

◆ deparseLockingClause()

static void deparseLockingClause ( deparse_expr_cxt context)
static

Definition at line 1409 of file deparse.c.

1410 {
1411  StringInfo buf = context->buf;
1412  PlannerInfo *root = context->root;
1413  RelOptInfo *rel = context->scanrel;
1414  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
1415  int relid = -1;
1416 
1417  while ((relid = bms_next_member(rel->relids, relid)) >= 0)
1418  {
1419  /*
1420  * Ignore relation if it appears in a lower subquery. Locking clause
1421  * for such a relation is included in the subquery if necessary.
1422  */
1423  if (bms_is_member(relid, fpinfo->lower_subquery_rels))
1424  continue;
1425 
1426  /*
1427  * Add FOR UPDATE/SHARE if appropriate. We apply locking during the
1428  * initial row fetch, rather than later on as is done for local
1429  * tables. The extra roundtrips involved in trying to duplicate the
1430  * local semantics exactly don't seem worthwhile (see also comments
1431  * for RowMarkType).
1432  *
1433  * Note: because we actually run the query as a cursor, this assumes
1434  * that DECLARE CURSOR ... FOR UPDATE is supported, which it isn't
1435  * before 8.3.
1436  */
1437  if (bms_is_member(relid, root->all_result_relids) &&
1438  (root->parse->commandType == CMD_UPDATE ||
1439  root->parse->commandType == CMD_DELETE))
1440  {
1441  /* Relation is UPDATE/DELETE target, so use FOR UPDATE */
1442  appendStringInfoString(buf, " FOR UPDATE");
1443 
1444  /* Add the relation alias if we are here for a join relation */
1445  if (IS_JOIN_REL(rel))
1446  appendStringInfo(buf, " OF %s%d", REL_ALIAS_PREFIX, relid);
1447  }
1448  else
1449  {
1450  PlanRowMark *rc = get_plan_rowmark(root->rowMarks, relid);
1451 
1452  if (rc)
1453  {
1454  /*
1455  * Relation is specified as a FOR UPDATE/SHARE target, so
1456  * handle that. (But we could also see LCS_NONE, meaning this
1457  * isn't a target relation after all.)
1458  *
1459  * For now, just ignore any [NO] KEY specification, since (a)
1460  * it's not clear what that means for a remote table that we
1461  * don't have complete information about, and (b) it wouldn't
1462  * work anyway on older remote servers. Likewise, we don't
1463  * worry about NOWAIT.
1464  */
1465  switch (rc->strength)
1466  {
1467  case LCS_NONE:
1468  /* No locking needed */
1469  break;
1470  case LCS_FORKEYSHARE:
1471  case LCS_FORSHARE:
1472  appendStringInfoString(buf, " FOR SHARE");
1473  break;
1474  case LCS_FORNOKEYUPDATE:
1475  case LCS_FORUPDATE:
1476  appendStringInfoString(buf, " FOR UPDATE");
1477  break;
1478  }
1479 
1480  /* Add the relation alias if we are here for a join relation */
1481  if (bms_membership(rel->relids) == BMS_MULTIPLE &&
1482  rc->strength != LCS_NONE)
1483  appendStringInfo(buf, " OF %s%d", REL_ALIAS_PREFIX, relid);
1484  }
1485  }
1486  }
1487 }
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1045
@ LCS_FORUPDATE
Definition: lockoptions.h:27
@ LCS_NONE
Definition: lockoptions.h:23
@ LCS_FORSHARE
Definition: lockoptions.h:25
@ LCS_FORKEYSHARE
Definition: lockoptions.h:24
@ LCS_FORNOKEYUPDATE
Definition: lockoptions.h:26
@ CMD_DELETE
Definition: nodes.h:725
@ CMD_UPDATE
Definition: nodes.h:723
while(p+4<=pend)
PlanRowMark * get_plan_rowmark(List *rowmarks, Index rtindex)
Definition: preptlist.c:487
Relids lower_subquery_rels
Definition: postgres_fdw.h:119
LockClauseStrength strength
Definition: plannodes.h:1354
List * rowMarks
Definition: pathnodes.h:289
Relids all_result_relids
Definition: pathnodes.h:277
CmdType commandType
Definition: parsenodes.h:121

References PlannerInfo::all_result_relids, appendStringInfo(), appendStringInfoString(), bms_is_member(), bms_membership(), BMS_MULTIPLE, bms_next_member(), deparse_expr_cxt::buf, buf, CMD_DELETE, CMD_UPDATE, Query::commandType, RelOptInfo::fdw_private, get_plan_rowmark(), IS_JOIN_REL, LCS_FORKEYSHARE, LCS_FORNOKEYUPDATE, LCS_FORSHARE, LCS_FORUPDATE, LCS_NONE, PgFdwRelationInfo::lower_subquery_rels, PlannerInfo::parse, REL_ALIAS_PREFIX, RelOptInfo::relids, deparse_expr_cxt::root, PlannerInfo::rowMarks, deparse_expr_cxt::scanrel, PlanRowMark::strength, and while().

Referenced by deparseSelectStmtForRel().

◆ deparseNullTest()

static void deparseNullTest ( NullTest node,
deparse_expr_cxt context 
)
static

Definition at line 3267 of file deparse.c.

3268 {
3269  StringInfo buf = context->buf;
3270 
3271  appendStringInfoChar(buf, '(');
3272  deparseExpr(node->arg, context);
3273 
3274  /*
3275  * For scalar inputs, we prefer to print as IS [NOT] NULL, which is
3276  * shorter and traditional. If it's a rowtype input but we're applying a
3277  * scalar test, must print IS [NOT] DISTINCT FROM NULL to be semantically
3278  * correct.
3279  */
3280  if (node->argisrow || !type_is_rowtype(exprType((Node *) node->arg)))
3281  {
3282  if (node->nulltesttype == IS_NULL)
3283  appendStringInfoString(buf, " IS NULL)");
3284  else
3285  appendStringInfoString(buf, " IS NOT NULL)");
3286  }
3287  else
3288  {
3289  if (node->nulltesttype == IS_NULL)
3290  appendStringInfoString(buf, " IS NOT DISTINCT FROM NULL)");
3291  else
3292  appendStringInfoString(buf, " IS DISTINCT FROM NULL)");
3293  }
3294 }
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2612
@ IS_NULL
Definition: primnodes.h:1632
NullTestType nulltesttype
Definition: primnodes.h:1639
bool argisrow
Definition: primnodes.h:1640
Expr * arg
Definition: primnodes.h:1638

References appendStringInfoChar(), appendStringInfoString(), NullTest::arg, NullTest::argisrow, deparse_expr_cxt::buf, buf, deparseExpr(), exprType(), IS_NULL, NullTest::nulltesttype, and type_is_rowtype().

Referenced by deparseExpr().

◆ deparseOperatorName()

static void deparseOperatorName ( StringInfo  buf,
Form_pg_operator  opform 
)
static

Definition at line 3125 of file deparse.c.

3126 {
3127  char *opname;
3128 
3129  /* opname is not a SQL identifier, so we should not quote it. */
3130  opname = NameStr(opform->oprname);
3131 
3132  /* Print schema name only if it's not pg_catalog */
3133  if (opform->oprnamespace != PG_CATALOG_NAMESPACE)
3134  {
3135  const char *opnspname;
3136 
3137  opnspname = get_namespace_name(opform->oprnamespace);
3138  /* Print fully qualified operator name. */
3139  appendStringInfo(buf, "OPERATOR(%s.%s)",
3140  quote_identifier(opnspname), opname);
3141  }
3142  else
3143  {
3144  /* Just print operator name. */
3145  appendStringInfoString(buf, opname);
3146  }
3147 }

References appendStringInfo(), appendStringInfoString(), buf, get_namespace_name(), NameStr, and quote_identifier().

Referenced by appendOrderBySuffix(), deparseOpExpr(), and deparseScalarArrayOpExpr().

◆ deparseOpExpr()

static void deparseOpExpr ( OpExpr node,
deparse_expr_cxt context 
)
static

Definition at line 2995 of file deparse.c.

2996 {
2997  StringInfo buf = context->buf;
2998  HeapTuple tuple;
2999  Form_pg_operator form;
3000  Expr *right;
3001  bool canSuppressRightConstCast = false;
3002  char oprkind;
3003 
3004  /* Retrieve information about the operator from system catalog. */
3005  tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(node->opno));
3006  if (!HeapTupleIsValid(tuple))
3007  elog(ERROR, "cache lookup failed for operator %u", node->opno);
3008  form = (Form_pg_operator) GETSTRUCT(tuple);
3009  oprkind = form->oprkind;
3010 
3011  /* Sanity check. */
3012  Assert((oprkind == 'l' && list_length(node->args) == 1) ||
3013  (oprkind == 'b' && list_length(node->args) == 2));
3014 
3015  right = llast(node->args);
3016 
3017  /* Always parenthesize the expression. */
3018  appendStringInfoChar(buf, '(');
3019 
3020  /* Deparse left operand, if any. */
3021  if (oprkind == 'b')
3022  {
3023  Expr *left = linitial(node->args);
3024  Oid leftType = exprType((Node *) left);
3025  Oid rightType = exprType((Node *) right);
3026  bool canSuppressLeftConstCast = false;
3027 
3028  /*
3029  * When considering a binary operator, if one operand is a Const that
3030  * can be printed as a bare string literal or NULL (i.e., it will look
3031  * like type UNKNOWN to the remote parser), the Const normally
3032  * receives an explicit cast to the operator's input type. However,
3033  * in Const-to-Var comparisons where both operands are of the same
3034  * type, we prefer to suppress the explicit cast, leaving the Const's
3035  * type resolution up to the remote parser. The remote's resolution
3036  * heuristic will assume that an unknown input type being compared to
3037  * a known input type is of that known type as well.
3038  *
3039  * This hack allows some cases to succeed where a remote column is
3040  * declared with a different type in the local (foreign) table. By
3041  * emitting "foreigncol = 'foo'" not "foreigncol = 'foo'::text" or the
3042  * like, we allow the remote parser to pick an "=" operator that's
3043  * compatible with whatever type the remote column really is, such as
3044  * an enum.
3045  *
3046  * We allow cast suppression to happen only when the other operand is
3047  * a plain foreign Var. Although the remote's unknown-type heuristic
3048  * would apply to other cases just as well, we would be taking a
3049  * bigger risk that the inferred type is something unexpected. With
3050  * this restriction, if anything goes wrong it's the user's fault for
3051  * not declaring the local column with the same type as the remote
3052  * column.
3053  */
3054  if (leftType == rightType)
3055  {
3056  if (IsA(left, Const))
3057  canSuppressLeftConstCast = isPlainForeignVar(right, context);
3058  else if (IsA(right, Const))
3059  canSuppressRightConstCast = isPlainForeignVar(left, context);
3060  }
3061 
3062  if (canSuppressLeftConstCast)
3063  deparseConst((Const *) left, context, -2);
3064  else
3065  deparseExpr(left, context);
3066 
3067  appendStringInfoChar(buf, ' ');
3068  }
3069 
3070  /* Deparse operator name. */
3071  deparseOperatorName(buf, form);
3072 
3073  /* Deparse right operand. */
3074  appendStringInfoChar(buf, ' ');
3075 
3076  if (canSuppressRightConstCast)
3077  deparseConst((Const *) right, context, -2);
3078  else
3079  deparseExpr(right, context);
3080 
3081  appendStringInfoChar(buf, ')');
3082 
3083  ReleaseSysCache(tuple);
3084 }
static bool isPlainForeignVar(Expr *node, deparse_expr_cxt *context)
Definition: deparse.c:3090
#define llast(l)
Definition: pg_list.h:196
Oid opno
Definition: primnodes.h:634

References appendStringInfoChar(), OpExpr::args, Assert(), deparse_expr_cxt::buf, buf, deparseConst(), deparseExpr(), deparseOperatorName(), elog(), ERROR, exprType(), GETSTRUCT, HeapTupleIsValid, IsA, isPlainForeignVar(), linitial, list_length(), llast, ObjectIdGetDatum, OPEROID, OpExpr::opno, ReleaseSysCache(), and SearchSysCache1().

Referenced by deparseExpr().

◆ deparseParam()

static void deparseParam ( Param node,
deparse_expr_cxt context 
)
static

Definition at line 2853 of file deparse.c.

2854 {
2855  if (context->params_list)
2856  {
2857  int pindex = 0;
2858  ListCell *lc;
2859 
2860  /* find its index in params_list */
2861  foreach(lc, *context->params_list)
2862  {
2863  pindex++;
2864  if (equal(node, (Node *) lfirst(lc)))
2865  break;
2866  }
2867  if (lc == NULL)
2868  {
2869  /* not in list, so add it */
2870  pindex++;
2871  *context->params_list = lappend(*context->params_list, node);
2872  }
2873 
2874  printRemoteParam(pindex, node->paramtype, node->paramtypmod, context);
2875  }
2876  else
2877  {
2878  printRemotePlaceholder(node->paramtype, node->paramtypmod, context);
2879  }
2880 }
static void printRemoteParam(int paramindex, Oid paramtype, int32 paramtypmod, deparse_expr_cxt *context)
Definition: deparse.c:3542
static void printRemotePlaceholder(Oid paramtype, int32 paramtypmod, deparse_expr_cxt *context)
Definition: deparse.c:3568
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3564
int32 paramtypmod
Definition: primnodes.h:311
Oid paramtype
Definition: primnodes.h:310

References equal(), lappend(), lfirst, deparse_expr_cxt::params_list, Param::paramtype, Param::paramtypmod, printRemoteParam(), and printRemotePlaceholder().

Referenced by deparseExpr().

◆ deparseRangeTblRef()

static void deparseRangeTblRef ( StringInfo  buf,
PlannerInfo root,
RelOptInfo foreignrel,
bool  make_subquery,
Index  ignore_rel,
List **  ignore_conds,
List **  params_list 
)
static

Definition at line 1798 of file deparse.c.

1801 {
1802  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
1803 
1804  /* Should only be called in these cases. */
1805  Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel));
1806 
1807  Assert(fpinfo->local_conds == NIL);
1808 
1809  /* If make_subquery is true, deparse the relation as a subquery. */
1810  if (make_subquery)
1811  {
1812  List *retrieved_attrs;
1813  int ncols;
1814 
1815  /*
1816  * The given relation shouldn't contain the target relation, because
1817  * this should only happen for input relations for a full join, and
1818  * such relations can never contain an UPDATE/DELETE target.
1819  */
1820  Assert(ignore_rel == 0 ||
1821  !bms_is_member(ignore_rel, foreignrel->relids));
1822 
1823  /* Deparse the subquery representing the relation. */
1824  appendStringInfoChar(buf, '(');
1825  deparseSelectStmtForRel(buf, root, foreignrel, NIL,
1826  fpinfo->remote_conds, NIL,
1827  false, false, true,
1828  &retrieved_attrs, params_list);
1829  appendStringInfoChar(buf, ')');
1830 
1831  /* Append the relation alias. */
1833  fpinfo->relation_index);
1834 
1835  /*
1836  * Append the column aliases if needed. Note that the subquery emits
1837  * expressions specified in the relation's reltarget (see
1838  * deparseSubqueryTargetList).
1839  */
1840  ncols = list_length(foreignrel->reltarget->exprs);
1841  if (ncols > 0)
1842  {
1843  int i;
1844 
1845  appendStringInfoChar(buf, '(');
1846  for (i = 1; i <= ncols; i++)
1847  {
1848  if (i > 1)
1849  appendStringInfoString(buf, ", ");
1850 
1852  }
1853  appendStringInfoChar(buf, ')');
1854  }
1855  }
1856  else
1857  deparseFromExprForRel(buf, root, foreignrel, true, ignore_rel,
1858  ignore_conds, params_list);
1859 }
#define SUBQUERY_REL_ALIAS_PREFIX
Definition: deparse.c:111
void deparseSelectStmtForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *rel, List *tlist, List *remote_conds, List *pathkeys, bool has_final_sort, bool has_limit, bool is_subquery, List **retrieved_attrs, List **params_list)
Definition: deparse.c:1159
#define SUBQUERY_COL_ALIAS_PREFIX
Definition: deparse.c:112

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert(), bms_is_member(), buf, deparseFromExprForRel(), deparseSelectStmtForRel(), PathTarget::exprs, RelOptInfo::fdw_private, i, IS_JOIN_REL, IS_SIMPLE_REL, list_length(), PgFdwRelationInfo::local_conds, NIL, PgFdwRelationInfo::relation_index, RelOptInfo::relids, RelOptInfo::reltarget, PgFdwRelationInfo::remote_conds, SUBQUERY_COL_ALIAS_PREFIX, and SUBQUERY_REL_ALIAS_PREFIX.

Referenced by deparseFromExprForRel().

◆ deparseRelabelType()

static void deparseRelabelType ( RelabelType node,
deparse_expr_cxt context 
)
static

Definition at line 3216 of file deparse.c.

3217 {
3218  deparseExpr(node->arg, context);
3219  if (node->relabelformat != COERCE_IMPLICIT_CAST)
3220  appendStringInfo(context->buf, "::%s",
3222  node->resulttypmod));
3223 }
int32 resulttypmod
Definition: primnodes.h:983
CoercionForm relabelformat
Definition: primnodes.h:985
Oid resulttype
Definition: primnodes.h:982
Expr * arg
Definition: primnodes.h:981

References appendStringInfo(), RelabelType::arg, deparse_expr_cxt::buf, COERCE_IMPLICIT_CAST, deparse_type_name(), deparseExpr(), RelabelType::relabelformat, RelabelType::resulttype, and RelabelType::resulttypmod.

Referenced by deparseExpr().

◆ deparseRelation()

static void deparseRelation ( StringInfo  buf,
Relation  rel 
)
static

Definition at line 2528 of file deparse.c.

2529 {
2530  ForeignTable *table;
2531  const char *nspname = NULL;
2532  const char *relname = NULL;
2533  ListCell *lc;
2534 
2535  /* obtain additional catalog information. */
2536  table = GetForeignTable(RelationGetRelid(rel));
2537 
2538  /*
2539  * Use value of FDW options if any, instead of the name of object itself.
2540  */
2541  foreach(lc, table->options)
2542  {
2543  DefElem *def = (DefElem *) lfirst(lc);
2544 
2545  if (strcmp(def->defname, "schema_name") == 0)
2546  nspname = defGetString(def);
2547  else if (strcmp(def->defname, "table_name") == 0)
2548  relname = defGetString(def);
2549  }
2550 
2551  /*
2552  * Note: we could skip printing the schema name if it's pg_catalog, but
2553  * that doesn't seem worth the trouble.
2554  */
2555  if (nspname == NULL)
2556  nspname = get_namespace_name(RelationGetNamespace(rel));
2557  if (relname == NULL)
2559 
2560  appendStringInfo(buf, "%s.%s",
2562 }
ForeignTable * GetForeignTable(Oid relid)
Definition: foreign.c:249
#define RelationGetRelationName(relation)
Definition: rel.h:522
#define RelationGetNamespace(relation)
Definition: rel.h:529
List * options
Definition: foreign.h:57

References appendStringInfo(), buf, defGetString(), DefElem::defname, get_namespace_name(), GetForeignTable(), lfirst, ForeignTable::options, quote_identifier(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, and relname.

Referenced by deparseAnalyzeSizeSql(), deparseAnalyzeSql(), deparseDeleteSql(), deparseDirectDeleteSql(), deparseDirectUpdateSql(), deparseFromExprForRel(), deparseInsertSql(), deparseTruncateSql(), and deparseUpdateSql().

◆ deparseReturningList()

static void deparseReturningList ( StringInfo  buf,
RangeTblEntry rte,
Index  rtindex,
Relation  rel,
bool  trig_after_row,
List withCheckOptionList,
List returningList,
List **  retrieved_attrs 
)
static

Definition at line 2230 of file deparse.c.

2236 {
2237  Bitmapset *attrs_used = NULL;
2238 
2239  if (trig_after_row)
2240  {
2241  /* whole-row reference acquires all non-system columns */
2242  attrs_used =
2244  }
2245 
2246  if (withCheckOptionList != NIL)
2247  {
2248  /*
2249  * We need the attrs, non-system and system, mentioned in the local
2250  * query's WITH CHECK OPTION list.
2251  *
2252  * Note: we do this to ensure that WCO constraints will be evaluated
2253  * on the data actually inserted/updated on the remote side, which
2254  * might differ from the data supplied by the core code, for example
2255  * as a result of remote triggers.
2256  */
2257  pull_varattnos((Node *) withCheckOptionList, rtindex,
2258  &attrs_used);
2259  }
2260 
2261  if (returningList != NIL)
2262  {
2263  /*
2264  * We need the attrs, non-system and system, mentioned in the local
2265  * query's RETURNING list.
2266  */
2267  pull_varattnos((Node *) returningList, rtindex,
2268  &attrs_used);
2269  }
2270 
2271  if (attrs_used != NULL)
2272  deparseTargetList(buf, rte, rtindex, rel, true, attrs_used, false,
2273  retrieved_attrs);
2274  else
2275  *retrieved_attrs = NIL;
2276 }
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:186
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:288

References bms_make_singleton(), buf, deparseTargetList(), FirstLowInvalidHeapAttributeNumber, NIL, and pull_varattnos().

Referenced by deparseDeleteSql(), deparseDirectDeleteSql(), deparseDirectUpdateSql(), deparseInsertSql(), and deparseUpdateSql().

◆ deparseScalarArrayOpExpr()

static void deparseScalarArrayOpExpr ( ScalarArrayOpExpr node,
deparse_expr_cxt context 
)
static

Definition at line 3171 of file deparse.c.

3172 {
3173  StringInfo buf = context->buf;
3174  HeapTuple tuple;
3175  Form_pg_operator form;
3176  Expr *arg1;
3177  Expr *arg2;
3178 
3179  /* Retrieve information about the operator from system catalog. */
3180  tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(node->opno));
3181  if (!HeapTupleIsValid(tuple))
3182  elog(ERROR, "cache lookup failed for operator %u", node->opno);
3183  form = (Form_pg_operator) GETSTRUCT(tuple);
3184 
3185  /* Sanity check. */
3186  Assert(list_length(node->args) == 2);
3187 
3188  /* Always parenthesize the expression. */
3189  appendStringInfoChar(buf, '(');
3190 
3191  /* Deparse left operand. */
3192  arg1 = linitial(node->args);
3193  deparseExpr(arg1, context);
3194  appendStringInfoChar(buf, ' ');
3195 
3196  /* Deparse operator name plus decoration. */
3197  deparseOperatorName(buf, form);
3198  appendStringInfo(buf, " %s (", node->useOr ? "ANY" : "ALL");
3199 
3200  /* Deparse right operand. */
3201  arg2 = lsecond(node->args);
3202  deparseExpr(arg2, context);
3203 
3204  appendStringInfoChar(buf, ')');
3205 
3206  /* Always parenthesize the expression. */
3207  appendStringInfoChar(buf, ')');
3208 
3209  ReleaseSysCache(tuple);
3210 }

References appendStringInfo(), appendStringInfoChar(), ScalarArrayOpExpr::args, Assert(), deparse_expr_cxt::buf, buf, deparseExpr(), deparseOperatorName(), elog(), ERROR, GETSTRUCT, HeapTupleIsValid, linitial, list_length(), lsecond, ObjectIdGetDatum, OPEROID, ScalarArrayOpExpr::opno, ReleaseSysCache(), SearchSysCache1(), and ScalarArrayOpExpr::useOr.

Referenced by deparseExpr().

◆ deparseSelectSql()

static void deparseSelectSql ( List tlist,
bool  is_subquery,
List **  retrieved_attrs,
deparse_expr_cxt context 
)
static

Definition at line 1241 of file deparse.c.

1243 {
1244  StringInfo buf = context->buf;
1245  RelOptInfo *foreignrel = context->foreignrel;
1246  PlannerInfo *root = context->root;
1247  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
1248 
1249  /*
1250  * Construct SELECT list
1251  */
1252  appendStringInfoString(buf, "SELECT ");
1253 
1254  if (is_subquery)
1255  {
1256  /*
1257  * For a relation that is deparsed as a subquery, emit expressions
1258  * specified in the relation's reltarget. Note that since this is for
1259  * the subquery, no need to care about *retrieved_attrs.
1260  */
1261  deparseSubqueryTargetList(context);
1262  }
1263  else if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
1264  {
1265  /*
1266  * For a join or upper relation the input tlist gives the list of
1267  * columns required to be fetched from the foreign server.
1268  */
1269  deparseExplicitTargetList(tlist, false, retrieved_attrs, context);
1270  }
1271  else
1272  {
1273  /*
1274  * For a base relation fpinfo->attrs_used gives the list of columns
1275  * required to be fetched from the foreign server.
1276  */
1277  RangeTblEntry *rte = planner_rt_fetch(foreignrel->relid, root);
1278 
1279  /*
1280  * Core code already has some lock on each rel being planned, so we
1281  * can use NoLock here.
1282  */
1283  Relation rel = table_open(rte->relid, NoLock);
1284 
1285  deparseTargetList(buf, rte, foreignrel->relid, rel, false,
1286  fpinfo->attrs_used, false, retrieved_attrs);
1287  table_close(rel, NoLock);
1288  }
1289 }
static void deparseSubqueryTargetList(deparse_expr_cxt *context)
Definition: deparse.c:1606
Bitmapset * attrs_used
Definition: postgres_fdw.h:50

References appendStringInfoString(), PgFdwRelationInfo::attrs_used, deparse_expr_cxt::buf, buf, deparseExplicitTargetList(), deparseSubqueryTargetList(), deparseTargetList(), RelOptInfo::fdw_private, deparse_expr_cxt::foreignrel, IS_JOIN_REL, IS_UPPER_REL, NoLock, planner_rt_fetch, RangeTblEntry::relid, RelOptInfo::relid, deparse_expr_cxt::root, table_close(), and table_open().

Referenced by deparseSelectStmtForRel().

◆ deparseSelectStmtForRel()

void deparseSelectStmtForRel ( StringInfo  buf,
PlannerInfo root,
RelOptInfo rel,
List tlist,
List remote_conds,
List pathkeys,
bool  has_final_sort,
bool  has_limit,
bool  is_subquery,
List **  retrieved_attrs,
List **  params_list 
)

Definition at line 1159 of file deparse.c.

1163 {
1164  deparse_expr_cxt context;
1165  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
1166  List *quals;
1167 
1168  /*
1169  * We handle relations for foreign tables, joins between those and upper
1170  * relations.
1171  */
1172  Assert(IS_JOIN_REL(rel) || IS_SIMPLE_REL(rel) || IS_UPPER_REL(rel));
1173 
1174  /* Fill portions of context common to upper, join and base relation */
1175  context.buf = buf;
1176  context.root = root;
1177  context.foreignrel = rel;
1178  context.scanrel = IS_UPPER_REL(rel) ? fpinfo->outerrel : rel;
1179  context.params_list = params_list;
1180 
1181  /* Construct SELECT clause */
1182  deparseSelectSql(tlist, is_subquery, retrieved_attrs, &context);
1183 
1184  /*
1185  * For upper relations, the WHERE clause is built from the remote
1186  * conditions of the underlying scan relation; otherwise, we can use the
1187  * supplied list of remote conditions directly.
1188  */
1189  if (IS_UPPER_REL(rel))
1190  {
1191  PgFdwRelationInfo *ofpinfo;
1192 
1193  ofpinfo = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
1194  quals = ofpinfo->remote_conds;
1195  }
1196  else
1197  quals = remote_conds;
1198 
1199  /* Construct FROM and WHERE clauses */
1200  deparseFromExpr(quals, &context);
1201 
1202  if (IS_UPPER_REL(rel))
1203  {
1204  /* Append GROUP BY clause */
1205  appendGroupByClause(tlist, &context);
1206 
1207  /* Append HAVING clause */
1208  if (remote_conds)
1209  {
1210  appendStringInfoString(buf, " HAVING ");
1211  appendConditions(remote_conds, &context);
1212  }
1213  }
1214 
1215  /* Add ORDER BY clause if we found any useful pathkeys */
1216  if (pathkeys)
1217  appendOrderByClause(pathkeys, has_final_sort, &context);
1218 
1219  /* Add LIMIT clause if necessary */
1220  if (has_limit)
1221  appendLimitClause(&context);
1222 
1223  /* Add any necessary FOR UPDATE/SHARE. */
1224  deparseLockingClause(&context);
1225 }
static void appendGroupByClause(List *tlist, deparse_expr_cxt *context)
Definition: deparse.c:3581
static void deparseFromExpr(List *quals, deparse_expr_cxt *context)
Definition: deparse.c:1299
static void deparseLockingClause(deparse_expr_cxt *context)
Definition: deparse.c:1409
static void appendOrderByClause(List *pathkeys, bool has_final_sort, deparse_expr_cxt *context)
Definition: deparse.c:3622
static void appendLimitClause(deparse_expr_cxt *context)
Definition: deparse.c:3699
static void deparseSelectSql(List *tlist, bool is_subquery, List **retrieved_attrs, deparse_expr_cxt *context)
Definition: deparse.c:1241

References appendConditions(), appendGroupByClause(), appendLimitClause(), appendOrderByClause(), appendStringInfoString(), Assert(), deparse_expr_cxt::buf, buf, deparseFromExpr(), deparseLockingClause(), deparseSelectSql(), RelOptInfo::fdw_private, deparse_expr_cxt::foreignrel, IS_JOIN_REL, IS_SIMPLE_REL, IS_UPPER_REL, PgFdwRelationInfo::outerrel, deparse_expr_cxt::params_list, PgFdwRelationInfo::remote_conds, deparse_expr_cxt::root, and deparse_expr_cxt::scanrel.

Referenced by deparseRangeTblRef(), estimate_path_cost_size(), and postgresGetForeignPlan().

◆ deparseSortGroupClause()

static Node * deparseSortGroupClause ( Index  ref,
List tlist,
bool  force_colno,
deparse_expr_cxt context 
)
static

Definition at line 3762 of file deparse.c.

3764 {
3765  StringInfo buf = context->buf;
3766  TargetEntry *tle;
3767  Expr *expr;
3768 
3769  tle = get_sortgroupref_tle(ref, tlist);
3770  expr = tle->expr;
3771 
3772  if (force_colno)
3773  {
3774  /* Use column-number form when requested by caller. */
3775  Assert(!tle->resjunk);
3776  appendStringInfo(buf, "%d", tle->resno);
3777  }
3778  else if (expr && IsA(expr, Const))
3779  {
3780  /*
3781  * Force a typecast here so that we don't emit something like "GROUP
3782  * BY 2", which will be misconstrued as a column position rather than
3783  * a constant.
3784  */
3785  deparseConst((Const *) expr, context, 1);
3786  }
3787  else if (!expr || IsA(expr, Var))
3788  deparseExpr(expr, context);
3789  else
3790  {
3791  /* Always parenthesize the expression. */
3792  appendStringInfoChar(buf, '(');
3793  deparseExpr(expr, context);
3794  appendStringInfoChar(buf, ')');
3795  }
3796 
3797  return (Node *) expr;
3798 }
AttrNumber resno
Definition: primnodes.h:1829
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:334

References appendStringInfo(), appendStringInfoChar(), Assert(), deparse_expr_cxt::buf, buf, deparseConst(), deparseExpr(), TargetEntry::expr, get_sortgroupref_tle(), IsA, TargetEntry::resjunk, and TargetEntry::resno.

Referenced by appendAggOrderBy(), and appendGroupByClause().

◆ deparseStringLiteral()

void deparseStringLiteral ( StringInfo  buf,
const char *  val 
)

Definition at line 2568 of file deparse.c.

2569 {
2570  const char *valptr;
2571 
2572  /*
2573  * Rather than making assumptions about the remote server's value of
2574  * standard_conforming_strings, always use E'foo' syntax if there are any
2575  * backslashes. This will fail on remote servers before 8.1, but those
2576  * are long out of support.
2577  */
2578  if (strchr(val, '\\') != NULL)
2580  appendStringInfoChar(buf, '\'');
2581  for (valptr = val; *valptr; valptr++)
2582  {
2583  char ch = *valptr;
2584 
2585  if (SQL_STR_DOUBLE(ch, true))
2588  }
2589  appendStringInfoChar(buf, '\'');
2590 }
#define ESCAPE_STRING_SYNTAX
Definition: c.h:1175
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1172
long val
Definition: informix.c:664

References appendStringInfoChar(), buf, ESCAPE_STRING_SYNTAX, SQL_STR_DOUBLE, and val.

Referenced by deparseAnalyzeSizeSql(), deparseConst(), and postgresImportForeignSchema().

◆ deparseSubqueryTargetList()

static void deparseSubqueryTargetList ( deparse_expr_cxt context)
static

Definition at line 1606 of file deparse.c.

1607 {
1608  StringInfo buf = context->buf;
1609  RelOptInfo *foreignrel = context->foreignrel;
1610  bool first;
1611  ListCell *lc;
1612 
1613  /* Should only be called in these cases. */
1614  Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel));
1615 
1616  first = true;
1617  foreach(lc, foreignrel->reltarget->exprs)
1618  {
1619  Node *node = (Node *) lfirst(lc);
1620 
1621  if (!first)
1622  appendStringInfoString(buf, ", ");
1623  first = false;
1624 
1625  deparseExpr((Expr *) node, context);
1626  }
1627 
1628  /* Don't generate bad syntax if no expressions */
1629  if (first)
1630  appendStringInfoString(buf, "NULL");
1631 }

References appendStringInfoString(), Assert(), deparse_expr_cxt::buf, buf, deparseExpr(), PathTarget::exprs, deparse_expr_cxt::foreignrel, IS_JOIN_REL, IS_SIMPLE_REL, lfirst, and RelOptInfo::reltarget.

Referenced by deparseSelectSql().

◆ deparseSubscriptingRef()

static void deparseSubscriptingRef ( SubscriptingRef node,
deparse_expr_cxt context 
)
static

Definition at line 2886 of file deparse.c.

2887 {
2888  StringInfo buf = context->buf;
2889  ListCell *lowlist_item;
2890  ListCell *uplist_item;
2891 
2892  /* Always parenthesize the expression. */
2893  appendStringInfoChar(buf, '(');
2894 
2895  /*
2896  * Deparse referenced array expression first. If that expression includes
2897  * a cast, we have to parenthesize to prevent the array subscript from
2898  * being taken as typename decoration. We can avoid that in the typical
2899  * case of subscripting a Var, but otherwise do it.
2900  */
2901  if (IsA(node->refexpr, Var))
2902  deparseExpr(node->refexpr, context);
2903  else
2904  {
2905  appendStringInfoChar(buf, '(');
2906  deparseExpr(node->refexpr, context);
2907  appendStringInfoChar(buf, ')');
2908  }
2909 
2910  /* Deparse subscript expressions. */
2911  lowlist_item = list_head(node->reflowerindexpr); /* could be NULL */
2912  foreach(uplist_item, node->refupperindexpr)
2913  {
2914  appendStringInfoChar(buf, '[');
2915  if (lowlist_item)
2916  {
2917  deparseExpr(lfirst(lowlist_item), context);
2918  appendStringInfoChar(buf, ':');
2919  lowlist_item = lnext(node->reflowerindexpr, lowlist_item);
2920  }
2921  deparseExpr(lfirst(uplist_item), context);
2922  appendStringInfoChar(buf, ']');
2923  }
2924 
2925  appendStringInfoChar(buf, ')');
2926 }
static ListCell * list_head(const List *l)
Definition: pg_list.h:126
List * refupperindexpr
Definition: primnodes.h:534
Expr * refexpr
Definition: primnodes.h:539
List * reflowerindexpr
Definition: primnodes.h:536

References appendStringInfoChar(), deparse_expr_cxt::buf, buf, deparseExpr(), IsA, lfirst, list_head(), lnext(), SubscriptingRef::refexpr, SubscriptingRef::reflowerindexpr, and SubscriptingRef::refupperindexpr.

Referenced by deparseExpr().

◆ deparseTargetList()

static void deparseTargetList ( StringInfo  buf,
RangeTblEntry rte,
Index  rtindex,
Relation  rel,
bool  is_returning,
Bitmapset attrs_used,
bool  qualify_col,
List **  retrieved_attrs 
)
static

Definition at line 1333 of file deparse.c.

1341 {
1342  TupleDesc tupdesc = RelationGetDescr(rel);
1343  bool have_wholerow;
1344  bool first;
1345  int i;
1346 
1347  *retrieved_attrs = NIL;
1348 
1349  /* If there's a whole-row reference, we'll need all the columns. */
1351  attrs_used);
1352 
1353  first = true;
1354  for (i = 1; i <= tupdesc->natts; i++)
1355  {
1356  Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
1357 
1358  /* Ignore dropped attributes. */
1359  if (attr->attisdropped)
1360  continue;
1361 
1362  if (have_wholerow ||
1364  attrs_used))
1365  {
1366  if (!first)
1367  appendStringInfoString(buf, ", ");
1368  else if (is_returning)
1369  appendStringInfoString(buf, " RETURNING ");
1370  first = false;
1371 
1372  deparseColumnRef(buf, rtindex, i, rte, qualify_col);
1373 
1374  *retrieved_attrs = lappend_int(*retrieved_attrs, i);
1375  }
1376  }
1377 
1378  /*
1379  * Add ctid if needed. We currently don't support retrieving any other
1380  * system columns.
1381  */
1383  attrs_used))
1384  {
1385  if (!first)
1386  appendStringInfoString(buf, ", ");
1387  else if (is_returning)
1388  appendStringInfoString(buf, " RETURNING ");
1389  first = false;
1390 
1391  if (qualify_col)
1392  ADD_REL_QUALIFIER(buf, rtindex);
1393  appendStringInfoString(buf, "ctid");
1394 
1395  *retrieved_attrs = lappend_int(*retrieved_attrs,
1397  }
1398 
1399  /* Don't generate bad syntax if no undropped columns */
1400  if (first && !is_returning)
1401  appendStringInfoString(buf, "NULL");
1402 }

References ADD_REL_QUALIFIER, appendStringInfoString(), bms_is_member(), buf, deparseColumnRef(), FirstLowInvalidHeapAttributeNumber, i, lappend_int(), TupleDescData::natts, NIL, RelationGetDescr, SelfItemPointerAttributeNumber, and TupleDescAttr.

Referenced by deparseColumnRef(), deparseReturningList(), and deparseSelectSql().

◆ deparseTruncateSql()

void deparseTruncateSql ( StringInfo  buf,
List rels,
DropBehavior  behavior,
bool  restart_seqs 
)

Definition at line 2365 of file deparse.c.

2369 {
2370  ListCell *cell;
2371 
2372  appendStringInfoString(buf, "TRUNCATE ");
2373 
2374  foreach(cell, rels)
2375  {
2376  Relation rel = lfirst(cell);
2377 
2378  if (cell != list_head(rels))
2379  appendStringInfoString(buf, ", ");
2380 
2381  deparseRelation(buf, rel);
2382  }
2383 
2384  appendStringInfo(buf, " %s IDENTITY",
2385  restart_seqs ? "RESTART" : "CONTINUE");
2386 
2387  if (behavior == DROP_RESTRICT)
2388  appendStringInfoString(buf, " RESTRICT");
2389  else if (behavior == DROP_CASCADE)
2390  appendStringInfoString(buf, " CASCADE");
2391 }
@ DROP_CASCADE
Definition: parsenodes.h:2209
@ DROP_RESTRICT
Definition: parsenodes.h:2208

References appendStringInfo(), appendStringInfoString(), buf, deparseRelation(), DROP_CASCADE, DROP_RESTRICT, lfirst, and list_head().

Referenced by postgresExecForeignTruncate().

◆ deparseUpdateSql()

void deparseUpdateSql ( StringInfo  buf,
RangeTblEntry rte,
Index  rtindex,
Relation  rel,
List targetAttrs,
List withCheckOptionList,
List returningList,
List **  retrieved_attrs 
)

Definition at line 2005 of file deparse.c.

2010 {
2011  TupleDesc tupdesc = RelationGetDescr(rel);
2012  AttrNumber pindex;
2013  bool first;
2014  ListCell *lc;
2015 
2016  appendStringInfoString(buf, "UPDATE ");
2017  deparseRelation(buf, rel);
2018  appendStringInfoString(buf, " SET ");
2019 
2020  pindex = 2; /* ctid is always the first param */
2021  first = true;
2022  foreach(lc, targetAttrs)
2023  {
2024  int attnum = lfirst_int(lc);
2025  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
2026 
2027  if (!first)
2028  appendStringInfoString(buf, ", ");
2029  first = false;
2030 
2031  deparseColumnRef(buf, rtindex, attnum, rte, false);
2032  if (attr->attgenerated)
2033  appendStringInfoString(buf, " = DEFAULT");
2034  else
2035  {
2036  appendStringInfo(buf, " = $%d", pindex);
2037  pindex++;
2038  }
2039  }
2040  appendStringInfoString(buf, " WHERE ctid = $1");
2041 
2042  deparseReturningList(buf, rte, rtindex, rel,
2043  rel->trigdesc && rel->trigdesc->trig_update_after_row,
2044  withCheckOptionList, returningList, retrieved_attrs);
2045 }
bool trig_update_after_row
Definition: reltrigger.h:62

References appendStringInfo(), appendStringInfoString(), attnum, buf, deparseColumnRef(), deparseRelation(), deparseReturningList(), lfirst_int, RelationGetDescr, TriggerDesc::trig_update_after_row, RelationData::trigdesc, and TupleDescAttr.

Referenced by postgresPlanForeignModify().

◆ deparseVar()

static void deparseVar ( Var node,
deparse_expr_cxt context 
)
static

Definition at line 2668 of file deparse.c.

2669 {
2670  Relids relids = context->scanrel->relids;
2671  int relno;
2672  int colno;
2673 
2674  /* Qualify columns when multiple relations are involved. */
2675  bool qualify_col = (bms_membership(relids) == BMS_MULTIPLE);
2676 
2677  /*
2678  * If the Var belongs to the foreign relation that is deparsed as a
2679  * subquery, use the relation and column alias to the Var provided by the
2680  * subquery, instead of the remote name.
2681  */
2682  if (is_subquery_var(node, context->scanrel, &relno, &colno))
2683  {
2684  appendStringInfo(context->buf, "%s%d.%s%d",
2686  SUBQUERY_COL_ALIAS_PREFIX, colno);
2687  return;
2688  }
2689 
2690  if (bms_is_member(node->varno, relids) && node->varlevelsup == 0)
2691  deparseColumnRef(context->buf, node->varno, node->varattno,
2692  planner_rt_fetch(node->varno, context->root),
2693  qualify_col);
2694  else
2695  {
2696  /* Treat like a Param */
2697  if (context->params_list)
2698  {
2699  int pindex = 0;
2700  ListCell *lc;
2701 
2702  /* find its index in params_list */
2703  foreach(lc, *context->params_list)
2704  {
2705  pindex++;
2706  if (equal(node, (Node *) lfirst(lc)))
2707  break;
2708  }
2709  if (lc == NULL)
2710  {
2711  /* not in list, so add it */
2712  pindex++;
2713  *context->params_list = lappend(*context->params_list, node);
2714  }
2715 
2716  printRemoteParam(pindex, node->vartype, node->vartypmod, context);
2717  }
2718  else
2719  {
2720  printRemotePlaceholder(node->vartype, node->vartypmod, context);
2721  }
2722  }
2723 }
static bool is_subquery_var(Var *node, RelOptInfo *foreignrel, int *relno, int *colno)
Definition: deparse.c:3807
Oid vartype
Definition: primnodes.h:224
AttrNumber varattno
Definition: primnodes.h:221
int varno
Definition: primnodes.h:216
int32 vartypmod
Definition: primnodes.h:226
Index varlevelsup
Definition: primnodes.h:234

References appendStringInfo(), bms_is_member(), bms_membership(), BMS_MULTIPLE, deparse_expr_cxt::buf, deparseColumnRef(), equal(), is_subquery_var(), lappend(), lfirst, deparse_expr_cxt::params_list, planner_rt_fetch, printRemoteParam(), printRemotePlaceholder(), RelOptInfo::relids, deparse_expr_cxt::root, deparse_expr_cxt::scanrel, SUBQUERY_COL_ALIAS_PREFIX, SUBQUERY_REL_ALIAS_PREFIX, Var::varattno, Var::varlevelsup, Var::varno, Var::vartype, and Var::vartypmod.

Referenced by deparseExpr().

◆ foreign_expr_walker()

static bool foreign_expr_walker ( Node node,
foreign_glob_cxt glob_cxt,
foreign_loc_cxt outer_cxt,
foreign_loc_cxt case_arg_cxt 
)
static

Definition at line 305 of file deparse.c.

309 {
310  bool check_type = true;
311  PgFdwRelationInfo *fpinfo;
312  foreign_loc_cxt inner_cxt;
313  Oid collation;
315 
316  /* Need do nothing for empty subexpressions */
317  if (node == NULL)
318  return true;
319 
320  /* May need server info from baserel's fdw_private struct */
321  fpinfo = (PgFdwRelationInfo *) (glob_cxt->foreignrel->fdw_private);
322 
323  /* Set up inner_cxt for possible recursion to child nodes */
324  inner_cxt.collation = InvalidOid;
325  inner_cxt.state = FDW_COLLATE_NONE;
326 
327  switch (nodeTag(node))
328  {
329  case T_Var:
330  {
331  Var *var = (Var *) node;
332 
333  /*
334  * If the Var is from the foreign table, we consider its
335  * collation (if any) safe to use. If it is from another
336  * table, we treat its collation the same way as we would a
337  * Param's collation, ie it's not safe for it to have a
338  * non-default collation.
339  */
340  if (bms_is_member(var->varno, glob_cxt->relids) &&
341  var->varlevelsup == 0)
342  {
343  /* Var belongs to foreign table */
344 
345  /*
346  * System columns other than ctid should not be sent to
347  * the remote, since we don't make any effort to ensure
348  * that local and remote values match (tableoid, in
349  * particular, almost certainly doesn't match).
350  */
351  if (var->varattno < 0 &&
353  return false;
354 
355  /* Else check the collation */
356  collation = var->varcollid;
358  }
359  else
360  {
361  /* Var belongs to some other table */
362  collation = var->varcollid;
363  if (collation == InvalidOid ||
364  collation == DEFAULT_COLLATION_OID)
365  {
366  /*
367  * It's noncollatable, or it's safe to combine with a
368  * collatable foreign Var, so set state to NONE.
369  */
371  }
372  else
373  {
374  /*
375  * Do not fail right away, since the Var might appear
376  * in a collation-insensitive context.
377  */
379  }
380  }
381  }
382  break;
383  case T_Const:
384  {
385  Const *c = (Const *) node;
386 
387  /*
388  * If the constant has nondefault collation, either it's of a
389  * non-builtin type, or it reflects folding of a CollateExpr.
390  * It's unsafe to send to the remote unless it's used in a
391  * non-collation-sensitive context.
392  */
393  collation = c->constcollid;
394  if (collation == InvalidOid ||
395  collation == DEFAULT_COLLATION_OID)
397  else
399  }
400  break;
401  case T_Param:
402  {
403  Param *p = (Param *) node;
404 
405  /*
406  * If it's a MULTIEXPR Param, punt. We can't tell from here
407  * whether the referenced sublink/subplan contains any remote
408  * Vars; if it does, handling that is too complicated to
409  * consider supporting at present. Fortunately, MULTIEXPR
410  * Params are not reduced to plain PARAM_EXEC until the end of
411  * planning, so we can easily detect this case. (Normal
412  * PARAM_EXEC Params are safe to ship because their values
413  * come from somewhere else in the plan tree; but a MULTIEXPR
414  * references a sub-select elsewhere in the same targetlist,
415  * so we'd be on the hook to evaluate it somehow if we wanted
416  * to handle such cases as direct foreign updates.)
417  */
418  if (p->paramkind == PARAM_MULTIEXPR)
419  return false;
420 
421  /*
422  * Collation rule is same as for Consts and non-foreign Vars.
423  */
424  collation = p->paramcollid;
425  if (collation == InvalidOid ||
426  collation == DEFAULT_COLLATION_OID)
428  else
430  }
431  break;
432  case T_SubscriptingRef:
433  {
434  SubscriptingRef *sr = (SubscriptingRef *) node;
435 
436  /* Assignment should not be in restrictions. */
437  if (sr->refassgnexpr != NULL)
438  return false;
439 
440  /*
441  * Recurse into the remaining subexpressions. The container
442  * subscripts will not affect collation of the SubscriptingRef
443  * result, so do those first and reset inner_cxt afterwards.
444  */
446  glob_cxt, &inner_cxt, case_arg_cxt))
447  return false;
448  inner_cxt.collation = InvalidOid;
449  inner_cxt.state = FDW_COLLATE_NONE;
451  glob_cxt, &inner_cxt, case_arg_cxt))
452  return false;
453  inner_cxt.collation = InvalidOid;
454  inner_cxt.state = FDW_COLLATE_NONE;
455  if (!foreign_expr_walker((Node *) sr->refexpr,
456  glob_cxt, &inner_cxt, case_arg_cxt))
457  return false;
458 
459  /*
460  * Container subscripting typically yields same collation as
461  * refexpr's, but in case it doesn't, use same logic as for
462  * function nodes.
463  */
464  collation = sr->refcollid;
465  if (collation == InvalidOid)
467  else if (inner_cxt.state == FDW_COLLATE_SAFE &&
468  collation == inner_cxt.collation)
470  else if (collation == DEFAULT_COLLATION_OID)
472  else
474  }
475  break;
476  case T_FuncExpr:
477  {
478  FuncExpr *fe = (FuncExpr *) node;
479 
480  /*
481  * If function used by the expression is not shippable, it
482  * can't be sent to remote because it might have incompatible
483  * semantics on remote side.
484  */
485  if (!is_shippable(fe->funcid, ProcedureRelationId, fpinfo))
486  return false;
487 
488  /*
489  * Recurse to input subexpressions.
490  */
491  if (!foreign_expr_walker((Node *) fe->args,
492  glob_cxt, &inner_cxt, case_arg_cxt))
493  return false;
494 
495  /*
496  * If function's input collation is not derived from a foreign
497  * Var, it can't be sent to remote.
498  */
499  if (fe->inputcollid == InvalidOid)
500  /* OK, inputs are all noncollatable */ ;
501  else if (inner_cxt.state != FDW_COLLATE_SAFE ||
502  fe->inputcollid != inner_cxt.collation)
503  return false;
504 
505  /*
506  * Detect whether node is introducing a collation not derived
507  * from a foreign Var. (If so, we just mark it unsafe for now
508  * rather than immediately returning false, since the parent
509  * node might not care.)
510  */
511  collation = fe->funccollid;
512  if (collation == InvalidOid)
514  else if (inner_cxt.state == FDW_COLLATE_SAFE &&
515  collation == inner_cxt.collation)
517  else if (collation == DEFAULT_COLLATION_OID)
519  else
521  }
522  break;
523  case T_OpExpr:
524  case T_DistinctExpr: /* struct-equivalent to OpExpr */
525  {
526  OpExpr *oe = (OpExpr *) node;
527 
528  /*
529  * Similarly, only shippable operators can be sent to remote.
530  * (If the operator is shippable, we assume its underlying
531  * function is too.)
532  */
533  if (!is_shippable(oe->opno, OperatorRelationId, fpinfo))
534  return false;
535 
536  /*
537  * Recurse to input subexpressions.
538  */
539  if (!foreign_expr_walker((Node *) oe->args,
540  glob_cxt, &inner_cxt, case_arg_cxt))
541  return false;
542 
543  /*
544  * If operator's input collation is not derived from a foreign
545  * Var, it can't be sent to remote.
546  */
547  if (oe->inputcollid == InvalidOid)
548  /* OK, inputs are all noncollatable */ ;
549  else if (inner_cxt.state != FDW_COLLATE_SAFE ||
550  oe->inputcollid != inner_cxt.collation)
551  return false;
552 
553  /* Result-collation handling is same as for functions */
554  collation = oe->opcollid;
555  if (collation == InvalidOid)
557  else if (inner_cxt.state == FDW_COLLATE_SAFE &&
558  collation == inner_cxt.collation)
560  else if (collation == DEFAULT_COLLATION_OID)
562  else
564  }
565  break;
566  case T_ScalarArrayOpExpr:
567  {
568  ScalarArrayOpExpr *oe = (ScalarArrayOpExpr *) node;
569 
570  /*
571  * Again, only shippable operators can be sent to remote.
572  */
573  if (!is_shippable(oe->opno, OperatorRelationId, fpinfo))
574  return false;
575 
576  /*
577  * Recurse to input subexpressions.
578  */
579  if (!foreign_expr_walker((Node *) oe->args,
580  glob_cxt, &inner_cxt, case_arg_cxt))
581  return false;
582 
583  /*
584  * If operator's input collation is not derived from a foreign
585  * Var, it can't be sent to remote.
586  */
587  if (oe->inputcollid == InvalidOid)
588  /* OK, inputs are all noncollatable */ ;
589  else if (inner_cxt.state != FDW_COLLATE_SAFE ||
590  oe->inputcollid != inner_cxt.collation)
591  return false;
592 
593  /* Output is always boolean and so noncollatable. */
594  collation = InvalidOid;
596  }
597  break;
598  case T_RelabelType:
599  {
600  RelabelType *r = (RelabelType *) node;
601 
602  /*
603  * Recurse to input subexpression.
604  */
605  if (!foreign_expr_walker((Node *) r->arg,
606  glob_cxt, &inner_cxt, case_arg_cxt))
607  return false;
608 
609  /*
610  * RelabelType must not introduce a collation not derived from
611  * an input foreign Var (same logic as for a real function).
612  */
613  collation = r->resultcollid;
614  if (collation == InvalidOid)
616  else if (inner_cxt.state == FDW_COLLATE_SAFE &&
617  collation == inner_cxt.collation)
619  else if (collation == DEFAULT_COLLATION_OID)
621  else
623  }
624  break;
625  case T_BoolExpr:
626  {
627  BoolExpr *b = (BoolExpr *) node;
628 
629  /*
630  * Recurse to input subexpressions.
631  */
632  if (!foreign_expr_walker((Node *) b->args,
633  glob_cxt, &inner_cxt, case_arg_cxt))
634  return false;
635 
636  /* Output is always boolean and so noncollatable. */
637  collation = InvalidOid;
639  }
640  break;
641  case T_NullTest:
642  {
643  NullTest *nt = (NullTest *) node;
644 
645  /*
646  * Recurse to input subexpressions.
647  */
648  if (!foreign_expr_walker((Node *) nt->arg,
649  glob_cxt, &inner_cxt, case_arg_cxt))
650  return false;
651 
652  /* Output is always boolean and so noncollatable. */
653  collation = InvalidOid;
655  }
656  break;
657  case T_CaseExpr:
658  {
659  CaseExpr *ce = (CaseExpr *) node;
660  foreign_loc_cxt arg_cxt;
661  foreign_loc_cxt tmp_cxt;
662  ListCell *lc;
663 
664  /*
665  * Recurse to CASE's arg expression, if any. Its collation
666  * has to be saved aside for use while examining CaseTestExprs
667  * within the WHEN expressions.
668  */
669  arg_cxt.collation = InvalidOid;
670  arg_cxt.state = FDW_COLLATE_NONE;
671  if (ce->arg)
672  {
673  if (!foreign_expr_walker((Node *) ce->arg,
674  glob_cxt, &arg_cxt, case_arg_cxt))
675  return false;
676  }
677 
678  /* Examine the CaseWhen subexpressions. */
679  foreach(lc, ce->args)
680  {
681  CaseWhen *cw = lfirst_node(CaseWhen, lc);
682 
683  if (ce->arg)
684  {
685  /*
686  * In a CASE-with-arg, the parser should have produced
687  * WHEN clauses of the form "CaseTestExpr = RHS",
688  * possibly with an implicit coercion inserted above
689  * the CaseTestExpr. However in an expression that's
690  * been through the optimizer, the WHEN clause could
691  * be almost anything (since the equality operator
692  * could have been expanded into an inline function).
693  * In such cases forbid pushdown, because
694  * deparseCaseExpr can't handle it.
695  */
696  Node *whenExpr = (Node *) cw->expr;
697  List *opArgs;
698 
699  if (!IsA(whenExpr, OpExpr))
700  return false;
701 
702  opArgs = ((OpExpr *) whenExpr)->args;
703  if (list_length(opArgs) != 2 ||
705  CaseTestExpr))
706  return false;
707  }
708 
709  /*
710  * Recurse to WHEN expression, passing down the arg info.
711  * Its collation doesn't affect the result (really, it
712  * should be boolean and thus not have a collation).
713  */
714  tmp_cxt.collation = InvalidOid;
715  tmp_cxt.state = FDW_COLLATE_NONE;
716  if (!foreign_expr_walker((Node *) cw->expr,
717  glob_cxt, &tmp_cxt, &arg_cxt))
718  return false;
719 
720  /* Recurse to THEN expression. */
721  if (!foreign_expr_walker((Node *) cw->result,
722  glob_cxt, &inner_cxt, case_arg_cxt))
723  return false;
724  }
725 
726  /* Recurse to ELSE expression. */
727  if (!foreign_expr_walker((Node *) ce->defresult,
728  glob_cxt, &inner_cxt, case_arg_cxt))
729  return false;
730 
731  /*
732  * Detect whether node is introducing a collation not derived
733  * from a foreign Var. (If so, we just mark it unsafe for now
734  * rather than immediately returning false, since the parent
735  * node might not care.) This is the same as for function
736  * nodes, except that the input collation is derived from only
737  * the THEN and ELSE subexpressions.
738  */
739  collation = ce->casecollid;
740  if (collation == InvalidOid)
742  else if (inner_cxt.state == FDW_COLLATE_SAFE &&
743  collation == inner_cxt.collation)
745  else if (collation == DEFAULT_COLLATION_OID)
747  else
749  }
750  break;
751  case T_CaseTestExpr:
752  {
753  CaseTestExpr *c = (CaseTestExpr *) node;
754 
755  /* Punt if we seem not to be inside a CASE arg WHEN. */
756  if (!case_arg_cxt)
757  return false;
758 
759  /*
760  * Otherwise, any nondefault collation attached to the
761  * CaseTestExpr node must be derived from foreign Var(s) in
762  * the CASE arg.
763  */
764  collation = c->collation;
765  if (collation == InvalidOid)
767  else if (case_arg_cxt->state == FDW_COLLATE_SAFE &&
768  collation == case_arg_cxt->collation)
770  else if (collation == DEFAULT_COLLATION_OID)
772  else
774  }
775  break;
776  case T_ArrayExpr:
777  {
778  ArrayExpr *a = (ArrayExpr *) node;
779 
780  /*
781  * Recurse to input subexpressions.
782  */
783  if (!foreign_expr_walker((Node *) a->elements,
784  glob_cxt, &inner_cxt, case_arg_cxt))
785  return false;
786 
787  /*
788  * ArrayExpr must not introduce a collation not derived from
789  * an input foreign Var (same logic as for a function).
790  */
791  collation = a->array_collid;
792  if (collation == InvalidOid)
794  else if (inner_cxt.state == FDW_COLLATE_SAFE &&
795  collation == inner_cxt.collation)
797  else if (collation == DEFAULT_COLLATION_OID)
799  else
801  }
802  break;
803  case T_List:
804  {
805  List *l = (List *) node;
806  ListCell *lc;
807 
808  /*
809  * Recurse to component subexpressions.
810  */
811  foreach(lc, l)
812  {
813  if (!foreign_expr_walker((Node *) lfirst(lc),
814  glob_cxt, &inner_cxt, case_arg_cxt))
815  return false;
816  }
817 
818  /*
819  * When processing a list, collation state just bubbles up
820  * from the list elements.
821  */
822  collation = inner_cxt.collation;
823  state = inner_cxt.state;
824 
825  /* Don't apply exprType() to the list. */
826  check_type = false;
827  }
828  break;
829  case T_Aggref:
830  {
831  Aggref *agg = (Aggref *) node;
832  ListCell *lc;
833 
834  /* Not safe to pushdown when not in grouping context */
835  if (!IS_UPPER_REL(glob_cxt->foreignrel))
836  return false;
837 
838  /* Only non-split aggregates are pushable. */
839  if (agg->aggsplit != AGGSPLIT_SIMPLE)
840  return false;
841 
842  /* As usual, it must be shippable. */
843  if (!is_shippable(agg->aggfnoid, ProcedureRelationId, fpinfo))
844  return false;
845 
846  /*
847  * Recurse to input args. aggdirectargs, aggorder and
848  * aggdistinct are all present in args, so no need to check
849  * their shippability explicitly.
850  */
851  foreach(lc, agg->args)
852  {
853  Node *n = (Node *) lfirst(lc);
854 
855  /* If TargetEntry, extract the expression from it */
856  if (IsA(n, TargetEntry))
857  {
858  TargetEntry *tle = (TargetEntry *) n;
859 
860  n = (Node *) tle->expr;
861  }
862 
863  if (!foreign_expr_walker(n,
864  glob_cxt, &inner_cxt, case_arg_cxt))
865  return false;
866  }
867 
868  /*
869  * For aggorder elements, check whether the sort operator, if
870  * specified, is shippable or not.
871  */
872  if (agg->aggorder)
873  {
874  ListCell *lc;
875 
876  foreach(lc, agg->aggorder)
877  {
878  SortGroupClause *srt = (SortGroupClause *) lfirst(lc);
879  Oid sortcoltype;
880  TypeCacheEntry *typentry;
881  TargetEntry *tle;
882 
884  agg->args);
885  sortcoltype = exprType((Node *) tle->expr);
886  typentry = lookup_type_cache(sortcoltype,
888  /* Check shippability of non-default sort operator. */
889  if (srt->sortop != typentry->lt_opr &&
890  srt->sortop != typentry->gt_opr &&
891  !is_shippable(srt->sortop, OperatorRelationId,
892  fpinfo))
893  return false;
894  }
895  }
896 
897  /* Check aggregate filter */
898  if (!foreign_expr_walker((Node *) agg->aggfilter,
899  glob_cxt, &inner_cxt, case_arg_cxt))
900  return false;
901 
902  /*
903  * If aggregate's input collation is not derived from a
904  * foreign Var, it can't be sent to remote.
905  */
906  if (agg->inputcollid == InvalidOid)
907  /* OK, inputs are all noncollatable */ ;
908  else if (inner_cxt.state != FDW_COLLATE_SAFE ||
909  agg->inputcollid != inner_cxt.collation)
910  return false;
911 
912  /*
913  * Detect whether node is introducing a collation not derived
914  * from a foreign Var. (If so, we just mark it unsafe for now
915  * rather than immediately returning false, since the parent
916  * node might not care.)
917  */
918  collation = agg->aggcollid;
919  if (collation == InvalidOid)
921  else if (inner_cxt.state == FDW_COLLATE_SAFE &&
922  collation == inner_cxt.collation)
924  else if (collation == DEFAULT_COLLATION_OID)
926  else
928  }
929  break;
930  default:
931 
932  /*
933  * If it's anything else, assume it's unsafe. This list can be
934  * expanded later, but don't forget to add deparse support below.
935  */
936  return false;
937  }
938 
939  /*
940  * If result type of given expression is not shippable, it can't be sent
941  * to remote because it might have incompatible semantics on remote side.
942  */
943  if (check_type && !is_shippable(exprType(node), TypeRelationId, fpinfo))
944  return false;
945 
946  /*
947  * Now, merge my collation information into my parent's state.
948  */
949  if (state > outer_cxt->state)
950  {
951  /* Override previous parent state */
952  outer_cxt->collation = collation;
953  outer_cxt->state = state;
954  }
955  else if (state == outer_cxt->state)
956  {
957  /* Merge, or detect error if there's a collation conflict */
958  switch (state)
959  {
960  case FDW_COLLATE_NONE:
961  /* Nothing + nothing is still nothing */
962  break;
963  case FDW_COLLATE_SAFE:
964  if (collation != outer_cxt->collation)
965  {
966  /*
967  * Non-default collation always beats default.
968  */
969  if (outer_cxt->collation == DEFAULT_COLLATION_OID)
970  {
971  /* Override previous parent state */
972  outer_cxt->collation = collation;
973  }
974  else if (collation != DEFAULT_COLLATION_OID)
975  {
976  /*
977  * Conflict; show state as indeterminate. We don't
978  * want to "return false" right away, since parent
979  * node might not care about collation.
980  */
981  outer_cxt->state = FDW_COLLATE_UNSAFE;
982  }
983  }
984  break;
985  case FDW_COLLATE_UNSAFE:
986  /* We're still conflicted ... */
987  break;
988  }
989  }
990 
991  /* It looks OK */
992  return true;
993 }
static bool foreign_expr_walker(Node *node, foreign_glob_cxt *glob_cxt, foreign_loc_cxt *outer_cxt, foreign_loc_cxt *case_arg_cxt)
Definition: deparse.c:305
int b
Definition: isn.c:70
int a
Definition: isn.c:69
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:678
@ T_List
Definition: nodes.h:317
@ T_CaseTestExpr
Definition: nodes.h:183
#define InvalidOid
Definition: postgres_ext.h:36
bool is_shippable(Oid objectId, Oid classId, PgFdwRelationInfo *fpinfo)
Definition: shippable.c:162
char * c
static int fe(enum e x)
Definition: preproc-init.c:111
@ PARAM_MULTIEXPR
Definition: primnodes.h:302
Oid inputcollid
Definition: primnodes.h:375
Oid aggcollid
Definition: primnodes.h:372
Oid casecollid
Definition: primnodes.h:1098
Oid constcollid
Definition: primnodes.h:258
Oid opcollid
Definition: primnodes.h:646
Oid inputcollid
Definition: primnodes.h:649
ParamKind paramkind
Definition: primnodes.h:308
Oid paramcollid
Definition: primnodes.h:312
Oid resultcollid
Definition: primnodes.h:984
Expr * refassgnexpr
Definition: primnodes.h:541
Oid varcollid
Definition: primnodes.h:228
RelOptInfo * foreignrel
Definition: deparse.c:68
Relids relids
Definition: deparse.c:69
FDWCollateState state
Definition: deparse.c:90
Definition: regguts.h:318

References a, Aggref::aggcollid, Aggref::aggfilter, Aggref::aggfnoid, Aggref::aggorder, Aggref::aggsplit, AGGSPLIT_SIMPLE, RelabelType::arg, CaseExpr::arg, NullTest::arg, Aggref::args, OpExpr::args, ScalarArrayOpExpr::args, CaseExpr::args, b, bms_is_member(), CaseExpr::casecollid, foreign_loc_cxt::collation, CaseExpr::defresult, CaseWhen::expr, TargetEntry::expr, exprType(), FDW_COLLATE_NONE, FDW_COLLATE_SAFE, FDW_COLLATE_UNSAFE, RelOptInfo::fdw_private, fe(), foreign_glob_cxt::foreignrel, get_sortgroupref_tle(), TypeCacheEntry::gt_opr, if(), Aggref::inputcollid, OpExpr::inputcollid, ScalarArrayOpExpr::inputcollid, InvalidOid, is_shippable(), IS_UPPER_REL, IsA, lfirst, lfirst_node, linitial, list_length(), lookup_type_cache(), TypeCacheEntry::lt_opr, nodeTag, OidIsValid, OpExpr::opcollid, OpExpr::opno, ScalarArrayOpExpr::opno, PARAM_MULTIEXPR, Param::paramcollid, Param::paramkind, SubscriptingRef::refassgnexpr, SubscriptingRef::refcollid, SubscriptingRef::refexpr, SubscriptingRef::reflowerindexpr, SubscriptingRef::refupperindexpr, foreign_glob_cxt::relids, CaseWhen::result, RelabelType::resultcollid, SelfItemPointerAttributeNumber, SortGroupClause::sortop, foreign_loc_cxt::state, strip_implicit_coercions(), T_Aggref, T_ArrayExpr, T_BoolExpr, T_CaseExpr, T_CaseTestExpr, T_Const, T_DistinctExpr, T_FuncExpr, T_List, T_NullTest, T_OpExpr, T_Param, T_RelabelType, T_ScalarArrayOpExpr, T_SubscriptingRef, T_Var, SortGroupClause::tleSortGroupRef, TYPECACHE_GT_OPR, TYPECACHE_LT_OPR, Var::varattno, Var::varcollid, Var::varlevelsup, and Var::varno.

Referenced by is_foreign_expr().

◆ get_jointype_name()

const char* get_jointype_name ( JoinType  jointype)

Definition at line 1533 of file deparse.c.

1534 {
1535  switch (jointype)
1536  {
1537  case JOIN_INNER:
1538  return "INNER";
1539 
1540  case JOIN_LEFT:
1541  return "LEFT";
1542 
1543  case JOIN_RIGHT:
1544  return "RIGHT";
1545 
1546  case JOIN_FULL:
1547  return "FULL";
1548 
1549  default:
1550  /* Shouldn't come here, but protect from buggy code. */
1551  elog(ERROR, "unsupported join type %d", jointype);
1552  }
1553 
1554  /* Keep compiler happy */
1555  return NULL;
1556 }
@ JOIN_FULL
Definition: nodes.h:752
@ JOIN_RIGHT
Definition: nodes.h:753
@ JOIN_LEFT
Definition: nodes.h:751

References elog(), ERROR, JOIN_FULL, JOIN_INNER, JOIN_LEFT, and JOIN_RIGHT.

Referenced by deparseFromExprForRel(), and foreign_join_ok().

◆ get_relation_column_alias_ids()

static void get_relation_column_alias_ids ( Var node,
RelOptInfo foreignrel,
int *  relno,
int *  colno 
)
static

Definition at line 3869 of file deparse.c.

3871 {
3872  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
3873  int i;
3874  ListCell *lc;
3875 
3876  /* Get the relation alias ID */
3877  *relno = fpinfo->relation_index;
3878 
3879  /* Get the column alias ID */
3880  i = 1;
3881  foreach(lc, foreignrel->reltarget->exprs)
3882  {
3883  if (equal(lfirst(lc), (Node *) node))
3884  {
3885  *colno = i;
3886  return;
3887  }
3888  i++;
3889  }
3890 
3891  /* Shouldn't get here */
3892  elog(ERROR, "unexpected expression in subquery output");
3893 }

References elog(), equal(), ERROR, PathTarget::exprs, RelOptInfo::fdw_private, i, lfirst, PgFdwRelationInfo::relation_index, and RelOptInfo::reltarget.

Referenced by is_subquery_var().

◆ is_foreign_expr()

bool is_foreign_expr ( PlannerInfo root,
RelOptInfo baserel,
Expr expr 
)

Definition at line 237 of file deparse.c.

240 {
241  foreign_glob_cxt glob_cxt;
242  foreign_loc_cxt loc_cxt;
243  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private);
244 
245  /*
246  * Check that the expression consists of nodes that are safe to execute
247  * remotely.
248  */
249  glob_cxt.root = root;
250  glob_cxt.foreignrel = baserel;
251 
252  /*
253  * For an upper relation, use relids from its underneath scan relation,
254  * because the upperrel's own relids currently aren't set to anything
255  * meaningful by the core code. For other relation, use their own relids.
256  */
257  if (IS_UPPER_REL(baserel))
258  glob_cxt.relids = fpinfo->outerrel->relids;
259  else
260  glob_cxt.relids = baserel->relids;
261  loc_cxt.collation = InvalidOid;
262  loc_cxt.state = FDW_COLLATE_NONE;
263  if (!foreign_expr_walker((Node *) expr, &glob_cxt, &loc_cxt, NULL))
264  return false;
265 
266  /*
267  * If the expression has a valid collation that does not arise from a
268  * foreign var, the expression can not be sent over.
269  */
270  if (loc_cxt.state == FDW_COLLATE_UNSAFE)
271  return false;
272 
273  /*
274  * An expression which includes any mutable functions can't be sent over
275  * because its result is not stable. For example, sending now() remote
276  * side could cause confusion from clock offsets. Future versions might
277  * be able to make this choice with more granularity. (We check this last
278  * because it requires a lot of expensive catalog lookups.)
279  */
280  if (contain_mutable_functions((Node *) expr))
281  return false;
282 
283  /* OK to evaluate on the remote server */
284  return true;
285 }
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:368
PlannerInfo * root
Definition: deparse.c:67

References foreign_loc_cxt::collation, contain_mutable_functions(), FDW_COLLATE_NONE, FDW_COLLATE_UNSAFE, RelOptInfo::fdw_private, foreign_expr_walker(), foreign_glob_cxt::foreignrel, if(), InvalidOid, IS_UPPER_REL, PgFdwRelationInfo::outerrel, foreign_glob_cxt::relids, RelOptInfo::relids, foreign_glob_cxt::root, and foreign_loc_cxt::state.

Referenced by add_foreign_final_paths(), classifyConditions(), find_em_for_rel(), find_em_for_rel_target(), foreign_grouping_ok(), foreign_join_ok(), postgresGetForeignPaths(), postgresGetForeignPlan(), and postgresPlanDirectModify().

◆ is_foreign_param()

bool is_foreign_param ( PlannerInfo root,
RelOptInfo baserel,
Expr expr 
)

Definition at line 1008 of file deparse.c.

1011 {
1012  if (expr == NULL)
1013  return false;
1014 
1015  switch (nodeTag(expr))
1016  {
1017  case T_Var:
1018  {
1019  /* It would have to be sent unless it's a foreign Var */
1020  Var *var = (Var *) expr;
1021  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private);
1022  Relids relids;
1023 
1024  if (IS_UPPER_REL(baserel))
1025  relids = fpinfo->outerrel->relids;
1026  else
1027  relids = baserel->relids;
1028 
1029  if (bms_is_member(var->varno, relids) && var->varlevelsup == 0)
1030  return false; /* foreign Var, so not a param */
1031  else
1032  return true; /* it'd have to be a param */
1033  break;
1034  }
1035  case T_Param:
1036  /* Params always have to be sent to the foreign server */
1037  return true;
1038  default:
1039  break;
1040  }
1041  return false;
1042 }

References bms_is_member(), RelOptInfo::fdw_private, if(), IS_UPPER_REL, nodeTag, PgFdwRelationInfo::outerrel, RelOptInfo::relids, T_Param, T_Var, Var::varlevelsup, and Var::varno.

Referenced by foreign_grouping_ok().

◆ is_foreign_pathkey()

bool is_foreign_pathkey ( PlannerInfo root,
RelOptInfo baserel,
PathKey pathkey 
)

Definition at line 1049 of file deparse.c.

1052 {
1053  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
1054  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) baserel->fdw_private;
1055 
1056  /*
1057  * is_foreign_expr would detect volatile expressions as well, but checking
1058  * ec_has_volatile here saves some cycles.
1059  */
1060  if (pathkey_ec->ec_has_volatile)
1061  return false;
1062 
1063  /* can't push down the sort if the pathkey's opfamily is not shippable */
1064  if (!is_shippable(pathkey->pk_opfamily, OperatorFamilyRelationId, fpinfo))
1065  return false;
1066 
1067  /* can push if a suitable EC member exists */
1068  return (find_em_for_rel(root, pathkey_ec, baserel) != NULL);
1069 }

References EquivalenceClass::ec_has_volatile, RelOptInfo::fdw_private, find_em_for_rel(), if(), is_shippable(), PathKey::pk_eclass, and PathKey::pk_opfamily.

Referenced by get_useful_pathkeys_for_relation().

◆ is_subquery_var()

static bool is_subquery_var ( Var node,
RelOptInfo foreignrel,
int *  relno,
int *  colno 
)
static

Definition at line 3807 of file deparse.c.

3808 {
3809  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
3810  RelOptInfo *outerrel = fpinfo->outerrel;
3811  RelOptInfo *innerrel = fpinfo->innerrel;
3812 
3813  /* Should only be called in these cases. */
3814  Assert(IS_SIMPLE_REL(foreignrel) || IS_JOIN_REL(foreignrel));
3815 
3816  /*
3817  * If the given relation isn't a join relation, it doesn't have any lower
3818  * subqueries, so the Var isn't a subquery output column.
3819  */
3820  if (!IS_JOIN_REL(foreignrel))
3821  return false;
3822 
3823  /*
3824  * If the Var doesn't belong to any lower subqueries, it isn't a subquery
3825  * output column.
3826  */
3827  if (!bms_is_member(node->varno, fpinfo->lower_subquery_rels))
3828  return false;
3829 
3830  if (bms_is_member(node->varno, outerrel->relids))
3831  {
3832  /*
3833  * If outer relation is deparsed as a subquery, the Var is an output
3834  * column of the subquery; get the IDs for the relation/column alias.
3835  */
3836  if (fpinfo->make_outerrel_subquery)
3837  {
3838  get_relation_column_alias_ids(node, outerrel, relno, colno);
3839  return true;
3840  }
3841 
3842  /* Otherwise, recurse into the outer relation. */
3843  return is_subquery_var(node, outerrel, relno, colno);
3844  }
3845  else
3846  {
3847  Assert(bms_is_member(node->varno, innerrel->relids));
3848 
3849  /*
3850  * If inner relation is deparsed as a subquery, the Var is an output
3851  * column of the subquery; get the IDs for the relation/column alias.
3852  */
3853  if (fpinfo->make_innerrel_subquery)
3854  {
3855  get_relation_column_alias_ids(node, innerrel, relno, colno);
3856  return true;
3857  }
3858 
3859  /* Otherwise, recurse into the inner relation. */
3860  return is_subquery_var(node, innerrel, relno, colno);
3861  }
3862 }
static void get_relation_column_alias_ids(Var *node, RelOptInfo *foreignrel, int *relno, int *colno)
Definition: deparse.c:3869

References Assert(), bms_is_member(), RelOptInfo::fdw_private, get_relation_column_alias_ids(), PgFdwRelationInfo::innerrel, IS_JOIN_REL, IS_SIMPLE_REL, PgFdwRelationInfo::lower_subquery_rels, PgFdwRelationInfo::make_innerrel_subquery, PgFdwRelationInfo::make_outerrel_subquery, PgFdwRelationInfo::outerrel, and Var::varno.

Referenced by deparseVar().

◆ isPlainForeignVar()

static bool isPlainForeignVar ( Expr node,
deparse_expr_cxt context 
)
static

Definition at line 3090 of file deparse.c.

3091 {
3092  /*
3093  * We allow the foreign Var to have an implicit RelabelType, mainly so
3094  * that this'll work with varchar columns. Note that deparseRelabelType
3095  * will not print such a cast, so we're not breaking the restriction that
3096  * the expression print as a plain Var. We won't risk it for an implicit
3097  * cast that requires a function, nor for non-implicit RelabelType; such
3098  * cases seem too likely to involve semantics changes compared to what
3099  * would happen on the remote side.
3100  */
3101  if (IsA(node, RelabelType) &&
3102  ((RelabelType *) node)->relabelformat == COERCE_IMPLICIT_CAST)
3103  node = ((RelabelType *) node)->arg;
3104 
3105  if (IsA(node, Var))
3106  {
3107  /*
3108  * The Var must be one that'll deparse as a foreign column reference
3109  * (cf. deparseVar).
3110  */
3111  Var *var = (Var *) node;
3112  Relids relids = context->scanrel->relids;
3113 
3114  if (bms_is_member(var->varno, relids) && var->varlevelsup == 0)
3115  return true;
3116  }
3117 
3118  return false;
3119 }

References bms_is_member(), COERCE_IMPLICIT_CAST, IsA, RelOptInfo::relids, deparse_expr_cxt::scanrel, Var::varlevelsup, and Var::varno.

Referenced by deparseOpExpr().

◆ printRemoteParam()

static void printRemoteParam ( int  paramindex,
Oid  paramtype,
int32  paramtypmod,
deparse_expr_cxt context 
)
static

Definition at line 3542 of file deparse.c.

3544 {
3545  StringInfo buf = context->buf;
3546  char *ptypename = deparse_type_name(paramtype, paramtypmod);
3547 
3548  appendStringInfo(buf, "$%d::%s", paramindex, ptypename);
3549 }

References appendStringInfo(), deparse_expr_cxt::buf, buf, and deparse_type_name().

Referenced by deparseParam(), and deparseVar().

◆ printRemotePlaceholder()

static void printRemotePlaceholder ( Oid  paramtype,
int32  paramtypmod,
deparse_expr_cxt context 
)
static

Definition at line 3568 of file deparse.c.

3570 {
3571  StringInfo buf = context->buf;
3572  char *ptypename = deparse_type_name(paramtype, paramtypmod);
3573 
3574  appendStringInfo(buf, "((SELECT null::%s)::%s)", ptypename, ptypename);
3575 }

References appendStringInfo(), deparse_expr_cxt::buf, buf, and deparse_type_name().

Referenced by deparseParam(), and deparseVar().

◆ rebuildInsertSql()

void rebuildInsertSql ( StringInfo  buf,
Relation  rel,
char *  orig_query,
List target_attrs,
int  values_end_len,
int  num_params,
int  num_rows 
)

Definition at line 1945 of file deparse.c.

1949 {
1950  TupleDesc tupdesc = RelationGetDescr(rel);
1951  int i;
1952  int pindex;
1953  bool first;
1954  ListCell *lc;
1955 
1956  /* Make sure the values_end_len is sensible */
1957  Assert((values_end_len > 0) && (values_end_len <= strlen(orig_query)));
1958 
1959  /* Copy up to the end of the first record from the original query */
1960  appendBinaryStringInfo(buf, orig_query, values_end_len);
1961 
1962  /*
1963  * Add records to VALUES clause (we already have parameters for the first
1964  * row, so start at the right offset).
1965  */
1966  pindex = num_params + 1;
1967  for (i = 0; i < num_rows; i++)
1968  {
1969  appendStringInfoString(buf, ", (");
1970 
1971  first = true;
1972  foreach(lc, target_attrs)
1973  {
1974  int attnum = lfirst_int(lc);
1975  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
1976 
1977  if (!first)
1978  appendStringInfoString(buf, ", ");
1979  first = false;
1980 
1981  if (attr->attgenerated)
1982  appendStringInfoString(buf, "DEFAULT");
1983  else
1984  {
1985  appendStringInfo(buf, "$%d", pindex);
1986  pindex++;
1987  }
1988  }
1989 
1990  appendStringInfoChar(buf, ')');
1991  }
1992 
1993  /* Copy stuff after VALUES clause from the original query */
1994  appendStringInfoString(buf, orig_query + values_end_len);
1995 }

References appendBinaryStringInfo(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert(), attnum, buf, i, lfirst_int, RelationGetDescr, and TupleDescAttr.

Referenced by execute_foreign_modify().