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

Go to the source code of this file.

Functions

static int extractRemainingColumns (ParseNamespaceColumn *src_nscolumns, List *src_colnames, List **src_colnos, List **res_colnames, List **res_colvars, ParseNamespaceColumn *res_nscolumns)
 
static NodetransformJoinUsingClause (ParseState *pstate, List *leftVars, List *rightVars)
 
static NodetransformJoinOnClause (ParseState *pstate, JoinExpr *j, List *namespace)
 
static ParseNamespaceItemtransformTableEntry (ParseState *pstate, RangeVar *r)
 
static ParseNamespaceItemtransformRangeSubselect (ParseState *pstate, RangeSubselect *r)
 
static ParseNamespaceItemtransformRangeFunction (ParseState *pstate, RangeFunction *r)
 
static ParseNamespaceItemtransformRangeTableFunc (ParseState *pstate, RangeTableFunc *rtf)
 
static TableSampleClausetransformRangeTableSample (ParseState *pstate, RangeTableSample *rts)
 
static ParseNamespaceItemgetNSItemForSpecialRelationTypes (ParseState *pstate, RangeVar *rv)
 
static NodetransformFromClauseItem (ParseState *pstate, Node *n, ParseNamespaceItem **top_nsitem, List **namespace)
 
static VarbuildVarFromNSColumn (ParseNamespaceColumn *nscol)
 
static NodebuildMergedJoinVar (ParseState *pstate, JoinType jointype, Var *l_colvar, Var *r_colvar)
 
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, LimitOption limitOption)
 
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)
 

Function Documentation

◆ addTargetToGroupList()

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

Definition at line 3404 of file parse_clause.c.

3406 {
3407  Oid restype = exprType((Node *) tle->expr);
3408 
3409  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3410  if (restype == UNKNOWNOID)
3411  {
3412  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3413  restype, TEXTOID, -1,
3416  -1);
3417  restype = TEXTOID;
3418  }
3419 
3420  /* avoid making duplicate grouplist entries */
3421  if (!targetIsInSortList(tle, InvalidOid, grouplist))
3422  {
3424  Oid sortop;
3425  Oid eqop;
3426  bool hashable;
3427  ParseCallbackState pcbstate;
3428 
3429  setup_parser_errposition_callback(&pcbstate, pstate, location);
3430 
3431  /* determine the eqop and optional sortop */
3432  get_sort_group_operators(restype,
3433  false, true, false,
3434  &sortop, &eqop, NULL,
3435  &hashable);
3436 
3438 
3439  grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3440  grpcl->eqop = eqop;
3441  grpcl->sortop = sortop;
3442  grpcl->nulls_first = false; /* OK with or without sortop */
3443  grpcl->hashable = hashable;
3444 
3445  grouplist = lappend(grouplist, grpcl);
3446  }
3447 
3448  return grouplist;
3449 }
List * lappend(List *list, void *datum)
Definition: list.c:338
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
#define makeNode(_type_)
Definition: nodes.h:159
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:157
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
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:192
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:588
@ COERCION_IMPLICIT
Definition: primnodes.h:566
Definition: nodes.h:112
Index tleSortGroupRef
Definition: parsenodes.h:1318
Expr * expr
Definition: primnodes.h:1555

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

◆ addTargetToSortList()

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

Definition at line 3261 of file parse_clause.c.

3263 {
3264  Oid restype = exprType((Node *) tle->expr);
3265  Oid sortop;
3266  Oid eqop;
3267  bool hashable;
3268  bool reverse;
3269  int location;
3270  ParseCallbackState pcbstate;
3271 
3272  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3273  if (restype == UNKNOWNOID)
3274  {
3275  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3276  restype, TEXTOID, -1,
3279  -1);
3280  restype = TEXTOID;
3281  }
3282 
3283  /*
3284  * Rather than clutter the API of get_sort_group_operators and the other
3285  * functions we're about to use, make use of error context callback to
3286  * mark any error reports with a parse position. We point to the operator
3287  * location if present, else to the expression being sorted. (NB: use the
3288  * original untransformed expression here; the TLE entry might well point
3289  * at a duplicate expression in the regular SELECT list.)
3290  */
3291  location = sortby->location;
3292  if (location < 0)
3293  location = exprLocation(sortby->node);
3294  setup_parser_errposition_callback(&pcbstate, pstate, location);
3295 
3296  /* determine the sortop, eqop, and directionality */
3297  switch (sortby->sortby_dir)
3298  {
3299  case SORTBY_DEFAULT:
3300  case SORTBY_ASC:
3301  get_sort_group_operators(restype,
3302  true, true, false,
3303  &sortop, &eqop, NULL,
3304  &hashable);
3305  reverse = false;
3306  break;
3307  case SORTBY_DESC:
3308  get_sort_group_operators(restype,
3309  false, true, true,
3310  NULL, &eqop, &sortop,
3311  &hashable);
3312  reverse = true;
3313  break;
3314  case SORTBY_USING:
3315  Assert(sortby->useOp != NIL);
3316  sortop = compatible_oper_opid(sortby->useOp,
3317  restype,
3318  restype,
3319  false);
3320 
3321  /*
3322  * Verify it's a valid ordering operator, fetch the corresponding
3323  * equality operator, and determine whether to consider it like
3324  * ASC or DESC.
3325  */
3326  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3327  if (!OidIsValid(eqop))
3328  ereport(ERROR,
3329  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3330  errmsg("operator %s is not a valid ordering operator",
3331  strVal(llast(sortby->useOp))),
3332  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3333 
3334  /*
3335  * Also see if the equality operator is hashable.
3336  */
3337  hashable = op_hashjoinable(eqop, restype);
3338  break;
3339  default:
3340  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3341  sortop = InvalidOid; /* keep compiler quiet */
3342  eqop = InvalidOid;
3343  hashable = false;
3344  reverse = false;
3345  break;
3346  }
3347 
3349 
3350  /* avoid making duplicate sortlist entries */
3351  if (!targetIsInSortList(tle, sortop, sortlist))
3352  {
3354 
3355  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3356 
3357  sortcl->eqop = eqop;
3358  sortcl->sortop = sortop;
3359  sortcl->hashable = hashable;
3360 
3361  switch (sortby->sortby_nulls)
3362  {
3363  case SORTBY_NULLS_DEFAULT:
3364  /* NULLS FIRST is default for DESC; other way for ASC */
3365  sortcl->nulls_first = reverse;
3366  break;
3367  case SORTBY_NULLS_FIRST:
3368  sortcl->nulls_first = true;
3369  break;
3370  case SORTBY_NULLS_LAST:
3371  sortcl->nulls_first = false;
3372  break;
3373  default:
3374  elog(ERROR, "unrecognized sortby_nulls: %d",
3375  sortby->sortby_nulls);
3376  break;
3377  }
3378 
3379  sortlist = lappend(sortlist, sortcl);
3380  }
3381 
3382  return sortlist;
3383 }
#define OidIsValid(objectId)
Definition: c.h:711
int errhint(const char *fmt,...)
Definition: elog.c:1153
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
Assert(fmt[strlen(fmt) - 1] !='\n')
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:266
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1419
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1243
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:499
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:61
@ SORTBY_NULLS_LAST
Definition: parsenodes.h:63
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:62
@ SORTBY_USING
Definition: parsenodes.h:56
@ SORTBY_DESC
Definition: parsenodes.h:55
@ SORTBY_ASC
Definition: parsenodes.h:54
@ SORTBY_DEFAULT
Definition: parsenodes.h:53
#define llast(l)
Definition: pg_list.h:196
#define NIL
Definition: pg_list.h:66
SortByNulls sortby_nulls
Definition: parsenodes.h:511
Node * node
Definition: parsenodes.h:509
List * useOp
Definition: parsenodes.h:512
SortByDir sortby_dir
Definition: parsenodes.h:510
int location
Definition: parsenodes.h:513
#define strVal(v)
Definition: value.h:82

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

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3459 of file parse_clause.c.

3460 {
3461  Index maxRef;
3462  ListCell *l;
3463 
3464  if (tle->ressortgroupref) /* already has one? */
3465  return tle->ressortgroupref;
3466 
3467  /* easiest way to pick an unused refnumber: max used + 1 */
3468  maxRef = 0;
3469  foreach(l, tlist)
3470  {
3471  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3472 
3473  if (ref > maxRef)
3474  maxRef = ref;
3475  }
3476  tle->ressortgroupref = maxRef + 1;
3477  return tle->ressortgroupref;
3478 }
unsigned int Index
Definition: c.h:550
#define lfirst(lc)
Definition: pg_list.h:170
Index ressortgroupref
Definition: primnodes.h:1558

References lfirst, and TargetEntry::ressortgroupref.

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

◆ buildMergedJoinVar()

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

Definition at line 1575 of file parse_clause.c.

1577 {
1578  Oid outcoltype;
1579  int32 outcoltypmod;
1580  Node *l_node,
1581  *r_node,
1582  *res_node;
1583 
1584  outcoltype = select_common_type(pstate,
1585  list_make2(l_colvar, r_colvar),
1586  "JOIN/USING",
1587  NULL);
1588  outcoltypmod = select_common_typmod(pstate,
1589  list_make2(l_colvar, r_colvar),
1590  outcoltype);
1591 
1592  /*
1593  * Insert coercion functions if needed. Note that a difference in typmod
1594  * can only happen if input has typmod but outcoltypmod is -1. In that
1595  * case we insert a RelabelType to clearly mark that result's typmod is
1596  * not same as input. We never need coerce_type_typmod.
1597  */
1598  if (l_colvar->vartype != outcoltype)
1599  l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
1600  outcoltype, outcoltypmod,
1602  else if (l_colvar->vartypmod != outcoltypmod)
1603  l_node = (Node *) makeRelabelType((Expr *) l_colvar,
1604  outcoltype, outcoltypmod,
1605  InvalidOid, /* fixed below */
1607  else
1608  l_node = (Node *) l_colvar;
1609 
1610  if (r_colvar->vartype != outcoltype)
1611  r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
1612  outcoltype, outcoltypmod,
1614  else if (r_colvar->vartypmod != outcoltypmod)
1615  r_node = (Node *) makeRelabelType((Expr *) r_colvar,
1616  outcoltype, outcoltypmod,
1617  InvalidOid, /* fixed below */
1619  else
1620  r_node = (Node *) r_colvar;
1621 
1622  /*
1623  * Choose what to emit
1624  */
1625  switch (jointype)
1626  {
1627  case JOIN_INNER:
1628 
1629  /*
1630  * We can use either var; prefer non-coerced one if available.
1631  */
1632  if (IsA(l_node, Var))
1633  res_node = l_node;
1634  else if (IsA(r_node, Var))
1635  res_node = r_node;
1636  else
1637  res_node = l_node;
1638  break;
1639  case JOIN_LEFT:
1640  /* Always use left var */
1641  res_node = l_node;
1642  break;
1643  case JOIN_RIGHT:
1644  /* Always use right var */
1645  res_node = r_node;
1646  break;
1647  case JOIN_FULL:
1648  {
1649  /*
1650  * Here we must build a COALESCE expression to ensure that the
1651  * join output is non-null if either input is.
1652  */
1654 
1655  c->coalescetype = outcoltype;
1656  /* coalescecollid will get set below */
1657  c->args = list_make2(l_node, r_node);
1658  c->location = -1;
1659  res_node = (Node *) c;
1660  break;
1661  }
1662  default:
1663  elog(ERROR, "unrecognized join type: %d", (int) jointype);
1664  res_node = NULL; /* keep compiler quiet */
1665  break;
1666  }
1667 
1668  /*
1669  * Apply assign_expr_collations to fix up the collation info in the
1670  * coercion and CoalesceExpr nodes, if we made any. This must be done now
1671  * so that the join node's alias vars show correct collation info.
1672  */
1673  assign_expr_collations(pstate, res_node);
1674 
1675  return res_node;
1676 }
signed int int32
Definition: c.h:430
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:402
#define IsA(nodeptr, _type_)
Definition: nodes.h:162
@ JOIN_FULL
Definition: nodes.h:289
@ JOIN_INNER
Definition: nodes.h:287
@ JOIN_RIGHT
Definition: nodes.h:290
@ JOIN_LEFT
Definition: nodes.h:288
int32 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
void assign_expr_collations(ParseState *pstate, Node *expr)
#define list_make2(x1, x2)
Definition: pg_list.h:212
char * c
Definition: primnodes.h:205
Oid vartype
Definition: primnodes.h:220
int32 vartypmod
Definition: primnodes.h:222

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

Referenced by transformFromClauseItem().

◆ buildVarFromNSColumn()

static Var * buildVarFromNSColumn ( ParseNamespaceColumn nscol)
static

Definition at line 1553 of file parse_clause.c.

1554 {
1555  Var *var;
1556 
1557  Assert(nscol->p_varno > 0); /* i.e., not deleted column */
1558  var = makeVar(nscol->p_varno,
1559  nscol->p_varattno,
1560  nscol->p_vartype,
1561  nscol->p_vartypmod,
1562  nscol->p_varcollid,
1563  0);
1564  /* makeVar doesn't offer parameters for these, so set by hand: */
1565  var->varnosyn = nscol->p_varnosyn;
1566  var->varattnosyn = nscol->p_varattnosyn;
1567  return var;
1568 }
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
AttrNumber p_varattno
Definition: parse_node.h:306
AttrNumber p_varattnosyn
Definition: parse_node.h:311

References Assert(), makeVar(), ParseNamespaceColumn::p_varattno, ParseNamespaceColumn::p_varattnosyn, ParseNamespaceColumn::p_varcollid, ParseNamespaceColumn::p_varno, ParseNamespaceColumn::p_varnosyn, ParseNamespaceColumn::p_vartype, and ParseNamespaceColumn::p_vartypmod.

Referenced by extractRemainingColumns(), and transformFromClauseItem().

◆ checkExprIsVarFree()

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

Definition at line 1793 of file parse_clause.c.

1794 {
1795  if (contain_vars_of_level(n, 0))
1796  {
1797  ereport(ERROR,
1798  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1799  /* translator: %s is name of a SQL construct, eg LIMIT */
1800  errmsg("argument of %s must not contain variables",
1801  constructName),
1802  parser_errposition(pstate,
1803  locate_var_of_level(n, 0))));
1804  }
1805 }
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:431
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:499

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

Referenced by transformFrameOffset(), and transformLimitClause().

◆ checkTargetlistEntrySQL92()

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

Definition at line 1818 of file parse_clause.c.

1820 {
1821  switch (exprKind)
1822  {
1823  case EXPR_KIND_GROUP_BY:
1824  /* reject aggregates and window functions */
1825  if (pstate->p_hasAggs &&
1826  contain_aggs_of_level((Node *) tle->expr, 0))
1827  ereport(ERROR,
1828  (errcode(ERRCODE_GROUPING_ERROR),
1829  /* translator: %s is name of a SQL construct, eg GROUP BY */
1830  errmsg("aggregate functions are not allowed in %s",
1831  ParseExprKindName(exprKind)),
1832  parser_errposition(pstate,
1833  locate_agg_of_level((Node *) tle->expr, 0))));
1834  if (pstate->p_hasWindowFuncs &&
1835  contain_windowfuncs((Node *) tle->expr))
1836  ereport(ERROR,
1837  (errcode(ERRCODE_WINDOWING_ERROR),
1838  /* translator: %s is name of a SQL construct, eg GROUP BY */
1839  errmsg("window functions are not allowed in %s",
1840  ParseExprKindName(exprKind)),
1841  parser_errposition(pstate,
1842  locate_windowfunc((Node *) tle->expr))));
1843  break;
1844  case EXPR_KIND_ORDER_BY:
1845  /* no extra checks needed */
1846  break;
1847  case EXPR_KIND_DISTINCT_ON:
1848  /* no extra checks needed */
1849  break;
1850  default:
1851  elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
1852  break;
1853  }
1854 }
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:2946
@ EXPR_KIND_DISTINCT_ON
Definition: parse_node.h:61
@ EXPR_KIND_ORDER_BY
Definition: parse_node.h:60
@ EXPR_KIND_GROUP_BY
Definition: parse_node.h:59
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
bool contain_aggs_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:67
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
bool p_hasWindowFuncs
Definition: parse_node.h:210
bool p_hasAggs
Definition: parse_node.h:209

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

◆ extractRemainingColumns()

static int extractRemainingColumns ( ParseNamespaceColumn src_nscolumns,
List src_colnames,
List **  src_colnos,
List **  res_colnames,
List **  res_colvars,
ParseNamespaceColumn res_nscolumns 
)
static

Definition at line 254 of file parse_clause.c.

259 {
260  int colcount = 0;
261  Bitmapset *prevcols;
262  int attnum;
263  ListCell *lc;
264 
265  /*
266  * While we could just test "list_member_int(*src_colnos, attnum)" to
267  * detect already-merged columns in the loop below, that would be O(N^2)
268  * for a wide input table. Instead build a bitmapset of just the merged
269  * USING columns, which we won't add to within the main loop.
270  */
271  prevcols = NULL;
272  foreach(lc, *src_colnos)
273  {
274  prevcols = bms_add_member(prevcols, lfirst_int(lc));
275  }
276 
277  attnum = 0;
278  foreach(lc, src_colnames)
279  {
280  char *colname = strVal(lfirst(lc));
281 
282  attnum++;
283  /* Non-dropped and not already merged? */
284  if (colname[0] != '\0' && !bms_is_member(attnum, prevcols))
285  {
286  /* Yes, so emit it as next output column */
287  *src_colnos = lappend_int(*src_colnos, attnum);
288  *res_colnames = lappend(*res_colnames, lfirst(lc));
289  *res_colvars = lappend(*res_colvars,
290  buildVarFromNSColumn(src_nscolumns + attnum - 1));
291  /* Copy the input relation's nscolumn data for this column */
292  res_nscolumns[colcount] = src_nscolumns[attnum - 1];
293  colcount++;
294  }
295  }
296  return colcount;
297 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:428
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:739
List * lappend_int(List *list, int datum)
Definition: list.c:356
static Var * buildVarFromNSColumn(ParseNamespaceColumn *nscol)
int16 attnum
Definition: pg_attribute.h:83
#define lfirst_int(lc)
Definition: pg_list.h:171

References attnum, bms_add_member(), bms_is_member(), buildVarFromNSColumn(), lappend(), lappend_int(), lfirst, lfirst_int, and strVal.

Referenced by transformFromClauseItem().

◆ findTargetlistEntrySQL92()

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

Definition at line 1874 of file parse_clause.c.

1876 {
1877  ListCell *tl;
1878 
1879  /*----------
1880  * Handle two special cases as mandated by the SQL92 spec:
1881  *
1882  * 1. Bare ColumnName (no qualifier or subscripts)
1883  * For a bare identifier, we search for a matching column name
1884  * in the existing target list. Multiple matches are an error
1885  * unless they refer to identical values; for example,
1886  * we allow SELECT a, a FROM table ORDER BY a
1887  * but not SELECT a AS b, b FROM table ORDER BY b
1888  * If no match is found, we fall through and treat the identifier
1889  * as an expression.
1890  * For GROUP BY, it is incorrect to match the grouping item against
1891  * targetlist entries: according to SQL92, an identifier in GROUP BY
1892  * is a reference to a column name exposed by FROM, not to a target
1893  * list column. However, many implementations (including pre-7.0
1894  * PostgreSQL) accept this anyway. So for GROUP BY, we look first
1895  * to see if the identifier matches any FROM column name, and only
1896  * try for a targetlist name if it doesn't. This ensures that we
1897  * adhere to the spec in the case where the name could be both.
1898  * DISTINCT ON isn't in the standard, so we can do what we like there;
1899  * we choose to make it work like ORDER BY, on the rather flimsy
1900  * grounds that ordinary DISTINCT works on targetlist entries.
1901  *
1902  * 2. IntegerConstant
1903  * This means to use the n'th item in the existing target list.
1904  * Note that it would make no sense to order/group/distinct by an
1905  * actual constant, so this does not create a conflict with SQL99.
1906  * GROUP BY column-number is not allowed by SQL92, but since
1907  * the standard has no other behavior defined for this syntax,
1908  * we may as well accept this common extension.
1909  *
1910  * Note that pre-existing resjunk targets must not be used in either case,
1911  * since the user didn't write them in his SELECT list.
1912  *
1913  * If neither special case applies, fall through to treat the item as
1914  * an expression per SQL99.
1915  *----------
1916  */
1917  if (IsA(node, ColumnRef) &&
1918  list_length(((ColumnRef *) node)->fields) == 1 &&
1919  IsA(linitial(((ColumnRef *) node)->fields), String))
1920  {
1921  char *name = strVal(linitial(((ColumnRef *) node)->fields));
1922  int location = ((ColumnRef *) node)->location;
1923 
1924  if (exprKind == EXPR_KIND_GROUP_BY)
1925  {
1926  /*
1927  * In GROUP BY, we must prefer a match against a FROM-clause
1928  * column to one against the targetlist. Look to see if there is
1929  * a matching column. If so, fall through to use SQL99 rules.
1930  * NOTE: if name could refer ambiguously to more than one column
1931  * name exposed by FROM, colNameToVar will ereport(ERROR). That's
1932  * just what we want here.
1933  *
1934  * Small tweak for 7.4.3: ignore matches in upper query levels.
1935  * This effectively changes the search order for bare names to (1)
1936  * local FROM variables, (2) local targetlist aliases, (3) outer
1937  * FROM variables, whereas before it was (1) (3) (2). SQL92 and
1938  * SQL99 do not allow GROUPing BY an outer reference, so this
1939  * breaks no cases that are legal per spec, and it seems a more
1940  * self-consistent behavior.
1941  */
1942  if (colNameToVar(pstate, name, true, location) != NULL)
1943  name = NULL;
1944  }
1945 
1946  if (name != NULL)
1947  {
1948  TargetEntry *target_result = NULL;
1949 
1950  foreach(tl, *tlist)
1951  {
1952  TargetEntry *tle = (TargetEntry *) lfirst(tl);
1953 
1954  if (!tle->resjunk &&
1955  strcmp(tle->resname, name) == 0)
1956  {
1957  if (target_result != NULL)
1958  {
1959  if (!equal(target_result->expr, tle->expr))
1960  ereport(ERROR,
1961  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1962 
1963  /*------
1964  translator: first %s is name of a SQL construct, eg ORDER BY */
1965  errmsg("%s \"%s\" is ambiguous",
1966  ParseExprKindName(exprKind),
1967  name),
1968  parser_errposition(pstate, location)));
1969  }
1970  else
1971  target_result = tle;
1972  /* Stay in loop to check for ambiguity */
1973  }
1974  }
1975  if (target_result != NULL)
1976  {
1977  /* return the first match, after suitable validation */
1978  checkTargetlistEntrySQL92(pstate, target_result, exprKind);
1979  return target_result;
1980  }
1981  }
1982  }
1983  if (IsA(node, A_Const))
1984  {
1985  A_Const *aconst = castNode(A_Const, node);
1986  int targetlist_pos = 0;
1987  int target_pos;
1988 
1989  if (!IsA(&aconst->val, Integer))
1990  ereport(ERROR,
1991  (errcode(ERRCODE_SYNTAX_ERROR),
1992  /* translator: %s is name of a SQL construct, eg ORDER BY */
1993  errmsg("non-integer constant in %s",
1994  ParseExprKindName(exprKind)),
1995  parser_errposition(pstate, aconst->location)));
1996 
1997  target_pos = intVal(&aconst->val);
1998  foreach(tl, *tlist)
1999  {
2000  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2001 
2002  if (!tle->resjunk)
2003  {
2004  if (++targetlist_pos == target_pos)
2005  {
2006  /* return the unique match, after suitable validation */
2007  checkTargetlistEntrySQL92(pstate, tle, exprKind);
2008  return tle;
2009  }
2010  }
2011  }
2012  ereport(ERROR,
2013  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2014  /* translator: %s is name of a SQL construct, eg ORDER BY */
2015  errmsg("%s position %d is not in select list",
2016  ParseExprKindName(exprKind), target_pos),
2017  parser_errposition(pstate, aconst->location)));
2018  }
2019 
2020  /*
2021  * Otherwise, we have an expression, so process it per SQL99 rules.
2022  */
2023  return findTargetlistEntrySQL99(pstate, node, tlist, exprKind);
2024 }
const char * name
Definition: encode.c:561
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:225
#define castNode(_type_, nodeptr)
Definition: nodes.h:180
static void checkTargetlistEntrySQL92(ParseState *pstate, TargetEntry *tle, ParseExprKind exprKind)
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Node * colNameToVar(ParseState *pstate, const char *colname, bool localonly, int location)
static int list_length(const List *l)
Definition: pg_list.h:150
#define linitial(l)
Definition: pg_list.h:176
int location
Definition: parsenodes.h:327
union ValUnion val
Definition: parsenodes.h:325
Definition: value.h:29
Definition: value.h:64
char * resname
Definition: primnodes.h:1557
bool resjunk
Definition: primnodes.h:1562
#define intVal(v)
Definition: value.h:79

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

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

◆ findTargetlistEntrySQL99()

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

Definition at line 2040 of file parse_clause.c.

2042 {
2043  TargetEntry *target_result;
2044  ListCell *tl;
2045  Node *expr;
2046 
2047  /*
2048  * Convert the untransformed node to a transformed expression, and search
2049  * for a match in the tlist. NOTE: it doesn't really matter whether there
2050  * is more than one match. Also, we are willing to match an existing
2051  * resjunk target here, though the SQL92 cases above must ignore resjunk
2052  * targets.
2053  */
2054  expr = transformExpr(pstate, node, exprKind);
2055 
2056  foreach(tl, *tlist)
2057  {
2058  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2059  Node *texpr;
2060 
2061  /*
2062  * Ignore any implicit cast on the existing tlist expression.
2063  *
2064  * This essentially allows the ORDER/GROUP/etc item to adopt the same
2065  * datatype previously selected for a textually-equivalent tlist item.
2066  * There can't be any implicit cast at top level in an ordinary SELECT
2067  * tlist at this stage, but the case does arise with ORDER BY in an
2068  * aggregate function.
2069  */
2070  texpr = strip_implicit_coercions((Node *) tle->expr);
2071 
2072  if (equal(expr, texpr))
2073  return tle;
2074  }
2075 
2076  /*
2077  * If no matches, construct a new target entry which is appended to the
2078  * end of the target list. This target is given resjunk = true so that it
2079  * will not be projected into the final tuple.
2080  */
2081  target_result = transformTargetEntry(pstate, node, expr, exprKind,
2082  NULL, true);
2083 
2084  *tlist = lappend(*tlist, target_result);
2085 
2086  return target_result;
2087 }
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:648
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:92
TargetEntry * transformTargetEntry(ParseState *pstate, Node *node, Node *expr, ParseExprKind exprKind, char *colname, bool resjunk)
Definition: parse_target.c:76

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

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

◆ findWindowClause()

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

Definition at line 3527 of file parse_clause.c.

3528 {
3529  ListCell *l;
3530 
3531  foreach(l, wclist)
3532  {
3533  WindowClause *wc = (WindowClause *) lfirst(l);
3534 
3535  if (wc->name && strcmp(wc->name, name) == 0)
3536  return wc;
3537  }
3538 
3539  return NULL;
3540 }

References lfirst, name, and WindowClause::name.

Referenced by transformWindowDefinitions().

◆ flatten_grouping_sets()

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

Definition at line 2126 of file parse_clause.c.

2127 {
2128  /* just in case of pathological input */
2130 
2131  if (expr == (Node *) NIL)
2132  return (Node *) NIL;
2133 
2134  switch (expr->type)
2135  {
2136  case T_RowExpr:
2137  {
2138  RowExpr *r = (RowExpr *) expr;
2139 
2140  if (r->row_format == COERCE_IMPLICIT_CAST)
2141  return flatten_grouping_sets((Node *) r->args,
2142  false, NULL);
2143  }
2144  break;
2145  case T_GroupingSet:
2146  {
2147  GroupingSet *gset = (GroupingSet *) expr;
2148  ListCell *l2;
2149  List *result_set = NIL;
2150 
2151  if (hasGroupingSets)
2152  *hasGroupingSets = true;
2153 
2154  /*
2155  * at the top level, we skip over all empty grouping sets; the
2156  * caller can supply the canonical GROUP BY () if nothing is
2157  * left.
2158  */
2159 
2160  if (toplevel && gset->kind == GROUPING_SET_EMPTY)
2161  return (Node *) NIL;
2162 
2163  foreach(l2, gset->content)
2164  {
2165  Node *n1 = lfirst(l2);
2166  Node *n2 = flatten_grouping_sets(n1, false, NULL);
2167 
2168  if (IsA(n1, GroupingSet) &&
2169  ((GroupingSet *) n1)->kind == GROUPING_SET_SETS)
2170  result_set = list_concat(result_set, (List *) n2);
2171  else
2172  result_set = lappend(result_set, n2);
2173  }
2174 
2175  /*
2176  * At top level, keep the grouping set node; but if we're in a
2177  * nested grouping set, then we need to concat the flattened
2178  * result into the outer list if it's simply nested.
2179  */
2180 
2181  if (toplevel || (gset->kind != GROUPING_SET_SETS))
2182  {
2183  return (Node *) makeGroupingSet(gset->kind, result_set, gset->location);
2184  }
2185  else
2186  return (Node *) result_set;
2187  }
2188  case T_List:
2189  {
2190  List *result = NIL;
2191  ListCell *l;
2192 
2193  foreach(l, (List *) expr)
2194  {
2195  Node *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets);
2196 
2197  if (n != (Node *) NIL)
2198  {
2199  if (IsA(n, List))
2200  result = list_concat(result, (List *) n);
2201  else
2202  result = lappend(result, n);
2203  }
2204  }
2205 
2206  return (Node *) result;
2207  }
2208  default:
2209  break;
2210  }
2211 
2212  return expr;
2213 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:797
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
@ GROUPING_SET_SETS
Definition: parsenodes.h:1381
@ GROUPING_SET_EMPTY
Definition: parsenodes.h:1377
void check_stack_depth(void)
Definition: postgres.c:3440
GroupingSetKind kind
Definition: parsenodes.h:1387
List * content
Definition: parsenodes.h:1388
Definition: pg_list.h:52
NodeTag type
Definition: nodes.h:113
List * args
Definition: primnodes.h:1207
CoercionForm row_format
Definition: primnodes.h:1222

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, and Node::type.

Referenced by transformGroupClause().

◆ get_matching_location()

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

Definition at line 3045 of file parse_clause.c.

3046 {
3047  ListCell *lcs;
3048  ListCell *lce;
3049 
3050  forboth(lcs, sortgrouprefs, lce, exprs)
3051  {
3052  if (lfirst_int(lcs) == sortgroupref)
3053  return exprLocation((Node *) lfirst(lce));
3054  }
3055  /* if no match, caller blew it */
3056  elog(ERROR, "get_matching_location: no matching sortgroupref");
3057  return -1; /* keep compiler quiet */
3058 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:465

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

Referenced by transformDistinctOnClause().

◆ getNSItemForSpecialRelationTypes()

static ParseNamespaceItem * getNSItemForSpecialRelationTypes ( ParseState pstate,
RangeVar rv 
)
static

Definition at line 1006 of file parse_clause.c.

1007 {
1008  ParseNamespaceItem *nsitem;
1009  CommonTableExpr *cte;
1010  Index levelsup;
1011 
1012  /*
1013  * if it is a qualified name, it can't be a CTE or tuplestore reference
1014  */
1015  if (rv->schemaname)
1016  return NULL;
1017 
1018  cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
1019  if (cte)
1020  nsitem = addRangeTableEntryForCTE(pstate, cte, levelsup, rv, true);
1021  else if (scanNameSpaceForENR(pstate, rv->relname))
1022  nsitem = addRangeTableEntryForENR(pstate, rv, true);
1023  else
1024  nsitem = NULL;
1025 
1026  return nsitem;
1027 }
ParseNamespaceItem * addRangeTableEntryForCTE(ParseState *pstate, CommonTableExpr *cte, Index levelsup, RangeVar *rv, bool inFromCl)
CommonTableExpr * scanNameSpaceForCTE(ParseState *pstate, const char *refname, Index *ctelevelsup)
bool scanNameSpaceForENR(ParseState *pstate, const char *refname)
ParseNamespaceItem * addRangeTableEntryForENR(ParseState *pstate, RangeVar *rv, bool inFromCl)
char * relname
Definition: primnodes.h:77
char * schemaname
Definition: primnodes.h:74

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

Referenced by transformFromClauseItem().

◆ resolve_unique_index_expr()

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

Definition at line 3070 of file parse_clause.c.

3072 {
3073  List *result = NIL;
3074  ListCell *l;
3075 
3076  foreach(l, infer->indexElems)
3077  {
3078  IndexElem *ielem = (IndexElem *) lfirst(l);
3080  Node *parse;
3081 
3082  /*
3083  * Raw grammar re-uses CREATE INDEX infrastructure for unique index
3084  * inference clause, and so will accept opclasses by name and so on.
3085  *
3086  * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
3087  * LAST ordering, since those are not significant for inference
3088  * purposes (any unique index matching the inference specification in
3089  * other regards is accepted indifferently). Actively reject this as
3090  * wrong-headed.
3091  */
3092  if (ielem->ordering != SORTBY_DEFAULT)
3093  ereport(ERROR,
3094  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3095  errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
3096  parser_errposition(pstate,
3097  exprLocation((Node *) infer))));
3098  if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
3099  ereport(ERROR,
3100  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3101  errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
3102  parser_errposition(pstate,
3103  exprLocation((Node *) infer))));
3104 
3105  if (!ielem->expr)
3106  {
3107  /* Simple index attribute */
3108  ColumnRef *n;
3109 
3110  /*
3111  * Grammar won't have built raw expression for us in event of
3112  * plain column reference. Create one directly, and perform
3113  * expression transformation. Planner expects this, and performs
3114  * its own normalization for the purposes of matching against
3115  * pg_index.
3116  */
3117  n = makeNode(ColumnRef);
3118  n->fields = list_make1(makeString(ielem->name));
3119  /* Location is approximately that of inference specification */
3120  n->location = infer->location;
3121  parse = (Node *) n;
3122  }
3123  else
3124  {
3125  /* Do parse transformation of the raw expression */
3126  parse = (Node *) ielem->expr;
3127  }
3128 
3129  /*
3130  * transformExpr() will reject subqueries, aggregates, window
3131  * functions, and SRFs, based on being passed
3132  * EXPR_KIND_INDEX_EXPRESSION. So we needn't worry about those
3133  * further ... not that they would match any available index
3134  * expression anyway.
3135  */
3136  pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
3137 
3138  /* Perform lookup of collation and operator class as required */
3139  if (!ielem->collation)
3140  pInfer->infercollid = InvalidOid;
3141  else
3142  pInfer->infercollid = LookupCollation(pstate, ielem->collation,
3143  exprLocation(pInfer->expr));
3144 
3145  if (!ielem->opclass)
3146  pInfer->inferopclass = InvalidOid;
3147  else
3148  pInfer->inferopclass = get_opclass_oid(BTREE_AM_OID,
3149  ielem->opclass, false);
3150 
3151  result = lappend(result, pInfer);
3152  }
3153 
3154  return result;
3155 }
Oid get_opclass_oid(Oid amID, List *opclassname, bool missing_ok)
Definition: opclasscmds.c:220
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:71
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:515
#define list_make1(x1)
Definition: pg_list.h:210
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:717
int location
Definition: parsenodes.h:258
List * fields
Definition: parsenodes.h:257
Node * expr
Definition: parsenodes.h:744
SortByDir ordering
Definition: parsenodes.h:749
SortByNulls nulls_ordering
Definition: parsenodes.h:750
List * opclass
Definition: parsenodes.h:747
char * name
Definition: parsenodes.h:743
List * collation
Definition: parsenodes.h:746
List * indexElems
Definition: parsenodes.h:1474
String * makeString(char *str)
Definition: value.c:63

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

◆ setNamespaceColumnVisibility()

static void setNamespaceColumnVisibility ( List namespace,
bool  cols_visible 
)
static

Definition at line 1683 of file parse_clause.c.

1684 {
1685  ListCell *lc;
1686 
1687  foreach(lc, namespace)
1688  {
1689  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1690 
1691  nsitem->p_cols_visible = cols_visible;
1692  }
1693 }

References lfirst, and ParseNamespaceItem::p_cols_visible.

Referenced by transformFromClauseItem().

◆ setNamespaceLateralState()

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

Definition at line 1700 of file parse_clause.c.

1701 {
1702  ListCell *lc;
1703 
1704  foreach(lc, namespace)
1705  {
1706  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1707 
1708  nsitem->p_lateral_only = lateral_only;
1709  nsitem->p_lateral_ok = lateral_ok;
1710  }
1711 }

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

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

◆ setTargetTable()

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

Definition at line 179 of file parse_clause.c.

181 {
182  ParseNamespaceItem *nsitem;
183 
184  /*
185  * ENRs hide tables of the same name, so we need to check for them first.
186  * In contrast, CTEs don't hide tables (for this purpose).
187  */
188  if (relation->schemaname == NULL &&
189  scanNameSpaceForENR(pstate, relation->relname))
190  ereport(ERROR,
191  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
192  errmsg("relation \"%s\" cannot be the target of a modifying statement",
193  relation->relname)));
194 
195  /* Close old target; this could only happen for multi-action rules */
196  if (pstate->p_target_relation != NULL)
198 
199  /*
200  * Open target rel and grab suitable lock (which we will hold till end of
201  * transaction).
202  *
203  * free_parsestate() will eventually do the corresponding table_close(),
204  * but *not* release the lock.
205  */
206  pstate->p_target_relation = parserOpenTable(pstate, relation,
208 
209  /*
210  * Now build an RTE and a ParseNamespaceItem.
211  */
212  nsitem = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
214  relation->alias, inh, false);
215 
216  /* remember the RTE/nsitem as being the query target */
217  pstate->p_target_nsitem = nsitem;
218 
219  /*
220  * Override addRangeTableEntry's default ACL_SELECT permissions check, and
221  * instead mark target table as requiring exactly the specified
222  * permissions.
223  *
224  * If we find an explicit reference to the rel later during parse
225  * analysis, we will add the ACL_SELECT bit back again; see
226  * markVarForSelectPriv and its callers.
227  */
228  nsitem->p_rte->requiredPerms = requiredPerms;
229 
230  /*
231  * If UPDATE/DELETE, add table to joinlist and namespace.
232  */
233  if (alsoSource)
234  addNSItemToQuery(pstate, nsitem, true, true, true);
235 
236  return nsitem->p_rtindex;
237 }
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
Relation parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
RangeTblEntry * p_rte
Definition: parse_node.h:272
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:194
Relation p_target_relation
Definition: parse_node.h:193
AclMode requiredPerms
Definition: parsenodes.h:1178
Alias * alias
Definition: primnodes.h:86
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126

References addNSItemToQuery(), addRangeTableEntryForRelation(), RangeVar::alias, ereport, errcode(), errmsg(), ERROR, NoLock, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, ParseState::p_target_nsitem, ParseState::p_target_relation, parserOpenTable(), RangeVar::relname, RangeTblEntry::requiredPerms, RowExclusiveLock, scanNameSpaceForENR(), RangeVar::schemaname, and table_close().

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

◆ targetIsInSortList()

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

Definition at line 3500 of file parse_clause.c.

3501 {
3502  Index ref = tle->ressortgroupref;
3503  ListCell *l;
3504 
3505  /* no need to scan list if tle has no marker */
3506  if (ref == 0)
3507  return false;
3508 
3509  foreach(l, sortList)
3510  {
3511  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3512 
3513  if (scl->tleSortGroupRef == ref &&
3514  (sortop == InvalidOid ||
3515  sortop == scl->sortop ||
3516  sortop == get_commutator(scl->sortop)))
3517  return true;
3518  }
3519  return false;
3520 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1491

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

◆ transformDistinctClause()

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

Definition at line 2854 of file parse_clause.c.

2856 {
2857  List *result = NIL;
2858  ListCell *slitem;
2859  ListCell *tlitem;
2860 
2861  /*
2862  * The distinctClause should consist of all ORDER BY items followed by all
2863  * other non-resjunk targetlist items. There must not be any resjunk
2864  * ORDER BY items --- that would imply that we are sorting by a value that
2865  * isn't necessarily unique within a DISTINCT group, so the results
2866  * wouldn't be well-defined. This construction ensures we follow the rule
2867  * that sortClause and distinctClause match; in fact the sortClause will
2868  * always be a prefix of distinctClause.
2869  *
2870  * Note a corner case: the same TLE could be in the ORDER BY list multiple
2871  * times with different sortops. We have to include it in the
2872  * distinctClause the same way to preserve the prefix property. The net
2873  * effect will be that the TLE value will be made unique according to both
2874  * sortops.
2875  */
2876  foreach(slitem, sortClause)
2877  {
2878  SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
2879  TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
2880 
2881  if (tle->resjunk)
2882  ereport(ERROR,
2883  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2884  is_agg ?
2885  errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
2886  errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
2887  parser_errposition(pstate,
2888  exprLocation((Node *) tle->expr))));
2889  result = lappend(result, copyObject(scl));
2890  }
2891 
2892  /*
2893  * Now add any remaining non-resjunk tlist items, using default sort/group
2894  * semantics for their data types.
2895  */
2896  foreach(tlitem, *targetlist)
2897  {
2898  TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
2899 
2900  if (tle->resjunk)
2901  continue; /* ignore junk */
2902  result = addTargetToGroupList(pstate, tle,
2903  result, *targetlist,
2904  exprLocation((Node *) tle->expr));
2905  }
2906 
2907  /*
2908  * Complain if we found nothing to make DISTINCT. Returning an empty list
2909  * would cause the parsed Query to look like it didn't have DISTINCT, with
2910  * results that would probably surprise the user. Note: this case is
2911  * presently impossible for aggregates because of grammar restrictions,
2912  * but we check anyway.
2913  */
2914  if (result == NIL)
2915  ereport(ERROR,
2916  (errcode(ERRCODE_SYNTAX_ERROR),
2917  is_agg ?
2918  errmsg("an aggregate with DISTINCT must have at least one argument") :
2919  errmsg("SELECT DISTINCT must have at least one column")));
2920 
2921  return result;
2922 }
#define copyObject(obj)
Definition: nodes.h:227
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:367

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

Referenced by transformAggregateCall(), transformPLAssignStmt(), and transformSelectStmt().

◆ transformDistinctOnClause()

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

Definition at line 2938 of file parse_clause.c.

2940 {
2941  List *result = NIL;
2942  List *sortgrouprefs = NIL;
2943  bool skipped_sortitem;
2944  ListCell *lc;
2945  ListCell *lc2;
2946 
2947  /*
2948  * Add all the DISTINCT ON expressions to the tlist (if not already
2949  * present, they are added as resjunk items). Assign sortgroupref numbers
2950  * to them, and make a list of these numbers. (NB: we rely below on the
2951  * sortgrouprefs list being one-for-one with the original distinctlist.
2952  * Also notice that we could have duplicate DISTINCT ON expressions and
2953  * hence duplicate entries in sortgrouprefs.)
2954  */
2955  foreach(lc, distinctlist)
2956  {
2957  Node *dexpr = (Node *) lfirst(lc);
2958  int sortgroupref;
2959  TargetEntry *tle;
2960 
2961  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
2963  sortgroupref = assignSortGroupRef(tle, *targetlist);
2964  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
2965  }
2966 
2967  /*
2968  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
2969  * semantics from ORDER BY items that match DISTINCT ON items, and also
2970  * adopt their column sort order. We insist that the distinctClause and
2971  * sortClause match, so throw error if we find the need to add any more
2972  * distinctClause items after we've skipped an ORDER BY item that wasn't
2973  * in DISTINCT ON.
2974  */
2975  skipped_sortitem = false;
2976  foreach(lc, sortClause)
2977  {
2978  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
2979 
2980  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
2981  {
2982  if (skipped_sortitem)
2983  ereport(ERROR,
2984  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2985  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2986  parser_errposition(pstate,
2988  sortgrouprefs,
2989  distinctlist))));
2990  else
2991  result = lappend(result, copyObject(scl));
2992  }
2993  else
2994  skipped_sortitem = true;
2995  }
2996 
2997  /*
2998  * Now add any remaining DISTINCT ON items, using default sort/group
2999  * semantics for their data types. (Note: this is pretty questionable; if
3000  * the ORDER BY list doesn't include all the DISTINCT ON items and more
3001  * besides, you certainly aren't using DISTINCT ON in the intended way,
3002  * and you probably aren't going to get consistent results. It might be
3003  * better to throw an error or warning here. But historically we've
3004  * allowed it, so keep doing so.)
3005  */
3006  forboth(lc, distinctlist, lc2, sortgrouprefs)
3007  {
3008  Node *dexpr = (Node *) lfirst(lc);
3009  int sortgroupref = lfirst_int(lc2);
3010  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
3011 
3012  if (targetIsInSortList(tle, InvalidOid, result))
3013  continue; /* already in list (with some semantics) */
3014  if (skipped_sortitem)
3015  ereport(ERROR,
3016  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3017  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3018  parser_errposition(pstate, exprLocation(dexpr))));
3019  result = addTargetToGroupList(pstate, tle,
3020  result, *targetlist,
3021  exprLocation(dexpr));
3022  }
3023 
3024  /*
3025  * An empty result list is impossible here because of grammar
3026  * restrictions.
3027  */
3028  Assert(result != NIL);
3029 
3030  return result;
3031 }
bool list_member_int(const List *list, int datum)
Definition: list.c:701
static int get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:345

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 transformPLAssignStmt(), and transformSelectStmt().

◆ transformFrameOffset()

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

Definition at line 3554 of file parse_clause.c.

3557 {
3558  const char *constructName = NULL;
3559  Node *node;
3560 
3561  *inRangeFunc = InvalidOid; /* default result */
3562 
3563  /* Quick exit if no offset expression */
3564  if (clause == NULL)
3565  return NULL;
3566 
3567  if (frameOptions & FRAMEOPTION_ROWS)
3568  {
3569  /* Transform the raw expression tree */
3570  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_ROWS);
3571 
3572  /*
3573  * Like LIMIT clause, simply coerce to int8
3574  */
3575  constructName = "ROWS";
3576  node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3577  }
3578  else if (frameOptions & FRAMEOPTION_RANGE)
3579  {
3580  /*
3581  * We must look up the in_range support function that's to be used,
3582  * possibly choosing one of several, and coerce the "offset" value to
3583  * the appropriate input type.
3584  */
3585  Oid nodeType;
3586  Oid preferredType;
3587  int nfuncs = 0;
3588  int nmatches = 0;
3589  Oid selectedType = InvalidOid;
3590  Oid selectedFunc = InvalidOid;
3591  CatCList *proclist;
3592  int i;
3593 
3594  /* Transform the raw expression tree */
3595  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_RANGE);
3596  nodeType = exprType(node);
3597 
3598  /*
3599  * If there are multiple candidates, we'll prefer the one that exactly
3600  * matches nodeType; or if nodeType is as yet unknown, prefer the one
3601  * that exactly matches the sort column type. (The second rule is
3602  * like what we do for "known_type operator unknown".)
3603  */
3604  preferredType = (nodeType != UNKNOWNOID) ? nodeType : rangeopcintype;
3605 
3606  /* Find the in_range support functions applicable to this case */
3607  proclist = SearchSysCacheList2(AMPROCNUM,
3608  ObjectIdGetDatum(rangeopfamily),
3609  ObjectIdGetDatum(rangeopcintype));
3610  for (i = 0; i < proclist->n_members; i++)
3611  {
3612  HeapTuple proctup = &proclist->members[i]->tuple;
3613  Form_pg_amproc procform = (Form_pg_amproc) GETSTRUCT(proctup);
3614 
3615  /* The search will find all support proc types; ignore others */
3616  if (procform->amprocnum != BTINRANGE_PROC)
3617  continue;
3618  nfuncs++;
3619 
3620  /* Ignore function if given value can't be coerced to that type */
3621  if (!can_coerce_type(1, &nodeType, &procform->amprocrighttype,
3623  continue;
3624  nmatches++;
3625 
3626  /* Remember preferred match, or any match if didn't find that */
3627  if (selectedType != preferredType)
3628  {
3629  selectedType = procform->amprocrighttype;
3630  selectedFunc = procform->amproc;
3631  }
3632  }
3633  ReleaseCatCacheList(proclist);
3634 
3635  /*
3636  * Throw error if needed. It seems worth taking the trouble to
3637  * distinguish "no support at all" from "you didn't match any
3638  * available offset type".
3639  */
3640  if (nfuncs == 0)
3641  ereport(ERROR,
3642  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3643  errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s",
3644  format_type_be(rangeopcintype)),
3645  parser_errposition(pstate, exprLocation(node))));
3646  if (nmatches == 0)
3647  ereport(ERROR,
3648  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3649  errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s and offset type %s",
3650  format_type_be(rangeopcintype),
3651  format_type_be(nodeType)),
3652  errhint("Cast the offset value to an appropriate type."),
3653  parser_errposition(pstate, exprLocation(node))));
3654  if (nmatches != 1 && selectedType != preferredType)
3655  ereport(ERROR,
3656  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3657  errmsg("RANGE with offset PRECEDING/FOLLOWING has multiple interpretations for column type %s and offset type %s",
3658  format_type_be(rangeopcintype),
3659  format_type_be(nodeType)),
3660  errhint("Cast the offset value to the exact intended type."),
3661  parser_errposition(pstate, exprLocation(node))));
3662 
3663  /* OK, coerce the offset to the right type */
3664  constructName = "RANGE";
3665  node = coerce_to_specific_type(pstate, node,
3666  selectedType, constructName);
3667  *inRangeFunc = selectedFunc;
3668  }
3669  else if (frameOptions & FRAMEOPTION_GROUPS)
3670  {
3671  /* Transform the raw expression tree */
3672  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_GROUPS);
3673 
3674  /*
3675  * Like LIMIT clause, simply coerce to int8
3676  */
3677  constructName = "GROUPS";
3678  node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3679  }
3680  else
3681  {
3682  Assert(false);
3683  node = NULL;
3684  }
3685 
3686  /* Disallow variables in frame offsets */
3687  checkExprIsVarFree(pstate, node, constructName);
3688 
3689  return node;
3690 }
void ReleaseCatCacheList(CatCList *list)
Definition: catcache.c:1777
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
int i
Definition: isn.c:73
#define BTINRANGE_PROC
Definition: nbtree.h:703
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:556
@ EXPR_KIND_WINDOW_FRAME_RANGE
Definition: parse_node.h:51
@ EXPR_KIND_WINDOW_FRAME_GROUPS
Definition: parse_node.h:53
@ EXPR_KIND_WINDOW_FRAME_ROWS
Definition: parse_node.h:52
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:545
#define FRAMEOPTION_GROUPS
Definition: parsenodes.h:547
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:546
FormData_pg_amproc * Form_pg_amproc
Definition: pg_amproc.h:68
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
CatCTup * members[FLEXIBLE_ARRAY_MEMBER]
Definition: catcache.h:178
int n_members
Definition: catcache.h:176
HeapTupleData tuple
Definition: catcache.h:121
@ AMPROCNUM
Definition: syscache.h:39
#define SearchSysCacheList2(cacheId, key1, key2)
Definition: syscache.h:217

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

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 113 of file parse_clause.c.

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

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

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

◆ transformFromClauseItem()

static Node * transformFromClauseItem ( ParseState pstate,
Node n,
ParseNamespaceItem **  top_nsitem,
List **  namespace 
)
static

Definition at line 1049 of file parse_clause.c.

1052 {
1053  /* Guard against stack overflow due to overly deep subtree */
1055 
1056  if (IsA(n, RangeVar))
1057  {
1058  /* Plain relation reference, or perhaps a CTE reference */
1059  RangeVar *rv = (RangeVar *) n;
1060  RangeTblRef *rtr;
1061  ParseNamespaceItem *nsitem;
1062 
1063  /* Check if it's a CTE or tuplestore reference */
1064  nsitem = getNSItemForSpecialRelationTypes(pstate, rv);
1065 
1066  /* if not found above, must be a table reference */
1067  if (!nsitem)
1068  nsitem = transformTableEntry(pstate, rv);
1069 
1070  *top_nsitem = nsitem;
1071  *namespace = list_make1(nsitem);
1072  rtr = makeNode(RangeTblRef);
1073  rtr->rtindex = nsitem->p_rtindex;
1074  return (Node *) rtr;
1075  }
1076  else if (IsA(n, RangeSubselect))
1077  {
1078  /* sub-SELECT is like a plain relation */
1079  RangeTblRef *rtr;
1080  ParseNamespaceItem *nsitem;
1081 
1082  nsitem = transformRangeSubselect(pstate, (RangeSubselect *) n);
1083  *top_nsitem = nsitem;
1084  *namespace = list_make1(nsitem);
1085  rtr = makeNode(RangeTblRef);
1086  rtr->rtindex = nsitem->p_rtindex;
1087  return (Node *) rtr;
1088  }
1089  else if (IsA(n, RangeFunction))
1090  {
1091  /* function is like a plain relation */
1092  RangeTblRef *rtr;
1093  ParseNamespaceItem *nsitem;
1094 
1095  nsitem = transformRangeFunction(pstate, (RangeFunction *) n);
1096  *top_nsitem = nsitem;
1097  *namespace = list_make1(nsitem);
1098  rtr = makeNode(RangeTblRef);
1099  rtr->rtindex = nsitem->p_rtindex;
1100  return (Node *) rtr;
1101  }
1102  else if (IsA(n, RangeTableFunc))
1103  {
1104  /* table function is like a plain relation */
1105  RangeTblRef *rtr;
1106  ParseNamespaceItem *nsitem;
1107 
1108  nsitem = transformRangeTableFunc(pstate, (RangeTableFunc *) n);
1109  *top_nsitem = nsitem;
1110  *namespace = list_make1(nsitem);
1111  rtr = makeNode(RangeTblRef);
1112  rtr->rtindex = nsitem->p_rtindex;
1113  return (Node *) rtr;
1114  }
1115  else if (IsA(n, RangeTableSample))
1116  {
1117  /* TABLESAMPLE clause (wrapping some other valid FROM node) */
1118  RangeTableSample *rts = (RangeTableSample *) n;
1119  Node *rel;
1120  RangeTblEntry *rte;
1121 
1122  /* Recursively transform the contained relation */
1123  rel = transformFromClauseItem(pstate, rts->relation,
1124  top_nsitem, namespace);
1125  rte = (*top_nsitem)->p_rte;
1126  /* We only support this on plain relations and matviews */
1127  if (rte->rtekind != RTE_RELATION ||
1128  (rte->relkind != RELKIND_RELATION &&
1129  rte->relkind != RELKIND_MATVIEW &&
1130  rte->relkind != RELKIND_PARTITIONED_TABLE))
1131  ereport(ERROR,
1132  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1133  errmsg("TABLESAMPLE clause can only be applied to tables and materialized views"),
1134  parser_errposition(pstate, exprLocation(rts->relation))));
1135 
1136  /* Transform TABLESAMPLE details and attach to the RTE */
1137  rte->tablesample = transformRangeTableSample(pstate, rts);
1138  return rel;
1139  }
1140  else if (IsA(n, JoinExpr))
1141  {
1142  /* A newfangled join expression */
1143  JoinExpr *j = (JoinExpr *) n;
1144  ParseNamespaceItem *nsitem;
1145  ParseNamespaceItem *l_nsitem;
1146  ParseNamespaceItem *r_nsitem;
1147  List *l_namespace,
1148  *r_namespace,
1149  *my_namespace,
1150  *l_colnames,
1151  *r_colnames,
1152  *res_colnames,
1153  *l_colnos,
1154  *r_colnos,
1155  *res_colvars;
1156  ParseNamespaceColumn *l_nscolumns,
1157  *r_nscolumns,
1158  *res_nscolumns;
1159  int res_colindex;
1160  bool lateral_ok;
1161  int sv_namespace_length;
1162  int k;
1163 
1164  /*
1165  * Recursively process the left subtree, then the right. We must do
1166  * it in this order for correct visibility of LATERAL references.
1167  */
1168  j->larg = transformFromClauseItem(pstate, j->larg,
1169  &l_nsitem,
1170  &l_namespace);
1171 
1172  /*
1173  * Make the left-side RTEs available for LATERAL access within the
1174  * right side, by temporarily adding them to the pstate's namespace
1175  * list. Per SQL:2008, if the join type is not INNER or LEFT then the
1176  * left-side names must still be exposed, but it's an error to
1177  * reference them. (Stupid design, but that's what it says.) Hence,
1178  * we always push them into the namespace, but mark them as not
1179  * lateral_ok if the jointype is wrong.
1180  *
1181  * Notice that we don't require the merged namespace list to be
1182  * conflict-free. See the comments for scanNameSpaceForRefname().
1183  */
1184  lateral_ok = (j->jointype == JOIN_INNER || j->jointype == JOIN_LEFT);
1185  setNamespaceLateralState(l_namespace, true, lateral_ok);
1186 
1187  sv_namespace_length = list_length(pstate->p_namespace);
1188  pstate->p_namespace = list_concat(pstate->p_namespace, l_namespace);
1189 
1190  /* And now we can process the RHS */
1191  j->rarg = transformFromClauseItem(pstate, j->rarg,
1192  &r_nsitem,
1193  &r_namespace);
1194 
1195  /* Remove the left-side RTEs from the namespace list again */
1196  pstate->p_namespace = list_truncate(pstate->p_namespace,
1197  sv_namespace_length);
1198 
1199  /*
1200  * Check for conflicting refnames in left and right subtrees. Must do
1201  * this because higher levels will assume I hand back a self-
1202  * consistent namespace list.
1203  */
1204  checkNameSpaceConflicts(pstate, l_namespace, r_namespace);
1205 
1206  /*
1207  * Generate combined namespace info for possible use below.
1208  */
1209  my_namespace = list_concat(l_namespace, r_namespace);
1210 
1211  /*
1212  * We'll work from the nscolumns data and eref alias column names for
1213  * each of the input nsitems. Note that these include dropped
1214  * columns, which is helpful because we can keep track of physical
1215  * input column numbers more easily.
1216  */
1217  l_nscolumns = l_nsitem->p_nscolumns;
1218  l_colnames = l_nsitem->p_names->colnames;
1219  r_nscolumns = r_nsitem->p_nscolumns;
1220  r_colnames = r_nsitem->p_names->colnames;
1221 
1222  /*
1223  * Natural join does not explicitly specify columns; must generate
1224  * columns to join. Need to run through the list of columns from each
1225  * table or join result and match up the column names. Use the first
1226  * table, and check every column in the second table for a match.
1227  * (We'll check that the matches were unique later on.) The result of
1228  * this step is a list of column names just like an explicitly-written
1229  * USING list.
1230  */
1231  if (j->isNatural)
1232  {
1233  List *rlist = NIL;
1234  ListCell *lx,
1235  *rx;
1236 
1237  Assert(j->usingClause == NIL); /* shouldn't have USING() too */
1238 
1239  foreach(lx, l_colnames)
1240  {
1241  char *l_colname = strVal(lfirst(lx));
1242  String *m_name = NULL;
1243 
1244  if (l_colname[0] == '\0')
1245  continue; /* ignore dropped columns */
1246 
1247  foreach(rx, r_colnames)
1248  {
1249  char *r_colname = strVal(lfirst(rx));
1250 
1251  if (strcmp(l_colname, r_colname) == 0)
1252  {
1253  m_name = makeString(l_colname);
1254  break;
1255  }
1256  }
1257 
1258  /* matched a right column? then keep as join column... */
1259  if (m_name != NULL)
1260  rlist = lappend(rlist, m_name);
1261  }
1262 
1263  j->usingClause = rlist;
1264  }
1265 
1266  /*
1267  * If a USING clause alias was specified, save the USING columns as
1268  * its column list.
1269  */
1270  if (j->join_using_alias)
1271  j->join_using_alias->colnames = j->usingClause;
1272 
1273  /*
1274  * Now transform the join qualifications, if any.
1275  */
1276  l_colnos = NIL;
1277  r_colnos = NIL;
1278  res_colnames = NIL;
1279  res_colvars = NIL;
1280 
1281  /* this may be larger than needed, but it's not worth being exact */
1282  res_nscolumns = (ParseNamespaceColumn *)
1283  palloc0((list_length(l_colnames) + list_length(r_colnames)) *
1284  sizeof(ParseNamespaceColumn));
1285  res_colindex = 0;
1286 
1287  if (j->usingClause)
1288  {
1289  /*
1290  * JOIN/USING (or NATURAL JOIN, as transformed above). Transform
1291  * the list into an explicit ON-condition, and generate a list of
1292  * merged result columns.
1293  */
1294  List *ucols = j->usingClause;
1295  List *l_usingvars = NIL;
1296  List *r_usingvars = NIL;
1297  ListCell *ucol;
1298 
1299  Assert(j->quals == NULL); /* shouldn't have ON() too */
1300 
1301  foreach(ucol, ucols)
1302  {
1303  char *u_colname = strVal(lfirst(ucol));
1304  ListCell *col;
1305  int ndx;
1306  int l_index = -1;
1307  int r_index = -1;
1308  Var *l_colvar,
1309  *r_colvar;
1310  Node *u_colvar;
1311  ParseNamespaceColumn *res_nscolumn;
1312 
1313  Assert(u_colname[0] != '\0');
1314 
1315  /* Check for USING(foo,foo) */
1316  foreach(col, res_colnames)
1317  {
1318  char *res_colname = strVal(lfirst(col));
1319 
1320  if (strcmp(res_colname, u_colname) == 0)
1321  ereport(ERROR,
1322  (errcode(ERRCODE_DUPLICATE_COLUMN),
1323  errmsg("column name \"%s\" appears more than once in USING clause",
1324  u_colname)));
1325  }
1326 
1327  /* Find it in left input */
1328  ndx = 0;
1329  foreach(col, l_colnames)
1330  {
1331  char *l_colname = strVal(lfirst(col));
1332 
1333  if (strcmp(l_colname, u_colname) == 0)
1334  {
1335  if (l_index >= 0)
1336  ereport(ERROR,
1337  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1338  errmsg("common column name \"%s\" appears more than once in left table",
1339  u_colname)));
1340  l_index = ndx;
1341  }
1342  ndx++;
1343  }
1344  if (l_index < 0)
1345  ereport(ERROR,
1346  (errcode(ERRCODE_UNDEFINED_COLUMN),
1347  errmsg("column \"%s\" specified in USING clause does not exist in left table",
1348  u_colname)));
1349  l_colnos = lappend_int(l_colnos, l_index + 1);
1350 
1351  /* Find it in right input */
1352  ndx = 0;
1353  foreach(col, r_colnames)
1354  {
1355  char *r_colname = strVal(lfirst(col));
1356 
1357  if (strcmp(r_colname, u_colname) == 0)
1358  {
1359  if (r_index >= 0)
1360  ereport(ERROR,
1361  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
1362  errmsg("common column name \"%s\" appears more than once in right table",
1363  u_colname)));
1364  r_index = ndx;
1365  }
1366  ndx++;
1367  }
1368  if (r_index < 0)
1369  ereport(ERROR,
1370  (errcode(ERRCODE_UNDEFINED_COLUMN),
1371  errmsg("column \"%s\" specified in USING clause does not exist in right table",
1372  u_colname)));
1373  r_colnos = lappend_int(r_colnos, r_index + 1);
1374 
1375  l_colvar = buildVarFromNSColumn(l_nscolumns + l_index);
1376  l_usingvars = lappend(l_usingvars, l_colvar);
1377  r_colvar = buildVarFromNSColumn(r_nscolumns + r_index);
1378  r_usingvars = lappend(r_usingvars, r_colvar);
1379 
1380  res_colnames = lappend(res_colnames, lfirst(ucol));
1381  u_colvar = buildMergedJoinVar(pstate,
1382  j->jointype,
1383  l_colvar,
1384  r_colvar);
1385  res_colvars = lappend(res_colvars, u_colvar);
1386  res_nscolumn = res_nscolumns + res_colindex;
1387  res_colindex++;
1388  if (u_colvar == (Node *) l_colvar)
1389  {
1390  /* Merged column is equivalent to left input */
1391  *res_nscolumn = l_nscolumns[l_index];
1392  }
1393  else if (u_colvar == (Node *) r_colvar)
1394  {
1395  /* Merged column is equivalent to right input */
1396  *res_nscolumn = r_nscolumns[r_index];
1397  }
1398  else
1399  {
1400  /*
1401  * Merged column is not semantically equivalent to either
1402  * input, so it needs to be referenced as the join output
1403  * column. We don't know the join's varno yet, so we'll
1404  * replace these zeroes below.
1405  */
1406  res_nscolumn->p_varno = 0;
1407  res_nscolumn->p_varattno = res_colindex;
1408  res_nscolumn->p_vartype = exprType(u_colvar);
1409  res_nscolumn->p_vartypmod = exprTypmod(u_colvar);
1410  res_nscolumn->p_varcollid = exprCollation(u_colvar);
1411  res_nscolumn->p_varnosyn = 0;
1412  res_nscolumn->p_varattnosyn = res_colindex;
1413  }
1414  }
1415 
1416  j->quals = transformJoinUsingClause(pstate,
1417  l_usingvars,
1418  r_usingvars);
1419  }
1420  else if (j->quals)
1421  {
1422  /* User-written ON-condition; transform it */
1423  j->quals = transformJoinOnClause(pstate, j, my_namespace);
1424  }
1425  else
1426  {
1427  /* CROSS JOIN: no quals */
1428  }
1429 
1430  /* Add remaining columns from each side to the output columns */
1431  res_colindex +=
1432  extractRemainingColumns(l_nscolumns, l_colnames, &l_colnos,
1433  &res_colnames, &res_colvars,
1434  res_nscolumns + res_colindex);
1435  res_colindex +=
1436  extractRemainingColumns(r_nscolumns, r_colnames, &r_colnos,
1437  &res_colnames, &res_colvars,
1438  res_nscolumns + res_colindex);
1439 
1440  /*
1441  * Now build an RTE and nsitem for the result of the join.
1442  * res_nscolumns isn't totally done yet, but that's OK because
1443  * addRangeTableEntryForJoin doesn't examine it, only store a pointer.
1444  */
1445  nsitem = addRangeTableEntryForJoin(pstate,
1446  res_colnames,
1447  res_nscolumns,
1448  j->jointype,
1449  list_length(j->usingClause),
1450  res_colvars,
1451  l_colnos,
1452  r_colnos,
1453  j->join_using_alias,
1454  j->alias,
1455  true);
1456 
1457  j->rtindex = nsitem->p_rtindex;
1458 
1459  /*
1460  * Now that we know the join RTE's rangetable index, we can fix up the
1461  * res_nscolumns data in places where it should contain that.
1462  */
1463  Assert(res_colindex == list_length(nsitem->p_names->colnames));
1464  for (k = 0; k < res_colindex; k++)
1465  {
1466  ParseNamespaceColumn *nscol = res_nscolumns + k;
1467 
1468  /* fill in join RTI for merged columns */
1469  if (nscol->p_varno == 0)
1470  nscol->p_varno = j->rtindex;
1471  if (nscol->p_varnosyn == 0)
1472  nscol->p_varnosyn = j->rtindex;
1473  /* if join has an alias, it syntactically hides all inputs */
1474  if (j->alias)
1475  {
1476  nscol->p_varnosyn = j->rtindex;
1477  nscol->p_varattnosyn = k + 1;
1478  }
1479  }
1480 
1481  /* make a matching link to the JoinExpr for later use */
1482  for (k = list_length(pstate->p_joinexprs) + 1; k < j->rtindex; k++)
1483  pstate->p_joinexprs = lappend(pstate->p_joinexprs, NULL);
1484  pstate->p_joinexprs = lappend(pstate->p_joinexprs, j);
1485  Assert(list_length(pstate->p_joinexprs) == j->rtindex);
1486 
1487  /*
1488  * If the join has a USING alias, build a ParseNamespaceItem for that
1489  * and add it to the list of nsitems in the join's input.
1490  */
1491  if (j->join_using_alias)
1492  {
1493  ParseNamespaceItem *jnsitem;
1494 
1495  jnsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1496  jnsitem->p_names = j->join_using_alias;
1497  jnsitem->p_rte = nsitem->p_rte;
1498  jnsitem->p_rtindex = nsitem->p_rtindex;
1499  /* no need to copy the first N columns, just use res_nscolumns */
1500  jnsitem->p_nscolumns = res_nscolumns;
1501  /* set default visibility flags; might get changed later */
1502  jnsitem->p_rel_visible = true;
1503  jnsitem->p_cols_visible = true;
1504  jnsitem->p_lateral_only = false;
1505  jnsitem->p_lateral_ok = true;
1506  /* Per SQL, we must check for alias conflicts */
1507  checkNameSpaceConflicts(pstate, list_make1(jnsitem), my_namespace);
1508  my_namespace = lappend(my_namespace, jnsitem);
1509  }
1510 
1511  /*
1512  * Prepare returned namespace list. If the JOIN has an alias then it
1513  * hides the contained RTEs completely; otherwise, the contained RTEs
1514  * are still visible as table names, but are not visible for
1515  * unqualified column-name access.
1516  *
1517  * Note: if there are nested alias-less JOINs, the lower-level ones
1518  * will remain in the list although they have neither p_rel_visible
1519  * nor p_cols_visible set. We could delete such list items, but it's
1520  * unclear that it's worth expending cycles to do so.
1521  */
1522  if (j->alias != NULL)
1523  my_namespace = NIL;
1524  else
1525  setNamespaceColumnVisibility(my_namespace, false);
1526 
1527  /*
1528  * The join RTE itself is always made visible for unqualified column
1529  * names. It's visible as a relation name only if it has an alias.
1530  */
1531  nsitem->p_rel_visible = (j->alias != NULL);
1532  nsitem->p_cols_visible = true;
1533  nsitem->p_lateral_only = false;
1534  nsitem->p_lateral_ok = true;
1535 
1536  *top_nsitem = nsitem;
1537  *namespace = lappend(my_namespace, nsitem);
1538 
1539  return (Node *) j;
1540  }
1541  else
1542  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
1543  return NULL; /* can't get here, keep compiler quiet */
1544 }
int j
Definition: isn.c:74
List * list_truncate(List *list, int new_size)
Definition: list.c:630
void * palloc0(Size size)
Definition: mcxt.c:1230
void * palloc(Size size)
Definition: mcxt.c:1199
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:266
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:764
#define nodeTag(nodeptr)
Definition: nodes.h:116
static Node * transformJoinOnClause(ParseState *pstate, JoinExpr *j, List *namespace)
Definition: parse_clause.c:364
static ParseNamespaceItem * transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
Definition: parse_clause.c:404
static ParseNamespaceItem * transformRangeTableFunc(ParseState *pstate, RangeTableFunc *rtf)
Definition: parse_clause.c:685
static void setNamespaceColumnVisibility(List *namespace, bool cols_visible)
static ParseNamespaceItem * getNSItemForSpecialRelationTypes(ParseState *pstate, RangeVar *rv)
static TableSampleClause * transformRangeTableSample(ParseState *pstate, RangeTableSample *rts)
Definition: parse_clause.c:903
static Node * transformJoinUsingClause(ParseState *pstate, List *leftVars, List *rightVars)
Definition: parse_clause.c:305
static Node * buildMergedJoinVar(ParseState *pstate, JoinType jointype, Var *l_colvar, Var *r_colvar)
static int extractRemainingColumns(ParseNamespaceColumn *src_nscolumns, List *src_colnames, List **src_colnos, List **res_colnames, List **res_colvars, ParseNamespaceColumn *res_nscolumns)
Definition: parse_clause.c:254
static ParseNamespaceItem * transformTableEntry(ParseState *pstate, RangeVar *r)
Definition: parse_clause.c:394
static ParseNamespaceItem * transformRangeFunction(ParseState *pstate, RangeFunction *r)
Definition: parse_clause.c:462
struct ParseNamespaceColumn ParseNamespaceColumn
Definition: parse_node.h:25
ParseNamespaceItem * addRangeTableEntryForJoin(ParseState *pstate, List *colnames, ParseNamespaceColumn *nscolumns, JoinType jointype, int nummergedcols, List *aliasvars, List *leftcols, List *rightcols, Alias *join_using_alias, Alias *alias, bool inFromCl)
@ RTE_RELATION
Definition: parsenodes.h:1009
List * colnames
Definition: primnodes.h:43
ParseNamespaceColumn * p_nscolumns
Definition: parse_node.h:275
List * p_joinexprs
Definition: parse_node.h:184
struct TableSampleClause * tablesample
Definition: parsenodes.h:1058
RTEKind rtekind
Definition: parsenodes.h:1028

References addRangeTableEntryForJoin(), Assert(), buildMergedJoinVar(), buildVarFromNSColumn(), check_stack_depth(), checkNameSpaceConflicts(), Alias::colnames, elog(), ereport, errcode(), errmsg(), ERROR, exprCollation(), exprLocation(), exprType(), exprTypmod(), extractRemainingColumns(), getNSItemForSpecialRelationTypes(), IsA, j, JOIN_INNER, JOIN_LEFT, lappend(), lappend_int(), lfirst, list_concat(), list_length(), list_make1, list_truncate(), makeNode, makeString(), NIL, nodeTag, ParseNamespaceItem::p_cols_visible, ParseState::p_joinexprs, ParseNamespaceItem::p_lateral_ok, ParseNamespaceItem::p_lateral_only, ParseNamespaceItem::p_names, ParseState::p_namespace, ParseNamespaceItem::p_nscolumns, ParseNamespaceItem::p_rel_visible, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, ParseNamespaceColumn::p_varattno, ParseNamespaceColumn::p_varattnosyn, ParseNamespaceColumn::p_varcollid, ParseNamespaceColumn::p_varno, ParseNamespaceColumn::p_varnosyn, ParseNamespaceColumn::p_vartype, ParseNamespaceColumn::p_vartypmod, palloc(), palloc0(), parser_errposition(), RangeTableSample::relation, RangeTblEntry::relkind, RTE_RELATION, RangeTblEntry::rtekind, RangeTblRef::rtindex, setNamespaceColumnVisibility(), setNamespaceLateralState(), strVal, RangeTblEntry::tablesample, transformJoinOnClause(), transformJoinUsingClause(), transformRangeFunction(), transformRangeSubselect(), transformRangeTableFunc(), transformRangeTableSample(), and transformTableEntry().

Referenced by transformFromClause().

◆ transformGroupClause()

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

Definition at line 2500 of file parse_clause.c.

2503 {
2504  List *result = NIL;
2505  List *flat_grouplist;
2506  List *gsets = NIL;
2507  ListCell *gl;
2508  bool hasGroupingSets = false;
2509  Bitmapset *seen_local = NULL;
2510 
2511  /*
2512  * Recursively flatten implicit RowExprs. (Technically this is only needed
2513  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2514  * anyway.)
2515  */
2516  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2517  true,
2518  &hasGroupingSets);
2519 
2520  /*
2521  * If the list is now empty, but hasGroupingSets is true, it's because we
2522  * elided redundant empty grouping sets. Restore a single empty grouping
2523  * set to leave a canonical form: GROUP BY ()
2524  */
2525 
2526  if (flat_grouplist == NIL && hasGroupingSets)
2527  {
2529  NIL,
2530  exprLocation((Node *) grouplist)));
2531  }
2532 
2533  foreach(gl, flat_grouplist)
2534  {
2535  Node *gexpr = (Node *) lfirst(gl);
2536 
2537  if (IsA(gexpr, GroupingSet))
2538  {
2539  GroupingSet *gset = (GroupingSet *) gexpr;
2540 
2541  switch (gset->kind)
2542  {
2543  case GROUPING_SET_EMPTY:
2544  gsets = lappend(gsets, gset);
2545  break;
2546  case GROUPING_SET_SIMPLE:
2547  /* can't happen */
2548  Assert(false);
2549  break;
2550  case GROUPING_SET_SETS:
2551  case GROUPING_SET_CUBE:
2552  case GROUPING_SET_ROLLUP:
2553  gsets = lappend(gsets,
2554  transformGroupingSet(&result,
2555  pstate, gset,
2556  targetlist, sortClause,
2557  exprKind, useSQL99, true));
2558  break;
2559  }
2560  }
2561  else
2562  {
2563  Index ref = transformGroupClauseExpr(&result, seen_local,
2564  pstate, gexpr,
2565  targetlist, sortClause,
2566  exprKind, useSQL99, true);
2567 
2568  if (ref > 0)
2569  {
2570  seen_local = bms_add_member(seen_local, ref);
2571  if (hasGroupingSets)
2572  gsets = lappend(gsets,
2574  list_make1_int(ref),
2575  exprLocation(gexpr)));
2576  }
2577  }
2578  }
2579 
2580  /* parser should prevent this */
2581  Assert(gsets == NIL || groupingSets != NULL);
2582 
2583  if (groupingSets)
2584  *groupingSets = gsets;
2585 
2586  return result;
2587 }
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
@ GROUPING_SET_CUBE
Definition: parsenodes.h:1380
@ GROUPING_SET_SIMPLE
Definition: parsenodes.h:1378
@ GROUPING_SET_ROLLUP
Definition: parsenodes.h:1379
#define list_make1_int(x1)
Definition: pg_list.h:225

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 transformPLAssignStmt(), transformSelectStmt(), and transformWindowDefinitions().

◆ 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 2235 of file parse_clause.c.

2239 {
2240  TargetEntry *tle;
2241  bool found = false;
2242 
2243  if (useSQL99)
2244  tle = findTargetlistEntrySQL99(pstate, gexpr,
2245  targetlist, exprKind);
2246  else
2247  tle = findTargetlistEntrySQL92(pstate, gexpr,
2248  targetlist, exprKind);
2249 
2250  if (tle->ressortgroupref > 0)
2251  {
2252  ListCell *sl;
2253 
2254  /*
2255  * Eliminate duplicates (GROUP BY x, x) but only at local level.
2256  * (Duplicates in grouping sets can affect the number of returned
2257  * rows, so can't be dropped indiscriminately.)
2258  *
2259  * Since we don't care about anything except the sortgroupref, we can
2260  * use a bitmapset rather than scanning lists.
2261  */
2262  if (bms_is_member(tle->ressortgroupref, seen_local))
2263  return 0;
2264 
2265  /*
2266  * If we're already in the flat clause list, we don't need to consider
2267  * adding ourselves again.
2268  */
2269  found = targetIsInSortList(tle, InvalidOid, *flatresult);
2270  if (found)
2271  return tle->ressortgroupref;
2272 
2273  /*
2274  * If the GROUP BY tlist entry also appears in ORDER BY, copy operator
2275  * info from the (first) matching ORDER BY item. This means that if
2276  * you write something like "GROUP BY foo ORDER BY foo USING <<<", the
2277  * GROUP BY operation silently takes on the equality semantics implied
2278  * by the ORDER BY. There are two reasons to do this: it improves the
2279  * odds that we can implement both GROUP BY and ORDER BY with a single
2280  * sort step, and it allows the user to choose the equality semantics
2281  * used by GROUP BY, should she be working with a datatype that has
2282  * more than one equality operator.
2283  *
2284  * If we're in a grouping set, though, we force our requested ordering
2285  * to be NULLS LAST, because if we have any hope of using a sorted agg
2286  * for the job, we're going to be tacking on generated NULL values
2287  * after the corresponding groups. If the user demands nulls first,
2288  * another sort step is going to be inevitable, but that's the
2289  * planner's problem.
2290  */
2291 
2292  foreach(sl, sortClause)
2293  {
2294  SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
2295 
2296  if (sc->tleSortGroupRef == tle->ressortgroupref)
2297  {
2298  SortGroupClause *grpc = copyObject(sc);
2299 
2300  if (!toplevel)
2301  grpc->nulls_first = false;
2302  *flatresult = lappend(*flatresult, grpc);
2303  found = true;
2304  break;
2305  }
2306  }
2307  }
2308 
2309  /*
2310  * If no match in ORDER BY, just add it to the result using default
2311  * sort/group semantics.
2312  */
2313  if (!found)
2314  *flatresult = addTargetToGroupList(pstate, tle,
2315  *flatresult, *targetlist,
2316  exprLocation(gexpr));
2317 
2318  /*
2319  * _something_ must have assigned us a sortgroupref by now...
2320  */
2321 
2322  return tle->ressortgroupref;
2323 }

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

◆ transformGroupClauseList()

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

Definition at line 2343 of file parse_clause.c.

2347 {
2348  Bitmapset *seen_local = NULL;
2349  List *result = NIL;
2350  ListCell *gl;
2351 
2352  foreach(gl, list)
2353  {
2354  Node *gexpr = (Node *) lfirst(gl);
2355 
2356  Index ref = transformGroupClauseExpr(flatresult,
2357  seen_local,
2358  pstate,
2359  gexpr,
2360  targetlist,
2361  sortClause,
2362  exprKind,
2363  useSQL99,
2364  toplevel);
2365 
2366  if (ref > 0)
2367  {
2368  seen_local = bms_add_member(seen_local, ref);
2369  result = lappend_int(result, ref);
2370  }
2371  }
2372 
2373  return result;
2374 }

References bms_add_member(), lappend_int(), lfirst, sort-test::list, NIL, and transformGroupClauseExpr().

Referenced by transformGroupingSet().

◆ transformGroupingSet()

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

Definition at line 2396 of file parse_clause.c.

2400 {
2401  ListCell *gl;
2402  List *content = NIL;
2403 
2404  Assert(toplevel || gset->kind != GROUPING_SET_SETS);
2405 
2406  foreach(gl, gset->content)
2407  {
2408  Node *n = lfirst(gl);
2409 
2410  if (IsA(n, List))
2411  {
2412  List *l = transformGroupClauseList(flatresult,
2413  pstate, (List *) n,
2414  targetlist, sortClause,
2415  exprKind, useSQL99, false);
2416 
2417  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2418  l,
2419  exprLocation(n)));
2420  }
2421  else if (IsA(n, GroupingSet))
2422  {
2423  GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
2424 
2425  content = lappend(content, transformGroupingSet(flatresult,
2426  pstate, gset2,
2427  targetlist, sortClause,
2428  exprKind, useSQL99, false));
2429  }
2430  else
2431  {
2432  Index ref = transformGroupClauseExpr(flatresult,
2433  NULL,
2434  pstate,
2435  n,
2436  targetlist,
2437  sortClause,
2438  exprKind,
2439  useSQL99,
2440  false);
2441 
2442  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2443  list_make1_int(ref),
2444  exprLocation(n)));
2445  }
2446  }
2447 
2448  /* Arbitrarily cap the size of CUBE, which has exponential growth */
2449  if (gset->kind == GROUPING_SET_CUBE)
2450  {
2451  if (list_length(content) > 12)
2452  ereport(ERROR,
2453  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2454  errmsg("CUBE is limited to 12 elements"),
2455  parser_errposition(pstate, gset->location)));
2456  }
2457 
2458  return (Node *) makeGroupingSet(gset->kind, content, gset->location);
2459 }
static List * transformGroupClauseList(List **flatresult, ParseState *pstate, List *list, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)

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

◆ transformJoinOnClause()

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

Definition at line 364 of file parse_clause.c.

365 {
366  Node *result;
367  List *save_namespace;
368 
369  /*
370  * The namespace that the join expression should see is just the two
371  * subtrees of the JOIN plus any outer references from upper pstate
372  * levels. Temporarily set this pstate's namespace accordingly. (We need
373  * not check for refname conflicts, because transformFromClauseItem()
374  * already did.) All namespace items are marked visible regardless of
375  * LATERAL state.
376  */
377  setNamespaceLateralState(namespace, false, true);
378 
379  save_namespace = pstate->p_namespace;
380  pstate->p_namespace = namespace;
381 
382  result = transformWhereClause(pstate, j->quals,
383  EXPR_KIND_JOIN_ON, "JOIN/ON");
384 
385  pstate->p_namespace = save_namespace;
386 
387  return result;
388 }
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
@ EXPR_KIND_JOIN_ON
Definition: parse_node.h:42

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

Referenced by transformFromClauseItem().

◆ transformJoinUsingClause()

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

Definition at line 305 of file parse_clause.c.

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

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

◆ transformLimitClause()

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

Definition at line 1749 of file parse_clause.c.

1752 {
1753  Node *qual;
1754 
1755  if (clause == NULL)
1756  return NULL;
1757 
1758  qual = transformExpr(pstate, clause, exprKind);
1759 
1760  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1761 
1762  /* LIMIT can't refer to any variables of the current query */
1763  checkExprIsVarFree(pstate, qual, constructName);
1764 
1765  /*
1766  * Don't allow NULLs in FETCH FIRST .. WITH TIES. This test is ugly and
1767  * extremely simplistic, in that you can pass a NULL anyway by hiding it
1768  * inside an expression -- but this protects ruleutils against emitting an
1769  * unadorned NULL that's not accepted back by the grammar.
1770  */
1771  if (exprKind == EXPR_KIND_LIMIT && limitOption == LIMIT_OPTION_WITH_TIES &&
1772  IsA(clause, A_Const) && castNode(A_Const, clause)->isnull)
1773  ereport(ERROR,
1774  (errcode(ERRCODE_INVALID_ROW_COUNT_IN_LIMIT_CLAUSE),
1775  errmsg("row count cannot be null in FETCH FIRST ... WITH TIES clause")));
1776 
1777  return qual;
1778 }
@ LIMIT_OPTION_WITH_TIES
Definition: nodes.h:423
@ EXPR_KIND_LIMIT
Definition: parse_node.h:62

References castNode, checkExprIsVarFree(), coerce_to_specific_type(), ereport, errcode(), errmsg(), ERROR, EXPR_KIND_LIMIT, IsA, LIMIT_OPTION_WITH_TIES, and transformExpr().

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

◆ transformOnConflictArbiter()

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

Definition at line 3166 of file parse_clause.c.

3170 {
3171  InferClause *infer = onConflictClause->infer;
3172 
3173  *arbiterExpr = NIL;
3174  *arbiterWhere = NULL;
3175  *constraint = InvalidOid;
3176 
3177  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3178  ereport(ERROR,
3179  (errcode(ERRCODE_SYNTAX_ERROR),
3180  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3181  errhint("For example, ON CONFLICT (column_name)."),
3182  parser_errposition(pstate,
3183  exprLocation((Node *) onConflictClause))));
3184 
3185  /*
3186  * To simplify certain aspects of its design, speculative insertion into
3187  * system catalogs is disallowed
3188  */
3189  if (IsCatalogRelation(pstate->p_target_relation))
3190  ereport(ERROR,
3191  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3192  errmsg("ON CONFLICT is not supported with system catalog tables"),
3193  parser_errposition(pstate,
3194  exprLocation((Node *) onConflictClause))));
3195 
3196  /* Same applies to table used by logical decoding as catalog table */
3198  ereport(ERROR,
3199  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3200  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3202  parser_errposition(pstate,
3203  exprLocation((Node *) onConflictClause))));
3204 
3205  /* ON CONFLICT DO NOTHING does not require an inference clause */
3206  if (infer)
3207  {
3208  if (infer->indexElems)
3209  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3210  pstate->p_target_relation);
3211 
3212  /*
3213  * Handling inference WHERE clause (for partial unique index
3214  * inference)
3215  */
3216  if (infer->whereClause)
3217  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3219 
3220  /*
3221  * If the arbiter is specified by constraint name, get the constraint
3222  * OID and mark the constrained columns as requiring SELECT privilege,
3223  * in the same way as would have happened if the arbiter had been
3224  * specified by explicit reference to the constraint's index columns.
3225  */
3226  if (infer->conname)
3227  {
3228  Oid relid = RelationGetRelid(pstate->p_target_relation);
3229  RangeTblEntry *rte = pstate->p_target_nsitem->p_rte;
3230  Bitmapset *conattnos;
3231 
3232  conattnos = get_relation_constraint_attnos(relid, infer->conname,
3233  false, constraint);
3234 
3235  /* Make sure the rel as a whole is marked for SELECT access */
3236  rte->requiredPerms |= ACL_SELECT;
3237  /* Mark the constrained columns as requiring SELECT access */
3238  rte->selectedCols = bms_add_members(rte->selectedCols, conattnos);
3239  }
3240  }
3241 
3242  /*
3243  * It's convenient to form a list of expressions based on the
3244  * representation used by CREATE INDEX, since the same restrictions are
3245  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3246  * primnode representation is used for inference elements, and so
3247  * assign_query_collations() can be trusted to do the right thing with the
3248  * post parse analysis query tree inference clause representation.
3249  */
3250 }
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:796
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:105
@ ONCONFLICT_UPDATE
Definition: nodes.h:411
static List * resolve_unique_index_expr(ParseState *pstate, InferClause *infer, Relation heapRel)
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:72
#define ACL_SELECT
Definition: parsenodes.h:84
Bitmapset * get_relation_constraint_attnos(Oid relid, const char *conname, bool missing_ok, Oid *constraintOid)
#define RelationGetRelid(relation)
Definition: rel.h:501
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:382
#define RelationGetRelationName(relation)
Definition: rel.h:535
char * conname
Definition: parsenodes.h:1476
Node * whereClause
Definition: parsenodes.h:1475
InferClause * infer
Definition: parsenodes.h:1490
OnConflictAction action
Definition: parsenodes.h:1489
Bitmapset * selectedCols
Definition: parsenodes.h:1180

References ACL_SELECT, OnConflictClause::action, 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, ParseNamespaceItem::p_rte, ParseState::p_target_nsitem, ParseState::p_target_relation, parser_errposition(), RelationGetRelationName, RelationGetRelid, RelationIsUsedAsCatalogTable, RangeTblEntry::requiredPerms, resolve_unique_index_expr(), RangeTblEntry::selectedCols, transformExpr(), and InferClause::whereClause.

Referenced by transformOnConflictClause().

◆ transformRangeFunction()

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

Definition at line 462 of file parse_clause.c.

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

References addRangeTableEntryForFunction(), arg, Assert(), assign_list_collations(), COERCE_EXPLICIT_CALL, RangeFunction::coldeflist, contain_vars_of_level(), ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_FROM_FUNCTION, exprLocation(), fc(), FigureColname(), RangeFunction::functions, RangeFunction::is_rowsfrom, IsA, lappend(), RangeFunction::lateral, lfirst, linitial, list_length(), list_make1, lsecond, makeFuncCall(), NIL, RangeFunction::ordinality, ParseState::p_last_srf, ParseState::p_lateral_active, parser_errposition(), strVal, SystemFuncName(), and transformExpr().

Referenced by transformFromClauseItem().

◆ transformRangeSubselect()

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

Definition at line 404 of file parse_clause.c.

405 {
406  Query *query;
407 
408  /*
409  * Set p_expr_kind to show this parse level is recursing to a subselect.
410  * We can't be nested within any expression, so don't need save-restore
411  * logic here.
412  */
413  Assert(pstate->p_expr_kind == EXPR_KIND_NONE);
415 
416  /*
417  * If the subselect is LATERAL, make lateral_only names of this level
418  * visible to it. (LATERAL can't nest within a single pstate level, so we
419  * don't need save/restore logic here.)
420  */
421  Assert(!pstate->p_lateral_active);
422  pstate->p_lateral_active = r->lateral;
423 
424  /*
425  * Analyze and transform the subquery. Note that if the subquery doesn't
426  * have an alias, it can't be explicitly selected for locking, but locking
427  * might still be required (if there is an all-tables locking clause).
428  */
429  query = parse_sub_analyze(r->subquery, pstate, NULL,
430  isLockedRefname(pstate,
431  r->alias == NULL ? NULL :
432  r->alias->aliasname),
433  true);
434 
435  /* Restore state */
436  pstate->p_lateral_active = false;
437  pstate->p_expr_kind = EXPR_KIND_NONE;
438 
439  /*
440  * Check that we got a SELECT. Anything else should be impossible given
441  * restrictions of the grammar, but check anyway.
442  */
443  if (!IsA(query, Query) ||
444  query->commandType != CMD_SELECT)
445  elog(ERROR, "unexpected non-SELECT command in subquery in FROM");
446 
447  /*
448  * OK, build an RTE and nsitem for the subquery.
449  */
450  return addRangeTableEntryForSubquery(pstate,
451  query,
452  r->alias,
453  r->lateral,
454  true);
455 }
@ CMD_SELECT
Definition: nodes.h:259
@ EXPR_KIND_FROM_SUBSELECT
Definition: parse_node.h:44
@ EXPR_KIND_NONE
Definition: parse_node.h:40
ParseNamespaceItem * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
bool isLockedRefname(ParseState *pstate, const char *refname)
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:223
char * aliasname
Definition: primnodes.h:42
ParseExprKind p_expr_kind
Definition: parse_node.h:197
CmdType commandType
Definition: parsenodes.h:122
Node * subquery
Definition: parsenodes.h:582
Alias * alias
Definition: parsenodes.h:583

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

◆ transformRangeTableFunc()

static ParseNamespaceItem * transformRangeTableFunc ( ParseState pstate,
RangeTableFunc rtf 
)
static

Definition at line 685 of file parse_clause.c.

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

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(), RangeTableFunc::docexpr, TableFunc::docexpr, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_FROM_FUNCTION, RangeTableFuncCol::for_ordinality, get_typcollation(), RangeTableFuncCol::is_not_null, IsA, j, lappend(), lappend_int(), lappend_oid(), RangeTableFunc::lateral, lfirst, lfirst_node, list_length(), ResTarget::location, RangeTableFunc::location, RangeTableFuncCol::location, TableFunc::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(), RangeTableFunc::rowexpr, TableFunc::rowexpr, TypeName::setof, strVal, transformExpr(), RangeTableFuncCol::typeName, typenameTypeIdAndMod(), and ResTarget::val.

Referenced by transformFromClauseItem().

◆ transformRangeTableSample()

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

Definition at line 903 of file parse_clause.c.

904 {
905  TableSampleClause *tablesample;
906  Oid handlerOid;
907  Oid funcargtypes[1];
908  TsmRoutine *tsm;
909  List *fargs;
910  ListCell *larg,
911  *ltyp;
912 
913  /*
914  * To validate the sample method name, look up the handler function, which
915  * has the same name, one dummy INTERNAL argument, and a result type of
916  * tsm_handler. (Note: tablesample method names are not schema-qualified
917  * in the SQL standard; but since they are just functions to us, we allow
918  * schema qualification to resolve any potential ambiguity.)
919  */
920  funcargtypes[0] = INTERNALOID;
921 
922  handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true);
923 
924  /* we want error to complain about no-such-method, not no-such-function */
925  if (!OidIsValid(handlerOid))
926  ereport(ERROR,
927  (errcode(ERRCODE_UNDEFINED_OBJECT),
928  errmsg("tablesample method %s does not exist",
929  NameListToString(rts->method)),
930  parser_errposition(pstate, rts->location)));
931 
932  /* check that handler has correct return type */
933  if (get_func_rettype(handlerOid) != TSM_HANDLEROID)
934  ereport(ERROR,
935  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
936  errmsg("function %s must return type %s",
937  NameListToString(rts->method), "tsm_handler"),
938  parser_errposition(pstate, rts->location)));
939 
940  /* OK, run the handler to get TsmRoutine, for argument type info */
941  tsm = GetTsmRoutine(handlerOid);
942 
943  tablesample = makeNode(TableSampleClause);
944  tablesample->tsmhandler = handlerOid;
945 
946  /* check user provided the expected number of arguments */
947  if (list_length(rts->args) != list_length(tsm->parameterTypes))
948  ereport(ERROR,
949  (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
950  errmsg_plural("tablesample method %s requires %d argument, not %d",
951  "tablesample method %s requires %d arguments, not %d",
953  NameListToString(rts->method),
955  list_length(rts->args)),
956  parser_errposition(pstate, rts->location)));
957 
958  /*
959  * Transform the arguments, typecasting them as needed. Note we must also
960  * assign collations now, because assign_query_collations() doesn't
961  * examine any substructure of RTEs.
962  */
963  fargs = NIL;
964  forboth(larg, rts->args, ltyp, tsm->parameterTypes)
965  {
966  Node *arg = (Node *) lfirst(larg);
967  Oid argtype = lfirst_oid(ltyp);
968 
970  arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE");
971  assign_expr_collations(pstate, arg);
972  fargs = lappend(fargs, arg);
973  }
974  tablesample->args = fargs;
975 
976  /* Process REPEATABLE (seed) */
977  if (rts->repeatable != NULL)
978  {
979  Node *arg;
980 
981  if (!tsm->repeatable_across_queries)
982  ereport(ERROR,
983  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
984  errmsg("tablesample method %s does not support REPEATABLE",
985  NameListToString(rts->method)),
986  parser_errposition(pstate, rts->location)));
987 
989  arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE");
990  assign_expr_collations(pstate, arg);
991  tablesample->repeatable = (Expr *) arg;
992  }
993  else
994  tablesample->repeatable = NULL;
995 
996  return tablesample;
997 }
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1016
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1637
char * NameListToString(List *names)
Definition: namespace.c:3145
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
Definition: parse_func.c:2146
#define lfirst_oid(lc)
Definition: pg_list.h:172
List * parameterTypes
Definition: tsmapi.h:61
bool repeatable_across_queries
Definition: tsmapi.h:64
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27

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

◆ transformSortClause()

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

Definition at line 2600 of file parse_clause.c.

2605 {
2606  List *sortlist = NIL;
2607  ListCell *olitem;
2608 
2609  foreach(olitem, orderlist)
2610  {
2611  SortBy *sortby = (SortBy *) lfirst(olitem);
2612  TargetEntry *tle;
2613 
2614  if (useSQL99)
2615  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2616  targetlist, exprKind);
2617  else
2618  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2619  targetlist, exprKind);
2620 
2621  sortlist = addTargetToSortList(pstate, tle,
2622  sortlist, *targetlist, sortby);
2623  }
2624 
2625  return sortlist;
2626 }
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)

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

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

◆ transformTableEntry()

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

Definition at line 394 of file parse_clause.c.

395 {
396  /* addRangeTableEntry does all the work */
397  return addRangeTableEntry(pstate, r, r->alias, r->inh, true);
398 }
ParseNamespaceItem * addRangeTableEntry(ParseState *pstate, RangeVar *relation, Alias *alias, bool inh, bool inFromCl)
bool inh
Definition: primnodes.h:80

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

Referenced by transformFromClauseItem().

◆ transformWhereClause()

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

Definition at line 1722 of file parse_clause.c.

1724 {
1725  Node *qual;
1726 
1727  if (clause == NULL)
1728  return NULL;
1729 
1730  qual = transformExpr(pstate, clause, exprKind);
1731 
1732  qual = coerce_to_boolean(pstate, qual, constructName);
1733 
1734  return qual;
1735 }

References coerce_to_boolean(), and transformExpr().

Referenced by AlterPolicy(), CreatePolicy(), CreateTriggerFiringOn(), ParseFuncOrColumn(), test_rls_hooks_permissive(), test_rls_hooks_restrictive(), transformDeleteStmt(), transformIndexStmt(), transformJoinOnClause(), transformMergeStmt(), transformOnConflictClause(), transformPLAssignStmt(), TransformPubWhereClauses(), transformRuleStmt(), transformSelectStmt(), and transformUpdateStmt().

◆ transformWindowDefinitions()

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

Definition at line 2633 of file parse_clause.c.

2636 {
2637  List *result = NIL;
2638  Index winref = 0;
2639  ListCell *lc;
2640 
2641  foreach(lc, windowdefs)
2642  {
2643  WindowDef *windef = (WindowDef *) lfirst(lc);
2644  WindowClause *refwc = NULL;
2645  List *partitionClause;
2646  List *orderClause;
2647  Oid rangeopfamily = InvalidOid;
2648  Oid rangeopcintype = InvalidOid;
2649  WindowClause *wc;
2650 
2651  winref++;
2652 
2653  /*
2654  * Check for duplicate window names.
2655  */
2656  if (windef->name &&
2657  findWindowClause(result, windef->name) != NULL)
2658  ereport(ERROR,
2659  (errcode(ERRCODE_WINDOWING_ERROR),
2660  errmsg("window \"%s\" is already defined", windef->name),
2661  parser_errposition(pstate, windef->location)));
2662 
2663  /*
2664  * If it references a previous window, look that up.
2665  */
2666  if (windef->refname)
2667  {
2668  refwc = findWindowClause(result, windef->refname);
2669  if (refwc == NULL)
2670  ereport(ERROR,
2671  (errcode(ERRCODE_UNDEFINED_OBJECT),
2672  errmsg("window \"%s\" does not exist",
2673  windef->refname),
2674  parser_errposition(pstate, windef->location)));
2675  }
2676 
2677  /*
2678  * Transform PARTITION and ORDER specs, if any. These are treated
2679  * almost exactly like top-level GROUP BY and ORDER BY clauses,
2680  * including the special handling of nondefault operator semantics.
2681  */
2682  orderClause = transformSortClause(pstate,
2683  windef->orderClause,
2684  targetlist,
2686  true /* force SQL99 rules */ );
2687  partitionClause = transformGroupClause(pstate,
2688  windef->partitionClause,
2689  NULL,
2690  targetlist,
2691  orderClause,
2693  true /* force SQL99 rules */ );
2694 
2695  /*
2696  * And prepare the new WindowClause.
2697  */
2698  wc = makeNode(WindowClause);
2699  wc->name = windef->name;
2700  wc->refname = windef->refname;
2701 
2702  /*
2703  * Per spec, a windowdef that references a previous one copies the
2704  * previous partition clause (and mustn't specify its own). It can
2705  * specify its own ordering clause, but only if the previous one had
2706  * none. It always specifies its own frame clause, and the previous
2707  * one must not have a frame clause. Yeah, it's bizarre that each of
2708  * these cases works differently, but SQL:2008 says so; see 7.11
2709  * <window clause> syntax rule 10 and general rule 1. The frame
2710  * clause rule is especially bizarre because it makes "OVER foo"
2711  * different from "OVER (foo)", and requires the latter to throw an
2712  * error if foo has a nondefault frame clause. Well, ours not to
2713  * reason why, but we do go out of our way to throw a useful error
2714  * message for such cases.
2715  */
2716  if (refwc)
2717  {
2718  if (partitionClause)
2719  ereport(ERROR,
2720  (errcode(ERRCODE_WINDOWING_ERROR),
2721  errmsg("cannot override PARTITION BY clause of window \"%s\"",
2722  windef->refname),
2723  parser_errposition(pstate, windef->location)));
2725  }
2726  else
2727  wc->partitionClause = partitionClause;
2728  if (refwc)
2729  {
2730  if (orderClause && refwc->orderClause)
2731  ereport(ERROR,
2732  (errcode(ERRCODE_WINDOWING_ERROR),
2733  errmsg("cannot override ORDER BY clause of window \"%s\"",
2734  windef->refname),
2735  parser_errposition(pstate, windef->location)));
2736  if (orderClause)
2737  {
2738  wc->orderClause = orderClause;
2739  wc->copiedOrder = false;
2740  }
2741  else
2742  {
2743  wc->orderClause = copyObject(refwc->orderClause);
2744  wc->copiedOrder = true;
2745  }
2746  }
2747  else
2748  {
2749  wc->orderClause = orderClause;
2750  wc->copiedOrder = false;
2751  }
2752  if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2753  {
2754  /*
2755  * Use this message if this is a WINDOW clause, or if it's an OVER
2756  * clause that includes ORDER BY or framing clauses. (We already
2757  * rejected PARTITION BY above, so no need to check that.)
2758  */
2759  if (windef->name ||
2760  orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2761  ereport(ERROR,
2762  (errcode(ERRCODE_WINDOWING_ERROR),
2763  errmsg("cannot copy window \"%s\" because it has a frame clause",
2764  windef->refname),
2765  parser_errposition(pstate, windef->location)));
2766  /* Else this clause is just OVER (foo), so say this: */
2767  ereport(ERROR,
2768  (errcode(ERRCODE_WINDOWING_ERROR),
2769  errmsg("cannot copy window \"%s\" because it has a frame clause",
2770  windef->refname),
2771  errhint("Omit the parentheses in this OVER clause."),
2772  parser_errposition(pstate, windef->location)));
2773  }
2774  wc->frameOptions = windef->frameOptions;
2775 
2776  /*
2777  * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
2778  * column; check that and get its sort opfamily info.
2779  */
2780  if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
2783  {
2784  SortGroupClause *sortcl;
2785  Node *sortkey;
2786  int16 rangestrategy;
2787 
2788  if (list_length(wc->orderClause) != 1)
2789  ereport(ERROR,
2790  (errcode(ERRCODE_WINDOWING_ERROR),
2791  errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
2792  parser_errposition(pstate, windef->location)));
2793  sortcl = linitial_node(SortGroupClause, wc->orderClause);
2794  sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
2795  /* Find the sort operator in pg_amop */
2796  if (!get_ordering_op_properties(sortcl->sortop,
2797  &rangeopfamily,
2798  &rangeopcintype,
2799  &rangestrategy))
2800  elog(ERROR, "operator %u is not a valid ordering operator",
2801  sortcl->sortop);
2802  /* Record properties of sort ordering */
2803  wc->inRangeColl = exprCollation(sortkey);
2804  wc->inRangeAsc = (rangestrategy == BTLessStrategyNumber);
2805  wc->inRangeNullsFirst = sortcl->nulls_first;
2806  }
2807 
2808  /* Per spec, GROUPS mode requires an ORDER BY clause */
2809  if (wc->frameOptions & FRAMEOPTION_GROUPS)
2810  {
2811  if (wc->orderClause == NIL)
2812  ereport(ERROR,
2813  (errcode(ERRCODE_WINDOWING_ERROR),
2814  errmsg("GROUPS mode requires an ORDER BY clause"),
2815  parser_errposition(pstate, windef->location)));
2816  }
2817 
2818  /* Process frame offset expressions */
2819  wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2820  rangeopfamily, rangeopcintype,
2821  &wc->startInRangeFunc,
2822  windef->startOffset);
2823  wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2824  rangeopfamily, rangeopcintype,
2825  &wc->endInRangeFunc,
2826  windef->endOffset);
2827  wc->runCondition = NIL;
2828  wc->winref = winref;
2829 
2830  result = lappend(result, wc);
2831  }
2832 
2833  return result;
2834 }
signed short int16
Definition: c.h:429
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:206
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
List * transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
static Node * transformFrameOffset(ParseState *pstate, int frameOptions, Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc, Node *clause)
static WindowClause * findWindowClause(List *wclist, const char *name)
@ EXPR_KIND_WINDOW_PARTITION
Definition: parse_node.h:49
@ EXPR_KIND_WINDOW_ORDER
Definition: parse_node.h:50
#define FRAMEOPTION_END_OFFSET
Definition: parsenodes.h:565
#define FRAMEOPTION_START_OFFSET
Definition: parsenodes.h:563
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:571
#define linitial_node(type, l)
Definition: pg_list.h:179
#define BTLessStrategyNumber
Definition: stratnum.h:29
Oid endInRangeFunc
Definition: parsenodes.h:1421
bool copiedOrder
Definition: parsenodes.h:1426
Node * startOffset
Definition: parsenodes.h:1417
char * refname
Definition: parsenodes.h:1413
List * partitionClause
Definition: parsenodes.h:1414
Oid startInRangeFunc
Definition: parsenodes.h:1420
bool inRangeNullsFirst
Definition: parsenodes.h:1424
Node * endOffset
Definition: parsenodes.h:1418
List * runCondition
Definition: parsenodes.h:1419
List * orderClause
Definition: parsenodes.h:1415
List * orderClause
Definition: parsenodes.h:530
List * partitionClause
Definition: parsenodes.h:529
Node * startOffset
Definition: parsenodes.h:532
char * refname
Definition: parsenodes.h:528
Node * endOffset
Definition: parsenodes.h:533
int frameOptions
Definition: parsenodes.h:531
int location
Definition: parsenodes.h:534
char * name
Definition: parsenodes.h:527
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:379

References BTLessStrategyNumber, 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_node, 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, WindowClause::runCondition, SortGroupClause::sortop, WindowClause::startInRangeFunc, WindowDef::startOffset, WindowClause::startOffset, transformFrameOffset(), transformGroupClause(), transformSortClause(), and WindowClause::winref.

Referenced by transformPLAssignStmt(), and transformSelectStmt().