PostgreSQL Source Code  git master
parse_clause.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/nbtree.h"
#include "access/table.h"
#include "access/tsmapi.h"
#include "catalog/catalog.h"
#include "catalog/heap.h"
#include "catalog/pg_am.h"
#include "catalog/pg_amproc.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/analyze.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parser.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/syscache.h"
Include dependency graph for parse_clause.c:

Go to the source code of this file.

Macros

#define makeDefaultNSItem(rte)   makeNamespaceItem(rte, true, true, false, true)
 

Functions

static void extractRemainingColumns (List *common_colnames, List *src_colnames, List *src_colvars, List **res_colnames, List **res_colvars)
 
static NodetransformJoinUsingClause (ParseState *pstate, RangeTblEntry *leftRTE, RangeTblEntry *rightRTE, List *leftVars, List *rightVars)
 
static NodetransformJoinOnClause (ParseState *pstate, JoinExpr *j, List *namespace)
 
static RangeTblEntrygetRTEForSpecialRelationTypes (ParseState *pstate, RangeVar *rv)
 
static RangeTblEntrytransformTableEntry (ParseState *pstate, RangeVar *r)
 
static RangeTblEntrytransformRangeSubselect (ParseState *pstate, RangeSubselect *r)
 
static RangeTblEntrytransformRangeFunction (ParseState *pstate, RangeFunction *r)
 
static RangeTblEntrytransformRangeTableFunc (ParseState *pstate, RangeTableFunc *t)
 
static TableSampleClausetransformRangeTableSample (ParseState *pstate, RangeTableSample *rts)
 
static NodetransformFromClauseItem (ParseState *pstate, Node *n, RangeTblEntry **top_rte, int *top_rti, List **namespace)
 
static NodebuildMergedJoinVar (ParseState *pstate, JoinType jointype, Var *l_colvar, Var *r_colvar)
 
static ParseNamespaceItemmakeNamespaceItem (RangeTblEntry *rte, bool rel_visible, bool cols_visible, bool lateral_only, bool lateral_ok)
 
static void setNamespaceColumnVisibility (List *namespace, bool cols_visible)
 
static void setNamespaceLateralState (List *namespace, bool lateral_only, bool lateral_ok)
 
static void checkExprIsVarFree (ParseState *pstate, Node *n, const char *constructName)
 
static TargetEntryfindTargetlistEntrySQL92 (ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
 
static TargetEntryfindTargetlistEntrySQL99 (ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
 
static int get_matching_location (int sortgroupref, List *sortgrouprefs, List *exprs)
 
static Listresolve_unique_index_expr (ParseState *pstate, InferClause *infer, Relation heapRel)
 
static ListaddTargetToGroupList (ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
 
static WindowClausefindWindowClause (List *wclist, const char *name)
 
static NodetransformFrameOffset (ParseState *pstate, int frameOptions, Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc, Node *clause)
 
void transformFromClause (ParseState *pstate, List *frmList)
 
int setTargetTable (ParseState *pstate, RangeVar *relation, bool inh, bool alsoSource, AclMode requiredPerms)
 
NodetransformWhereClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
 
NodetransformLimitClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
 
static void checkTargetlistEntrySQL92 (ParseState *pstate, TargetEntry *tle, ParseExprKind exprKind)
 
static Nodeflatten_grouping_sets (Node *expr, bool toplevel, bool *hasGroupingSets)
 
static Index transformGroupClauseExpr (List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
 
static ListtransformGroupClauseList (List **flatresult, ParseState *pstate, List *list, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
 
static NodetransformGroupingSet (List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
 
ListtransformGroupClause (ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
 
ListtransformSortClause (ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
 
ListtransformWindowDefinitions (ParseState *pstate, List *windowdefs, List **targetlist)
 
ListtransformDistinctClause (ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
 
ListtransformDistinctOnClause (ParseState *pstate, List *distinctlist, List **targetlist, List *sortClause)
 
void transformOnConflictArbiter (ParseState *pstate, OnConflictClause *onConflictClause, List **arbiterExpr, Node **arbiterWhere, Oid *constraint)
 
ListaddTargetToSortList (ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
 
Index assignSortGroupRef (TargetEntry *tle, List *tlist)
 
bool targetIsInSortList (TargetEntry *tle, Oid sortop, List *sortList)
 

Macro Definition Documentation

◆ makeDefaultNSItem

#define makeDefaultNSItem (   rte)    makeNamespaceItem(rte, true, true, false, true)

Definition at line 55 of file parse_clause.c.

Function Documentation

◆ addTargetToGroupList()

static List * addTargetToGroupList ( ParseState pstate,
TargetEntry tle,
List grouplist,
List targetlist,
int  location 
)
static

Definition at line 3360 of file parse_clause.c.

References assignSortGroupRef(), cancel_parser_errposition_callback(), COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, SortGroupClause::eqop, TargetEntry::expr, exprType(), get_sort_group_operators(), SortGroupClause::hashable, InvalidOid, lappend(), makeNode, SortGroupClause::nulls_first, setup_parser_errposition_callback(), SortGroupClause::sortop, targetIsInSortList(), and SortGroupClause::tleSortGroupRef.

Referenced by transformDistinctClause(), transformDistinctOnClause(), and transformGroupClauseExpr().

3362 {
3363  Oid restype = exprType((Node *) tle->expr);
3364 
3365  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3366  if (restype == UNKNOWNOID)
3367  {
3368  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3369  restype, TEXTOID, -1,
3372  -1);
3373  restype = TEXTOID;
3374  }
3375 
3376  /* avoid making duplicate grouplist entries */
3377  if (!targetIsInSortList(tle, InvalidOid, grouplist))
3378  {
3380  Oid sortop;
3381  Oid eqop;
3382  bool hashable;
3383  ParseCallbackState pcbstate;
3384 
3385  setup_parser_errposition_callback(&pcbstate, pstate, location);
3386 
3387  /* determine the eqop and optional sortop */
3388  get_sort_group_operators(restype,
3389  false, true, false,
3390  &sortop, &eqop, NULL,
3391  &hashable);
3392 
3394 
3395  grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3396  grpcl->eqop = eqop;
3397  grpcl->sortop = sortop;
3398  grpcl->nulls_first = false; /* OK with or without sortop */
3399  grpcl->hashable = hashable;
3400 
3401  grouplist = lappend(grouplist, grpcl);
3402  }
3403 
3404  return grouplist;
3405 }
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
Index tleSortGroupRef
Definition: parsenodes.h:1234
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:525
unsigned int Oid
Definition: postgres_ext.h:31
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
List * lappend(List *list, void *datum)
Definition: list.c:322
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define makeNode(_type_)
Definition: nodes.h:573
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:187
Expr * expr
Definition: primnodes.h:1393
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41

◆ addTargetToSortList()

List* addTargetToSortList ( ParseState pstate,
TargetEntry tle,
List sortlist,
List targetlist,
SortBy sortby 
)

Definition at line 3217 of file parse_clause.c.

References Assert, assignSortGroupRef(), cancel_parser_errposition_callback(), COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, compatible_oper_opid(), elog, SortGroupClause::eqop, ereport, errcode(), errhint(), errmsg(), ERROR, TargetEntry::expr, exprLocation(), exprType(), get_equality_op_for_ordering_op(), get_sort_group_operators(), SortGroupClause::hashable, InvalidOid, lappend(), llast, SortBy::location, makeNode, NIL, SortBy::node, SortGroupClause::nulls_first, OidIsValid, op_hashjoinable(), setup_parser_errposition_callback(), SORTBY_ASC, SORTBY_DEFAULT, SORTBY_DESC, SortBy::sortby_dir, SortBy::sortby_nulls, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, SORTBY_USING, SortGroupClause::sortop, strVal, targetIsInSortList(), SortGroupClause::tleSortGroupRef, and SortBy::useOp.

Referenced by transformAggregateCall(), and transformSortClause().

3219 {
3220  Oid restype = exprType((Node *) tle->expr);
3221  Oid sortop;
3222  Oid eqop;
3223  bool hashable;
3224  bool reverse;
3225  int location;
3226  ParseCallbackState pcbstate;
3227 
3228  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3229  if (restype == UNKNOWNOID)
3230  {
3231  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3232  restype, TEXTOID, -1,
3235  -1);
3236  restype = TEXTOID;
3237  }
3238 
3239  /*
3240  * Rather than clutter the API of get_sort_group_operators and the other
3241  * functions we're about to use, make use of error context callback to
3242  * mark any error reports with a parse position. We point to the operator
3243  * location if present, else to the expression being sorted. (NB: use the
3244  * original untransformed expression here; the TLE entry might well point
3245  * at a duplicate expression in the regular SELECT list.)
3246  */
3247  location = sortby->location;
3248  if (location < 0)
3249  location = exprLocation(sortby->node);
3250  setup_parser_errposition_callback(&pcbstate, pstate, location);
3251 
3252  /* determine the sortop, eqop, and directionality */
3253  switch (sortby->sortby_dir)
3254  {
3255  case SORTBY_DEFAULT:
3256  case SORTBY_ASC:
3257  get_sort_group_operators(restype,
3258  true, true, false,
3259  &sortop, &eqop, NULL,
3260  &hashable);
3261  reverse = false;
3262  break;
3263  case SORTBY_DESC:
3264  get_sort_group_operators(restype,
3265  false, true, true,
3266  NULL, &eqop, &sortop,
3267  &hashable);
3268  reverse = true;
3269  break;
3270  case SORTBY_USING:
3271  Assert(sortby->useOp != NIL);
3272  sortop = compatible_oper_opid(sortby->useOp,
3273  restype,
3274  restype,
3275  false);
3276 
3277  /*
3278  * Verify it's a valid ordering operator, fetch the corresponding
3279  * equality operator, and determine whether to consider it like
3280  * ASC or DESC.
3281  */
3282  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3283  if (!OidIsValid(eqop))
3284  ereport(ERROR,
3285  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3286  errmsg("operator %s is not a valid ordering operator",
3287  strVal(llast(sortby->useOp))),
3288  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3289 
3290  /*
3291  * Also see if the equality operator is hashable.
3292  */
3293  hashable = op_hashjoinable(eqop, restype);
3294  break;
3295  default:
3296  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3297  sortop = InvalidOid; /* keep compiler quiet */
3298  eqop = InvalidOid;
3299  hashable = false;
3300  reverse = false;
3301  break;
3302  }
3303 
3305 
3306  /* avoid making duplicate sortlist entries */
3307  if (!targetIsInSortList(tle, sortop, sortlist))
3308  {
3310 
3311  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3312 
3313  sortcl->eqop = eqop;
3314  sortcl->sortop = sortop;
3315  sortcl->hashable = hashable;
3316 
3317  switch (sortby->sortby_nulls)
3318  {
3319  case SORTBY_NULLS_DEFAULT:
3320  /* NULLS FIRST is default for DESC; other way for ASC */
3321  sortcl->nulls_first = reverse;
3322  break;
3323  case SORTBY_NULLS_FIRST:
3324  sortcl->nulls_first = true;
3325  break;
3326  case SORTBY_NULLS_LAST:
3327  sortcl->nulls_first = false;
3328  break;
3329  default:
3330  elog(ERROR, "unrecognized sortby_nulls: %d",
3331  sortby->sortby_nulls);
3332  break;
3333  }
3334 
3335  sortlist = lappend(sortlist, sortcl);
3336  }
3337 
3338  return sortlist;
3339 }
#define NIL
Definition: pg_list.h:65
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
int errhint(const char *fmt,...)
Definition: elog.c:1069
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
SortByDir sortby_dir
Definition: parsenodes.h:470
List * useOp
Definition: parsenodes.h:472
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:264
#define llast(l)
Definition: pg_list.h:215
Index tleSortGroupRef
Definition: parsenodes.h:1234
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1244
#define ERROR
Definition: elog.h:43
SortByNulls sortby_nulls
Definition: parsenodes.h:471
#define ereport(elevel, rest)
Definition: elog.h:141
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
List * lappend(List *list, void *datum)
Definition: list.c:322
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define makeNode(_type_)
Definition: nodes.h:573
#define Assert(condition)
Definition: c.h:739
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:187
Expr * expr
Definition: primnodes.h:1393
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int errmsg(const char *fmt,...)
Definition: elog.c:822
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:494
#define elog(elevel,...)
Definition: elog.h:228
Node * node
Definition: parsenodes.h:469
int location
Definition: parsenodes.h:473

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3415 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

Referenced by addTargetToGroupList(), addTargetToSortList(), build_minmax_path(), create_unique_plan(), and transformDistinctOnClause().

3416 {
3417  Index maxRef;
3418  ListCell *l;
3419 
3420  if (tle->ressortgroupref) /* already has one? */
3421  return tle->ressortgroupref;
3422 
3423  /* easiest way to pick an unused refnumber: max used + 1 */
3424  maxRef = 0;
3425  foreach(l, tlist)
3426  {
3427  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3428 
3429  if (ref > maxRef)
3430  maxRef = ref;
3431  }
3432  tle->ressortgroupref = maxRef + 1;
3433  return tle->ressortgroupref;
3434 }
unsigned int Index
Definition: c.h:476
#define lfirst(lc)
Definition: pg_list.h:190
Index ressortgroupref
Definition: primnodes.h:1396

◆ buildMergedJoinVar()

static Node * buildMergedJoinVar ( ParseState pstate,
JoinType  jointype,
Var l_colvar,
Var r_colvar 
)
static

Definition at line 1501 of file parse_clause.c.

References CoalesceExpr::args, assign_expr_collations(), CoalesceExpr::coalescetype, COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, elog, ERROR, InvalidOid, IsA, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, list_make2, CoalesceExpr::location, makeNode, makeRelabelType(), select_common_type(), Var::vartype, and Var::vartypmod.

Referenced by transformFromClauseItem().

1503 {
1504  Oid outcoltype;
1505  int32 outcoltypmod;
1506  Node *l_node,
1507  *r_node,
1508  *res_node;
1509 
1510  /*
1511  * Choose output type if input types are dissimilar.
1512  */
1513  outcoltype = l_colvar->vartype;
1514  outcoltypmod = l_colvar->vartypmod;
1515  if (outcoltype != r_colvar->vartype)
1516  {
1517  outcoltype = select_common_type(pstate,
1518  list_make2(l_colvar, r_colvar),
1519  "JOIN/USING",
1520  NULL);
1521  outcoltypmod = -1; /* ie, unknown */
1522  }
1523  else if (outcoltypmod != r_colvar->vartypmod)
1524  {
1525  /* same type, but not same typmod */
1526  outcoltypmod = -1; /* ie, unknown */
1527  }
1528 
1529  /*
1530  * Insert coercion functions if needed. Note that a difference in typmod
1531  * can only happen if input has typmod but outcoltypmod is -1. In that
1532  * case we insert a RelabelType to clearly mark that result's typmod is
1533  * not same as input. We never need coerce_type_typmod.
1534  */
1535  if (l_colvar->vartype != outcoltype)
1536  l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
1537  outcoltype, outcoltypmod,
1539  else if (l_colvar->vartypmod != outcoltypmod)
1540  l_node = (Node *) makeRelabelType((Expr *) l_colvar,
1541  outcoltype, outcoltypmod,
1542  InvalidOid, /* fixed below */
1544  else
1545  l_node = (Node *) l_colvar;
1546 
1547  if (r_colvar->vartype != outcoltype)
1548  r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
1549  outcoltype, outcoltypmod,
1551  else if (r_colvar->vartypmod != outcoltypmod)
1552  r_node = (Node *) makeRelabelType((Expr *) r_colvar,
1553  outcoltype, outcoltypmod,
1554  InvalidOid, /* fixed below */
1556  else
1557  r_node = (Node *) r_colvar;
1558 
1559  /*
1560  * Choose what to emit
1561  */
1562  switch (jointype)
1563  {
1564  case JOIN_INNER:
1565 
1566  /*
1567  * We can use either var; prefer non-coerced one if available.
1568  */
1569  if (IsA(l_node, Var))
1570  res_node = l_node;
1571  else if (IsA(r_node, Var))
1572  res_node = r_node;
1573  else
1574  res_node = l_node;
1575  break;
1576  case JOIN_LEFT:
1577  /* Always use left var */
1578  res_node = l_node;
1579  break;
1580  case JOIN_RIGHT:
1581  /* Always use right var */
1582  res_node = r_node;
1583  break;
1584  case JOIN_FULL:
1585  {
1586  /*
1587  * Here we must build a COALESCE expression to ensure that the
1588  * join output is non-null if either input is.
1589  */
1591 
1592  c->coalescetype = outcoltype;
1593  /* coalescecollid will get set below */
1594  c->args = list_make2(l_node, r_node);
1595  c->location = -1;
1596  res_node = (Node *) c;
1597  break;
1598  }
1599  default:
1600  elog(ERROR, "unrecognized join type: %d", (int) jointype);
1601  res_node = NULL; /* keep compiler quiet */
1602  break;
1603  }
1604 
1605  /*
1606  * Apply assign_expr_collations to fix up the collation info in the
1607  * coercion and CoalesceExpr nodes, if we made any. This must be done now
1608  * so that the join node's alias vars show correct collation info.
1609  */
1610  assign_expr_collations(pstate, res_node);
1611 
1612  return res_node;
1613 }
#define list_make2(x1, x2)
Definition: pg_list.h:229
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:525
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:167
signed int int32
Definition: c.h:347
void assign_expr_collations(ParseState *pstate, Node *expr)
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:174
List * args
Definition: primnodes.h:1072
char * c
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:400
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:573
#define elog(elevel,...)
Definition: elog.h:228
Oid coalescetype
Definition: primnodes.h:1070
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
int32 vartypmod
Definition: primnodes.h:175

◆ checkExprIsVarFree()

static void checkExprIsVarFree ( ParseState pstate,
Node n,
const char *  constructName 
)
static

Definition at line 1736 of file parse_clause.c.

References contain_vars_of_level(), ereport, errcode(), errmsg(), ERROR, locate_var_of_level(), and parser_errposition().

Referenced by transformFrameOffset(), and transformLimitClause().

1737 {
1738  if (contain_vars_of_level(n, 0))
1739  {
1740  ereport(ERROR,
1741  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1742  /* translator: %s is name of a SQL construct, eg LIMIT */
1743  errmsg("argument of %s must not contain variables",
1744  constructName),
1745  parser_errposition(pstate,
1746  locate_var_of_level(n, 0))));
1747  }
1748 }
int errcode(int sqlerrcode)
Definition: elog.c:608
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:437
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:369
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ checkTargetlistEntrySQL92()

static void checkTargetlistEntrySQL92 ( ParseState pstate,
TargetEntry tle,
ParseExprKind  exprKind 
)
static

Definition at line 1761 of file parse_clause.c.

References contain_aggs_of_level(), contain_windowfuncs(), elog, ereport, errcode(), errmsg(), ERROR, TargetEntry::expr, EXPR_KIND_DISTINCT_ON, EXPR_KIND_GROUP_BY, EXPR_KIND_ORDER_BY, locate_agg_of_level(), locate_windowfunc(), ParseState::p_hasAggs, ParseState::p_hasWindowFuncs, ParseExprKindName(), and parser_errposition().

Referenced by findTargetlistEntrySQL92().

1763 {
1764  switch (exprKind)
1765  {
1766  case EXPR_KIND_GROUP_BY:
1767  /* reject aggregates and window functions */
1768  if (pstate->p_hasAggs &&
1769  contain_aggs_of_level((Node *) tle->expr, 0))
1770  ereport(ERROR,
1771  (errcode(ERRCODE_GROUPING_ERROR),
1772  /* translator: %s is name of a SQL construct, eg GROUP BY */
1773  errmsg("aggregate functions are not allowed in %s",
1774  ParseExprKindName(exprKind)),
1775  parser_errposition(pstate,
1776  locate_agg_of_level((Node *) tle->expr, 0))));
1777  if (pstate->p_hasWindowFuncs &&
1778  contain_windowfuncs((Node *) tle->expr))
1779  ereport(ERROR,
1780  (errcode(ERRCODE_WINDOWING_ERROR),
1781  /* translator: %s is name of a SQL construct, eg GROUP BY */
1782  errmsg("window functions are not allowed in %s",
1783  ParseExprKindName(exprKind)),
1784  parser_errposition(pstate,
1785  locate_windowfunc((Node *) tle->expr))));
1786  break;
1787  case EXPR_KIND_ORDER_BY:
1788  /* no extra checks needed */
1789  break;
1790  case EXPR_KIND_DISTINCT_ON:
1791  /* no extra checks needed */
1792  break;
1793  default:
1794  elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
1795  break;
1796  }
1797 }
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
bool p_hasAggs
Definition: parse_node.h:203
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3481
bool p_hasWindowFuncs
Definition: parse_node.h:204
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
Expr * expr
Definition: primnodes.h:1393
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
bool contain_aggs_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:67
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197

◆ extractRemainingColumns()

static void extractRemainingColumns ( List common_colnames,
List src_colnames,
List src_colvars,
List **  res_colnames,
List **  res_colvars 
)
static

Definition at line 253 of file parse_clause.c.

References Assert, cnames, forboth, lappend(), lfirst, list_length(), NIL, and strVal.

Referenced by transformFromClauseItem().

256 {
257  List *new_colnames = NIL;
258  List *new_colvars = NIL;
259  ListCell *lnames,
260  *lvars;
261 
262  Assert(list_length(src_colnames) == list_length(src_colvars));
263 
264  forboth(lnames, src_colnames, lvars, src_colvars)
265  {
266  char *colname = strVal(lfirst(lnames));
267  bool match = false;
268  ListCell *cnames;
269 
270  foreach(cnames, common_colnames)
271  {
272  char *ccolname = strVal(lfirst(cnames));
273 
274  if (strcmp(colname, ccolname) == 0)
275  {
276  match = true;
277  break;
278  }
279  }
280 
281  if (!match)
282  {
283  new_colnames = lappend(new_colnames, lfirst(lnames));
284  new_colvars = lappend(new_colvars, lfirst(lvars));
285  }
286  }
287 
288  *res_colnames = new_colnames;
289  *res_colvars = new_colvars;
290 }
#define NIL
Definition: pg_list.h:65
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
#define strVal(v)
Definition: value.h:54
List * lappend(List *list, void *datum)
Definition: list.c:322
static const struct cname cnames[]
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
Definition: pg_list.h:50

◆ findTargetlistEntrySQL92()

static TargetEntry * findTargetlistEntrySQL92 ( ParseState pstate,
Node node,
List **  tlist,
ParseExprKind  exprKind 
)
static

Definition at line 1817 of file parse_clause.c.

References checkTargetlistEntrySQL92(), colNameToVar(), equal(), ereport, errcode(), errmsg(), ERROR, TargetEntry::expr, EXPR_KIND_GROUP_BY, findTargetlistEntrySQL99(), intVal, IsA, lfirst, linitial, list_length(), name, ParseExprKindName(), parser_errposition(), TargetEntry::resjunk, TargetEntry::resname, strVal, and val.

Referenced by transformDistinctOnClause(), transformGroupClauseExpr(), and transformSortClause().

1819 {
1820  ListCell *tl;
1821 
1822  /*----------
1823  * Handle two special cases as mandated by the SQL92 spec:
1824  *
1825  * 1. Bare ColumnName (no qualifier or subscripts)
1826  * For a bare identifier, we search for a matching column name
1827  * in the existing target list. Multiple matches are an error
1828  * unless they refer to identical values; for example,
1829  * we allow SELECT a, a FROM table ORDER BY a
1830  * but not SELECT a AS b, b FROM table ORDER BY b
1831  * If no match is found, we fall through and treat the identifier
1832  * as an expression.
1833  * For GROUP BY, it is incorrect to match the grouping item against
1834  * targetlist entries: according to SQL92, an identifier in GROUP BY
1835  * is a reference to a column name exposed by FROM, not to a target
1836  * list column. However, many implementations (including pre-7.0
1837  * PostgreSQL) accept this anyway. So for GROUP BY, we look first
1838  * to see if the identifier matches any FROM column name, and only
1839  * try for a targetlist name if it doesn't. This ensures that we
1840  * adhere to the spec in the case where the name could be both.
1841  * DISTINCT ON isn't in the standard, so we can do what we like there;
1842  * we choose to make it work like ORDER BY, on the rather flimsy
1843  * grounds that ordinary DISTINCT works on targetlist entries.
1844  *
1845  * 2. IntegerConstant
1846  * This means to use the n'th item in the existing target list.
1847  * Note that it would make no sense to order/group/distinct by an
1848  * actual constant, so this does not create a conflict with SQL99.
1849  * GROUP BY column-number is not allowed by SQL92, but since
1850  * the standard has no other behavior defined for this syntax,
1851  * we may as well accept this common extension.
1852  *
1853  * Note that pre-existing resjunk targets must not be used in either case,
1854  * since the user didn't write them in his SELECT list.
1855  *
1856  * If neither special case applies, fall through to treat the item as
1857  * an expression per SQL99.
1858  *----------
1859  */
1860  if (IsA(node, ColumnRef) &&
1861  list_length(((ColumnRef *) node)->fields) == 1 &&
1862  IsA(linitial(((ColumnRef *) node)->fields), String))
1863  {
1864  char *name = strVal(linitial(((ColumnRef *) node)->fields));
1865  int location = ((ColumnRef *) node)->location;
1866 
1867  if (exprKind == EXPR_KIND_GROUP_BY)
1868  {
1869  /*
1870  * In GROUP BY, we must prefer a match against a FROM-clause
1871  * column to one against the targetlist. Look to see if there is
1872  * a matching column. If so, fall through to use SQL99 rules.
1873  * NOTE: if name could refer ambiguously to more than one column
1874  * name exposed by FROM, colNameToVar will ereport(ERROR). That's
1875  * just what we want here.
1876  *
1877  * Small tweak for 7.4.3: ignore matches in upper query levels.
1878  * This effectively changes the search order for bare names to (1)
1879  * local FROM variables, (2) local targetlist aliases, (3) outer
1880  * FROM variables, whereas before it was (1) (3) (2). SQL92 and
1881  * SQL99 do not allow GROUPing BY an outer reference, so this
1882  * breaks no cases that are legal per spec, and it seems a more
1883  * self-consistent behavior.
1884  */
1885  if (colNameToVar(pstate, name, true, location) != NULL)
1886  name = NULL;
1887  }
1888 
1889  if (name != NULL)
1890  {
1891  TargetEntry *target_result = NULL;
1892 
1893  foreach(tl, *tlist)
1894  {
1895  TargetEntry *tle = (TargetEntry *) lfirst(tl);
1896 
1897  if (!tle->resjunk &&
1898  strcmp(tle->resname, name) == 0)
1899  {
1900  if (target_result != NULL)
1901  {
1902  if (!equal(target_result->expr, tle->expr))
1903  ereport(ERROR,
1904  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1905 
1906  /*------
1907  translator: first %s is name of a SQL construct, eg ORDER BY */
1908  errmsg("%s \"%s\" is ambiguous",
1909  ParseExprKindName(exprKind),
1910  name),
1911  parser_errposition(pstate, location)));
1912  }
1913  else
1914  target_result = tle;
1915  /* Stay in loop to check for ambiguity */
1916  }
1917  }
1918  if (target_result != NULL)
1919  {
1920  /* return the first match, after suitable validation */
1921  checkTargetlistEntrySQL92(pstate, target_result, exprKind);
1922  return target_result;
1923  }
1924  }
1925  }
1926  if (IsA(node, A_Const))
1927  {
1928  Value *val = &((A_Const *) node)->val;
1929  int location = ((A_Const *) node)->location;
1930  int targetlist_pos = 0;
1931  int target_pos;
1932 
1933  if (!IsA(val, Integer))
1934  ereport(ERROR,
1935  (errcode(ERRCODE_SYNTAX_ERROR),
1936  /* translator: %s is name of a SQL construct, eg ORDER BY */
1937  errmsg("non-integer constant in %s",
1938  ParseExprKindName(exprKind)),
1939  parser_errposition(pstate, location)));
1940 
1941  target_pos = intVal(val);
1942  foreach(tl, *tlist)
1943  {
1944  TargetEntry *tle = (TargetEntry *) lfirst(tl);
1945 
1946  if (!tle->resjunk)
1947  {
1948  if (++targetlist_pos == target_pos)
1949  {
1950  /* return the unique match, after suitable validation */
1951  checkTargetlistEntrySQL92(pstate, tle, exprKind);
1952  return tle;
1953  }
1954  }
1955  }
1956  ereport(ERROR,
1957  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1958  /* translator: %s is name of a SQL construct, eg ORDER BY */
1959  errmsg("%s position %d is not in select list",
1960  ParseExprKindName(exprKind), target_pos),
1961  parser_errposition(pstate, location)));
1962  }
1963 
1964  /*
1965  * Otherwise, we have an expression, so process it per SQL99 rules.
1966  */
1967  return findTargetlistEntrySQL99(pstate, node, tlist, exprKind);
1968 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3011
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:608
char * resname
Definition: primnodes.h:1395
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3481
bool resjunk
Definition: primnodes.h:1400
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
#define lfirst(lc)
Definition: pg_list.h:190
Definition: value.h:42
Expr * expr
Definition: primnodes.h:1393
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
static void checkTargetlistEntrySQL92(ParseState *pstate, TargetEntry *tle, ParseExprKind exprKind)
const char * name
Definition: encode.c:521
#define intVal(v)
Definition: value.h:52
int errmsg(const char *fmt,...)
Definition: elog.c:822
long val
Definition: informix.c:664
Node * colNameToVar(ParseState *pstate, const char *colname, bool localonly, int location)

◆ findTargetlistEntrySQL99()

static TargetEntry * findTargetlistEntrySQL99 ( ParseState pstate,
Node node,
List **  tlist,
ParseExprKind  exprKind 
)
static

Definition at line 1984 of file parse_clause.c.

References equal(), TargetEntry::expr, lappend(), lfirst, strip_implicit_coercions(), transformExpr(), and transformTargetEntry().

Referenced by findTargetlistEntrySQL92(), transformGroupClauseExpr(), and transformSortClause().

1986 {
1987  TargetEntry *target_result;
1988  ListCell *tl;
1989  Node *expr;
1990 
1991  /*
1992  * Convert the untransformed node to a transformed expression, and search
1993  * for a match in the tlist. NOTE: it doesn't really matter whether there
1994  * is more than one match. Also, we are willing to match an existing
1995  * resjunk target here, though the SQL92 cases above must ignore resjunk
1996  * targets.
1997  */
1998  expr = transformExpr(pstate, node, exprKind);
1999 
2000  foreach(tl, *tlist)
2001  {
2002  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2003  Node *texpr;
2004 
2005  /*
2006  * Ignore any implicit cast on the existing tlist expression.
2007  *
2008  * This essentially allows the ORDER/GROUP/etc item to adopt the same
2009  * datatype previously selected for a textually-equivalent tlist item.
2010  * There can't be any implicit cast at top level in an ordinary SELECT
2011  * tlist at this stage, but the case does arise with ORDER BY in an
2012  * aggregate function.
2013  */
2014  texpr = strip_implicit_coercions((Node *) tle->expr);
2015 
2016  if (equal(expr, texpr))
2017  return tle;
2018  }
2019 
2020  /*
2021  * If no matches, construct a new target entry which is appended to the
2022  * end of the target list. This target is given resjunk = true so that it
2023  * will not be projected into the final tuple.
2024  */
2025  target_result = transformTargetEntry(pstate, node, expr, exprKind,
2026  NULL, true);
2027 
2028  *tlist = lappend(*tlist, target_result);
2029 
2030  return target_result;
2031 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3011
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Definition: nodes.h:525
List * lappend(List *list, void *datum)
Definition: list.c:322
#define lfirst(lc)
Definition: pg_list.h:190
Expr * expr
Definition: primnodes.h:1393
TargetEntry * transformTargetEntry(ParseState *pstate, Node *node, Node *expr, ParseExprKind exprKind, char *colname, bool resjunk)
Definition: parse_target.c:86
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:611

◆ findWindowClause()

static WindowClause * findWindowClause ( List wclist,
const char *  name 
)
static

Definition at line 3483 of file parse_clause.c.

References lfirst, and WindowClause::name.

Referenced by transformWindowDefinitions().

3484 {
3485  ListCell *l;
3486 
3487  foreach(l, wclist)
3488  {
3489  WindowClause *wc = (WindowClause *) lfirst(l);
3490 
3491  if (wc->name && strcmp(wc->name, name) == 0)
3492  return wc;
3493  }
3494 
3495  return NULL;
3496 }
#define lfirst(lc)
Definition: pg_list.h:190
const char * name
Definition: encode.c:521

◆ flatten_grouping_sets()

static Node* flatten_grouping_sets ( Node expr,
bool  toplevel,
bool hasGroupingSets 
)
static

Definition at line 2070 of file parse_clause.c.

References RowExpr::args, check_stack_depth(), COERCE_IMPLICIT_CAST, GroupingSet::content, GROUPING_SET_EMPTY, GROUPING_SET_SETS, IsA, GroupingSet::kind, lappend(), lfirst, list_concat(), GroupingSet::location, makeGroupingSet(), NIL, RowExpr::row_format, T_GroupingSet, T_List, T_RowExpr, and Node::type.

Referenced by transformGroupClause().

2071 {
2072  /* just in case of pathological input */
2074 
2075  if (expr == (Node *) NIL)
2076  return (Node *) NIL;
2077 
2078  switch (expr->type)
2079  {
2080  case T_RowExpr:
2081  {
2082  RowExpr *r = (RowExpr *) expr;
2083 
2084  if (r->row_format == COERCE_IMPLICIT_CAST)
2085  return flatten_grouping_sets((Node *) r->args,
2086  false, NULL);
2087  }
2088  break;
2089  case T_GroupingSet:
2090  {
2091  GroupingSet *gset = (GroupingSet *) expr;
2092  ListCell *l2;
2093  List *result_set = NIL;
2094 
2095  if (hasGroupingSets)
2096  *hasGroupingSets = true;
2097 
2098  /*
2099  * at the top level, we skip over all empty grouping sets; the
2100  * caller can supply the canonical GROUP BY () if nothing is
2101  * left.
2102  */
2103 
2104  if (toplevel && gset->kind == GROUPING_SET_EMPTY)
2105  return (Node *) NIL;
2106 
2107  foreach(l2, gset->content)
2108  {
2109  Node *n1 = lfirst(l2);
2110  Node *n2 = flatten_grouping_sets(n1, false, NULL);
2111 
2112  if (IsA(n1, GroupingSet) &&
2113  ((GroupingSet *) n1)->kind == GROUPING_SET_SETS)
2114  result_set = list_concat(result_set, (List *) n2);
2115  else
2116  result_set = lappend(result_set, n2);
2117  }
2118 
2119  /*
2120  * At top level, keep the grouping set node; but if we're in a
2121  * nested grouping set, then we need to concat the flattened
2122  * result into the outer list if it's simply nested.
2123  */
2124 
2125  if (toplevel || (gset->kind != GROUPING_SET_SETS))
2126  {
2127  return (Node *) makeGroupingSet(gset->kind, result_set, gset->location);
2128  }
2129  else
2130  return (Node *) result_set;
2131  }
2132  case T_List:
2133  {
2134  List *result = NIL;
2135  ListCell *l;
2136 
2137  foreach(l, (List *) expr)
2138  {
2139  Node *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets);
2140 
2141  if (n != (Node *) NIL)
2142  {
2143  if (IsA(n, List))
2144  result = list_concat(result, (List *) n);
2145  else
2146  result = lappend(result, n);
2147  }
2148  }
2149 
2150  return (Node *) result;
2151  }
2152  default:
2153  break;
2154  }
2155 
2156  return expr;
2157 }
#define NIL
Definition: pg_list.h:65
List * args
Definition: primnodes.h:1008
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
List * content
Definition: parsenodes.h:1304
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
GroupingSetKind kind
Definition: parsenodes.h:1303
NodeTag type
Definition: nodes.h:527
void check_stack_depth(void)
Definition: postgres.c:3284
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
Definition: nodes.h:297
List * lappend(List *list, void *datum)
Definition: list.c:322
#define lfirst(lc)
Definition: pg_list.h:190
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:788
CoercionForm row_format
Definition: primnodes.h:1023
Definition: pg_list.h:50

◆ get_matching_location()

static int get_matching_location ( int  sortgroupref,
List sortgrouprefs,
List exprs 
)
static

Definition at line 2988 of file parse_clause.c.

References elog, ERROR, exprLocation(), forboth, lfirst, and lfirst_int.

Referenced by transformDistinctOnClause().

2989 {
2990  ListCell *lcs;
2991  ListCell *lce;
2992 
2993  forboth(lcs, sortgrouprefs, lce, exprs)
2994  {
2995  if (lfirst_int(lcs) == sortgroupref)
2996  return exprLocation((Node *) lfirst(lce));
2997  }
2998  /* if no match, caller blew it */
2999  elog(ERROR, "get_matching_location: no matching sortgroupref");
3000  return -1; /* keep compiler quiet */
3001 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Definition: nodes.h:525
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:191
#define lfirst(lc)
Definition: pg_list.h:190
#define elog(elevel,...)
Definition: elog.h:228

◆ getRTEForSpecialRelationTypes()

static RangeTblEntry * getRTEForSpecialRelationTypes ( ParseState pstate,
RangeVar rv 
)
static

Definition at line 1018 of file parse_clause.c.

References addRangeTableEntryForCTE(), addRangeTableEntryForENR(), RangeVar::relname, scanNameSpaceForCTE(), scanNameSpaceForENR(), and RangeVar::schemaname.

Referenced by transformFromClauseItem().

1019 {
1020  CommonTableExpr *cte;
1021  Index levelsup;
1022  RangeTblEntry *rte;
1023 
1024  /*
1025  * if it is a qualified name, it can't be a CTE or tuplestore reference
1026  */
1027  if (rv->schemaname)
1028  return NULL;
1029 
1030  cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
1031  if (cte)
1032  rte = addRangeTableEntryForCTE(pstate, cte, levelsup, rv, true);
1033  else if (scanNameSpaceForENR(pstate, rv->relname))
1034  rte = addRangeTableEntryForENR(pstate, rv, true);
1035  else
1036  rte = NULL;
1037 
1038  return rte;
1039 }
RangeTblEntry * addRangeTableEntryForENR(ParseState *pstate, RangeVar *rv, bool inFromCl)
char * schemaname
Definition: primnodes.h:67
char * relname
Definition: primnodes.h:68
bool scanNameSpaceForENR(ParseState *pstate, const char *refname)
unsigned int Index
Definition: c.h:476
CommonTableExpr * scanNameSpaceForCTE(ParseState *pstate, const char *refname, Index *ctelevelsup)
RangeTblEntry * addRangeTableEntryForCTE(ParseState *pstate, CommonTableExpr *cte, Index levelsup, RangeVar *rv, bool inFromCl)

◆ makeNamespaceItem()

static ParseNamespaceItem * makeNamespaceItem ( RangeTblEntry rte,
bool  rel_visible,
bool  cols_visible,
bool  lateral_only,
bool  lateral_ok 
)
static

Definition at line 1620 of file parse_clause.c.

References ParseNamespaceItem::p_cols_visible, ParseNamespaceItem::p_lateral_ok, ParseNamespaceItem::p_lateral_only, ParseNamespaceItem::p_rel_visible, ParseNamespaceItem::p_rte, and palloc().

1622 {
1623  ParseNamespaceItem *nsitem;
1624 
1625  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1626  nsitem->p_rte = rte;
1627  nsitem->p_rel_visible = rel_visible;
1628  nsitem->p_cols_visible = cols_visible;
1629  nsitem->p_lateral_only = lateral_only;
1630  nsitem->p_lateral_ok = lateral_ok;
1631  return nsitem;
1632 }
RangeTblEntry * p_rte
Definition: parse_node.h:251
void * palloc(Size size)
Definition: mcxt.c:949

◆ resolve_unique_index_expr()

static List * resolve_unique_index_expr ( ParseState pstate,
InferClause infer,
Relation  heapRel 
)
static

Definition at line 3013 of file parse_clause.c.

References IndexElem::collation, ereport, errcode(), errmsg(), ERROR, IndexElem::expr, InferenceElem::expr, EXPR_KIND_INDEX_EXPRESSION, exprLocation(), ColumnRef::fields, get_opclass_oid(), InferClause::indexElems, InferenceElem::infercollid, InferenceElem::inferopclass, InvalidOid, lappend(), lfirst, list_make1, ColumnRef::location, LookupCollation(), makeNode, makeString(), IndexElem::name, NIL, IndexElem::nulls_ordering, IndexElem::opclass, IndexElem::ordering, parse(), parser_errposition(), SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, and transformExpr().

Referenced by transformOnConflictArbiter().

3015 {
3016  List *result = NIL;
3017  ListCell *l;
3018 
3019  foreach(l, infer->indexElems)
3020  {
3021  IndexElem *ielem = (IndexElem *) lfirst(l);
3023  Node *parse;
3024 
3025  /*
3026  * Raw grammar re-uses CREATE INDEX infrastructure for unique index
3027  * inference clause, and so will accept opclasses by name and so on.
3028  *
3029  * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
3030  * LAST ordering, since those are not significant for inference
3031  * purposes (any unique index matching the inference specification in
3032  * other regards is accepted indifferently). Actively reject this as
3033  * wrong-headed.
3034  */
3035  if (ielem->ordering != SORTBY_DEFAULT)
3036  ereport(ERROR,
3037  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3038  errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
3039  parser_errposition(pstate,
3040  exprLocation((Node *) infer))));
3041  if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
3042  ereport(ERROR,
3043  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3044  errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
3045  parser_errposition(pstate,
3046  exprLocation((Node *) infer))));
3047 
3048  if (!ielem->expr)
3049  {
3050  /* Simple index attribute */
3051  ColumnRef *n;
3052 
3053  /*
3054  * Grammar won't have built raw expression for us in event of
3055  * plain column reference. Create one directly, and perform
3056  * expression transformation. Planner expects this, and performs
3057  * its own normalization for the purposes of matching against
3058  * pg_index.
3059  */
3060  n = makeNode(ColumnRef);
3061  n->fields = list_make1(makeString(ielem->name));
3062  /* Location is approximately that of inference specification */
3063  n->location = infer->location;
3064  parse = (Node *) n;
3065  }
3066  else
3067  {
3068  /* Do parse transformation of the raw expression */
3069  parse = (Node *) ielem->expr;
3070  }
3071 
3072  /*
3073  * transformExpr() will reject subqueries, aggregates, window
3074  * functions, and SRFs, based on being passed
3075  * EXPR_KIND_INDEX_EXPRESSION. So we needn't worry about those
3076  * further ... not that they would match any available index
3077  * expression anyway.
3078  */
3079  pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
3080 
3081  /* Perform lookup of collation and operator class as required */
3082  if (!ielem->collation)
3083  pInfer->infercollid = InvalidOid;
3084  else
3085  pInfer->infercollid = LookupCollation(pstate, ielem->collation,
3086  exprLocation(pInfer->expr));
3087 
3088  if (!ielem->opclass)
3089  pInfer->inferopclass = InvalidOid;
3090  else
3091  pInfer->inferopclass = get_opclass_oid(BTREE_AM_OID,
3092  ielem->opclass, false);
3093 
3094  result = lappend(result, pInfer);
3095  }
3096 
3097  return result;
3098 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
SortByDir ordering
Definition: parsenodes.h:704
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
List * indexElems
Definition: parsenodes.h:1389
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
Oid get_opclass_oid(Oid amID, List *opclassname, bool missing_ok)
Definition: opclasscmds.c:222
int location
Definition: parsenodes.h:236
#define list_make1(x1)
Definition: pg_list.h:227
Node * expr
Definition: parsenodes.h:700
SortByNulls nulls_ordering
Definition: parsenodes.h:705
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:513
#define InvalidOid
Definition: postgres_ext.h:36
List * opclass
Definition: parsenodes.h:703
#define makeNode(_type_)
Definition: nodes.h:573
#define lfirst(lc)
Definition: pg_list.h:190
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
char * name
Definition: parsenodes.h:699
int errmsg(const char *fmt,...)
Definition: elog.c:822
List * collation
Definition: parsenodes.h:702
Definition: pg_list.h:50
List * fields
Definition: parsenodes.h:235
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648

◆ setNamespaceColumnVisibility()

static void setNamespaceColumnVisibility ( List namespace,
bool  cols_visible 
)
static

Definition at line 1639 of file parse_clause.c.

References lfirst, and ParseNamespaceItem::p_cols_visible.

Referenced by transformFromClauseItem().

1640 {
1641  ListCell *lc;
1642 
1643  foreach(lc, namespace)
1644  {
1645  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1646 
1647  nsitem->p_cols_visible = cols_visible;
1648  }
1649 }
#define lfirst(lc)
Definition: pg_list.h:190

◆ setNamespaceLateralState()

static void setNamespaceLateralState ( List namespace,
bool  lateral_only,
bool  lateral_ok 
)
static

Definition at line 1656 of file parse_clause.c.

References lfirst, ParseNamespaceItem::p_lateral_ok, and ParseNamespaceItem::p_lateral_only.

Referenced by transformFromClause(), transformFromClauseItem(), and transformJoinOnClause().

1657 {
1658  ListCell *lc;
1659 
1660  foreach(lc, namespace)
1661  {
1662  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1663 
1664  nsitem->p_lateral_only = lateral_only;
1665  nsitem->p_lateral_ok = lateral_ok;
1666  }
1667 }
#define lfirst(lc)
Definition: pg_list.h:190

◆ setTargetTable()

int setTargetTable ( ParseState pstate,
RangeVar relation,
bool  inh,
bool  alsoSource,
AclMode  requiredPerms 
)

Definition at line 182 of file parse_clause.c.

References addRangeTableEntryForRelation(), addRTEtoQuery(), RangeVar::alias, Assert, ereport, errcode(), errmsg(), ERROR, list_length(), NoLock, ParseState::p_rtable, ParseState::p_target_rangetblentry, ParseState::p_target_relation, parserOpenTable(), RangeVar::relname, RangeTblEntry::requiredPerms, RowExclusiveLock, rt_fetch, scanNameSpaceForENR(), RangeVar::schemaname, and table_close().

Referenced by transformDeleteStmt(), transformInsertStmt(), and transformUpdateStmt().

184 {
185  RangeTblEntry *rte;
186  int rtindex;
187 
188  /*
189  * ENRs hide tables of the same name, so we need to check for them first.
190  * In contrast, CTEs don't hide tables (for this purpose).
191  */
192  if (relation->schemaname == NULL &&
193  scanNameSpaceForENR(pstate, relation->relname))
194  ereport(ERROR,
195  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
196  errmsg("relation \"%s\" cannot be the target of a modifying statement",
197  relation->relname)));
198 
199  /* Close old target; this could only happen for multi-action rules */
200  if (pstate->p_target_relation != NULL)
202 
203  /*
204  * Open target rel and grab suitable lock (which we will hold till end of
205  * transaction).
206  *
207  * free_parsestate() will eventually do the corresponding table_close(),
208  * but *not* release the lock.
209  */
210  pstate->p_target_relation = parserOpenTable(pstate, relation,
212 
213  /*
214  * Now build an RTE.
215  */
216  rte = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
218  relation->alias, inh, false);
219  pstate->p_target_rangetblentry = rte;
220 
221  /* assume new rte is at end */
222  rtindex = list_length(pstate->p_rtable);
223  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
224 
225  /*
226  * Override addRangeTableEntry's default ACL_SELECT permissions check, and
227  * instead mark target table as requiring exactly the specified
228  * permissions.
229  *
230  * If we find an explicit reference to the rel later during parse
231  * analysis, we will add the ACL_SELECT bit back again; see
232  * markVarForSelectPriv and its callers.
233  */
234  rte->requiredPerms = requiredPerms;
235 
236  /*
237  * If UPDATE/DELETE, add table to joinlist and namespace.
238  *
239  * Note: some callers know that they can find the new ParseNamespaceItem
240  * at the end of the pstate->p_namespace list. This is a bit ugly but not
241  * worth complicating this function's signature for.
242  */
243  if (alsoSource)
244  addRTEtoQuery(pstate, rte, true, true, true);
245 
246  return rtindex;
247 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Relation parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
int errcode(int sqlerrcode)
Definition: elog.c:608
AclMode requiredPerms
Definition: parsenodes.h:1096
char * schemaname
Definition: primnodes.h:67
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
bool scanNameSpaceForENR(ParseState *pstate, const char *refname)
#define RowExclusiveLock
Definition: lockdefs.h:38
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
#define ereport(elevel, rest)
Definition: elog.h:141
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:188
#define Assert(condition)
Definition: c.h:739
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:822
Relation p_target_relation
Definition: parse_node.h:187
Alias * alias
Definition: primnodes.h:72
List * p_rtable
Definition: parse_node.h:177

◆ targetIsInSortList()

bool targetIsInSortList ( TargetEntry tle,
Oid  sortop,
List sortList 
)

Definition at line 3456 of file parse_clause.c.

References get_commutator(), InvalidOid, lfirst, TargetEntry::ressortgroupref, SortGroupClause::sortop, and SortGroupClause::tleSortGroupRef.

Referenced by addTargetToGroupList(), addTargetToSortList(), check_output_expressions(), examine_simple_variable(), targetIsInAllPartitionLists(), transformDistinctOnClause(), and transformGroupClauseExpr().

3457 {
3458  Index ref = tle->ressortgroupref;
3459  ListCell *l;
3460 
3461  /* no need to scan list if tle has no marker */
3462  if (ref == 0)
3463  return false;
3464 
3465  foreach(l, sortList)
3466  {
3467  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3468 
3469  if (scl->tleSortGroupRef == ref &&
3470  (sortop == InvalidOid ||
3471  sortop == scl->sortop ||
3472  sortop == get_commutator(scl->sortop)))
3473  return true;
3474  }
3475  return false;
3476 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1311
Index tleSortGroupRef
Definition: parsenodes.h:1234
unsigned int Index
Definition: c.h:476
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:190
Index ressortgroupref
Definition: primnodes.h:1396

◆ transformDistinctClause()

List* transformDistinctClause ( ParseState pstate,
List **  targetlist,
List sortClause,
bool  is_agg 
)

Definition at line 2797 of file parse_clause.c.

References addTargetToGroupList(), copyObject, ereport, errcode(), errmsg(), ERROR, TargetEntry::expr, exprLocation(), get_sortgroupclause_tle(), lappend(), lfirst, NIL, parser_errposition(), and TargetEntry::resjunk.

Referenced by transformAggregateCall(), and transformSelectStmt().

2799 {
2800  List *result = NIL;
2801  ListCell *slitem;
2802  ListCell *tlitem;
2803 
2804  /*
2805  * The distinctClause should consist of all ORDER BY items followed by all
2806  * other non-resjunk targetlist items. There must not be any resjunk
2807  * ORDER BY items --- that would imply that we are sorting by a value that
2808  * isn't necessarily unique within a DISTINCT group, so the results
2809  * wouldn't be well-defined. This construction ensures we follow the rule
2810  * that sortClause and distinctClause match; in fact the sortClause will
2811  * always be a prefix of distinctClause.
2812  *
2813  * Note a corner case: the same TLE could be in the ORDER BY list multiple
2814  * times with different sortops. We have to include it in the
2815  * distinctClause the same way to preserve the prefix property. The net
2816  * effect will be that the TLE value will be made unique according to both
2817  * sortops.
2818  */
2819  foreach(slitem, sortClause)
2820  {
2821  SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
2822  TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
2823 
2824  if (tle->resjunk)
2825  ereport(ERROR,
2826  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2827  is_agg ?
2828  errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
2829  errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
2830  parser_errposition(pstate,
2831  exprLocation((Node *) tle->expr))));
2832  result = lappend(result, copyObject(scl));
2833  }
2834 
2835  /*
2836  * Now add any remaining non-resjunk tlist items, using default sort/group
2837  * semantics for their data types.
2838  */
2839  foreach(tlitem, *targetlist)
2840  {
2841  TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
2842 
2843  if (tle->resjunk)
2844  continue; /* ignore junk */
2845  result = addTargetToGroupList(pstate, tle,
2846  result, *targetlist,
2847  exprLocation((Node *) tle->expr));
2848  }
2849 
2850  /*
2851  * Complain if we found nothing to make DISTINCT. Returning an empty list
2852  * would cause the parsed Query to look like it didn't have DISTINCT, with
2853  * results that would probably surprise the user. Note: this case is
2854  * presently impossible for aggregates because of grammar restrictions,
2855  * but we check anyway.
2856  */
2857  if (result == NIL)
2858  ereport(ERROR,
2859  (errcode(ERRCODE_SYNTAX_ERROR),
2860  is_agg ?
2861  errmsg("an aggregate with DISTINCT must have at least one argument") :
2862  errmsg("SELECT DISTINCT must have at least one column")));
2863 
2864  return result;
2865 }
#define NIL
Definition: pg_list.h:65
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:389
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
bool resjunk
Definition: primnodes.h:1400
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
#define lfirst(lc)
Definition: pg_list.h:190
Expr * expr
Definition: primnodes.h:1393
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50

◆ transformDistinctOnClause()

List* transformDistinctOnClause ( ParseState pstate,
List distinctlist,
List **  targetlist,
List sortClause 
)

Definition at line 2881 of file parse_clause.c.

References addTargetToGroupList(), Assert, assignSortGroupRef(), copyObject, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_DISTINCT_ON, exprLocation(), findTargetlistEntrySQL92(), forboth, get_matching_location(), get_sortgroupref_tle(), InvalidOid, lappend(), lappend_int(), lfirst, lfirst_int, list_member_int(), NIL, parser_errposition(), targetIsInSortList(), and SortGroupClause::tleSortGroupRef.

Referenced by transformSelectStmt().

2883 {
2884  List *result = NIL;
2885  List *sortgrouprefs = NIL;
2886  bool skipped_sortitem;
2887  ListCell *lc;
2888  ListCell *lc2;
2889 
2890  /*
2891  * Add all the DISTINCT ON expressions to the tlist (if not already
2892  * present, they are added as resjunk items). Assign sortgroupref numbers
2893  * to them, and make a list of these numbers. (NB: we rely below on the
2894  * sortgrouprefs list being one-for-one with the original distinctlist.
2895  * Also notice that we could have duplicate DISTINCT ON expressions and
2896  * hence duplicate entries in sortgrouprefs.)
2897  */
2898  foreach(lc, distinctlist)
2899  {
2900  Node *dexpr = (Node *) lfirst(lc);
2901  int sortgroupref;
2902  TargetEntry *tle;
2903 
2904  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
2906  sortgroupref = assignSortGroupRef(tle, *targetlist);
2907  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
2908  }
2909 
2910  /*
2911  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
2912  * semantics from ORDER BY items that match DISTINCT ON items, and also
2913  * adopt their column sort order. We insist that the distinctClause and
2914  * sortClause match, so throw error if we find the need to add any more
2915  * distinctClause items after we've skipped an ORDER BY item that wasn't
2916  * in DISTINCT ON.
2917  */
2918  skipped_sortitem = false;
2919  foreach(lc, sortClause)
2920  {
2921  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
2922 
2923  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
2924  {
2925  if (skipped_sortitem)
2926  ereport(ERROR,
2927  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2928  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2929  parser_errposition(pstate,
2931  sortgrouprefs,
2932  distinctlist))));
2933  else
2934  result = lappend(result, copyObject(scl));
2935  }
2936  else
2937  skipped_sortitem = true;
2938  }
2939 
2940  /*
2941  * Now add any remaining DISTINCT ON items, using default sort/group
2942  * semantics for their data types. (Note: this is pretty questionable; if
2943  * the ORDER BY list doesn't include all the DISTINCT ON items and more
2944  * besides, you certainly aren't using DISTINCT ON in the intended way,
2945  * and you probably aren't going to get consistent results. It might be
2946  * better to throw an error or warning here. But historically we've
2947  * allowed it, so keep doing so.)
2948  */
2949  forboth(lc, distinctlist, lc2, sortgrouprefs)
2950  {
2951  Node *dexpr = (Node *) lfirst(lc);
2952  int sortgroupref = lfirst_int(lc2);
2953  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
2954 
2955  if (targetIsInSortList(tle, InvalidOid, result))
2956  continue; /* already in list (with some semantics) */
2957  if (skipped_sortitem)
2958  ereport(ERROR,
2959  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2960  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2961  parser_errposition(pstate, exprLocation(dexpr))));
2962  result = addTargetToGroupList(pstate, tle,
2963  result, *targetlist,
2964  exprLocation(dexpr));
2965  }
2966 
2967  /*
2968  * An empty result list is impossible here because of grammar
2969  * restrictions.
2970  */
2971  Assert(result != NIL);
2972 
2973  return result;
2974 }
#define NIL
Definition: pg_list.h:65
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Index tleSortGroupRef
Definition: parsenodes.h:1234
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
static int get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:191
bool list_member_int(const List *list, int datum)
Definition: list.c:655
#define ereport(elevel, rest)
Definition: elog.h:141
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:367
List * lappend_int(List *list, int datum)
Definition: list.c:340
List * lappend(List *list, void *datum)
Definition: list.c:322
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50

◆ transformFrameOffset()

static Node * transformFrameOffset ( ParseState pstate,
int  frameOptions,
Oid  rangeopfamily,
Oid  rangeopcintype,
Oid inRangeFunc,
Node clause 
)
static

Definition at line 3510 of file parse_clause.c.

References AMPROCNUM, Assert, BTINRANGE_PROC, can_coerce_type(), checkExprIsVarFree(), coerce_to_specific_type(), COERCION_IMPLICIT, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_WINDOW_FRAME_GROUPS, EXPR_KIND_WINDOW_FRAME_RANGE, EXPR_KIND_WINDOW_FRAME_ROWS, exprLocation(), exprType(), format_type_be(), FRAMEOPTION_GROUPS, FRAMEOPTION_RANGE, FRAMEOPTION_ROWS, GETSTRUCT, i, InvalidOid, catclist::members, catclist::n_members, ObjectIdGetDatum, parser_errposition(), ReleaseCatCacheList(), SearchSysCacheList2, transformExpr(), and catctup::tuple.

Referenced by transformWindowDefinitions().

3513 {
3514  const char *constructName = NULL;
3515  Node *node;
3516 
3517  *inRangeFunc = InvalidOid; /* default result */
3518 
3519  /* Quick exit if no offset expression */
3520  if (clause == NULL)
3521  return NULL;
3522 
3523  if (frameOptions & FRAMEOPTION_ROWS)
3524  {
3525  /* Transform the raw expression tree */
3526  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_ROWS);
3527 
3528  /*
3529  * Like LIMIT clause, simply coerce to int8
3530  */
3531  constructName = "ROWS";
3532  node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3533  }
3534  else if (frameOptions & FRAMEOPTION_RANGE)
3535  {
3536  /*
3537  * We must look up the in_range support function that's to be used,
3538  * possibly choosing one of several, and coerce the "offset" value to
3539  * the appropriate input type.
3540  */
3541  Oid nodeType;
3542  Oid preferredType;
3543  int nfuncs = 0;
3544  int nmatches = 0;
3545  Oid selectedType = InvalidOid;
3546  Oid selectedFunc = InvalidOid;
3547  CatCList *proclist;
3548  int i;
3549 
3550  /* Transform the raw expression tree */
3551  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_RANGE);
3552  nodeType = exprType(node);
3553 
3554  /*
3555  * If there are multiple candidates, we'll prefer the one that exactly
3556  * matches nodeType; or if nodeType is as yet unknown, prefer the one
3557  * that exactly matches the sort column type. (The second rule is
3558  * like what we do for "known_type operator unknown".)
3559  */
3560  preferredType = (nodeType != UNKNOWNOID) ? nodeType : rangeopcintype;
3561 
3562  /* Find the in_range support functions applicable to this case */
3563  proclist = SearchSysCacheList2(AMPROCNUM,
3564  ObjectIdGetDatum(rangeopfamily),
3565  ObjectIdGetDatum(rangeopcintype));
3566  for (i = 0; i < proclist->n_members; i++)
3567  {
3568  HeapTuple proctup = &proclist->members[i]->tuple;
3569  Form_pg_amproc procform = (Form_pg_amproc) GETSTRUCT(proctup);
3570 
3571  /* The search will find all support proc types; ignore others */
3572  if (procform->amprocnum != BTINRANGE_PROC)
3573  continue;
3574  nfuncs++;
3575 
3576  /* Ignore function if given value can't be coerced to that type */
3577  if (!can_coerce_type(1, &nodeType, &procform->amprocrighttype,
3579  continue;
3580  nmatches++;
3581 
3582  /* Remember preferred match, or any match if didn't find that */
3583  if (selectedType != preferredType)
3584  {
3585  selectedType = procform->amprocrighttype;
3586  selectedFunc = procform->amproc;
3587  }
3588  }
3589  ReleaseCatCacheList(proclist);
3590 
3591  /*
3592  * Throw error if needed. It seems worth taking the trouble to
3593  * distinguish "no support at all" from "you didn't match any
3594  * available offset type".
3595  */
3596  if (nfuncs == 0)
3597  ereport(ERROR,
3598  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3599  errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s",
3600  format_type_be(rangeopcintype)),
3601  parser_errposition(pstate, exprLocation(node))));
3602  if (nmatches == 0)
3603  ereport(ERROR,
3604  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3605  errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s and offset type %s",
3606  format_type_be(rangeopcintype),
3607  format_type_be(nodeType)),
3608  errhint("Cast the offset value to an appropriate type."),
3609  parser_errposition(pstate, exprLocation(node))));
3610  if (nmatches != 1 && selectedType != preferredType)
3611  ereport(ERROR,
3612  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3613  errmsg("RANGE with offset PRECEDING/FOLLOWING has multiple interpretations for column type %s and offset type %s",
3614  format_type_be(rangeopcintype),
3615  format_type_be(nodeType)),
3616  errhint("Cast the offset value to the exact intended type."),
3617  parser_errposition(pstate, exprLocation(node))));
3618 
3619  /* OK, coerce the offset to the right type */
3620  constructName = "RANGE";
3621  node = coerce_to_specific_type(pstate, node,
3622  selectedType, constructName);
3623  *inRangeFunc = selectedFunc;
3624  }
3625  else if (frameOptions & FRAMEOPTION_GROUPS)
3626  {
3627  /* Transform the raw expression tree */
3628  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_GROUPS);
3629 
3630  /*
3631  * Like LIMIT clause, simply coerce to int8
3632  */
3633  constructName = "GROUPS";
3634  node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3635  }
3636  else
3637  {
3638  Assert(false);
3639  node = NULL;
3640  }
3641 
3642  /* Disallow variables in frame offsets */
3643  checkExprIsVarFree(pstate, node, constructName);
3644 
3645  return node;
3646 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
int n_members
Definition: catcache.h:176
int errhint(const char *fmt,...)
Definition: elog.c:1069
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
FormData_pg_amproc * Form_pg_amproc
Definition: pg_amproc.h:68
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:543
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
unsigned int Oid
Definition: postgres_ext.h:31
void ReleaseCatCacheList(CatCList *list)
Definition: catcache.c:1782
CatCTup * members[FLEXIBLE_ARRAY_MEMBER]
Definition: catcache.h:178
#define BTINRANGE_PROC
Definition: nbtree.h:395
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
#define SearchSysCacheList2(cacheId, key1, key2)
Definition: syscache.h:212
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:505
#define Assert(condition)
Definition: c.h:739
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:506
int errmsg(const char *fmt,...)
Definition: elog.c:822
int i
#define FRAMEOPTION_GROUPS
Definition: parsenodes.h:507
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
HeapTupleData tuple
Definition: catcache.h:121

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 116 of file parse_clause.c.

References checkNameSpaceConflicts(), lappend(), lfirst, list_concat(), ParseState::p_joinlist, ParseState::p_namespace, setNamespaceLateralState(), and transformFromClauseItem().

Referenced by transformDeleteStmt(), transformSelectStmt(), and transformUpdateStmt().

117 {
118  ListCell *fl;
119 
120  /*
121  * The grammar will have produced a list of RangeVars, RangeSubselects,
122  * RangeFunctions, and/or JoinExprs. Transform each one (possibly adding
123  * entries to the rtable), check for duplicate refnames, and then add it
124  * to the joinlist and namespace.
125  *
126  * Note we must process the items left-to-right for proper handling of
127  * LATERAL references.
128  */
129  foreach(fl, frmList)
130  {
131  Node *n = lfirst(fl);
132  RangeTblEntry *rte;
133  int rtindex;
134  List *namespace;
135 
136  n = transformFromClauseItem(pstate, n,
137  &rte,
138  &rtindex,
139  &namespace);
140 
141  checkNameSpaceConflicts(pstate, pstate->p_namespace, namespace);
142 
143  /* Mark the new namespace items as visible only to LATERAL */
144  setNamespaceLateralState(namespace, true, true);
145 
146  pstate->p_joinlist = lappend(pstate->p_joinlist, n);
147  pstate->p_namespace = list_concat(pstate->p_namespace, namespace);
148  }
149 
150  /*
151  * We're done parsing the FROM list, so make all namespace items
152  * unconditionally visible. Note that this will also reset lateral_only
153  * for any namespace items that were already present when we were called;
154  * but those should have been that way already.
155  */
156  setNamespaceLateralState(pstate->p_namespace, false, true);
157 }
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
List * p_namespace
Definition: parse_node.h:181
static void setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
void checkNameSpaceConflicts(ParseState *pstate, List *namespace1, List *namespace2)
List * lappend(List *list, void *datum)
Definition: list.c:322
#define lfirst(lc)
Definition: pg_list.h:190
static Node * transformFromClauseItem(ParseState *pstate, Node *n, RangeTblEntry **top_rte, int *top_rti, List **namespace)
List * p_joinlist
Definition: parse_node.h:179
Definition: pg_list.h:50

◆ transformFromClauseItem()

static Node * transformFromClauseItem ( ParseState pstate,
Node n,
RangeTblEntry **  top_rte,
int *  top_rti,
List **  namespace 
)
static

Definition at line 1063 of file parse_clause.c.

References addRangeTableEntryForJoin(), JoinExpr::alias, Alias::aliasname, Assert, buildMergedJoinVar(), castNode, checkNameSpaceConflicts(), Alias::colnames, elog, ereport, errcode(), errmsg(), ERROR, expandRTE(), exprLocation(), extractRemainingColumns(), getRTEForSpecialRelationTypes(), IsA, JoinExpr::isNatural, JOIN_INNER, JOIN_LEFT, JoinExpr::jointype, lappend(), JoinExpr::larg, lfirst, list_concat(), list_length(), list_make1, list_nth(), list_truncate(), makeNode, makeString(), NIL, nodeTag, ParseState::p_joinexprs, ParseState::p_namespace, ParseState::p_rtable, parser_errposition(), JoinExpr::quals, JoinExpr::rarg, RangeTableSample::relation, RangeTblEntry::relkind, rt_fetch, RangeTblRef::rtindex, JoinExpr::rtindex, setNamespaceColumnVisibility(), setNamespaceLateralState(), strVal, RangeTblEntry::tablesample, transformJoinOnClause(), transformJoinUsingClause(), transformRangeFunction(), transformRangeSubselect(), transformRangeTableFunc(), transformRangeTableSample(), transformTableEntry(), and JoinExpr::usingClause.

Referenced by transformFromClause().

1066 {
1067  if (IsA(n, RangeVar))
1068  {
1069  /* Plain relation reference, or perhaps a CTE reference */
1070  RangeVar *rv = (RangeVar *) n;
1071  RangeTblRef *rtr;
1072  RangeTblEntry *rte;
1073  int rtindex;
1074 
1075  /* Check if it's a CTE or tuplestore reference */
1076  rte = getRTEForSpecialRelationTypes(pstate, rv);
1077 
1078  /* if not found above, must be a table reference */
1079  if (!rte)
1080  rte = transformTableEntry(pstate, rv);
1081 
1082  /* assume new rte is at end */
1083  rtindex = list_length(pstate->p_rtable);
1084  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
1085  *top_rte = rte;
1086  *top_rti = rtindex;
1087  *namespace = list_make1(makeDefaultNSItem(rte));
1088  rtr = makeNode(RangeTblRef);
1089  rtr->rtindex = rtindex;
1090  return (Node *) rtr;
1091  }
1092  else if (IsA(n, RangeSubselect))
1093  {
1094  /* sub-SELECT is like a plain relation */
1095  RangeTblRef *rtr;
1096  RangeTblEntry *rte;
1097  int rtindex;
1098 
1099  rte = transformRangeSubselect(pstate, (RangeSubselect *) n);
1100  /* assume new rte is at end */
1101  rtindex = list_length(pstate->p_rtable);
1102  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
1103  *top_rte = rte;
1104  *top_rti = rtindex;
1105  *namespace = list_make1(makeDefaultNSItem(rte));
1106  rtr = makeNode(RangeTblRef);
1107  rtr->rtindex = rtindex;
1108  return (Node *) rtr;
1109  }
1110  else if (IsA(n, RangeFunction))
1111  {
1112  /* function is like a plain relation */
1113  RangeTblRef *rtr;
1114  RangeTblEntry *rte;
1115  int rtindex;
1116 
1117  rte = transformRangeFunction(pstate, (RangeFunction *) n);
1118  /* assume new rte is at end */
1119  rtindex = list_length(pstate->p_rtable);
1120  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
1121  *top_rte = rte;
1122  *top_rti = rtindex;
1123  *namespace = list_make1(makeDefaultNSItem(rte));
1124  rtr = makeNode(RangeTblRef);
1125  rtr->rtindex = rtindex;
1126  return (Node *) rtr;
1127  }
1128  else if (IsA(n, RangeTableFunc))
1129  {
1130  /* table function is like a plain relation */
1131  RangeTblRef *rtr;
1132  RangeTblEntry *rte;
1133  int rtindex;
1134 
1135  rte = transformRangeTableFunc(pstate, (RangeTableFunc *) n);
1136  /* assume new rte is at end */
1137  rtindex = list_length(pstate->p_rtable);
1138  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
1139  *top_rte = rte;
1140  *top_rti = rtindex;
1141  *namespace = list_make1(makeDefaultNSItem(rte));
1142  rtr = makeNode(RangeTblRef);
1143  rtr->rtindex = rtindex;
1144  return (Node *) rtr;
1145  }
1146  else if (IsA(n, RangeTableSample))
1147  {
1148  /* TABLESAMPLE clause (wrapping some other valid FROM node) */
1149  RangeTableSample *rts = (RangeTableSample *) n;
1150  Node *rel;
1151  RangeTblRef *rtr;
1152  RangeTblEntry *rte;
1153 
1154  /* Recursively transform the contained relation */
1155  rel = transformFromClauseItem(pstate, rts->relation,
1156  top_rte, top_rti, namespace);
1157  /* Currently, grammar could only return a RangeVar as contained rel */
1158  rtr = castNode(RangeTblRef, rel);
1159  rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
1160  /* We only support this on plain relations and matviews */
1161  if (rte->relkind != RELKIND_RELATION &&
1162  rte->relkind != RELKIND_MATVIEW &&
1163  rte->relkind != RELKIND_PARTITIONED_TABLE)
1164  ereport(ERROR,
1165  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1166  errmsg("TABLESAMPLE clause can only be applied to tables and materialized views"),
1167  parser_errposition(pstate, exprLocation(rts->relation))));
1168 
1169  /* Transform TABLESAMPLE details and attach to the RTE */
1170  rte->tablesample = transformRangeTableSample(pstate, rts);
1171  return (Node *) rtr;
1172  }
1173  else if (IsA(n, JoinExpr))
1174  {
1175  /* A newfangled join expression */
1176  JoinExpr *j = (JoinExpr *) n;
1177  RangeTblEntry *l_rte;
1178  RangeTblEntry *r_rte;
1179  int l_rtindex;
1180  int r_rtindex;
1181  List *l_namespace,
1182  *r_namespace,
1183  *my_namespace,
1184  *l_colnames,
1185  *r_colnames,
1186  *res_colnames,
1187  *l_colvars,
1188  *r_colvars,
1189  *res_colvars;
1190  bool lateral_ok;
1191  int sv_namespace_length;
1192  RangeTblEntry *rte;
1193  int k;
1194 
1195  /*
1196  * Recursively process the left subtree, then the right. We must do
1197  * it in this order for correct visibility of LATERAL references.
1198  */
1199  j->larg = transformFromClauseItem(pstate, j->larg,
1200  &l_rte,
1201  &l_rtindex,
1202  &l_namespace);
1203 
1204  /*
1205  * Make the left-side RTEs available for LATERAL access within the
1206  * right side, by temporarily adding them to the pstate's namespace
1207  * list. Per SQL:2008, if the join type is not INNER or LEFT then the
1208  * left-side names must still be exposed, but it's an error to
1209  * reference them. (Stupid design, but that's what it says.) Hence,
1210  * we always push them into the namespace, but mark them as not
1211  * lateral_ok if the jointype is wrong.
1212  *
1213  * Notice that we don't require the merged namespace list to be
1214  * conflict-free. See the comments for scanNameSpaceForRefname().
1215  */
1216  lateral_ok = (j->jointype == JOIN_INNER || j->jointype == JOIN_LEFT);
1217  setNamespaceLateralState(l_namespace, true, lateral_ok);
1218 
1219  sv_namespace_length = list_length(pstate->p_namespace);
1220  pstate->p_namespace = list_concat(pstate->p_namespace, l_namespace);
1221 
1222  /* And now we can process the RHS */
1223  j->rarg = transformFromClauseItem(pstate, j->rarg,
1224  &r_rte,
1225  &r_rtindex,
1226  &r_namespace);
1227 
1228  /* Remove the left-side RTEs from the namespace list again */
1229  pstate->p_namespace = list_truncate(pstate->p_namespace,
1230  sv_namespace_length);
1231 
1232  /*
1233  * Check for conflicting refnames in left and right subtrees. Must do
1234  * this because higher levels will assume I hand back a self-
1235  * consistent namespace list.
1236  */
1237  checkNameSpaceConflicts(pstate, l_namespace, r_namespace);
1238 
1239  /*
1240  * Generate combined namespace info for possible use below.
1241  */
1242  my_namespace = list_concat(l_namespace, r_namespace);
1243 
1244  /*
1245  * Extract column name and var lists from both subtrees
1246  *
1247  * Note: expandRTE returns new lists, safe for me to modify
1248  */
1249  expandRTE(l_rte, l_rtindex, 0, -1, false,
1250  &l_colnames, &l_colvars);
1251  expandRTE(r_rte, r_rtindex, 0, -1, false,
1252  &r_colnames, &r_colvars);
1253 
1254  /*
1255  * Natural join does not explicitly specify columns; must generate
1256  * columns to join. Need to run through the list of columns from each
1257  * table or join result and match up the column names. Use the first
1258  * table, and check every column in the second table for a match.
1259  * (We'll check that the matches were unique later on.) The result of
1260  * this step is a list of column names just like an explicitly-written
1261  * USING list.
1262  */
1263  if (j->isNatural)
1264  {
1265  List *rlist = NIL;
1266  ListCell *lx,
1267  *rx;
1268 
1269  Assert(j->usingClause == NIL); /* shouldn't have USING() too */
1270 
1271  foreach(lx, l_colnames)
1272  {
1273  char *l_colname = strVal(lfirst(lx));
1274  Value *m_name = NULL;
1275 
1276  foreach(rx, r_colnames)
1277  {
1278  char *r_colname = strVal(lfirst(rx));
1279 
1280  if (strcmp(l_colname, r_colname) == 0)
1281  {
1282  m_name = makeString(l_colname);
1283  break;
1284  }
1285  }
1286 
1287  /* matched a right column? then keep as join column... */
1288  if (m_name != NULL)
1289  rlist = lappend(rlist, m_name);
1290  }
1291 
1292  j->usingClause = rlist;
1293  }
1294 
1295  /*
1296  * Now transform the join qualifications, if any.
1297  */
1298  res_colnames = NIL;
1299  res_colvars = NIL;
1300 
1301  if (j->usingClause)
1302  {
1303  /*
1304  * JOIN/USING (or NATURAL JOIN, as transformed above). Transform
1305  * the list into an explicit ON-condition, and generate a list of
1306  * merged result columns.
1307  */
1308  List *ucols = j->usingClause;
1309  List *l_usingvars = NIL;
1310  List *r_usingvars = NIL;
1311  ListCell *ucol;
1312 
1313  Assert(j->quals == NULL); /* shouldn't have ON() too */
1314 
1315  foreach(ucol, ucols)
1316  {
1317  char *u_colname = strVal(lfirst(ucol));
1318  ListCell *col;
1319  int ndx;
1320  int l_index = -1;
1321  int r_index = -1;
1322  Var *l_colvar,
1323  *r_colvar;
1324 
1325  /* Check for USING(foo,foo) */
1326  foreach(col, res_colnames)
1327  {
1328  char *res_colname = strVal(lfirst(col));
1329 
1330  if (strcmp(res_colname, u_colname) == 0)
1331  ereport(ERROR,
1332  (errcode(ERRCODE_DUPLICATE_COLUMN),
1333  errmsg("column name \"%s\" appears more than once in USING clause",
1334  u_colname)));
1335  }
1336 
1337  /* Find it in left input */
1338  ndx = 0;
1339  foreach(col, l_colnames)
1340  {
1341  char *l_colname = strVal(lfirst(col));
1342 
1343  if (strcmp(l_colname, u_colname) == 0)
1344  {
1345  if (l_index >= 0)
1346  ereport(ERROR,
1347  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1348  errmsg("common column name \"%s\" appears more than once in left table",
1349  u_colname)));
1350  l_index = ndx;
1351  }
1352  ndx++;
1353  }
1354  if (l_index < 0)
1355  ereport(ERROR,
1356  (errcode(ERRCODE_UNDEFINED_COLUMN),
1357  errmsg("column \"%s\" specified in USING clause does not exist in left table",
1358  u_colname)));
1359 
1360  /* Find it in right input */
1361  ndx = 0;
1362  foreach(col, r_colnames)
1363  {
1364  char *r_colname = strVal(lfirst(col));
1365 
1366  if (strcmp(r_colname, u_colname) == 0)
1367  {
1368  if (r_index >= 0)
1369  ereport(ERROR,
1370  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1371  errmsg("common column name \"%s\" appears more than once in right table",
1372  u_colname)));
1373  r_index = ndx;
1374  }
1375  ndx++;
1376  }
1377  if (r_index < 0)
1378  ereport(ERROR,
1379  (errcode(ERRCODE_UNDEFINED_COLUMN),
1380  errmsg("column \"%s\" specified in USING clause does not exist in right table",
1381  u_colname)));
1382 
1383  l_colvar = list_nth(l_colvars, l_index);
1384  l_usingvars = lappend(l_usingvars, l_colvar);
1385  r_colvar = list_nth(r_colvars, r_index);
1386  r_usingvars = lappend(r_usingvars, r_colvar);
1387 
1388  res_colnames = lappend(res_colnames, lfirst(ucol));
1389  res_colvars = lappend(res_colvars,
1390  buildMergedJoinVar(pstate,
1391  j->jointype,
1392  l_colvar,
1393  r_colvar));
1394  }
1395 
1396  j->quals = transformJoinUsingClause(pstate,
1397  l_rte,
1398  r_rte,
1399  l_usingvars,
1400  r_usingvars);
1401  }
1402  else if (j->quals)
1403  {
1404  /* User-written ON-condition; transform it */
1405  j->quals = transformJoinOnClause(pstate, j, my_namespace);
1406  }
1407  else
1408  {
1409  /* CROSS JOIN: no quals */
1410  }
1411 
1412  /* Add remaining columns from each side to the output columns */
1413  extractRemainingColumns(res_colnames,
1414  l_colnames, l_colvars,
1415  &l_colnames, &l_colvars);
1416  extractRemainingColumns(res_colnames,
1417  r_colnames, r_colvars,
1418  &r_colnames, &r_colvars);
1419  res_colnames = list_concat(res_colnames, l_colnames);
1420  res_colvars = list_concat(res_colvars, l_colvars);
1421  res_colnames = list_concat(res_colnames, r_colnames);
1422  res_colvars = list_concat(res_colvars, r_colvars);
1423 
1424  /*
1425  * Check alias (AS clause), if any.
1426  */
1427  if (j->alias)
1428  {
1429  if (j->alias->colnames != NIL)
1430  {
1431  if (list_length(j->alias->colnames) > list_length(res_colnames))
1432  ereport(ERROR,
1433  (errcode(ERRCODE_SYNTAX_ERROR),
1434  errmsg("column alias list for \"%s\" has too many entries",
1435  j->alias->aliasname)));
1436  }
1437  }
1438 
1439  /*
1440  * Now build an RTE for the result of the join
1441  */
1442  rte = addRangeTableEntryForJoin(pstate,
1443  res_colnames,
1444  j->jointype,
1445  res_colvars,
1446  j->alias,
1447  true);
1448 
1449  /* assume new rte is at end */
1450  j->rtindex = list_length(pstate->p_rtable);
1451  Assert(rte == rt_fetch(j->rtindex, pstate->p_rtable));
1452 
1453  *top_rte = rte;
1454  *top_rti = j->rtindex;
1455 
1456  /* make a matching link to the JoinExpr for later use */
1457  for (k = list_length(pstate->p_joinexprs) + 1; k < j->rtindex; k++)
1458  pstate->p_joinexprs = lappend(pstate->p_joinexprs, NULL);
1459  pstate->p_joinexprs = lappend(pstate->p_joinexprs, j);
1460  Assert(list_length(pstate->p_joinexprs) == j->rtindex);
1461 
1462  /*
1463  * Prepare returned namespace list. If the JOIN has an alias then it
1464  * hides the contained RTEs completely; otherwise, the contained RTEs
1465  * are still visible as table names, but are not visible for
1466  * unqualified column-name access.
1467  *
1468  * Note: if there are nested alias-less JOINs, the lower-level ones
1469  * will remain in the list although they have neither p_rel_visible
1470  * nor p_cols_visible set. We could delete such list items, but it's
1471  * unclear that it's worth expending cycles to do so.
1472  */
1473  if (j->alias != NULL)
1474  my_namespace = NIL;
1475  else
1476  setNamespaceColumnVisibility(my_namespace, false);
1477 
1478  /*
1479  * The join RTE itself is always made visible for unqualified column
1480  * names. It's visible as a relation name only if it has an alias.
1481  */
1482  *namespace = lappend(my_namespace,
1483  makeNamespaceItem(rte,
1484  (j->alias != NULL),
1485  true,
1486  false,
1487  true));
1488 
1489  return (Node *) j;
1490  }
1491  else
1492  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
1493  return NULL; /* can't get here, keep compiler quiet */
1494 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static RangeTblEntry * transformRangeTableFunc(ParseState *pstate, RangeTableFunc *t)
Definition: parse_clause.c:694
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
RangeTblEntry * addRangeTableEntryForJoin(ParseState *pstate, List *colnames, JoinType jointype, List *aliasvars, Alias *alias, bool inFromCl)
List * colnames
Definition: primnodes.h:43
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
List * list_truncate(List *list, int new_size)
Definition: list.c:586
static Node * transformJoinUsingClause(ParseState *pstate, RangeTblEntry *leftRTE, RangeTblEntry *rightRTE, List *leftVars, List *rightVars)
Definition: parse_clause.c:298
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
int errcode(int sqlerrcode)
Definition: elog.c:608
Definition: primnodes.h:167
static void extractRemainingColumns(List *common_colnames, List *src_colnames, List *src_colvars, List **res_colnames, List **res_colvars)
Definition: parse_clause.c:253
Node * larg
Definition: primnodes.h:1476
#define list_make1(x1)
Definition: pg_list.h:227
#define ERROR
Definition: elog.h:43
static RangeTblEntry * transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
Definition: parse_clause.c:402
static void * list_nth(const List *list, int n)
Definition: pg_list.h:277
static RangeTblEntry * transformTableEntry(ParseState *pstate, RangeVar *r)
Definition: parse_clause.c:388
List * p_namespace
Definition: parse_node.h:181
static void setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
#define makeDefaultNSItem(rte)
Definition: parse_clause.c:55
void checkNameSpaceConflicts(ParseState *pstate, List *namespace1, List *namespace2)
#define ereport(elevel, rest)
Definition: elog.h:141
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * lappend(List *list, void *datum)
Definition: list.c:322
bool isNatural
Definition: primnodes.h:1475
static Node * buildMergedJoinVar(ParseState *pstate, JoinType jointype, Var *l_colvar, Var *r_colvar)
List * usingClause
Definition: primnodes.h:1478
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
static TableSampleClause * transformRangeTableSample(ParseState *pstate, RangeTableSample *rts)
Definition: parse_clause.c:915
static void setNamespaceColumnVisibility(List *namespace, bool cols_visible)
Node * quals
Definition: primnodes.h:1479
static RangeTblEntry * getRTEForSpecialRelationTypes(ParseState *pstate, RangeVar *rv)
#define makeNode(_type_)
Definition: nodes.h:573
Node * rarg
Definition: primnodes.h:1477
Alias * alias
Definition: primnodes.h:1480
JoinType jointype
Definition: primnodes.h:1474
#define Assert(condition)
Definition: c.h:739
static RangeTblEntry * transformRangeFunction(ParseState *pstate, RangeFunction *r)
Definition: parse_clause.c:469
#define lfirst(lc)
Definition: pg_list.h:190
static Node * transformFromClauseItem(ParseState *pstate, Node *n, RangeTblEntry **top_rte, int *top_rti, List **namespace)
char * aliasname
Definition: primnodes.h:42
Definition: value.h:42
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
#define nodeTag(nodeptr)
Definition: nodes.h:530
static ParseNamespaceItem * makeNamespaceItem(RangeTblEntry *rte, bool rel_visible, bool cols_visible, bool lateral_only, bool lateral_ok)
int errmsg(const char *fmt,...)
Definition: elog.c:822
static Node * transformJoinOnClause(ParseState *pstate, JoinExpr *j, List *namespace)
Definition: parse_clause.c:358
#define elog(elevel,...)
Definition: elog.h:228
int rtindex
Definition: primnodes.h:1481
Definition: pg_list.h:50
struct TableSampleClause * tablesample
Definition: parsenodes.h:1004
List * p_joinexprs
Definition: parse_node.h:178
List * p_rtable
Definition: parse_node.h:177

◆ transformGroupClause()

List* transformGroupClause ( ParseState pstate,
List grouplist,
List **  groupingSets,
List **  targetlist,
List sortClause,
ParseExprKind  exprKind,
bool  useSQL99 
)

Definition at line 2444 of file parse_clause.c.

References Assert, bms_add_member(), exprLocation(), flatten_grouping_sets(), GROUPING_SET_CUBE, GROUPING_SET_EMPTY, GROUPING_SET_ROLLUP, GROUPING_SET_SETS, GROUPING_SET_SIMPLE, IsA, GroupingSet::kind, lappend(), lfirst, list_make1, list_make1_int, makeGroupingSet(), NIL, transformGroupClauseExpr(), and transformGroupingSet().

Referenced by transformSelectStmt(), and transformWindowDefinitions().

2447 {
2448  List *result = NIL;
2449  List *flat_grouplist;
2450  List *gsets = NIL;
2451  ListCell *gl;
2452  bool hasGroupingSets = false;
2453  Bitmapset *seen_local = NULL;
2454 
2455  /*
2456  * Recursively flatten implicit RowExprs. (Technically this is only needed
2457  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2458  * anyway.)
2459  */
2460  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2461  true,
2462  &hasGroupingSets);
2463 
2464  /*
2465  * If the list is now empty, but hasGroupingSets is true, it's because we
2466  * elided redundant empty grouping sets. Restore a single empty grouping
2467  * set to leave a canonical form: GROUP BY ()
2468  */
2469 
2470  if (flat_grouplist == NIL && hasGroupingSets)
2471  {
2473  NIL,
2474  exprLocation((Node *) grouplist)));
2475  }
2476 
2477  foreach(gl, flat_grouplist)
2478  {
2479  Node *gexpr = (Node *) lfirst(gl);
2480 
2481  if (IsA(gexpr, GroupingSet))
2482  {
2483  GroupingSet *gset = (GroupingSet *) gexpr;
2484 
2485  switch (gset->kind)
2486  {
2487  case GROUPING_SET_EMPTY:
2488  gsets = lappend(gsets, gset);
2489  break;
2490  case GROUPING_SET_SIMPLE:
2491  /* can't happen */
2492  Assert(false);
2493  break;
2494  case GROUPING_SET_SETS:
2495  case GROUPING_SET_CUBE:
2496  case GROUPING_SET_ROLLUP:
2497  gsets = lappend(gsets,
2498  transformGroupingSet(&result,
2499  pstate, gset,
2500  targetlist, sortClause,
2501  exprKind, useSQL99, true));
2502  break;
2503  }
2504  }
2505  else
2506  {
2507  Index ref = transformGroupClauseExpr(&result, seen_local,
2508  pstate, gexpr,
2509  targetlist, sortClause,
2510  exprKind, useSQL99, true);
2511 
2512  if (ref > 0)
2513  {
2514  seen_local = bms_add_member(seen_local, ref);
2515  if (hasGroupingSets)
2516  gsets = lappend(gsets,
2518  list_make1_int(ref),
2519  exprLocation(gexpr)));
2520  }
2521  }
2522  }
2523 
2524  /* parser should prevent this */
2525  Assert(gsets == NIL || groupingSets != NULL);
2526 
2527  if (groupingSets)
2528  *groupingSets = gsets;
2529 
2530  return result;
2531 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Definition: nodes.h:525
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
GroupingSetKind kind
Definition: parsenodes.h:1303
#define list_make1(x1)
Definition: pg_list.h:227
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
#define list_make1_int(x1)
Definition: pg_list.h:238
List * lappend(List *list, void *datum)
Definition: list.c:322
unsigned int Index
Definition: c.h:476
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:788
Definition: pg_list.h:50
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)

◆ transformGroupClauseExpr()

static Index transformGroupClauseExpr ( List **  flatresult,
Bitmapset seen_local,
ParseState pstate,
Node gexpr,
List **  targetlist,
List sortClause,
ParseExprKind  exprKind,
bool  useSQL99,
bool  toplevel 
)
static

Definition at line 2179 of file parse_clause.c.

References addTargetToGroupList(), bms_is_member(), copyObject, exprLocation(), findTargetlistEntrySQL92(), findTargetlistEntrySQL99(), InvalidOid, lappend(), lfirst, SortGroupClause::nulls_first, TargetEntry::ressortgroupref, targetIsInSortList(), and SortGroupClause::tleSortGroupRef.

Referenced by transformGroupClause(), transformGroupClauseList(), and transformGroupingSet().

2183 {
2184  TargetEntry *tle;
2185  bool found = false;
2186 
2187  if (useSQL99)
2188  tle = findTargetlistEntrySQL99(pstate, gexpr,
2189  targetlist, exprKind);
2190  else
2191  tle = findTargetlistEntrySQL92(pstate, gexpr,
2192  targetlist, exprKind);
2193 
2194  if (tle->ressortgroupref > 0)
2195  {
2196  ListCell *sl;
2197 
2198  /*
2199  * Eliminate duplicates (GROUP BY x, x) but only at local level.
2200  * (Duplicates in grouping sets can affect the number of returned
2201  * rows, so can't be dropped indiscriminately.)
2202  *
2203  * Since we don't care about anything except the sortgroupref, we can
2204  * use a bitmapset rather than scanning lists.
2205  */
2206  if (bms_is_member(tle->ressortgroupref, seen_local))
2207  return 0;
2208 
2209  /*
2210  * If we're already in the flat clause list, we don't need to consider
2211  * adding ourselves again.
2212  */
2213  found = targetIsInSortList(tle, InvalidOid, *flatresult);
2214  if (found)
2215  return tle->ressortgroupref;
2216 
2217  /*
2218  * If the GROUP BY tlist entry also appears in ORDER BY, copy operator
2219  * info from the (first) matching ORDER BY item. This means that if
2220  * you write something like "GROUP BY foo ORDER BY foo USING <<<", the
2221  * GROUP BY operation silently takes on the equality semantics implied
2222  * by the ORDER BY. There are two reasons to do this: it improves the
2223  * odds that we can implement both GROUP BY and ORDER BY with a single
2224  * sort step, and it allows the user to choose the equality semantics
2225  * used by GROUP BY, should she be working with a datatype that has
2226  * more than one equality operator.
2227  *
2228  * If we're in a grouping set, though, we force our requested ordering
2229  * to be NULLS LAST, because if we have any hope of using a sorted agg
2230  * for the job, we're going to be tacking on generated NULL values
2231  * after the corresponding groups. If the user demands nulls first,
2232  * another sort step is going to be inevitable, but that's the
2233  * planner's problem.
2234  */
2235 
2236  foreach(sl, sortClause)
2237  {
2238  SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
2239 
2240  if (sc->tleSortGroupRef == tle->ressortgroupref)
2241  {
2242  SortGroupClause *grpc = copyObject(sc);
2243 
2244  if (!toplevel)
2245  grpc->nulls_first = false;
2246  *flatresult = lappend(*flatresult, grpc);
2247  found = true;
2248  break;
2249  }
2250  }
2251  }
2252 
2253  /*
2254  * If no match in ORDER BY, just add it to the result using default
2255  * sort/group semantics.
2256  */
2257  if (!found)
2258  *flatresult = addTargetToGroupList(pstate, tle,
2259  *flatresult, *targetlist,
2260  exprLocation(gexpr));
2261 
2262  /*
2263  * _something_ must have assigned us a sortgroupref by now...
2264  */
2265 
2266  return tle->ressortgroupref;
2267 }
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Index tleSortGroupRef
Definition: parsenodes.h:1234
List * lappend(List *list, void *datum)
Definition: list.c:322
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define lfirst(lc)
Definition: pg_list.h:190
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Index ressortgroupref
Definition: primnodes.h:1396
#define copyObject(obj)
Definition: nodes.h:641
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427

◆ transformGroupClauseList()

static List* transformGroupClauseList ( List **  flatresult,
ParseState pstate,
List list,
List **  targetlist,
List sortClause,
ParseExprKind  exprKind,
bool  useSQL99,
bool  toplevel 
)
static

Definition at line 2287 of file parse_clause.c.

References bms_add_member(), lappend_int(), lfirst, NIL, and transformGroupClauseExpr().

Referenced by transformGroupingSet().

2291 {
2292  Bitmapset *seen_local = NULL;
2293  List *result = NIL;
2294  ListCell *gl;
2295 
2296  foreach(gl, list)
2297  {
2298  Node *gexpr = (Node *) lfirst(gl);
2299 
2300  Index ref = transformGroupClauseExpr(flatresult,
2301  seen_local,
2302  pstate,
2303  gexpr,
2304  targetlist,
2305  sortClause,
2306  exprKind,
2307  useSQL99,
2308  toplevel);
2309 
2310  if (ref > 0)
2311  {
2312  seen_local = bms_add_member(seen_local, ref);
2313  result = lappend_int(result, ref);
2314  }
2315  }
2316 
2317  return result;
2318 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:525
List * lappend_int(List *list, int datum)
Definition: list.c:340
unsigned int Index
Definition: c.h:476
#define lfirst(lc)
Definition: pg_list.h:190
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
Definition: pg_list.h:50
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)

◆ transformGroupingSet()

static Node* transformGroupingSet ( List **  flatresult,
ParseState pstate,
GroupingSet gset,
List **  targetlist,
List sortClause,
ParseExprKind  exprKind,
bool  useSQL99,
bool  toplevel 
)
static

Definition at line 2340 of file parse_clause.c.

References Assert, GroupingSet::content, ereport, errcode(), errmsg(), ERROR, exprLocation(), GROUPING_SET_CUBE, GROUPING_SET_SETS, GROUPING_SET_SIMPLE, IsA, GroupingSet::kind, lappend(), lfirst, list_length(), list_make1_int, GroupingSet::location, makeGroupingSet(), NIL, parser_errposition(), transformGroupClauseExpr(), and transformGroupClauseList().

Referenced by transformGroupClause().

2344 {
2345  ListCell *gl;
2346  List *content = NIL;
2347 
2348  Assert(toplevel || gset->kind != GROUPING_SET_SETS);
2349 
2350  foreach(gl, gset->content)
2351  {
2352  Node *n = lfirst(gl);
2353 
2354  if (IsA(n, List))
2355  {
2356  List *l = transformGroupClauseList(flatresult,
2357  pstate, (List *) n,
2358  targetlist, sortClause,
2359  exprKind, useSQL99, false);
2360 
2361  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2362  l,
2363  exprLocation(n)));
2364  }
2365  else if (IsA(n, GroupingSet))
2366  {
2367  GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
2368 
2369  content = lappend(content, transformGroupingSet(flatresult,
2370  pstate, gset2,
2371  targetlist, sortClause,
2372  exprKind, useSQL99, false));
2373  }
2374  else
2375  {
2376  Index ref = transformGroupClauseExpr(flatresult,
2377  NULL,
2378  pstate,
2379  n,
2380  targetlist,
2381  sortClause,
2382  exprKind,
2383  useSQL99,
2384  false);
2385 
2386  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2387  list_make1_int(ref),
2388  exprLocation(n)));
2389  }
2390  }
2391 
2392  /* Arbitrarily cap the size of CUBE, which has exponential growth */
2393  if (gset->kind == GROUPING_SET_CUBE)
2394  {
2395  if (list_length(content) > 12)
2396  ereport(ERROR,
2397  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2398  errmsg("CUBE is limited to 12 elements"),
2399  parser_errposition(pstate, gset->location)));
2400  }
2401 
2402  return (Node *) makeGroupingSet(gset->kind, content, gset->location);
2403 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
List * content
Definition: parsenodes.h:1304
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
GroupingSetKind kind
Definition: parsenodes.h:1303
#define ERROR
Definition: elog.h:43
static List * transformGroupClauseList(List **flatresult, ParseState *pstate, List *list, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
#define list_make1_int(x1)
Definition: pg_list.h:238
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
unsigned int Index
Definition: c.h:476
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:788
Definition: pg_list.h:50
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)

◆ transformJoinOnClause()

static Node * transformJoinOnClause ( ParseState pstate,
JoinExpr j,
List namespace 
)
static

Definition at line 358 of file parse_clause.c.

References EXPR_KIND_JOIN_ON, ParseState::p_namespace, JoinExpr::quals, setNamespaceLateralState(), and transformWhereClause().

Referenced by transformFromClauseItem().

359 {
360  Node *result;
361  List *save_namespace;
362 
363  /*
364  * The namespace that the join expression should see is just the two
365  * subtrees of the JOIN plus any outer references from upper pstate
366  * levels. Temporarily set this pstate's namespace accordingly. (We need
367  * not check for refname conflicts, because transformFromClauseItem()
368  * already did.) All namespace items are marked visible regardless of
369  * LATERAL state.
370  */
371  setNamespaceLateralState(namespace, false, true);
372 
373  save_namespace = pstate->p_namespace;
374  pstate->p_namespace = namespace;
375 
376  result = transformWhereClause(pstate, j->quals,
377  EXPR_KIND_JOIN_ON, "JOIN/ON");
378 
379  pstate->p_namespace = save_namespace;
380 
381  return result;
382 }
Definition: nodes.h:525
List * p_namespace
Definition: parse_node.h:181
static void setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
Node * quals
Definition: primnodes.h:1479
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Definition: pg_list.h:50

◆ transformJoinUsingClause()

static Node * transformJoinUsingClause ( ParseState pstate,
RangeTblEntry leftRTE,
RangeTblEntry rightRTE,
List leftVars,
List rightVars 
)
static

Definition at line 298 of file parse_clause.c.

References AEXPR_OP, AND_EXPR, coerce_to_boolean(), copyObject, EXPR_KIND_JOIN_USING, forboth, lappend(), lfirst, linitial, list_length(), makeBoolExpr(), makeSimpleA_Expr(), markVarForSelectPriv(), NIL, and transformExpr().

Referenced by transformFromClauseItem().

301 {
302  Node *result;
303  List *andargs = NIL;
304  ListCell *lvars,
305  *rvars;
306 
307  /*
308  * We cheat a little bit here by building an untransformed operator tree
309  * whose leaves are the already-transformed Vars. This requires collusion
310  * from transformExpr(), which normally could be expected to complain
311  * about already-transformed subnodes. However, this does mean that we
312  * have to mark the columns as requiring SELECT privilege for ourselves;
313  * transformExpr() won't do it.
314  */
315  forboth(lvars, leftVars, rvars, rightVars)
316  {
317  Var *lvar = (Var *) lfirst(lvars);
318  Var *rvar = (Var *) lfirst(rvars);
319  A_Expr *e;
320 
321  /* Require read access to the join variables */
322  markVarForSelectPriv(pstate, lvar, leftRTE);
323  markVarForSelectPriv(pstate, rvar, rightRTE);
324 
325  /* Now create the lvar = rvar join condition */
326  e = makeSimpleA_Expr(AEXPR_OP, "=",
327  (Node *) copyObject(lvar), (Node *) copyObject(rvar),
328  -1);
329 
330  /* Prepare to combine into an AND clause, if multiple join columns */
331  andargs = lappend(andargs, e);
332  }
333 
334  /* Only need an AND if there's more than one join column */
335  if (list_length(andargs) == 1)
336  result = (Node *) linitial(andargs);
337  else
338  result = (Node *) makeBoolExpr(AND_EXPR, andargs, -1);
339 
340  /*
341  * Since the references are already Vars, and are certainly from the input
342  * relations, we don't have to go through the same pushups that
343  * transformJoinOnClause() does. Just invoke transformExpr() to fix up
344  * the operators, and we're done.
345  */
346  result = transformExpr(pstate, result, EXPR_KIND_JOIN_USING);
347 
348  result = coerce_to_boolean(pstate, result, "JOIN/USING");
349 
350  return result;
351 }
#define NIL
Definition: pg_list.h:65
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
void markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Definition: nodes.h:525
A_Expr * makeSimpleA_Expr(A_Expr_Kind kind, char *name, Node *lexpr, Node *rexpr, int location)
Definition: makefuncs.c:48
Definition: primnodes.h:167
Expr * makeBoolExpr(BoolExprType boolop, List *args, int location)
Definition: makefuncs.c:367
#define linitial(l)
Definition: pg_list.h:195
List * lappend(List *list, void *datum)
Definition: list.c:322
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
e
Definition: preproc-init.c:82
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

◆ transformLimitClause()

Node* transformLimitClause ( ParseState pstate,
Node clause,
ParseExprKind  exprKind,
const char *  constructName 
)

Definition at line 1705 of file parse_clause.c.

References checkExprIsVarFree(), coerce_to_specific_type(), and transformExpr().

Referenced by transformSelectStmt(), transformSetOperationStmt(), and transformValuesClause().

1707 {
1708  Node *qual;
1709 
1710  if (clause == NULL)
1711  return NULL;
1712 
1713  qual = transformExpr(pstate, clause, exprKind);
1714 
1715  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1716 
1717  /* LIMIT can't refer to any variables of the current query */
1718  checkExprIsVarFree(pstate, qual, constructName);
1719 
1720  return qual;
1721 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Definition: nodes.h:525
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)

◆ transformOnConflictArbiter()

void transformOnConflictArbiter ( ParseState pstate,
OnConflictClause onConflictClause,
List **  arbiterExpr,
Node **  arbiterWhere,
Oid constraint 
)

Definition at line 3109 of file parse_clause.c.

References ACL_SELECT, OnConflictClause::action, addRTEtoQuery(), bms_add_members(), InferClause::conname, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_INDEX_PREDICATE, exprLocation(), get_relation_constraint_attnos(), InferClause::indexElems, OnConflictClause::infer, InvalidOid, IsCatalogRelation(), NIL, ONCONFLICT_UPDATE, ParseState::p_namespace, ParseState::p_target_rangetblentry, ParseState::p_target_relation, parser_errposition(), RelationGetRelationName, RelationGetRelid, RelationIsUsedAsCatalogTable, RangeTblEntry::requiredPerms, resolve_unique_index_expr(), RangeTblEntry::selectedCols, transformExpr(), and InferClause::whereClause.

Referenced by transformOnConflictClause().

3113 {
3114  InferClause *infer = onConflictClause->infer;
3115 
3116  *arbiterExpr = NIL;
3117  *arbiterWhere = NULL;
3118  *constraint = InvalidOid;
3119 
3120  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3121  ereport(ERROR,
3122  (errcode(ERRCODE_SYNTAX_ERROR),
3123  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3124  errhint("For example, ON CONFLICT (column_name)."),
3125  parser_errposition(pstate,
3126  exprLocation((Node *) onConflictClause))));
3127 
3128  /*
3129  * To simplify certain aspects of its design, speculative insertion into
3130  * system catalogs is disallowed
3131  */
3132  if (IsCatalogRelation(pstate->p_target_relation))
3133  ereport(ERROR,
3134  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3135  errmsg("ON CONFLICT is not supported with system catalog tables"),
3136  parser_errposition(pstate,
3137  exprLocation((Node *) onConflictClause))));
3138 
3139  /* Same applies to table used by logical decoding as catalog table */
3141  ereport(ERROR,
3142  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3143  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3145  parser_errposition(pstate,
3146  exprLocation((Node *) onConflictClause))));
3147 
3148  /* ON CONFLICT DO NOTHING does not require an inference clause */
3149  if (infer)
3150  {
3151  List *save_namespace;
3152 
3153  /*
3154  * While we process the arbiter expressions, accept only non-qualified
3155  * references to the target table. Hide any other relations.
3156  */
3157  save_namespace = pstate->p_namespace;
3158  pstate->p_namespace = NIL;
3159  addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
3160  false, false, true);
3161 
3162  if (infer->indexElems)
3163  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3164  pstate->p_target_relation);
3165 
3166  /*
3167  * Handling inference WHERE clause (for partial unique index
3168  * inference)
3169  */
3170  if (infer->whereClause)
3171  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3173 
3174  pstate->p_namespace = save_namespace;
3175 
3176  /*
3177  * If the arbiter is specified by constraint name, get the constraint
3178  * OID and mark the constrained columns as requiring SELECT privilege,
3179  * in the same way as would have happened if the arbiter had been
3180  * specified by explicit reference to the constraint's index columns.
3181  */
3182  if (infer->conname)
3183  {
3184  Oid relid = RelationGetRelid(pstate->p_target_relation);
3185  RangeTblEntry *rte = pstate->p_target_rangetblentry;
3186  Bitmapset *conattnos;
3187 
3188  conattnos = get_relation_constraint_attnos(relid, infer->conname,
3189  false, constraint);
3190 
3191  /* Make sure the rel as a whole is marked for SELECT access */
3192  rte->requiredPerms |= ACL_SELECT;
3193  /* Mark the constrained columns as requiring SELECT access */
3194  rte->selectedCols = bms_add_members(rte->selectedCols, conattnos);
3195  }
3196  }
3197 
3198  /*
3199  * It's convenient to form a list of expressions based on the
3200  * representation used by CREATE INDEX, since the same restrictions are
3201  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3202  * primnode representation is used for inference elements, and so
3203  * assign_query_collations() can be trusted to do the right thing with the
3204  * post parse analysis query tree inference clause representation.
3205  */
3206 }
#define NIL
Definition: pg_list.h:65
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:99
int errhint(const char *fmt,...)
Definition: elog.c:1069
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
List * indexElems
Definition: parsenodes.h:1389
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
AclMode requiredPerms
Definition: parsenodes.h:1096
unsigned int Oid
Definition: postgres_ext.h:31
Bitmapset * selectedCols
Definition: parsenodes.h:1098
#define ERROR
Definition: elog.h:43
List * p_namespace
Definition: parse_node.h:181
char * conname
Definition: parsenodes.h:1391
Bitmapset * get_relation_constraint_attnos(Oid relid, const char *conname, bool missing_ok, Oid *constraintOid)
#define RelationGetRelationName(relation)
Definition: rel.h:456
#define ereport(elevel, rest)
Definition: elog.h:141
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define ACL_SELECT
Definition: parsenodes.h:75
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:188
InferClause * infer
Definition: parsenodes.h:1405
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:314
#define InvalidOid
Definition: postgres_ext.h:36
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Node * whereClause
Definition: parsenodes.h:1390
int errmsg(const char *fmt,...)
Definition: elog.c:822
Relation p_target_relation
Definition: parse_node.h:187
OnConflictAction action
Definition: parsenodes.h:1404
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:422
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:793
static List * resolve_unique_index_expr(ParseState *pstate, InferClause *infer, Relation heapRel)

◆ transformRangeFunction()

static RangeTblEntry * transformRangeFunction ( ParseState pstate,
RangeFunction r 
)
static

Definition at line 469 of file parse_clause.c.

References addRangeTableEntryForFunction(), FuncCall::agg_distinct, FuncCall::agg_filter, FuncCall::agg_order, FuncCall::agg_star, arg, FuncCall::args, Assert, assign_list_collations(), RangeFunction::coldeflist, contain_vars_of_level(), ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_FROM_FUNCTION, exprLocation(), fc(), FigureColname(), FuncCall::func_variadic, FuncCall::funcname, RangeFunction::functions, RangeFunction::is_rowsfrom, IsA, lappend(), RangeFunction::lateral, lfirst, linitial, list_length(), list_make1, FuncCall::location, lsecond, makeFuncCall(), NIL, RangeFunction::ordinality, FuncCall::over, ParseState::p_last_srf, ParseState::p_lateral_active, parser_errposition(), strVal, SystemFuncName(), and transformExpr().

Referenced by transformFromClauseItem().

470 {
471  List *funcexprs = NIL;
472  List *funcnames = NIL;
473  List *coldeflists = NIL;
474  bool is_lateral;
475  RangeTblEntry *rte;
476  ListCell *lc;
477 
478  /*
479  * We make lateral_only names of this level visible, whether or not the
480  * RangeFunction is explicitly marked LATERAL. This is needed for SQL
481  * spec compliance in the case of UNNEST(), and seems useful on
482  * convenience grounds for all functions in FROM.
483  *
484  * (LATERAL can't nest within a single pstate level, so we don't need
485  * save/restore logic here.)
486  */
487  Assert(!pstate->p_lateral_active);
488  pstate->p_lateral_active = true;
489 
490  /*
491  * Transform the raw expressions.
492  *
493  * While transforming, also save function names for possible use as alias
494  * and column names. We use the same transformation rules as for a SELECT
495  * output expression. For a FuncCall node, the result will be the
496  * function name, but it is possible for the grammar to hand back other
497  * node types.
498  *
499  * We have to get this info now, because FigureColname only works on raw
500  * parsetrees. Actually deciding what to do with the names is left up to
501  * addRangeTableEntryForFunction.
502  *
503  * Likewise, collect column definition lists if there were any. But
504  * complain if we find one here and the RangeFunction has one too.
505  */
506  foreach(lc, r->functions)
507  {
508  List *pair = (List *) lfirst(lc);
509  Node *fexpr;
510  List *coldeflist;
511  Node *newfexpr;
512  Node *last_srf;
513 
514  /* Disassemble the function-call/column-def-list pairs */
515  Assert(list_length(pair) == 2);
516  fexpr = (Node *) linitial(pair);
517  coldeflist = (List *) lsecond(pair);
518 
519  /*
520  * If we find a function call unnest() with more than one argument and
521  * no special decoration, transform it into separate unnest() calls on
522  * each argument. This is a kluge, for sure, but it's less nasty than
523  * other ways of implementing the SQL-standard UNNEST() syntax.
524  *
525  * If there is any decoration (including a coldeflist), we don't
526  * transform, which probably means a no-such-function error later. We
527  * could alternatively throw an error right now, but that doesn't seem
528  * tremendously helpful. If someone is using any such decoration,
529  * then they're not using the SQL-standard syntax, and they're more
530  * likely expecting an un-tweaked function call.
531  *
532  * Note: the transformation changes a non-schema-qualified unnest()
533  * function name into schema-qualified pg_catalog.unnest(). This
534  * choice is also a bit debatable, but it seems reasonable to force
535  * use of built-in unnest() when we make this transformation.
536  */
537  if (IsA(fexpr, FuncCall))
538  {
539  FuncCall *fc = (FuncCall *) fexpr;
540 
541  if (list_length(fc->funcname) == 1 &&
542  strcmp(strVal(linitial(fc->funcname)), "unnest") == 0 &&
543  list_length(fc->args) > 1 &&
544  fc->agg_order == NIL &&
545  fc->agg_filter == NULL &&
546  !fc->agg_star &&
547  !fc->agg_distinct &&
548  !fc->func_variadic &&
549  fc->over == NULL &&
550  coldeflist == NIL)
551  {
552  ListCell *lc;
553 
554  foreach(lc, fc->args)
555  {
556  Node *arg = (Node *) lfirst(lc);
557  FuncCall *newfc;
558 
559  last_srf = pstate->p_last_srf;
560 
561  newfc = makeFuncCall(SystemFuncName("unnest"),
562  list_make1(arg),
563  fc->location);
564 
565  newfexpr = transformExpr(pstate, (Node *) newfc,
567 
568  /* nodeFunctionscan.c requires SRFs to be at top level */
569  if (pstate->p_last_srf != last_srf &&
570  pstate->p_last_srf != newfexpr)
571  ereport(ERROR,
572  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
573  errmsg("set-returning functions must appear at top level of FROM"),
574  parser_errposition(pstate,
575  exprLocation(pstate->p_last_srf))));
576 
577  funcexprs = lappend(funcexprs, newfexpr);
578 
579  funcnames = lappend(funcnames,
580  FigureColname((Node *) newfc));
581 
582  /* coldeflist is empty, so no error is possible */
583 
584  coldeflists = lappend(coldeflists, coldeflist);
585  }
586  continue; /* done with this function item */
587  }
588  }
589 
590  /* normal case ... */
591  last_srf = pstate->p_last_srf;
592 
593  newfexpr = transformExpr(pstate, fexpr,
595 
596  /* nodeFunctionscan.c requires SRFs to be at top level */
597  if (pstate->p_last_srf != last_srf &&
598  pstate->p_last_srf != newfexpr)
599  ereport(ERROR,
600  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
601  errmsg("set-returning functions must appear at top level of FROM"),
602  parser_errposition(pstate,
603  exprLocation(pstate->p_last_srf))));
604 
605  funcexprs = lappend(funcexprs, newfexpr);
606 
607  funcnames = lappend(funcnames,
608  FigureColname(fexpr));
609 
610  if (coldeflist && r->coldeflist)
611  ereport(ERROR,
612  (errcode(ERRCODE_SYNTAX_ERROR),
613  errmsg("multiple column definition lists are not allowed for the same function"),
614  parser_errposition(pstate,
615  exprLocation((Node *) r->coldeflist))));
616 
617  coldeflists = lappend(coldeflists, coldeflist);
618  }
619 
620  pstate->p_lateral_active = false;
621 
622  /*
623  * We must assign collations now so that the RTE exposes correct collation
624  * info for Vars created from it.
625  */
626  assign_list_collations(pstate, funcexprs);
627 
628  /*
629  * Install the top-level coldeflist if there was one (we already checked
630  * that there was no conflicting per-function coldeflist).
631  *
632  * We only allow this when there's a single function (even after UNNEST
633  * expansion) and no WITH ORDINALITY. The reason for the latter
634  * restriction is that it's not real clear whether the ordinality column
635  * should be in the coldeflist, and users are too likely to make mistakes
636  * in one direction or the other. Putting the coldeflist inside ROWS
637  * FROM() is much clearer in this case.
638  */
639  if (r->coldeflist)
640  {
641  if (list_length(funcexprs) != 1)
642  {
643  if (r->is_rowsfrom)
644  ereport(ERROR,
645  (errcode(ERRCODE_SYNTAX_ERROR),
646  errmsg("ROWS FROM() with multiple functions cannot have a column definition list"),
647  errhint("Put a separate column definition list for each function inside ROWS FROM()."),
648  parser_errposition(pstate,
649  exprLocation((Node *) r->coldeflist))));
650  else
651  ereport(ERROR,
652  (errcode(ERRCODE_SYNTAX_ERROR),
653  errmsg("UNNEST() with multiple arguments cannot have a column definition list"),
654  errhint("Use separate UNNEST() calls inside ROWS FROM(), and attach a column definition list to each one."),
655  parser_errposition(pstate,
656  exprLocation((Node *) r->coldeflist))));
657  }
658  if (r->ordinality)
659  ereport(ERROR,
660  (errcode(ERRCODE_SYNTAX_ERROR),
661  errmsg("WITH ORDINALITY cannot be used with a column definition list"),
662  errhint("Put the column definition list inside ROWS FROM()."),
663  parser_errposition(pstate,
664  exprLocation((Node *) r->coldeflist))));
665 
666  coldeflists = list_make1(r->coldeflist);
667  }
668 
669  /*
670  * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
671  * there are any lateral cross-references in it.
672  */
673  is_lateral = r->lateral || contain_vars_of_level((Node *) funcexprs, 0);
674 
675  /*
676  * OK, build an RTE for the function.
677  */
678  rte = addRangeTableEntryForFunction(pstate,
679  funcnames, funcexprs, coldeflists,
680  r, is_lateral, true);
681 
682  return rte;
683 }
#define NIL
Definition: pg_list.h:65
List * SystemFuncName(char *name)
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
int errhint(const char *fmt,...)
Definition: elog.c:1069
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Node * agg_filter
Definition: parsenodes.h:353
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:608
static int fc(const char *x)
Definition: preproc-init.c:99
int location
Definition: parsenodes.h:359
List * agg_order
Definition: parsenodes.h:352
#define lsecond(l)
Definition: pg_list.h:200
#define list_make1(x1)
Definition: pg_list.h:227
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
struct WindowDef * over
Definition: parsenodes.h:358
List * coldeflist
Definition: parsenodes.h:568
char * FigureColname(Node *node)
void assign_list_collations(ParseState *pstate, List *exprs)
List * functions
Definition: parsenodes.h:566
#define ereport(elevel, rest)
Definition: elog.h:141
bool is_rowsfrom
Definition: parsenodes.h:565
List * lappend(List *list, void *datum)
Definition: list.c:322
bool func_variadic
Definition: parsenodes.h:357
FuncCall * makeFuncCall(List *name, List *args, int location)
Definition: makefuncs.c:583
Node * p_last_srf
Definition: parse_node.h:209
bool p_lateral_active
Definition: parse_node.h:183
RangeTblEntry * addRangeTableEntryForFunction(ParseState *pstate, List *funcnames, List *funcexprs, List *coldeflists, RangeFunction *rangefunc, bool lateral, bool inFromCl)
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:369
List * args
Definition: parsenodes.h:351
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
void * arg
List * funcname
Definition: parsenodes.h:350
bool agg_distinct
Definition: parsenodes.h:356
bool agg_star
Definition: parsenodes.h:355
Definition: pg_list.h:50

◆ transformRangeSubselect()

static RangeTblEntry * transformRangeSubselect ( ParseState pstate,
RangeSubselect r 
)
static

Definition at line 402 of file parse_clause.c.

References addRangeTableEntryForSubquery(), RangeSubselect::alias, Alias::aliasname, Assert, CMD_SELECT, Query::commandType, elog, ERROR, EXPR_KIND_FROM_SUBSELECT, EXPR_KIND_NONE, IsA, isLockedRefname(), RangeSubselect::lateral, ParseState::p_expr_kind, ParseState::p_lateral_active, parse_sub_analyze(), and RangeSubselect::subquery.

Referenced by transformFromClauseItem().

403 {
404  Query *query;
405  RangeTblEntry *rte;
406 
407  /*
408  * We require user to supply an alias for a subselect, per SQL92. To relax
409  * this, we'd have to be prepared to gin up a unique alias for an
410  * unlabeled subselect. (This is just elog, not ereport, because the
411  * grammar should have enforced it already. It'd probably be better to
412  * report the error here, but we don't have a good error location here.)
413  */
414  if (r->alias == NULL)
415  elog(ERROR, "subquery in FROM must have an alias");
416 
417  /*
418  * Set p_expr_kind to show this parse level is recursing to a subselect.
419  * We can't be nested within any expression, so don't need save-restore
420  * logic here.
421  */
422  Assert(pstate->p_expr_kind == EXPR_KIND_NONE);
424 
425  /*
426  * If the subselect is LATERAL, make lateral_only names of this level
427  * visible to it. (LATERAL can't nest within a single pstate level, so we
428  * don't need save/restore logic here.)
429  */
430  Assert(!pstate->p_lateral_active);
431  pstate->p_lateral_active = r->lateral;
432 
433  /*
434  * Analyze and transform the subquery.
435  */
436  query = parse_sub_analyze(r->subquery, pstate, NULL,
437  isLockedRefname(pstate, r->alias->aliasname),
438  true);
439 
440  /* Restore state */
441  pstate->p_lateral_active = false;
442  pstate->p_expr_kind = EXPR_KIND_NONE;
443 
444  /*
445  * Check that we got a SELECT. Anything else should be impossible given
446  * restrictions of the grammar, but check anyway.
447  */
448  if (!IsA(query, Query) ||
449  query->commandType != CMD_SELECT)
450  elog(ERROR, "unexpected non-SELECT command in subquery in FROM");
451 
452  /*
453  * OK, build an RTE for the subquery.
454  */
455  rte = addRangeTableEntryForSubquery(pstate,
456  query,
457  r->alias,
458  r->lateral,
459  true);
460 
461  return rte;
462 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Node * subquery
Definition: parsenodes.h:542
#define ERROR
Definition: elog.h:43
RangeTblEntry * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
ParseExprKind p_expr_kind
Definition: parse_node.h:191
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:164
bool p_lateral_active
Definition: parse_node.h:183
CmdType commandType
Definition: parsenodes.h:112
#define Assert(condition)
Definition: c.h:739
char * aliasname
Definition: primnodes.h:42
Alias * alias
Definition: parsenodes.h:543
#define elog(elevel,...)
Definition: elog.h:228
bool isLockedRefname(ParseState *pstate, const char *refname)

◆ transformRangeTableFunc()

static RangeTblEntry * transformRangeTableFunc ( ParseState pstate,
RangeTableFunc t 
)
static

Definition at line 694 of file parse_clause.c.

References addRangeTableEntryForTableFunc(), RangeTableFunc::alias, Assert, assign_expr_collations(), bms_add_member(), coerce_to_specific_type(), coerce_to_specific_type_typmod(), TableFunc::colcollations, RangeTableFuncCol::coldefexpr, TableFunc::coldefexprs, RangeTableFuncCol::colexpr, TableFunc::colexprs, RangeTableFuncCol::colname, TableFunc::colnames, TableFunc::coltypes, TableFunc::coltypmods, RangeTableFunc::columns, contain_vars_of_level(), TableFunc::docexpr, RangeTableFunc::docexpr, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_FROM_FUNCTION, RangeTableFuncCol::for_ordinality, get_typcollation(), RangeTableFuncCol::is_not_null, IsA, lappend(), lappend_int(), lappend_oid(), RangeTableFunc::lateral, lfirst, list_length(), TableFunc::location, ResTarget::location, RangeTableFunc::location, RangeTableFuncCol::location, makeNode, makeString(), ResTarget::name, RangeTableFunc::namespaces, NIL, TableFunc::notnulls, TableFunc::ns_names, TableFunc::ns_uris, TableFunc::ordinalitycol, ParseState::p_lateral_active, palloc(), parser_errposition(), pfree(), pstrdup(), TableFunc::rowexpr, RangeTableFunc::rowexpr, TypeName::setof, strVal, transformExpr(), RangeTableFuncCol::typeName, typenameTypeIdAndMod(), and ResTarget::val.

Referenced by transformFromClauseItem().

695 {
697  const char *constructName;
698  Oid docType;
699  RangeTblEntry *rte;
700  bool is_lateral;
701  ListCell *col;
702  char **names;
703  int colno;
704 
705  /* Currently only XMLTABLE is supported */
706  constructName = "XMLTABLE";
707  docType = XMLOID;
708 
709  /*
710  * We make lateral_only names of this level visible, whether or not the
711  * RangeTableFunc is explicitly marked LATERAL. This is needed for SQL
712  * spec compliance and seems useful on convenience grounds for all
713  * functions in FROM.
714  *
715  * (LATERAL can't nest within a single pstate level, so we don't need
716  * save/restore logic here.)
717  */
718  Assert(!pstate->p_lateral_active);
719  pstate->p_lateral_active = true;
720 
721  /* Transform and apply typecast to the row-generating expression ... */
722  Assert(rtf->rowexpr != NULL);
723  tf->rowexpr = coerce_to_specific_type(pstate,
724  transformExpr(pstate, rtf->rowexpr, EXPR_KIND_FROM_FUNCTION),
725  TEXTOID,
726  constructName);
727  assign_expr_collations(pstate, tf->rowexpr);
728 
729  /* ... and to the document itself */
730  Assert(rtf->docexpr != NULL);
731  tf->docexpr = coerce_to_specific_type(pstate,
732  transformExpr(pstate, rtf->docexpr, EXPR_KIND_FROM_FUNCTION),
733  docType,
734  constructName);
735  assign_expr_collations(pstate, tf->docexpr);
736 
737  /* undef ordinality column number */
738  tf->ordinalitycol = -1;
739 
740  /* Process column specs */
741  names = palloc(sizeof(char *) * list_length(rtf->columns));
742 
743  colno = 0;
744  foreach(col, rtf->columns)
745  {
746  RangeTableFuncCol *rawc = (RangeTableFuncCol *) lfirst(col);
747  Oid typid;
748  int32 typmod;
749  Node *colexpr;
750  Node *coldefexpr;
751  int j;
752 
753  tf->colnames = lappend(tf->colnames,
754  makeString(pstrdup(rawc->colname)));
755 
756  /*
757  * Determine the type and typmod for the new column. FOR ORDINALITY
758  * columns are INTEGER per spec; the others are user-specified.
759  */
760  if (rawc->for_ordinality)
761  {
762  if (tf->ordinalitycol != -1)
763  ereport(ERROR,
764  (errcode(ERRCODE_SYNTAX_ERROR),
765  errmsg("only one FOR ORDINALITY column is allowed"),
766  parser_errposition(pstate, rawc->location)));
767 
768  typid = INT4OID;
769  typmod = -1;
770  tf->ordinalitycol = colno;
771  }
772  else
773  {
774  if (rawc->typeName->setof)
775  ereport(ERROR,
776  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
777  errmsg("column \"%s\" cannot be declared SETOF",
778  rawc->colname),
779  parser_errposition(pstate, rawc->location)));
780 
781  typenameTypeIdAndMod(pstate, rawc->typeName,
782  &typid, &typmod);
783  }
784 
785  tf->coltypes = lappend_oid(tf->coltypes, typid);
786  tf->coltypmods = lappend_int(tf->coltypmods, typmod);
788  get_typcollation(typid));
789 
790  /* Transform the PATH and DEFAULT expressions */
791  if (rawc->colexpr)
792  {
793  colexpr = coerce_to_specific_type(pstate,
794  transformExpr(pstate, rawc->colexpr,
796  TEXTOID,
797  constructName);
798  assign_expr_collations(pstate, colexpr);
799  }
800  else
801  colexpr = NULL;
802 
803  if (rawc->coldefexpr)
804  {
805  coldefexpr = coerce_to_specific_type_typmod(pstate,
806  transformExpr(pstate, rawc->coldefexpr,
808  typid, typmod,
809  constructName);
810  assign_expr_collations(pstate, coldefexpr);
811  }
812  else
813  coldefexpr = NULL;
814 
815  tf->colexprs = lappend(tf->colexprs, colexpr);
816  tf->coldefexprs = lappend(tf->coldefexprs, coldefexpr);
817 
818  if (rawc->is_not_null)
819  tf->notnulls = bms_add_member(tf->notnulls, colno);
820 
821  /* make sure column names are unique */
822  for (j = 0; j < colno; j++)
823  if (strcmp(names[j], rawc->colname) == 0)
824  ereport(ERROR,
825  (errcode(ERRCODE_SYNTAX_ERROR),
826  errmsg("column name \"%s\" is not unique",
827  rawc->colname),
828  parser_errposition(pstate, rawc->location)));
829  names[colno] = rawc->colname;
830 
831  colno++;
832  }
833  pfree(names);
834 
835  /* Namespaces, if any, also need to be transformed */
836  if (rtf->namespaces != NIL)
837  {
838  ListCell *ns;
839  ListCell *lc2;
840  List *ns_uris = NIL;
841  List *ns_names = NIL;
842  bool default_ns_seen = false;
843 
844  foreach(ns, rtf->namespaces)
845  {
846  ResTarget *r = (ResTarget *) lfirst(ns);
847  Node *ns_uri;
848 
849  Assert(IsA(r, ResTarget));
850  ns_uri = transformExpr(pstate, r->val, EXPR_KIND_FROM_FUNCTION);
851  ns_uri = coerce_to_specific_type(pstate, ns_uri,
852  TEXTOID, constructName);
853  assign_expr_collations(pstate, ns_uri);
854  ns_uris = lappend(ns_uris, ns_uri);
855 
856  /* Verify consistency of name list: no dupes, only one DEFAULT */
857  if (r->name != NULL)
858  {
859  foreach(lc2, ns_names)
860  {
861  Value *ns_node = (Value *) lfirst(lc2);
862 
863  if (ns_node == NULL)
864  continue;
865  if (strcmp(strVal(ns_node), r->name) == 0)
866  ereport(ERROR,
867  (errcode(ERRCODE_SYNTAX_ERROR),
868  errmsg("namespace name \"%s\" is not unique",
869  r->name),
870  parser_errposition(pstate, r->location)));
871  }
872  }
873  else
874  {
875  if (default_ns_seen)
876  ereport(ERROR,
877  (errcode(ERRCODE_SYNTAX_ERROR),
878  errmsg("only one default namespace is allowed"),
879  parser_errposition(pstate, r->location)));
880  default_ns_seen = true;
881  }
882 
883  /* We represent DEFAULT by a null pointer */
884  ns_names = lappend(ns_names,
885  r->name ? makeString(r->name) : NULL);
886  }
887 
888  tf->ns_uris = ns_uris;
889  tf->ns_names = ns_names;
890  }
891 
892  tf->location = rtf->location;
893 
894  pstate->p_lateral_active = false;
895 
896  /*
897  * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
898  * there are any lateral cross-references in it.
899  */
900  is_lateral = rtf->lateral || contain_vars_of_level((Node *) tf, 0);
901 
902  rte = addRangeTableEntryForTableFunc(pstate,
903  tf, rtf->alias, is_lateral, true);
904 
905  return rte;
906 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Node * docexpr
Definition: primnodes.h:87
Node * val
Definition: parsenodes.h:442
List * colnames
Definition: primnodes.h:89
char * name
Definition: parsenodes.h:440
List * coltypmods
Definition: primnodes.h:91
char * pstrdup(const char *in)
Definition: mcxt.c:1186
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:358
List * colcollations
Definition: primnodes.h:92
signed int int32
Definition: c.h:347
int location
Definition: parsenodes.h:443
void assign_expr_collations(ParseState *pstate, Node *expr)
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
bool setof
Definition: parsenodes.h:211
List * coldefexprs
Definition: primnodes.h:94
List * ns_names
Definition: primnodes.h:86
Node * rowexpr
Definition: primnodes.h:88
TypeName * typeName
Definition: parsenodes.h:597
Bitmapset * notnulls
Definition: primnodes.h:95
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend_int(List *list, int datum)
Definition: list.c:340
List * lappend(List *list, void *datum)
Definition: list.c:322
int ordinalitycol
Definition: primnodes.h:96
List * coltypes
Definition: primnodes.h:90
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:310
List * colexprs
Definition: primnodes.h:93
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2823
bool p_lateral_active
Definition: parse_node.h:183
#define makeNode(_type_)
Definition: nodes.h:573
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
Definition: value.h:42
List * ns_uris
Definition: primnodes.h:85
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:369
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
RangeTblEntry * addRangeTableEntryForTableFunc(ParseState *pstate, TableFunc *tf, Alias *alias, bool lateral, bool inFromCl)
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
int location
Definition: primnodes.h:97
Definition: pg_list.h:50
Node * coerce_to_specific_type_typmod(ParseState *pstate, Node *node, Oid targetTypeId, int32 targetTypmod, const char *constructName)

◆ transformRangeTableSample()

static TableSampleClause * transformRangeTableSample ( ParseState pstate,
RangeTableSample rts 
)
static

Definition at line 915 of file parse_clause.c.

References arg, RangeTableSample::args, TableSampleClause::args, assign_expr_collations(), coerce_to_specific_type(), ereport, errcode(), errmsg(), errmsg_plural(), ERROR, EXPR_KIND_FROM_FUNCTION, forboth, get_func_rettype(), GetTsmRoutine(), lappend(), lfirst, lfirst_oid, list_length(), RangeTableSample::location, LookupFuncName(), makeNode, RangeTableSample::method, NameListToString(), NIL, OidIsValid, TsmRoutine::parameterTypes, parser_errposition(), RangeTableSample::repeatable, TableSampleClause::repeatable, TsmRoutine::repeatable_across_queries, transformExpr(), and TableSampleClause::tsmhandler.

Referenced by transformFromClauseItem().

916 {
917  TableSampleClause *tablesample;
918  Oid handlerOid;
919  Oid funcargtypes[1];
920  TsmRoutine *tsm;
921  List *fargs;
922  ListCell *larg,
923  *ltyp;
924 
925  /*
926  * To validate the sample method name, look up the handler function, which
927  * has the same name, one dummy INTERNAL argument, and a result type of
928  * tsm_handler. (Note: tablesample method names are not schema-qualified
929  * in the SQL standard; but since they are just functions to us, we allow
930  * schema qualification to resolve any potential ambiguity.)
931  */
932  funcargtypes[0] = INTERNALOID;
933 
934  handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true);
935 
936  /* we want error to complain about no-such-method, not no-such-function */
937  if (!OidIsValid(handlerOid))
938  ereport(ERROR,
939  (errcode(ERRCODE_UNDEFINED_OBJECT),
940  errmsg("tablesample method %s does not exist",
941  NameListToString(rts->method)),
942  parser_errposition(pstate, rts->location)));
943 
944  /* check that handler has correct return type */
945  if (get_func_rettype(handlerOid) != TSM_HANDLEROID)
946  ereport(ERROR,
947  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
948  errmsg("function %s must return type %s",
949  NameListToString(rts->method), "tsm_handler"),
950  parser_errposition(pstate, rts->location)));
951 
952  /* OK, run the handler to get TsmRoutine, for argument type info */
953  tsm = GetTsmRoutine(handlerOid);
954 
955  tablesample = makeNode(TableSampleClause);
956  tablesample->tsmhandler = handlerOid;
957 
958  /* check user provided the expected number of arguments */
959  if (list_length(rts->args) != list_length(tsm->parameterTypes))
960  ereport(ERROR,
961  (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
962  errmsg_plural("tablesample method %s requires %d argument, not %d",
963  "tablesample method %s requires %d arguments, not %d",
965  NameListToString(rts->method),
967  list_length(rts->args)),
968  parser_errposition(pstate, rts->location)));
969 
970  /*
971  * Transform the arguments, typecasting them as needed. Note we must also
972  * assign collations now, because assign_query_collations() doesn't
973  * examine any substructure of RTEs.
974  */
975  fargs = NIL;
976  forboth(larg, rts->args, ltyp, tsm->parameterTypes)
977  {
978  Node *arg = (Node *) lfirst(larg);
979  Oid argtype = lfirst_oid(ltyp);
980 
981  arg = transformExpr(pstate, arg, EXPR_KIND_FROM_FUNCTION);
982  arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE");
983  assign_expr_collations(pstate, arg);
984  fargs = lappend(fargs, arg);
985  }
986  tablesample->args = fargs;
987 
988  /* Process REPEATABLE (seed) */
989  if (rts->repeatable != NULL)
990  {
991  Node *arg;
992 
993  if (!tsm->repeatable_across_queries)
994  ereport(ERROR,
995  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
996  errmsg("tablesample method %s does not support REPEATABLE",
997  NameListToString(rts->method)),
998  parser_errposition(pstate, rts->location)));
999 
1000  arg = transformExpr(pstate, rts->repeatable, EXPR_KIND_FROM_FUNCTION);
1001  arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE");
1002  assign_expr_collations(pstate, arg);
1003  tablesample->repeatable = (Expr *) arg;
1004  }
1005  else
1006  tablesample->repeatable = NULL;
1007 
1008  return tablesample;
1009 }
#define NIL
Definition: pg_list.h:65
bool repeatable_across_queries
Definition: tsmapi.h:64
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:932
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1457
void assign_expr_collations(ParseState *pstate, Node *expr)
#define ERROR
Definition: elog.h:43
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
Definition: parse_func.c:2101
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
char * NameListToString(List *names)
Definition: namespace.c:3094
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
#define makeNode(_type_)
Definition: nodes.h:573
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
void * arg
List * parameterTypes
Definition: tsmapi.h:61
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ transformSortClause()

List* transformSortClause ( ParseState pstate,
List orderlist,
List **  targetlist,
ParseExprKind  exprKind,
bool  useSQL99 
)

Definition at line 2544 of file parse_clause.c.

References addTargetToSortList(), findTargetlistEntrySQL92(), findTargetlistEntrySQL99(), lfirst, NIL, and SortBy::node.

Referenced by transformAggregateCall(), transformSelectStmt(), transformSetOperationStmt(), transformValuesClause(), and transformWindowDefinitions().

2549 {
2550  List *sortlist = NIL;
2551  ListCell *olitem;
2552 
2553  foreach(olitem, orderlist)
2554  {
2555  SortBy *sortby = (SortBy *) lfirst(olitem);
2556  TargetEntry *tle;
2557 
2558  if (useSQL99)
2559  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2560  targetlist, exprKind);
2561  else
2562  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2563  targetlist, exprKind);
2564 
2565  sortlist = addTargetToSortList(pstate, tle,
2566  sortlist, *targetlist, sortby);
2567  }
2568 
2569  return sortlist;
2570 }
#define NIL
Definition: pg_list.h:65
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
#define lfirst(lc)
Definition: pg_list.h:190
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Node * node
Definition: parsenodes.h:469
Definition: pg_list.h:50

◆ transformTableEntry()

static RangeTblEntry * transformTableEntry ( ParseState pstate,
RangeVar r 
)
static

Definition at line 388 of file parse_clause.c.

References addRangeTableEntry(), RangeVar::alias, and RangeVar::inh.

Referenced by transformFromClauseItem().

389 {
390  RangeTblEntry *rte;
391 
392  /* We need only build a range table entry */
393  rte = addRangeTableEntry(pstate, r, r->alias, r->inh, true);
394 
395  return rte;
396 }
RangeTblEntry * addRangeTableEntry(ParseState *pstate, RangeVar *relation, Alias *alias, bool inh, bool inFromCl)
bool inh
Definition: primnodes.h:69
Alias * alias
Definition: primnodes.h:72

◆ transformWhereClause()

Node* transformWhereClause ( ParseState pstate,
Node clause,
ParseExprKind  exprKind,
const char *  constructName 
)

Definition at line 1678 of file parse_clause.c.

References coerce_to_boolean(), and transformExpr().

Referenced by AlterPolicy(), CreatePolicy(), CreateTrigger(), ParseFuncOrColumn(), test_rls_hooks_permissive(), test_rls_hooks_restrictive(), transformDeleteStmt(), transformIndexStmt(), transformJoinOnClause(), transformOnConflictClause(), transformRuleStmt(), transformSelectStmt(), and transformUpdateStmt().

1680 {
1681  Node *qual;
1682 
1683  if (clause == NULL)
1684  return NULL;
1685 
1686  qual = transformExpr(pstate, clause, exprKind);
1687 
1688  qual = coerce_to_boolean(pstate, qual, constructName);
1689 
1690  return qual;
1691 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Definition: nodes.h:525
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

◆ transformWindowDefinitions()

List* transformWindowDefinitions ( ParseState pstate,
List windowdefs,
List **  targetlist 
)

Definition at line 2577 of file parse_clause.c.

References BTLessStrategyNumber, castNode, WindowClause::copiedOrder, copyObject, elog, WindowClause::endInRangeFunc, WindowDef::endOffset, WindowClause::endOffset, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, exprCollation(), findWindowClause(), FRAMEOPTION_DEFAULTS, FRAMEOPTION_END_OFFSET, FRAMEOPTION_GROUPS, FRAMEOPTION_RANGE, FRAMEOPTION_START_OFFSET, WindowDef::frameOptions, WindowClause::frameOptions, get_ordering_op_properties(), get_sortgroupclause_expr(), WindowClause::inRangeAsc, WindowClause::inRangeColl, WindowClause::inRangeNullsFirst, InvalidOid, lappend(), lfirst, linitial, list_length(), WindowDef::location, makeNode, WindowDef::name, WindowClause::name, NIL, SortGroupClause::nulls_first, WindowDef::orderClause, WindowClause::orderClause, parser_errposition(), WindowDef::partitionClause, WindowClause::partitionClause, WindowDef::refname, WindowClause::refname, SortGroupClause::sortop, WindowClause::startInRangeFunc, WindowDef::startOffset, WindowClause::startOffset, transformFrameOffset(), transformGroupClause(), transformSortClause(), and WindowClause::winref.

Referenced by transformSelectStmt().

2580 {
2581  List *result = NIL;
2582  Index winref = 0;
2583  ListCell *lc;
2584 
2585  foreach(lc, windowdefs)
2586  {
2587  WindowDef *windef = (WindowDef *) lfirst(lc);
2588  WindowClause *refwc = NULL;
2589  List *partitionClause;
2590  List *orderClause;
2591  Oid rangeopfamily = InvalidOid;
2592  Oid rangeopcintype = InvalidOid;
2593  WindowClause *wc;
2594 
2595  winref++;
2596 
2597  /*
2598  * Check for duplicate window names.
2599  */
2600  if (windef->name &&
2601  findWindowClause(result, windef->name) != NULL)
2602  ereport(ERROR,
2603  (errcode(ERRCODE_WINDOWING_ERROR),
2604  errmsg("window \"%s\" is already defined", windef->name),
2605  parser_errposition(pstate, windef->location)));
2606 
2607  /*
2608  * If it references a previous window, look that up.
2609  */
2610  if (windef->refname)
2611  {
2612  refwc = findWindowClause(result, windef->refname);
2613  if (refwc == NULL)
2614  ereport(ERROR,
2615  (errcode(ERRCODE_UNDEFINED_OBJECT),
2616  errmsg("window \"%s\" does not exist",
2617  windef->refname),
2618  parser_errposition(pstate, windef->location)));
2619  }
2620 
2621  /*
2622  * Transform PARTITION and ORDER specs, if any. These are treated
2623  * almost exactly like top-level GROUP BY and ORDER BY clauses,
2624  * including the special handling of nondefault operator semantics.
2625  */
2626  orderClause = transformSortClause(pstate,
2627  windef->orderClause,
2628  targetlist,
2630  true /* force SQL99 rules */ );
2631  partitionClause = transformGroupClause(pstate,
2632  windef->partitionClause,
2633  NULL,
2634  targetlist,
2635  orderClause,
2637  true /* force SQL99 rules */ );
2638 
2639  /*
2640  * And prepare the new WindowClause.
2641  */
2642  wc = makeNode(WindowClause);
2643  wc->name = windef->name;
2644  wc->refname = windef->refname;
2645 
2646  /*
2647  * Per spec, a windowdef that references a previous one copies the
2648  * previous partition clause (and mustn't specify its own). It can
2649  * specify its own ordering clause, but only if the previous one had
2650  * none. It always specifies its own frame clause, and the previous
2651  * one must not have a frame clause. Yeah, it's bizarre that each of
2652  * these cases works differently, but SQL:2008 says so; see 7.11
2653  * <window clause> syntax rule 10 and general rule 1. The frame
2654  * clause rule is especially bizarre because it makes "OVER foo"
2655  * different from "OVER (foo)", and requires the latter to throw an
2656  * error if foo has a nondefault frame clause. Well, ours not to
2657  * reason why, but we do go out of our way to throw a useful error
2658  * message for such cases.
2659  */
2660  if (refwc)
2661  {
2662  if (partitionClause)
2663  ereport(ERROR,
2664  (errcode(ERRCODE_WINDOWING_ERROR),
2665  errmsg("cannot override PARTITION BY clause of window \"%s\"",
2666  windef->refname),
2667  parser_errposition(pstate, windef->location)));
2669  }
2670  else
2671  wc->partitionClause = partitionClause;
2672  if (refwc)
2673  {
2674  if (orderClause && refwc->orderClause)
2675  ereport(ERROR,
2676  (errcode(ERRCODE_WINDOWING_ERROR),
2677  errmsg("cannot override ORDER BY clause of window \"%s\"",
2678  windef->refname),
2679  parser_errposition(pstate, windef->location)));
2680  if (orderClause)
2681  {
2682  wc->orderClause = orderClause;
2683  wc->copiedOrder = false;
2684  }
2685  else
2686  {
2687  wc->orderClause = copyObject(refwc->orderClause);
2688  wc->copiedOrder = true;
2689  }
2690  }
2691  else
2692  {
2693  wc->orderClause = orderClause;
2694  wc->copiedOrder = false;
2695  }
2696  if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2697  {
2698  /*
2699  * Use this message if this is a WINDOW clause, or if it's an OVER
2700  * clause that includes ORDER BY or framing clauses. (We already
2701  * rejected PARTITION BY above, so no need to check that.)
2702  */
2703  if (windef->name ||
2704  orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2705  ereport(ERROR,
2706  (errcode(ERRCODE_WINDOWING_ERROR),
2707  errmsg("cannot copy window \"%s\" because it has a frame clause",
2708  windef->refname),
2709  parser_errposition(pstate, windef->location)));
2710  /* Else this clause is just OVER (foo), so say this: */
2711  ereport(ERROR,
2712  (errcode(ERRCODE_WINDOWING_ERROR),
2713  errmsg("cannot copy window \"%s\" because it has a frame clause",
2714  windef->refname),
2715  errhint("Omit the parentheses in this OVER clause."),
2716  parser_errposition(pstate, windef->location)));
2717  }
2718  wc->frameOptions = windef->frameOptions;
2719 
2720  /*
2721  * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
2722  * column; check that and get its sort opfamily info.
2723  */
2724  if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
2727  {
2728  SortGroupClause *sortcl;
2729  Node *sortkey;
2730  int16 rangestrategy;
2731 
2732  if (list_length(wc->orderClause) != 1)
2733  ereport(ERROR,
2734  (errcode(ERRCODE_WINDOWING_ERROR),
2735  errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
2736  parser_errposition(pstate, windef->location)));
2737  sortcl = castNode(SortGroupClause, linitial(wc->orderClause));
2738  sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
2739  /* Find the sort operator in pg_amop */
2740  if (!get_ordering_op_properties(sortcl->sortop,
2741  &rangeopfamily,
2742  &rangeopcintype,
2743  &rangestrategy))
2744  elog(ERROR, "operator %u is not a valid ordering operator",
2745  sortcl->sortop);
2746  /* Record properties of sort ordering */
2747  wc->inRangeColl = exprCollation(sortkey);
2748  wc->inRangeAsc = (rangestrategy == BTLessStrategyNumber);
2749  wc->inRangeNullsFirst = sortcl->nulls_first;
2750  }
2751 
2752  /* Per spec, GROUPS mode requires an ORDER BY clause */
2753  if (wc->frameOptions & FRAMEOPTION_GROUPS)
2754  {
2755  if (wc->orderClause == NIL)
2756  ereport(ERROR,
2757  (errcode(ERRCODE_WINDOWING_ERROR),
2758  errmsg("GROUPS mode requires an ORDER BY clause"),
2759  parser_errposition(pstate, windef->location)));
2760  }
2761 
2762  /* Process frame offset expressions */
2763  wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2764  rangeopfamily, rangeopcintype,
2765  &wc->startInRangeFunc,
2766  windef->startOffset);
2767  wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2768  rangeopfamily, rangeopcintype,
2769  &wc->endInRangeFunc,
2770  windef->endOffset);
2771  wc->winref = winref;
2772 
2773  result = lappend(result, wc);
2774  }
2775 
2776  return result;
2777 }
signed short int16
Definition: c.h:346
List * partitionClause
Definition: parsenodes.h:489
char * refname
Definition: parsenodes.h:1329
#define NIL
Definition: pg_list.h:65
bool copiedOrder
Definition: parsenodes.h:1341
int errhint(const char *fmt,...)
Definition: elog.c:1069
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:531
bool inRangeNullsFirst
Definition: parsenodes.h:1339
int frameOptions
Definition: parsenodes.h:491
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
char * name
Definition: parsenodes.h:487
Oid endInRangeFunc
Definition: parsenodes.h:1336
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:401
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
#define FRAMEOPTION_START_OFFSET
Definition: parsenodes.h:523
Node * startOffset
Definition: parsenodes.h:492
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
List * partitionClause
Definition: parsenodes.h:1330
int location
Definition: parsenodes.h:494
Node * endOffset
Definition: parsenodes.h:493
List * transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
Node * startOffset
Definition: parsenodes.h:1333
List * orderClause
Definition: parsenodes.h:490
unsigned int Index
Definition: c.h:476
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:573
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:505
#define lfirst(lc)
Definition: pg_list.h:190
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:204
Node * endOffset
Definition: parsenodes.h:1334
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:719
#define FRAMEOPTION_END_OFFSET
Definition: parsenodes.h:525
List * orderClause
Definition: parsenodes.h:1331
int errmsg(const char *fmt,...)
Definition: elog.c:822
static Node * transformFrameOffset(ParseState *pstate, int frameOptions, Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc, Node *clause)
#define elog(elevel,...)
Definition: elog.h:228
#define FRAMEOPTION_GROUPS
Definition: parsenodes.h:507
char * refname
Definition: parsenodes.h:488
#define copyObject(obj)
Definition: nodes.h:641
#define BTLessStrategyNumber
Definition: stratnum.h:29
Definition: pg_list.h:50
Oid startInRangeFunc
Definition: parsenodes.h:1335
static WindowClause * findWindowClause(List *wclist, const char *name)