PostgreSQL Source Code  git master
parse_clause.c File Reference
#include "postgres.h"
#include "miscadmin.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 "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "parser/parser.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 "rewrite/rewriteManip.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/catcache.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/rel.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 57 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 3362 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().

3364 {
3365  Oid restype = exprType((Node *) tle->expr);
3366 
3367  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3368  if (restype == UNKNOWNOID)
3369  {
3370  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3371  restype, TEXTOID, -1,
3374  -1);
3375  restype = TEXTOID;
3376  }
3377 
3378  /* avoid making duplicate grouplist entries */
3379  if (!targetIsInSortList(tle, InvalidOid, grouplist))
3380  {
3382  Oid sortop;
3383  Oid eqop;
3384  bool hashable;
3385  ParseCallbackState pcbstate;
3386 
3387  setup_parser_errposition_callback(&pcbstate, pstate, location);
3388 
3389  /* determine the eqop and optional sortop */
3390  get_sort_group_operators(restype,
3391  false, true, false,
3392  &sortop, &eqop, NULL,
3393  &hashable);
3394 
3396 
3397  grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3398  grpcl->eqop = eqop;
3399  grpcl->sortop = sortop;
3400  grpcl->nulls_first = false; /* OK with or without sortop */
3401  grpcl->hashable = hashable;
3402 
3403  grouplist = lappend(grouplist, grpcl);
3404  }
3405 
3406  return grouplist;
3407 }
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:161
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
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:42

◆ addTargetToSortList()

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

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

3221 {
3222  Oid restype = exprType((Node *) tle->expr);
3223  Oid sortop;
3224  Oid eqop;
3225  bool hashable;
3226  bool reverse;
3227  int location;
3228  ParseCallbackState pcbstate;
3229 
3230  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3231  if (restype == UNKNOWNOID)
3232  {
3233  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3234  restype, TEXTOID, -1,
3237  -1);
3238  restype = TEXTOID;
3239  }
3240 
3241  /*
3242  * Rather than clutter the API of get_sort_group_operators and the other
3243  * functions we're about to use, make use of error context callback to
3244  * mark any error reports with a parse position. We point to the operator
3245  * location if present, else to the expression being sorted. (NB: use the
3246  * original untransformed expression here; the TLE entry might well point
3247  * at a duplicate expression in the regular SELECT list.)
3248  */
3249  location = sortby->location;
3250  if (location < 0)
3251  location = exprLocation(sortby->node);
3252  setup_parser_errposition_callback(&pcbstate, pstate, location);
3253 
3254  /* determine the sortop, eqop, and directionality */
3255  switch (sortby->sortby_dir)
3256  {
3257  case SORTBY_DEFAULT:
3258  case SORTBY_ASC:
3259  get_sort_group_operators(restype,
3260  true, true, false,
3261  &sortop, &eqop, NULL,
3262  &hashable);
3263  reverse = false;
3264  break;
3265  case SORTBY_DESC:
3266  get_sort_group_operators(restype,
3267  false, true, true,
3268  NULL, &eqop, &sortop,
3269  &hashable);
3270  reverse = true;
3271  break;
3272  case SORTBY_USING:
3273  Assert(sortby->useOp != NIL);
3274  sortop = compatible_oper_opid(sortby->useOp,
3275  restype,
3276  restype,
3277  false);
3278 
3279  /*
3280  * Verify it's a valid ordering operator, fetch the corresponding
3281  * equality operator, and determine whether to consider it like
3282  * ASC or DESC.
3283  */
3284  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3285  if (!OidIsValid(eqop))
3286  ereport(ERROR,
3287  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3288  errmsg("operator %s is not a valid ordering operator",
3289  strVal(llast(sortby->useOp))),
3290  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3291 
3292  /*
3293  * Also see if the equality operator is hashable.
3294  */
3295  hashable = op_hashjoinable(eqop, restype);
3296  break;
3297  default:
3298  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3299  sortop = InvalidOid; /* keep compiler quiet */
3300  eqop = InvalidOid;
3301  hashable = false;
3302  reverse = false;
3303  break;
3304  }
3305 
3307 
3308  /* avoid making duplicate sortlist entries */
3309  if (!targetIsInSortList(tle, sortop, sortlist))
3310  {
3312 
3313  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3314 
3315  sortcl->eqop = eqop;
3316  sortcl->sortop = sortop;
3317  sortcl->hashable = hashable;
3318 
3319  switch (sortby->sortby_nulls)
3320  {
3321  case SORTBY_NULLS_DEFAULT:
3322  /* NULLS FIRST is default for DESC; other way for ASC */
3323  sortcl->nulls_first = reverse;
3324  break;
3325  case SORTBY_NULLS_FIRST:
3326  sortcl->nulls_first = true;
3327  break;
3328  case SORTBY_NULLS_LAST:
3329  sortcl->nulls_first = false;
3330  break;
3331  default:
3332  elog(ERROR, "unrecognized sortby_nulls: %d",
3333  sortby->sortby_nulls);
3334  break;
3335  }
3336 
3337  sortlist = lappend(sortlist, sortcl);
3338  }
3339 
3340  return sortlist;
3341 }
#define NIL
Definition: pg_list.h:65
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
int errhint(const char *fmt,...)
Definition: elog.c:974
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1192
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:570
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
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:145
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:732
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:42
int errmsg(const char *fmt,...)
Definition: elog.c:784
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:494
#define elog(elevel,...)
Definition: elog.h:226
Node * node
Definition: parsenodes.h:469
int location
Definition: parsenodes.h:473

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3417 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

3418 {
3419  Index maxRef;
3420  ListCell *l;
3421 
3422  if (tle->ressortgroupref) /* already has one? */
3423  return tle->ressortgroupref;
3424 
3425  /* easiest way to pick an unused refnumber: max used + 1 */
3426  maxRef = 0;
3427  foreach(l, tlist)
3428  {
3429  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3430 
3431  if (ref > maxRef)
3432  maxRef = ref;
3433  }
3434  tle->ressortgroupref = maxRef + 1;
3435  return tle->ressortgroupref;
3436 }
unsigned int Index
Definition: c.h:475
#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 1503 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().

1505 {
1506  Oid outcoltype;
1507  int32 outcoltypmod;
1508  Node *l_node,
1509  *r_node,
1510  *res_node;
1511 
1512  /*
1513  * Choose output type if input types are dissimilar.
1514  */
1515  outcoltype = l_colvar->vartype;
1516  outcoltypmod = l_colvar->vartypmod;
1517  if (outcoltype != r_colvar->vartype)
1518  {
1519  outcoltype = select_common_type(pstate,
1520  list_make2(l_colvar, r_colvar),
1521  "JOIN/USING",
1522  NULL);
1523  outcoltypmod = -1; /* ie, unknown */
1524  }
1525  else if (outcoltypmod != r_colvar->vartypmod)
1526  {
1527  /* same type, but not same typmod */
1528  outcoltypmod = -1; /* ie, unknown */
1529  }
1530 
1531  /*
1532  * Insert coercion functions if needed. Note that a difference in typmod
1533  * can only happen if input has typmod but outcoltypmod is -1. In that
1534  * case we insert a RelabelType to clearly mark that result's typmod is
1535  * not same as input. We never need coerce_type_typmod.
1536  */
1537  if (l_colvar->vartype != outcoltype)
1538  l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
1539  outcoltype, outcoltypmod,
1541  else if (l_colvar->vartypmod != outcoltypmod)
1542  l_node = (Node *) makeRelabelType((Expr *) l_colvar,
1543  outcoltype, outcoltypmod,
1544  InvalidOid, /* fixed below */
1546  else
1547  l_node = (Node *) l_colvar;
1548 
1549  if (r_colvar->vartype != outcoltype)
1550  r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
1551  outcoltype, outcoltypmod,
1553  else if (r_colvar->vartypmod != outcoltypmod)
1554  r_node = (Node *) makeRelabelType((Expr *) r_colvar,
1555  outcoltype, outcoltypmod,
1556  InvalidOid, /* fixed below */
1558  else
1559  r_node = (Node *) r_colvar;
1560 
1561  /*
1562  * Choose what to emit
1563  */
1564  switch (jointype)
1565  {
1566  case JOIN_INNER:
1567 
1568  /*
1569  * We can use either var; prefer non-coerced one if available.
1570  */
1571  if (IsA(l_node, Var))
1572  res_node = l_node;
1573  else if (IsA(r_node, Var))
1574  res_node = r_node;
1575  else
1576  res_node = l_node;
1577  break;
1578  case JOIN_LEFT:
1579  /* Always use left var */
1580  res_node = l_node;
1581  break;
1582  case JOIN_RIGHT:
1583  /* Always use right var */
1584  res_node = r_node;
1585  break;
1586  case JOIN_FULL:
1587  {
1588  /*
1589  * Here we must build a COALESCE expression to ensure that the
1590  * join output is non-null if either input is.
1591  */
1593 
1594  c->coalescetype = outcoltype;
1595  /* coalescecollid will get set below */
1596  c->args = list_make2(l_node, r_node);
1597  c->location = -1;
1598  res_node = (Node *) c;
1599  break;
1600  }
1601  default:
1602  elog(ERROR, "unrecognized join type: %d", (int) jointype);
1603  res_node = NULL; /* keep compiler quiet */
1604  break;
1605  }
1606 
1607  /*
1608  * Apply assign_expr_collations to fix up the collation info in the
1609  * coercion and CoalesceExpr nodes, if we made any. This must be done now
1610  * so that the join node's alias vars show correct collation info.
1611  */
1612  assign_expr_collations(pstate, res_node);
1613 
1614  return res_node;
1615 }
#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:346
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:226
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 1738 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().

1739 {
1740  if (contain_vars_of_level(n, 0))
1741  {
1742  ereport(ERROR,
1743  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1744  /* translator: %s is name of a SQL construct, eg LIMIT */
1745  errmsg("argument of %s must not contain variables",
1746  constructName),
1747  parser_errposition(pstate,
1748  locate_var_of_level(n, 0))));
1749  }
1750 }
int errcode(int sqlerrcode)
Definition: elog.c:570
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:111
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ checkTargetlistEntrySQL92()

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

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

1765 {
1766  switch (exprKind)
1767  {
1768  case EXPR_KIND_GROUP_BY:
1769  /* reject aggregates and window functions */
1770  if (pstate->p_hasAggs &&
1771  contain_aggs_of_level((Node *) tle->expr, 0))
1772  ereport(ERROR,
1773  (errcode(ERRCODE_GROUPING_ERROR),
1774  /* translator: %s is name of a SQL construct, eg GROUP BY */
1775  errmsg("aggregate functions are not allowed in %s",
1776  ParseExprKindName(exprKind)),
1777  parser_errposition(pstate,
1778  locate_agg_of_level((Node *) tle->expr, 0))));
1779  if (pstate->p_hasWindowFuncs &&
1780  contain_windowfuncs((Node *) tle->expr))
1781  ereport(ERROR,
1782  (errcode(ERRCODE_WINDOWING_ERROR),
1783  /* translator: %s is name of a SQL construct, eg GROUP BY */
1784  errmsg("window functions are not allowed in %s",
1785  ParseExprKindName(exprKind)),
1786  parser_errposition(pstate,
1787  locate_windowfunc((Node *) tle->expr))));
1788  break;
1789  case EXPR_KIND_ORDER_BY:
1790  /* no extra checks needed */
1791  break;
1792  case EXPR_KIND_DISTINCT_ON:
1793  /* no extra checks needed */
1794  break;
1795  default:
1796  elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
1797  break;
1798  }
1799 }
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:570
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:3482
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:111
bool contain_aggs_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:67
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
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 255 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

258 {
259  List *new_colnames = NIL;
260  List *new_colvars = NIL;
261  ListCell *lnames,
262  *lvars;
263 
264  Assert(list_length(src_colnames) == list_length(src_colvars));
265 
266  forboth(lnames, src_colnames, lvars, src_colvars)
267  {
268  char *colname = strVal(lfirst(lnames));
269  bool match = false;
270  ListCell *cnames;
271 
272  foreach(cnames, common_colnames)
273  {
274  char *ccolname = strVal(lfirst(cnames));
275 
276  if (strcmp(colname, ccolname) == 0)
277  {
278  match = true;
279  break;
280  }
281  }
282 
283  if (!match)
284  {
285  new_colnames = lappend(new_colnames, lfirst(lnames));
286  new_colvars = lappend(new_colvars, lfirst(lvars));
287  }
288  }
289 
290  *res_colnames = new_colnames;
291  *res_colvars = new_colvars;
292 }
#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:732
#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 1819 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().

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

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

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

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

◆ findWindowClause()

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

Definition at line 3485 of file parse_clause.c.

References lfirst, and WindowClause::name.

Referenced by transformWindowDefinitions().

3486 {
3487  ListCell *l;
3488 
3489  foreach(l, wclist)
3490  {
3491  WindowClause *wc = (WindowClause *) lfirst(l);
3492 
3493  if (wc->name && strcmp(wc->name, name) == 0)
3494  return wc;
3495  }
3496 
3497  return NULL;
3498 }
#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 2072 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().

2073 {
2074  /* just in case of pathological input */
2076 
2077  if (expr == (Node *) NIL)
2078  return (Node *) NIL;
2079 
2080  switch (expr->type)
2081  {
2082  case T_RowExpr:
2083  {
2084  RowExpr *r = (RowExpr *) expr;
2085 
2086  if (r->row_format == COERCE_IMPLICIT_CAST)
2087  return flatten_grouping_sets((Node *) r->args,
2088  false, NULL);
2089  }
2090  break;
2091  case T_GroupingSet:
2092  {
2093  GroupingSet *gset = (GroupingSet *) expr;
2094  ListCell *l2;
2095  List *result_set = NIL;
2096 
2097  if (hasGroupingSets)
2098  *hasGroupingSets = true;
2099 
2100  /*
2101  * at the top level, we skip over all empty grouping sets; the
2102  * caller can supply the canonical GROUP BY () if nothing is
2103  * left.
2104  */
2105 
2106  if (toplevel && gset->kind == GROUPING_SET_EMPTY)
2107  return (Node *) NIL;
2108 
2109  foreach(l2, gset->content)
2110  {
2111  Node *n1 = lfirst(l2);
2112  Node *n2 = flatten_grouping_sets(n1, false, NULL);
2113 
2114  if (IsA(n1, GroupingSet) &&
2115  ((GroupingSet *) n1)->kind == GROUPING_SET_SETS)
2116  result_set = list_concat(result_set, (List *) n2);
2117  else
2118  result_set = lappend(result_set, n2);
2119  }
2120 
2121  /*
2122  * At top level, keep the grouping set node; but if we're in a
2123  * nested grouping set, then we need to concat the flattened
2124  * result into the outer list if it's simply nested.
2125  */
2126 
2127  if (toplevel || (gset->kind != GROUPING_SET_SETS))
2128  {
2129  return (Node *) makeGroupingSet(gset->kind, result_set, gset->location);
2130  }
2131  else
2132  return (Node *) result_set;
2133  }
2134  case T_List:
2135  {
2136  List *result = NIL;
2137  ListCell *l;
2138 
2139  foreach(l, (List *) expr)
2140  {
2141  Node *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets);
2142 
2143  if (n != (Node *) NIL)
2144  {
2145  if (IsA(n, List))
2146  result = list_concat(result, (List *) n);
2147  else
2148  result = lappend(result, n);
2149  }
2150  }
2151 
2152  return (Node *) result;
2153  }
2154  default:
2155  break;
2156  }
2157 
2158  return expr;
2159 }
#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:3262
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 2990 of file parse_clause.c.

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

Referenced by transformDistinctOnClause().

2991 {
2992  ListCell *lcs;
2993  ListCell *lce;
2994 
2995  forboth(lcs, sortgrouprefs, lce, exprs)
2996  {
2997  if (lfirst_int(lcs) == sortgroupref)
2998  return exprLocation((Node *) lfirst(lce));
2999  }
3000  /* if no match, caller blew it */
3001  elog(ERROR, "get_matching_location: no matching sortgroupref");
3002  return -1; /* keep compiler quiet */
3003 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1192
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:226

◆ getRTEForSpecialRelationTypes()

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

Definition at line 1020 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

1021 {
1022  CommonTableExpr *cte;
1023  Index levelsup;
1024  RangeTblEntry *rte;
1025 
1026  /*
1027  * if it is a qualified name, it can't be a CTE or tuplestore reference
1028  */
1029  if (rv->schemaname)
1030  return NULL;
1031 
1032  cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
1033  if (cte)
1034  rte = addRangeTableEntryForCTE(pstate, cte, levelsup, rv, true);
1035  else if (scanNameSpaceForENR(pstate, rv->relname))
1036  rte = addRangeTableEntryForENR(pstate, rv, true);
1037  else
1038  rte = NULL;
1039 
1040  return rte;
1041 }
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:475
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 1622 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().

1624 {
1625  ParseNamespaceItem *nsitem;
1626 
1627  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1628  nsitem->p_rte = rte;
1629  nsitem->p_rel_visible = rel_visible;
1630  nsitem->p_cols_visible = cols_visible;
1631  nsitem->p_lateral_only = lateral_only;
1632  nsitem->p_lateral_ok = lateral_ok;
1633  return nsitem;
1634 }
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 3015 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().

3017 {
3018  List *result = NIL;
3019  ListCell *l;
3020 
3021  foreach(l, infer->indexElems)
3022  {
3023  IndexElem *ielem = (IndexElem *) lfirst(l);
3025  Node *parse;
3026 
3027  /*
3028  * Raw grammar re-uses CREATE INDEX infrastructure for unique index
3029  * inference clause, and so will accept opclasses by name and so on.
3030  *
3031  * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
3032  * LAST ordering, since those are not significant for inference
3033  * purposes (any unique index matching the inference specification in
3034  * other regards is accepted indifferently). Actively reject this as
3035  * wrong-headed.
3036  */
3037  if (ielem->ordering != SORTBY_DEFAULT)
3038  ereport(ERROR,
3039  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3040  errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
3041  parser_errposition(pstate,
3042  exprLocation((Node *) infer))));
3043  if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
3044  ereport(ERROR,
3045  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3046  errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
3047  parser_errposition(pstate,
3048  exprLocation((Node *) infer))));
3049 
3050  if (!ielem->expr)
3051  {
3052  /* Simple index attribute */
3053  ColumnRef *n;
3054 
3055  /*
3056  * Grammar won't have built raw expression for us in event of
3057  * plain column reference. Create one directly, and perform
3058  * expression transformation. Planner expects this, and performs
3059  * its own normalization for the purposes of matching against
3060  * pg_index.
3061  */
3062  n = makeNode(ColumnRef);
3063  n->fields = list_make1(makeString(ielem->name));
3064  /* Location is approximately that of inference specification */
3065  n->location = infer->location;
3066  parse = (Node *) n;
3067  }
3068  else
3069  {
3070  /* Do parse transformation of the raw expression */
3071  parse = (Node *) ielem->expr;
3072  }
3073 
3074  /*
3075  * transformExpr() will reject subqueries, aggregates, window
3076  * functions, and SRFs, based on being passed
3077  * EXPR_KIND_INDEX_EXPRESSION. So we needn't worry about those
3078  * further ... not that they would match any available index
3079  * expression anyway.
3080  */
3081  pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
3082 
3083  /* Perform lookup of collation and operator class as required */
3084  if (!ielem->collation)
3085  pInfer->infercollid = InvalidOid;
3086  else
3087  pInfer->infercollid = LookupCollation(pstate, ielem->collation,
3088  exprLocation(pInfer->expr));
3089 
3090  if (!ielem->opclass)
3091  pInfer->inferopclass = InvalidOid;
3092  else
3093  pInfer->inferopclass = get_opclass_oid(BTREE_AM_OID,
3094  ielem->opclass, false);
3095 
3096  result = lappend(result, pInfer);
3097  }
3098 
3099  return result;
3100 }
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:1192
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
List * indexElems
Definition: parsenodes.h:1389
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:570
Oid get_opclass_oid(Oid amID, List *opclassname, bool missing_ok)
Definition: opclasscmds.c:223
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:514
#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:111
char * name
Definition: parsenodes.h:699
int errmsg(const char *fmt,...)
Definition: elog.c:784
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 1641 of file parse_clause.c.

References lfirst, and ParseNamespaceItem::p_cols_visible.

Referenced by transformFromClauseItem().

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

◆ setNamespaceLateralState()

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

Definition at line 1658 of file parse_clause.c.

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

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

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

◆ setTargetTable()

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

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

186 {
187  RangeTblEntry *rte;
188  int rtindex;
189 
190  /*
191  * ENRs hide tables of the same name, so we need to check for them first.
192  * In contrast, CTEs don't hide tables (for this purpose).
193  */
194  if (relation->schemaname == NULL &&
195  scanNameSpaceForENR(pstate, relation->relname))
196  ereport(ERROR,
197  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
198  errmsg("relation \"%s\" cannot be the target of a modifying statement",
199  relation->relname)));
200 
201  /* Close old target; this could only happen for multi-action rules */
202  if (pstate->p_target_relation != NULL)
204 
205  /*
206  * Open target rel and grab suitable lock (which we will hold till end of
207  * transaction).
208  *
209  * free_parsestate() will eventually do the corresponding table_close(),
210  * but *not* release the lock.
211  */
212  pstate->p_target_relation = parserOpenTable(pstate, relation,
214 
215  /*
216  * Now build an RTE.
217  */
218  rte = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
220  relation->alias, inh, false);
221  pstate->p_target_rangetblentry = rte;
222 
223  /* assume new rte is at end */
224  rtindex = list_length(pstate->p_rtable);
225  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
226 
227  /*
228  * Override addRangeTableEntry's default ACL_SELECT permissions check, and
229  * instead mark target table as requiring exactly the specified
230  * permissions.
231  *
232  * If we find an explicit reference to the rel later during parse
233  * analysis, we will add the ACL_SELECT bit back again; see
234  * markVarForSelectPriv and its callers.
235  */
236  rte->requiredPerms = requiredPerms;
237 
238  /*
239  * If UPDATE/DELETE, add table to joinlist and namespace.
240  *
241  * Note: some callers know that they can find the new ParseNamespaceItem
242  * at the end of the pstate->p_namespace list. This is a bit ugly but not
243  * worth complicating this function's signature for.
244  */
245  if (alsoSource)
246  addRTEtoQuery(pstate, rte, true, true, true);
247 
248  return rtindex;
249 }
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:570
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:732
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:784
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 3458 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().

3459 {
3460  Index ref = tle->ressortgroupref;
3461  ListCell *l;
3462 
3463  /* no need to scan list if tle has no marker */
3464  if (ref == 0)
3465  return false;
3466 
3467  foreach(l, sortList)
3468  {
3469  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3470 
3471  if (scl->tleSortGroupRef == ref &&
3472  (sortop == InvalidOid ||
3473  sortop == scl->sortop ||
3474  sortop == get_commutator(scl->sortop)))
3475  return true;
3476  }
3477  return false;
3478 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1311
Index tleSortGroupRef
Definition: parsenodes.h:1234
unsigned int Index
Definition: c.h:475
#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 2799 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().

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

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

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

119 {
120  ListCell *fl;
121 
122  /*
123  * The grammar will have produced a list of RangeVars, RangeSubselects,
124  * RangeFunctions, and/or JoinExprs. Transform each one (possibly adding
125  * entries to the rtable), check for duplicate refnames, and then add it
126  * to the joinlist and namespace.
127  *
128  * Note we must process the items left-to-right for proper handling of
129  * LATERAL references.
130  */
131  foreach(fl, frmList)
132  {
133  Node *n = lfirst(fl);
134  RangeTblEntry *rte;
135  int rtindex;
136  List *namespace;
137 
138  n = transformFromClauseItem(pstate, n,
139  &rte,
140  &rtindex,
141  &namespace);
142 
143  checkNameSpaceConflicts(pstate, pstate->p_namespace, namespace);
144 
145  /* Mark the new namespace items as visible only to LATERAL */
146  setNamespaceLateralState(namespace, true, true);
147 
148  pstate->p_joinlist = lappend(pstate->p_joinlist, n);
149  pstate->p_namespace = list_concat(pstate->p_namespace, namespace);
150  }
151 
152  /*
153  * We're done parsing the FROM list, so make all namespace items
154  * unconditionally visible. Note that this will also reset lateral_only
155  * for any namespace items that were already present when we were called;
156  * but those should have been that way already.
157  */
158  setNamespaceLateralState(pstate->p_namespace, false, true);
159 }
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 1065 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().

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

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

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

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

Referenced by transformGroupingSet().

2293 {
2294  Bitmapset *seen_local = NULL;
2295  List *result = NIL;
2296  ListCell *gl;
2297 
2298  foreach(gl, list)
2299  {
2300  Node *gexpr = (Node *) lfirst(gl);
2301 
2302  Index ref = transformGroupClauseExpr(flatresult,
2303  seen_local,
2304  pstate,
2305  gexpr,
2306  targetlist,
2307  sortClause,
2308  exprKind,
2309  useSQL99,
2310  toplevel);
2311 
2312  if (ref > 0)
2313  {
2314  seen_local = bms_add_member(seen_local, ref);
2315  result = lappend_int(result, ref);
2316  }
2317  }
2318 
2319  return result;
2320 }
#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:475
#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 2342 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().

2346 {
2347  ListCell *gl;
2348  List *content = NIL;
2349 
2350  Assert(toplevel || gset->kind != GROUPING_SET_SETS);
2351 
2352  foreach(gl, gset->content)
2353  {
2354  Node *n = lfirst(gl);
2355 
2356  if (IsA(n, List))
2357  {
2358  List *l = transformGroupClauseList(flatresult,
2359  pstate, (List *) n,
2360  targetlist, sortClause,
2361  exprKind, useSQL99, false);
2362 
2363  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2364  l,
2365  exprLocation(n)));
2366  }
2367  else if (IsA(n, GroupingSet))
2368  {
2369  GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
2370 
2371  content = lappend(content, transformGroupingSet(flatresult,
2372  pstate, gset2,
2373  targetlist, sortClause,
2374  exprKind, useSQL99, false));
2375  }
2376  else
2377  {
2378  Index ref = transformGroupClauseExpr(flatresult,
2379  NULL,
2380  pstate,
2381  n,
2382  targetlist,
2383  sortClause,
2384  exprKind,
2385  useSQL99,
2386  false);
2387 
2388  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2389  list_make1_int(ref),
2390  exprLocation(n)));
2391  }
2392  }
2393 
2394  /* Arbitrarily cap the size of CUBE, which has exponential growth */
2395  if (gset->kind == GROUPING_SET_CUBE)
2396  {
2397  if (list_length(content) > 12)
2398  ereport(ERROR,
2399  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2400  errmsg("CUBE is limited to 12 elements"),
2401  parser_errposition(pstate, gset->location)));
2402  }
2403 
2404  return (Node *) makeGroupingSet(gset->kind, content, gset->location);
2405 }
#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:1192
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:570
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:475
#define Assert(condition)
Definition: c.h:732
#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:111
int errmsg(const char *fmt,...)
Definition: elog.c:784
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 360 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

361 {
362  Node *result;
363  List *save_namespace;
364 
365  /*
366  * The namespace that the join expression should see is just the two
367  * subtrees of the JOIN plus any outer references from upper pstate
368  * levels. Temporarily set this pstate's namespace accordingly. (We need
369  * not check for refname conflicts, because transformFromClauseItem()
370  * already did.) All namespace items are marked visible regardless of
371  * LATERAL state.
372  */
373  setNamespaceLateralState(namespace, false, true);
374 
375  save_namespace = pstate->p_namespace;
376  pstate->p_namespace = namespace;
377 
378  result = transformWhereClause(pstate, j->quals,
379  EXPR_KIND_JOIN_ON, "JOIN/ON");
380 
381  pstate->p_namespace = save_namespace;
382 
383  return result;
384 }
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 300 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().

303 {
304  Node *result;
305  List *andargs = NIL;
306  ListCell *lvars,
307  *rvars;
308 
309  /*
310  * We cheat a little bit here by building an untransformed operator tree
311  * whose leaves are the already-transformed Vars. This requires collusion
312  * from transformExpr(), which normally could be expected to complain
313  * about already-transformed subnodes. However, this does mean that we
314  * have to mark the columns as requiring SELECT privilege for ourselves;
315  * transformExpr() won't do it.
316  */
317  forboth(lvars, leftVars, rvars, rightVars)
318  {
319  Var *lvar = (Var *) lfirst(lvars);
320  Var *rvar = (Var *) lfirst(rvars);
321  A_Expr *e;
322 
323  /* Require read access to the join variables */
324  markVarForSelectPriv(pstate, lvar, leftRTE);
325  markVarForSelectPriv(pstate, rvar, rightRTE);
326 
327  /* Now create the lvar = rvar join condition */
328  e = makeSimpleA_Expr(AEXPR_OP, "=",
329  (Node *) copyObject(lvar), (Node *) copyObject(rvar),
330  -1);
331 
332  /* Prepare to combine into an AND clause, if multiple join columns */
333  andargs = lappend(andargs, e);
334  }
335 
336  /* Only need an AND if there's more than one join column */
337  if (list_length(andargs) == 1)
338  result = (Node *) linitial(andargs);
339  else
340  result = (Node *) makeBoolExpr(AND_EXPR, andargs, -1);
341 
342  /*
343  * Since the references are already Vars, and are certainly from the input
344  * relations, we don't have to go through the same pushups that
345  * transformJoinOnClause() does. Just invoke transformExpr() to fix up
346  * the operators, and we're done.
347  */
348  result = transformExpr(pstate, result, EXPR_KIND_JOIN_USING);
349 
350  result = coerce_to_boolean(pstate, result, "JOIN/USING");
351 
352  return result;
353 }
#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:145
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 1707 of file parse_clause.c.

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

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

1709 {
1710  Node *qual;
1711 
1712  if (clause == NULL)
1713  return NULL;
1714 
1715  qual = transformExpr(pstate, clause, exprKind);
1716 
1717  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1718 
1719  /* LIMIT can't refer to any variables of the current query */
1720  checkExprIsVarFree(pstate, qual, constructName);
1721 
1722  return qual;
1723 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
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 3111 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().

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

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

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

◆ transformRangeTableFunc()

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

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

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

918 {
919  TableSampleClause *tablesample;
920  Oid handlerOid;
921  Oid funcargtypes[1];
922  TsmRoutine *tsm;
923  List *fargs;
924  ListCell *larg,
925  *ltyp;
926 
927  /*
928  * To validate the sample method name, look up the handler function, which
929  * has the same name, one dummy INTERNAL argument, and a result type of
930  * tsm_handler. (Note: tablesample method names are not schema-qualified
931  * in the SQL standard; but since they are just functions to us, we allow
932  * schema qualification to resolve any potential ambiguity.)
933  */
934  funcargtypes[0] = INTERNALOID;
935 
936  handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true);
937 
938  /* we want error to complain about no-such-method, not no-such-function */
939  if (!OidIsValid(handlerOid))
940  ereport(ERROR,
941  (errcode(ERRCODE_UNDEFINED_OBJECT),
942  errmsg("tablesample method %s does not exist",
943  NameListToString(rts->method)),
944  parser_errposition(pstate, rts->location)));
945 
946  /* check that handler has correct return type */
947  if (get_func_rettype(handlerOid) != TSM_HANDLEROID)
948  ereport(ERROR,
949  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
950  errmsg("function %s must return type %s",
951  NameListToString(rts->method), "tsm_handler"),
952  parser_errposition(pstate, rts->location)));
953 
954  /* OK, run the handler to get TsmRoutine, for argument type info */
955  tsm = GetTsmRoutine(handlerOid);
956 
957  tablesample = makeNode(TableSampleClause);
958  tablesample->tsmhandler = handlerOid;
959 
960  /* check user provided the expected number of arguments */
961  if (list_length(rts->args) != list_length(tsm->parameterTypes))
962  ereport(ERROR,
963  (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
964  errmsg_plural("tablesample method %s requires %d argument, not %d",
965  "tablesample method %s requires %d arguments, not %d",
967  NameListToString(rts->method),
969  list_length(rts->args)),
970  parser_errposition(pstate, rts->location)));
971 
972  /*
973  * Transform the arguments, typecasting them as needed. Note we must also
974  * assign collations now, because assign_query_collations() doesn't
975  * examine any substructure of RTEs.
976  */
977  fargs = NIL;
978  forboth(larg, rts->args, ltyp, tsm->parameterTypes)
979  {
980  Node *arg = (Node *) lfirst(larg);
981  Oid argtype = lfirst_oid(ltyp);
982 
983  arg = transformExpr(pstate, arg, EXPR_KIND_FROM_FUNCTION);
984  arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE");
985  assign_expr_collations(pstate, arg);
986  fargs = lappend(fargs, arg);
987  }
988  tablesample->args = fargs;
989 
990  /* Process REPEATABLE (seed) */
991  if (rts->repeatable != NULL)
992  {
993  Node *arg;
994 
995  if (!tsm->repeatable_across_queries)
996  ereport(ERROR,
997  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
998  errmsg("tablesample method %s does not support REPEATABLE",
999  NameListToString(rts->method)),
1000  parser_errposition(pstate, rts->location)));
1001 
1002  arg = transformExpr(pstate, rts->repeatable, EXPR_KIND_FROM_FUNCTION);
1003  arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE");
1004  assign_expr_collations(pstate, arg);
1005  tablesample->repeatable = (Expr *) arg;
1006  }
1007  else
1008  tablesample->repeatable = NULL;
1009 
1010  return tablesample;
1011 }
#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:837
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:570
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
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:2100
#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:111
int errmsg(const char *fmt,...)
Definition: elog.c:784
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 2546 of file parse_clause.c.

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

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

2551 {
2552  List *sortlist = NIL;
2553  ListCell *olitem;
2554 
2555  foreach(olitem, orderlist)
2556  {
2557  SortBy *sortby = (SortBy *) lfirst(olitem);
2558  TargetEntry *tle;
2559 
2560  if (useSQL99)
2561  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2562  targetlist, exprKind);
2563  else
2564  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2565  targetlist, exprKind);
2566 
2567  sortlist = addTargetToSortList(pstate, tle,
2568  sortlist, *targetlist, sortby);
2569  }
2570 
2571  return sortlist;
2572 }
#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 390 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

391 {
392  RangeTblEntry *rte;
393 
394  /* We need only build a range table entry */
395  rte = addRangeTableEntry(pstate, r, r->alias, r->inh, true);
396 
397  return rte;
398 }
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 1680 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().

1682 {
1683  Node *qual;
1684 
1685  if (clause == NULL)
1686  return NULL;
1687 
1688  qual = transformExpr(pstate, clause, exprKind);
1689 
1690  qual = coerce_to_boolean(pstate, qual, constructName);
1691 
1692  return qual;
1693 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
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 2579 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().

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