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 (ParseState *pstate, 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 (ParseState *pstate, ParseNamespaceColumn *nscol)
 
static NodebuildMergedJoinVar (ParseState *pstate, JoinType jointype, Var *l_colvar, Var *r_colvar)
 
static void markRelsAsNulledBy (ParseState *pstate, Node *n, int jindex)
 
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 3530 of file parse_clause.c.

3532 {
3533  Oid restype = exprType((Node *) tle->expr);
3534 
3535  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3536  if (restype == UNKNOWNOID)
3537  {
3538  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3539  restype, TEXTOID, -1,
3542  -1);
3543  restype = TEXTOID;
3544  }
3545 
3546  /* avoid making duplicate grouplist entries */
3547  if (!targetIsInSortList(tle, InvalidOid, grouplist))
3548  {
3550  Oid sortop;
3551  Oid eqop;
3552  bool hashable;
3553  ParseCallbackState pcbstate;
3554 
3555  setup_parser_errposition_callback(&pcbstate, pstate, location);
3556 
3557  /* determine the eqop and optional sortop */
3558  get_sort_group_operators(restype,
3559  false, true, false,
3560  &sortop, &eqop, NULL,
3561  &hashable);
3562 
3564 
3565  grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3566  grpcl->eqop = eqop;
3567  grpcl->sortop = sortop;
3568  grpcl->nulls_first = false; /* OK with or without sortop */
3569  grpcl->hashable = hashable;
3570 
3571  grouplist = lappend(grouplist, grpcl);
3572  }
3573 
3574  return grouplist;
3575 }
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:176
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:161
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
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:663
@ COERCION_IMPLICIT
Definition: primnodes.h:641
Definition: nodes.h:129
Index tleSortGroupRef
Definition: parsenodes.h:1393
Expr * expr
Definition: primnodes.h:1816

References assignSortGroupRef(), cancel_parser_errposition_callback(), COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, SortGroupClause::eqop, TargetEntry::expr, exprType(), get_sort_group_operators(), 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 3387 of file parse_clause.c.

3389 {
3390  Oid restype = exprType((Node *) tle->expr);
3391  Oid sortop;
3392  Oid eqop;
3393  bool hashable;
3394  bool reverse;
3395  int location;
3396  ParseCallbackState pcbstate;
3397 
3398  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3399  if (restype == UNKNOWNOID)
3400  {
3401  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3402  restype, TEXTOID, -1,
3405  -1);
3406  restype = TEXTOID;
3407  }
3408 
3409  /*
3410  * Rather than clutter the API of get_sort_group_operators and the other
3411  * functions we're about to use, make use of error context callback to
3412  * mark any error reports with a parse position. We point to the operator
3413  * location if present, else to the expression being sorted. (NB: use the
3414  * original untransformed expression here; the TLE entry might well point
3415  * at a duplicate expression in the regular SELECT list.)
3416  */
3417  location = sortby->location;
3418  if (location < 0)
3419  location = exprLocation(sortby->node);
3420  setup_parser_errposition_callback(&pcbstate, pstate, location);
3421 
3422  /* determine the sortop, eqop, and directionality */
3423  switch (sortby->sortby_dir)
3424  {
3425  case SORTBY_DEFAULT:
3426  case SORTBY_ASC:
3427  get_sort_group_operators(restype,
3428  true, true, false,
3429  &sortop, &eqop, NULL,
3430  &hashable);
3431  reverse = false;
3432  break;
3433  case SORTBY_DESC:
3434  get_sort_group_operators(restype,
3435  false, true, true,
3436  NULL, &eqop, &sortop,
3437  &hashable);
3438  reverse = true;
3439  break;
3440  case SORTBY_USING:
3441  Assert(sortby->useOp != NIL);
3442  sortop = compatible_oper_opid(sortby->useOp,
3443  restype,
3444  restype,
3445  false);
3446 
3447  /*
3448  * Verify it's a valid ordering operator, fetch the corresponding
3449  * equality operator, and determine whether to consider it like
3450  * ASC or DESC.
3451  */
3452  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3453  if (!OidIsValid(eqop))
3454  ereport(ERROR,
3455  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3456  errmsg("operator %s is not a valid ordering operator",
3457  strVal(llast(sortby->useOp))),
3458  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3459 
3460  /*
3461  * Also see if the equality operator is hashable.
3462  */
3463  hashable = op_hashjoinable(eqop, restype);
3464  break;
3465  default:
3466  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3467  sortop = InvalidOid; /* keep compiler quiet */
3468  eqop = InvalidOid;
3469  hashable = false;
3470  reverse = false;
3471  break;
3472  }
3473 
3475 
3476  /* avoid making duplicate sortlist entries */
3477  if (!targetIsInSortList(tle, sortop, sortlist))
3478  {
3480 
3481  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3482 
3483  sortcl->eqop = eqop;
3484  sortcl->sortop = sortop;
3485  sortcl->hashable = hashable;
3486 
3487  switch (sortby->sortby_nulls)
3488  {
3489  case SORTBY_NULLS_DEFAULT:
3490  /* NULLS FIRST is default for DESC; other way for ASC */
3491  sortcl->nulls_first = reverse;
3492  break;
3493  case SORTBY_NULLS_FIRST:
3494  sortcl->nulls_first = true;
3495  break;
3496  case SORTBY_NULLS_LAST:
3497  sortcl->nulls_first = false;
3498  break;
3499  default:
3500  elog(ERROR, "unrecognized sortby_nulls: %d",
3501  sortby->sortby_nulls);
3502  break;
3503  }
3504 
3505  sortlist = lappend(sortlist, sortcl);
3506  }
3507 
3508  return sortlist;
3509 }
#define OidIsValid(objectId)
Definition: c.h:759
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
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:1287
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:198
#define NIL
Definition: pg_list.h:68
SortByNulls sortby_nulls
Definition: parsenodes.h:546
Node * node
Definition: parsenodes.h:544
List * useOp
Definition: parsenodes.h:547
SortByDir sortby_dir
Definition: parsenodes.h:545
int location
Definition: parsenodes.h:548
#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(), 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 3585 of file parse_clause.c.

3586 {
3587  Index maxRef;
3588  ListCell *l;
3589 
3590  if (tle->ressortgroupref) /* already has one? */
3591  return tle->ressortgroupref;
3592 
3593  /* easiest way to pick an unused refnumber: max used + 1 */
3594  maxRef = 0;
3595  foreach(l, tlist)
3596  {
3597  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3598 
3599  if (ref > maxRef)
3600  maxRef = ref;
3601  }
3602  tle->ressortgroupref = maxRef + 1;
3603  return tle->ressortgroupref;
3604 }
unsigned int Index
Definition: c.h:598
#define lfirst(lc)
Definition: pg_list.h:172
Index ressortgroupref
Definition: primnodes.h:1822

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

1661 {
1662  Oid outcoltype;
1663  int32 outcoltypmod;
1664  Node *l_node,
1665  *r_node,
1666  *res_node;
1667 
1668  outcoltype = select_common_type(pstate,
1669  list_make2(l_colvar, r_colvar),
1670  "JOIN/USING",
1671  NULL);
1672  outcoltypmod = select_common_typmod(pstate,
1673  list_make2(l_colvar, r_colvar),
1674  outcoltype);
1675 
1676  /*
1677  * Insert coercion functions if needed. Note that a difference in typmod
1678  * can only happen if input has typmod but outcoltypmod is -1. In that
1679  * case we insert a RelabelType to clearly mark that result's typmod is
1680  * not same as input. We never need coerce_type_typmod.
1681  */
1682  if (l_colvar->vartype != outcoltype)
1683  l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
1684  outcoltype, outcoltypmod,
1686  else if (l_colvar->vartypmod != outcoltypmod)
1687  l_node = (Node *) makeRelabelType((Expr *) l_colvar,
1688  outcoltype, outcoltypmod,
1689  InvalidOid, /* fixed below */
1691  else
1692  l_node = (Node *) l_colvar;
1693 
1694  if (r_colvar->vartype != outcoltype)
1695  r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
1696  outcoltype, outcoltypmod,
1698  else if (r_colvar->vartypmod != outcoltypmod)
1699  r_node = (Node *) makeRelabelType((Expr *) r_colvar,
1700  outcoltype, outcoltypmod,
1701  InvalidOid, /* fixed below */
1703  else
1704  r_node = (Node *) r_colvar;
1705 
1706  /*
1707  * Choose what to emit
1708  */
1709  switch (jointype)
1710  {
1711  case JOIN_INNER:
1712 
1713  /*
1714  * We can use either var; prefer non-coerced one if available.
1715  */
1716  if (IsA(l_node, Var))
1717  res_node = l_node;
1718  else if (IsA(r_node, Var))
1719  res_node = r_node;
1720  else
1721  res_node = l_node;
1722  break;
1723  case JOIN_LEFT:
1724  /* Always use left var */
1725  res_node = l_node;
1726  break;
1727  case JOIN_RIGHT:
1728  /* Always use right var */
1729  res_node = r_node;
1730  break;
1731  case JOIN_FULL:
1732  {
1733  /*
1734  * Here we must build a COALESCE expression to ensure that the
1735  * join output is non-null if either input is.
1736  */
1738 
1739  c->coalescetype = outcoltype;
1740  /* coalescecollid will get set below */
1741  c->args = list_make2(l_node, r_node);
1742  c->location = -1;
1743  res_node = (Node *) c;
1744  break;
1745  }
1746  default:
1747  elog(ERROR, "unrecognized join type: %d", (int) jointype);
1748  res_node = NULL; /* keep compiler quiet */
1749  break;
1750  }
1751 
1752  /*
1753  * Apply assign_expr_collations to fix up the collation info in the
1754  * coercion and CoalesceExpr nodes, if we made any. This must be done now
1755  * so that the join node's alias vars show correct collation info.
1756  */
1757  assign_expr_collations(pstate, res_node);
1758 
1759  return res_node;
1760 }
signed int int32
Definition: c.h:478
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:405
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
@ JOIN_FULL
Definition: nodes.h:306
@ JOIN_INNER
Definition: nodes.h:304
@ JOIN_RIGHT
Definition: nodes.h:307
@ JOIN_LEFT
Definition: nodes.h:305
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:214
char * c
Definition: primnodes.h:226

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

Referenced by transformFromClauseItem().

◆ buildVarFromNSColumn()

static Var * buildVarFromNSColumn ( ParseState pstate,
ParseNamespaceColumn nscol 
)
static

Definition at line 1633 of file parse_clause.c.

1634 {
1635  Var *var;
1636 
1637  Assert(nscol->p_varno > 0); /* i.e., not deleted column */
1638  var = makeVar(nscol->p_varno,
1639  nscol->p_varattno,
1640  nscol->p_vartype,
1641  nscol->p_vartypmod,
1642  nscol->p_varcollid,
1643  0);
1644  /* makeVar doesn't offer parameters for these, so set by hand: */
1645  var->varnosyn = nscol->p_varnosyn;
1646  var->varattnosyn = nscol->p_varattnosyn;
1647 
1648  /* ... and update varnullingrels */
1649  markNullableIfNeeded(pstate, var);
1650 
1651  return var;
1652 }
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
void markNullableIfNeeded(ParseState *pstate, Var *var)
AttrNumber p_varattno
Definition: parse_node.h:321
AttrNumber p_varattnosyn
Definition: parse_node.h:326

References Assert(), makeVar(), markNullableIfNeeded(), 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 1918 of file parse_clause.c.

1919 {
1920  if (contain_vars_of_level(n, 0))
1921  {
1922  ereport(ERROR,
1923  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1924  /* translator: %s is name of a SQL construct, eg LIMIT */
1925  errmsg("argument of %s must not contain variables",
1926  constructName),
1927  parser_errposition(pstate,
1928  locate_var_of_level(n, 0))));
1929  }
1930 }
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:441
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:509

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

1945 {
1946  switch (exprKind)
1947  {
1948  case EXPR_KIND_GROUP_BY:
1949  /* reject aggregates and window functions */
1950  if (pstate->p_hasAggs &&
1951  contain_aggs_of_level((Node *) tle->expr, 0))
1952  ereport(ERROR,
1953  (errcode(ERRCODE_GROUPING_ERROR),
1954  /* translator: %s is name of a SQL construct, eg GROUP BY */
1955  errmsg("aggregate functions are not allowed in %s",
1956  ParseExprKindName(exprKind)),
1957  parser_errposition(pstate,
1958  locate_agg_of_level((Node *) tle->expr, 0))));
1959  if (pstate->p_hasWindowFuncs &&
1960  contain_windowfuncs((Node *) tle->expr))
1961  ereport(ERROR,
1962  (errcode(ERRCODE_WINDOWING_ERROR),
1963  /* translator: %s is name of a SQL construct, eg GROUP BY */
1964  errmsg("window functions are not allowed in %s",
1965  ParseExprKindName(exprKind)),
1966  parser_errposition(pstate,
1967  locate_windowfunc((Node *) tle->expr))));
1968  break;
1969  case EXPR_KIND_ORDER_BY:
1970  /* no extra checks needed */
1971  break;
1972  case EXPR_KIND_DISTINCT_ON:
1973  /* no extra checks needed */
1974  break;
1975  default:
1976  elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
1977  break;
1978  }
1979 }
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:2983
@ 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:215
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:149
bool contain_aggs_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:85
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:253
bool p_hasWindowFuncs
Definition: parse_node.h:223
bool p_hasAggs
Definition: parse_node.h:222

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 ( ParseState pstate,
ParseNamespaceColumn src_nscolumns,
List src_colnames,
List **  src_colnos,
List **  res_colnames,
List **  res_colvars,
ParseNamespaceColumn res_nscolumns 
)
static

Definition at line 257 of file parse_clause.c.

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

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

2001 {
2002  ListCell *tl;
2003 
2004  /*----------
2005  * Handle two special cases as mandated by the SQL92 spec:
2006  *
2007  * 1. Bare ColumnName (no qualifier or subscripts)
2008  * For a bare identifier, we search for a matching column name
2009  * in the existing target list. Multiple matches are an error
2010  * unless they refer to identical values; for example,
2011  * we allow SELECT a, a FROM table ORDER BY a
2012  * but not SELECT a AS b, b FROM table ORDER BY b
2013  * If no match is found, we fall through and treat the identifier
2014  * as an expression.
2015  * For GROUP BY, it is incorrect to match the grouping item against
2016  * targetlist entries: according to SQL92, an identifier in GROUP BY
2017  * is a reference to a column name exposed by FROM, not to a target
2018  * list column. However, many implementations (including pre-7.0
2019  * PostgreSQL) accept this anyway. So for GROUP BY, we look first
2020  * to see if the identifier matches any FROM column name, and only
2021  * try for a targetlist name if it doesn't. This ensures that we
2022  * adhere to the spec in the case where the name could be both.
2023  * DISTINCT ON isn't in the standard, so we can do what we like there;
2024  * we choose to make it work like ORDER BY, on the rather flimsy
2025  * grounds that ordinary DISTINCT works on targetlist entries.
2026  *
2027  * 2. IntegerConstant
2028  * This means to use the n'th item in the existing target list.
2029  * Note that it would make no sense to order/group/distinct by an
2030  * actual constant, so this does not create a conflict with SQL99.
2031  * GROUP BY column-number is not allowed by SQL92, but since
2032  * the standard has no other behavior defined for this syntax,
2033  * we may as well accept this common extension.
2034  *
2035  * Note that pre-existing resjunk targets must not be used in either case,
2036  * since the user didn't write them in his SELECT list.
2037  *
2038  * If neither special case applies, fall through to treat the item as
2039  * an expression per SQL99.
2040  *----------
2041  */
2042  if (IsA(node, ColumnRef) &&
2043  list_length(((ColumnRef *) node)->fields) == 1 &&
2044  IsA(linitial(((ColumnRef *) node)->fields), String))
2045  {
2046  char *name = strVal(linitial(((ColumnRef *) node)->fields));
2047  int location = ((ColumnRef *) node)->location;
2048 
2049  if (exprKind == EXPR_KIND_GROUP_BY)
2050  {
2051  /*
2052  * In GROUP BY, we must prefer a match against a FROM-clause
2053  * column to one against the targetlist. Look to see if there is
2054  * a matching column. If so, fall through to use SQL99 rules.
2055  * NOTE: if name could refer ambiguously to more than one column
2056  * name exposed by FROM, colNameToVar will ereport(ERROR). That's
2057  * just what we want here.
2058  *
2059  * Small tweak for 7.4.3: ignore matches in upper query levels.
2060  * This effectively changes the search order for bare names to (1)
2061  * local FROM variables, (2) local targetlist aliases, (3) outer
2062  * FROM variables, whereas before it was (1) (3) (2). SQL92 and
2063  * SQL99 do not allow GROUPing BY an outer reference, so this
2064  * breaks no cases that are legal per spec, and it seems a more
2065  * self-consistent behavior.
2066  */
2067  if (colNameToVar(pstate, name, true, location) != NULL)
2068  name = NULL;
2069  }
2070 
2071  if (name != NULL)
2072  {
2073  TargetEntry *target_result = NULL;
2074 
2075  foreach(tl, *tlist)
2076  {
2077  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2078 
2079  if (!tle->resjunk &&
2080  strcmp(tle->resname, name) == 0)
2081  {
2082  if (target_result != NULL)
2083  {
2084  if (!equal(target_result->expr, tle->expr))
2085  ereport(ERROR,
2086  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
2087 
2088  /*------
2089  translator: first %s is name of a SQL construct, eg ORDER BY */
2090  errmsg("%s \"%s\" is ambiguous",
2091  ParseExprKindName(exprKind),
2092  name),
2093  parser_errposition(pstate, location)));
2094  }
2095  else
2096  target_result = tle;
2097  /* Stay in loop to check for ambiguity */
2098  }
2099  }
2100  if (target_result != NULL)
2101  {
2102  /* return the first match, after suitable validation */
2103  checkTargetlistEntrySQL92(pstate, target_result, exprKind);
2104  return target_result;
2105  }
2106  }
2107  }
2108  if (IsA(node, A_Const))
2109  {
2110  A_Const *aconst = castNode(A_Const, node);
2111  int targetlist_pos = 0;
2112  int target_pos;
2113 
2114  if (!IsA(&aconst->val, Integer))
2115  ereport(ERROR,
2116  (errcode(ERRCODE_SYNTAX_ERROR),
2117  /* translator: %s is name of a SQL construct, eg ORDER BY */
2118  errmsg("non-integer constant in %s",
2119  ParseExprKindName(exprKind)),
2120  parser_errposition(pstate, aconst->location)));
2121 
2122  target_pos = intVal(&aconst->val);
2123  foreach(tl, *tlist)
2124  {
2125  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2126 
2127  if (!tle->resjunk)
2128  {
2129  if (++targetlist_pos == target_pos)
2130  {
2131  /* return the unique match, after suitable validation */
2132  checkTargetlistEntrySQL92(pstate, tle, exprKind);
2133  return tle;
2134  }
2135  }
2136  }
2137  ereport(ERROR,
2138  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2139  /* translator: %s is name of a SQL construct, eg ORDER BY */
2140  errmsg("%s position %d is not in select list",
2141  ParseExprKindName(exprKind), target_pos),
2142  parser_errposition(pstate, aconst->location)));
2143  }
2144 
2145  /*
2146  * Otherwise, we have an expression, so process it per SQL99 rules.
2147  */
2148  return findTargetlistEntrySQL99(pstate, node, tlist, exprKind);
2149 }
const char * name
Definition: encode.c:571
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
#define castNode(_type_, nodeptr)
Definition: nodes.h:197
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:152
#define linitial(l)
Definition: pg_list.h:178
int location
Definition: parsenodes.h:362
union ValUnion val
Definition: parsenodes.h:360
Definition: value.h:29
Definition: value.h:64
#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(), 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 2165 of file parse_clause.c.

2167 {
2168  TargetEntry *target_result;
2169  ListCell *tl;
2170  Node *expr;
2171 
2172  /*
2173  * Convert the untransformed node to a transformed expression, and search
2174  * for a match in the tlist. NOTE: it doesn't really matter whether there
2175  * is more than one match. Also, we are willing to match an existing
2176  * resjunk target here, though the SQL92 cases above must ignore resjunk
2177  * targets.
2178  */
2179  expr = transformExpr(pstate, node, exprKind);
2180 
2181  foreach(tl, *tlist)
2182  {
2183  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2184  Node *texpr;
2185 
2186  /*
2187  * Ignore any implicit cast on the existing tlist expression.
2188  *
2189  * This essentially allows the ORDER/GROUP/etc item to adopt the same
2190  * datatype previously selected for a textually-equivalent tlist item.
2191  * There can't be any implicit cast at top level in an ordinary SELECT
2192  * tlist at this stage, but the case does arise with ORDER BY in an
2193  * aggregate function.
2194  */
2195  texpr = strip_implicit_coercions((Node *) tle->expr);
2196 
2197  if (equal(expr, texpr))
2198  return tle;
2199  }
2200 
2201  /*
2202  * If no matches, construct a new target entry which is appended to the
2203  * end of the target list. This target is given resjunk = true so that it
2204  * will not be projected into the final tuple.
2205  */
2206  target_result = transformTargetEntry(pstate, node, expr, exprKind,
2207  NULL, true);
2208 
2209  *tlist = lappend(*tlist, target_result);
2210 
2211  return target_result;
2212 }
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:664
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:103
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 3653 of file parse_clause.c.

3654 {
3655  ListCell *l;
3656 
3657  foreach(l, wclist)
3658  {
3659  WindowClause *wc = (WindowClause *) lfirst(l);
3660 
3661  if (wc->name && strcmp(wc->name, name) == 0)
3662  return wc;
3663  }
3664 
3665  return NULL;
3666 }

References lfirst, and name.

Referenced by transformWindowDefinitions().

◆ flatten_grouping_sets()

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

Definition at line 2251 of file parse_clause.c.

2252 {
2253  /* just in case of pathological input */
2255 
2256  if (expr == (Node *) NIL)
2257  return (Node *) NIL;
2258 
2259  switch (expr->type)
2260  {
2261  case T_RowExpr:
2262  {
2263  RowExpr *r = (RowExpr *) expr;
2264 
2265  if (r->row_format == COERCE_IMPLICIT_CAST)
2266  return flatten_grouping_sets((Node *) r->args,
2267  false, NULL);
2268  }
2269  break;
2270  case T_GroupingSet:
2271  {
2272  GroupingSet *gset = (GroupingSet *) expr;
2273  ListCell *l2;
2274  List *result_set = NIL;
2275 
2276  if (hasGroupingSets)
2277  *hasGroupingSets = true;
2278 
2279  /*
2280  * at the top level, we skip over all empty grouping sets; the
2281  * caller can supply the canonical GROUP BY () if nothing is
2282  * left.
2283  */
2284 
2285  if (toplevel && gset->kind == GROUPING_SET_EMPTY)
2286  return (Node *) NIL;
2287 
2288  foreach(l2, gset->content)
2289  {
2290  Node *n1 = lfirst(l2);
2291  Node *n2 = flatten_grouping_sets(n1, false, NULL);
2292 
2293  if (IsA(n1, GroupingSet) &&
2294  ((GroupingSet *) n1)->kind == GROUPING_SET_SETS)
2295  result_set = list_concat(result_set, (List *) n2);
2296  else
2297  result_set = lappend(result_set, n2);
2298  }
2299 
2300  /*
2301  * At top level, keep the grouping set node; but if we're in a
2302  * nested grouping set, then we need to concat the flattened
2303  * result into the outer list if it's simply nested.
2304  */
2305 
2306  if (toplevel || (gset->kind != GROUPING_SET_SETS))
2307  {
2308  return (Node *) makeGroupingSet(gset->kind, result_set, gset->location);
2309  }
2310  else
2311  return (Node *) result_set;
2312  }
2313  case T_List:
2314  {
2315  List *result = NIL;
2316  ListCell *l;
2317 
2318  foreach(l, (List *) expr)
2319  {
2320  Node *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets);
2321 
2322  if (n != (Node *) NIL)
2323  {
2324  if (IsA(n, List))
2325  result = list_concat(result, (List *) n);
2326  else
2327  result = lappend(result, n);
2328  }
2329  }
2330 
2331  return (Node *) result;
2332  }
2333  default:
2334  break;
2335  }
2336 
2337  return expr;
2338 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:805
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
@ GROUPING_SET_SETS
Definition: parsenodes.h:1457
@ GROUPING_SET_EMPTY
Definition: parsenodes.h:1453
void check_stack_depth(void)
Definition: postgres.c:3461
List * content
Definition: parsenodes.h:1464
Definition: pg_list.h:54
NodeTag type
Definition: nodes.h:130
List * args
Definition: primnodes.h:1336

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

Referenced by transformGroupClause().

◆ get_matching_location()

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

Definition at line 3170 of file parse_clause.c.

3171 {
3172  ListCell *lcs;
3173  ListCell *lce;
3174 
3175  forboth(lcs, sortgrouprefs, lce, exprs)
3176  {
3177  if (lfirst_int(lcs) == sortgroupref)
3178  return exprLocation((Node *) lfirst(lce));
3179  }
3180  /* if no match, caller blew it */
3181  elog(ERROR, "get_matching_location: no matching sortgroupref");
3182  return -1; /* keep compiler quiet */
3183 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:467

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

Referenced by transformDistinctOnClause().

◆ getNSItemForSpecialRelationTypes()

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

Definition at line 1011 of file parse_clause.c.

1012 {
1013  ParseNamespaceItem *nsitem;
1014  CommonTableExpr *cte;
1015  Index levelsup;
1016 
1017  /*
1018  * if it is a qualified name, it can't be a CTE or tuplestore reference
1019  */
1020  if (rv->schemaname)
1021  return NULL;
1022 
1023  cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
1024  if (cte)
1025  nsitem = addRangeTableEntryForCTE(pstate, cte, levelsup, rv, true);
1026  else if (scanNameSpaceForENR(pstate, rv->relname))
1027  nsitem = addRangeTableEntryForENR(pstate, rv, true);
1028  else
1029  nsitem = NULL;
1030 
1031  return nsitem;
1032 }
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:74
char * schemaname
Definition: primnodes.h:71

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

Referenced by transformFromClauseItem().

◆ markRelsAsNulledBy()

static void markRelsAsNulledBy ( ParseState pstate,
Node n,
int  jindex 
)
static

Definition at line 1767 of file parse_clause.c.

1768 {
1769  int varno;
1770  ListCell *lc;
1771 
1772  /* Note: we can't see FromExpr here */
1773  if (IsA(n, RangeTblRef))
1774  {
1775  varno = ((RangeTblRef *) n)->rtindex;
1776  }
1777  else if (IsA(n, JoinExpr))
1778  {
1779  JoinExpr *j = (JoinExpr *) n;
1780 
1781  /* recurse to children */
1782  markRelsAsNulledBy(pstate, j->larg, jindex);
1783  markRelsAsNulledBy(pstate, j->rarg, jindex);
1784  varno = j->rtindex;
1785  }
1786  else
1787  {
1788  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
1789  varno = 0; /* keep compiler quiet */
1790  }
1791 
1792  /*
1793  * Now add jindex to the p_nullingrels set for relation varno. Since we
1794  * maintain the p_nullingrels list lazily, we might need to extend it to
1795  * make the varno'th entry exist.
1796  */
1797  while (list_length(pstate->p_nullingrels) < varno)
1798  pstate->p_nullingrels = lappend(pstate->p_nullingrels, NULL);
1799  lc = list_nth_cell(pstate->p_nullingrels, varno - 1);
1800  lfirst(lc) = bms_add_member((Bitmapset *) lfirst(lc), jindex);
1801 }
int j
Definition: isn.c:74
#define nodeTag(nodeptr)
Definition: nodes.h:133
static void markRelsAsNulledBy(ParseState *pstate, Node *n, int jindex)
static ListCell * list_nth_cell(const List *list, int n)
Definition: pg_list.h:277
List * p_nullingrels
Definition: parse_node.h:197

References bms_add_member(), elog(), ERROR, IsA, j, lappend(), lfirst, list_length(), list_nth_cell(), nodeTag, and ParseState::p_nullingrels.

Referenced by transformFromClauseItem().

◆ resolve_unique_index_expr()

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

Definition at line 3195 of file parse_clause.c.

3197 {
3198  List *result = NIL;
3199  ListCell *l;
3200 
3201  foreach(l, infer->indexElems)
3202  {
3203  IndexElem *ielem = (IndexElem *) lfirst(l);
3205  Node *parse;
3206 
3207  /*
3208  * Raw grammar re-uses CREATE INDEX infrastructure for unique index
3209  * inference clause, and so will accept opclasses by name and so on.
3210  *
3211  * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
3212  * LAST ordering, since those are not significant for inference
3213  * purposes (any unique index matching the inference specification in
3214  * other regards is accepted indifferently). Actively reject this as
3215  * wrong-headed.
3216  */
3217  if (ielem->ordering != SORTBY_DEFAULT)
3218  ereport(ERROR,
3219  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3220  errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
3221  parser_errposition(pstate,
3222  exprLocation((Node *) infer))));
3223  if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
3224  ereport(ERROR,
3225  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3226  errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
3227  parser_errposition(pstate,
3228  exprLocation((Node *) infer))));
3229 
3230  if (!ielem->expr)
3231  {
3232  /* Simple index attribute */
3233  ColumnRef *n;
3234 
3235  /*
3236  * Grammar won't have built raw expression for us in event of
3237  * plain column reference. Create one directly, and perform
3238  * expression transformation. Planner expects this, and performs
3239  * its own normalization for the purposes of matching against
3240  * pg_index.
3241  */
3242  n = makeNode(ColumnRef);
3243  n->fields = list_make1(makeString(ielem->name));
3244  /* Location is approximately that of inference specification */
3245  n->location = infer->location;
3246  parse = (Node *) n;
3247  }
3248  else
3249  {
3250  /* Do parse transformation of the raw expression */
3251  parse = (Node *) ielem->expr;
3252  }
3253 
3254  /*
3255  * transformExpr() will reject subqueries, aggregates, window
3256  * functions, and SRFs, based on being passed
3257  * EXPR_KIND_INDEX_EXPRESSION. So we needn't worry about those
3258  * further ... not that they would match any available index
3259  * expression anyway.
3260  */
3261  pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
3262 
3263  /* Perform lookup of collation and operator class as required */
3264  if (!ielem->collation)
3265  pInfer->infercollid = InvalidOid;
3266  else
3267  pInfer->infercollid = LookupCollation(pstate, ielem->collation,
3268  exprLocation(pInfer->expr));
3269 
3270  if (!ielem->opclass)
3271  pInfer->inferopclass = InvalidOid;
3272  else
3273  pInfer->inferopclass = get_opclass_oid(BTREE_AM_OID,
3274  ielem->opclass, false);
3275 
3276  result = lappend(result, pInfer);
3277  }
3278 
3279  return result;
3280 }
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:212
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:293
List * fields
Definition: parsenodes.h:292
Node * expr
Definition: parsenodes.h:779
SortByDir ordering
Definition: parsenodes.h:784
SortByNulls nulls_ordering
Definition: parsenodes.h:785
List * opclass
Definition: parsenodes.h:782
char * name
Definition: parsenodes.h:778
List * collation
Definition: parsenodes.h:781
List * indexElems
Definition: parsenodes.h:1563
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 1808 of file parse_clause.c.

1809 {
1810  ListCell *lc;
1811 
1812  foreach(lc, namespace)
1813  {
1814  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1815 
1816  nsitem->p_cols_visible = cols_visible;
1817  }
1818 }

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

1826 {
1827  ListCell *lc;
1828 
1829  foreach(lc, namespace)
1830  {
1831  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1832 
1833  nsitem->p_lateral_only = lateral_only;
1834  nsitem->p_lateral_ok = lateral_ok;
1835  }
1836 }

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

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

References addNSItemToQuery(), addRangeTableEntryForRelation(), RangeVar::alias, ereport, errcode(), errmsg(), ERROR, NoLock, ParseNamespaceItem::p_perminfo, ParseNamespaceItem::p_rtindex, ParseState::p_target_nsitem, ParseState::p_target_relation, parserOpenTable(), RangeVar::relname, RTEPermissionInfo::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 3626 of file parse_clause.c.

3627 {
3628  Index ref = tle->ressortgroupref;
3629  ListCell *l;
3630 
3631  /* no need to scan list if tle has no marker */
3632  if (ref == 0)
3633  return false;
3634 
3635  foreach(l, sortList)
3636  {
3637  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3638 
3639  if (scl->tleSortGroupRef == ref &&
3640  (sortop == InvalidOid ||
3641  sortop == scl->sortop ||
3642  sortop == get_commutator(scl->sortop)))
3643  return true;
3644  }
3645  return false;
3646 }
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 2979 of file parse_clause.c.

2981 {
2982  List *result = NIL;
2983  ListCell *slitem;
2984  ListCell *tlitem;
2985 
2986  /*
2987  * The distinctClause should consist of all ORDER BY items followed by all
2988  * other non-resjunk targetlist items. There must not be any resjunk
2989  * ORDER BY items --- that would imply that we are sorting by a value that
2990  * isn't necessarily unique within a DISTINCT group, so the results
2991  * wouldn't be well-defined. This construction ensures we follow the rule
2992  * that sortClause and distinctClause match; in fact the sortClause will
2993  * always be a prefix of distinctClause.
2994  *
2995  * Note a corner case: the same TLE could be in the ORDER BY list multiple
2996  * times with different sortops. We have to include it in the
2997  * distinctClause the same way to preserve the prefix property. The net
2998  * effect will be that the TLE value will be made unique according to both
2999  * sortops.
3000  */
3001  foreach(slitem, sortClause)
3002  {
3003  SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
3004  TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
3005 
3006  if (tle->resjunk)
3007  ereport(ERROR,
3008  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3009  is_agg ?
3010  errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
3011  errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
3012  parser_errposition(pstate,
3013  exprLocation((Node *) tle->expr))));
3014  result = lappend(result, copyObject(scl));
3015  }
3016 
3017  /*
3018  * Now add any remaining non-resjunk tlist items, using default sort/group
3019  * semantics for their data types.
3020  */
3021  foreach(tlitem, *targetlist)
3022  {
3023  TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
3024 
3025  if (tle->resjunk)
3026  continue; /* ignore junk */
3027  result = addTargetToGroupList(pstate, tle,
3028  result, *targetlist,
3029  exprLocation((Node *) tle->expr));
3030  }
3031 
3032  /*
3033  * Complain if we found nothing to make DISTINCT. Returning an empty list
3034  * would cause the parsed Query to look like it didn't have DISTINCT, with
3035  * results that would probably surprise the user. Note: this case is
3036  * presently impossible for aggregates because of grammar restrictions,
3037  * but we check anyway.
3038  */
3039  if (result == NIL)
3040  ereport(ERROR,
3041  (errcode(ERRCODE_SYNTAX_ERROR),
3042  is_agg ?
3043  errmsg("an aggregate with DISTINCT must have at least one argument") :
3044  errmsg("SELECT DISTINCT must have at least one column")));
3045 
3046  return result;
3047 }
#define copyObject(obj)
Definition: nodes.h:244
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, and parser_errposition().

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

◆ transformDistinctOnClause()

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

Definition at line 3063 of file parse_clause.c.

3065 {
3066  List *result = NIL;
3067  List *sortgrouprefs = NIL;
3068  bool skipped_sortitem;
3069  ListCell *lc;
3070  ListCell *lc2;
3071 
3072  /*
3073  * Add all the DISTINCT ON expressions to the tlist (if not already
3074  * present, they are added as resjunk items). Assign sortgroupref numbers
3075  * to them, and make a list of these numbers. (NB: we rely below on the
3076  * sortgrouprefs list being one-for-one with the original distinctlist.
3077  * Also notice that we could have duplicate DISTINCT ON expressions and
3078  * hence duplicate entries in sortgrouprefs.)
3079  */
3080  foreach(lc, distinctlist)
3081  {
3082  Node *dexpr = (Node *) lfirst(lc);
3083  int sortgroupref;
3084  TargetEntry *tle;
3085 
3086  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
3088  sortgroupref = assignSortGroupRef(tle, *targetlist);
3089  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
3090  }
3091 
3092  /*
3093  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
3094  * semantics from ORDER BY items that match DISTINCT ON items, and also
3095  * adopt their column sort order. We insist that the distinctClause and
3096  * sortClause match, so throw error if we find the need to add any more
3097  * distinctClause items after we've skipped an ORDER BY item that wasn't
3098  * in DISTINCT ON.
3099  */
3100  skipped_sortitem = false;
3101  foreach(lc, sortClause)
3102  {
3103  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
3104 
3105  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
3106  {
3107  if (skipped_sortitem)
3108  ereport(ERROR,
3109  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3110  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3111  parser_errposition(pstate,
3113  sortgrouprefs,
3114  distinctlist))));
3115  else
3116  result = lappend(result, copyObject(scl));
3117  }
3118  else
3119  skipped_sortitem = true;
3120  }
3121 
3122  /*
3123  * Now add any remaining DISTINCT ON items, using default sort/group
3124  * semantics for their data types. (Note: this is pretty questionable; if
3125  * the ORDER BY list doesn't include all the DISTINCT ON items and more
3126  * besides, you certainly aren't using DISTINCT ON in the intended way,
3127  * and you probably aren't going to get consistent results. It might be
3128  * better to throw an error or warning here. But historically we've
3129  * allowed it, so keep doing so.)
3130  */
3131  forboth(lc, distinctlist, lc2, sortgrouprefs)
3132  {
3133  Node *dexpr = (Node *) lfirst(lc);
3134  int sortgroupref = lfirst_int(lc2);
3135  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
3136 
3137  if (targetIsInSortList(tle, InvalidOid, result))
3138  continue; /* already in list (with some semantics) */
3139  if (skipped_sortitem)
3140  ereport(ERROR,
3141  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3142  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3143  parser_errposition(pstate, exprLocation(dexpr))));
3144  result = addTargetToGroupList(pstate, tle,
3145  result, *targetlist,
3146  exprLocation(dexpr));
3147  }
3148 
3149  /*
3150  * An empty result list is impossible here because of grammar
3151  * restrictions.
3152  */
3153  Assert(result != NIL);
3154 
3155  return result;
3156 }
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 3680 of file parse_clause.c.

3683 {
3684  const char *constructName = NULL;
3685  Node *node;
3686 
3687  *inRangeFunc = InvalidOid; /* default result */
3688 
3689  /* Quick exit if no offset expression */
3690  if (clause == NULL)
3691  return NULL;
3692 
3693  if (frameOptions & FRAMEOPTION_ROWS)
3694  {
3695  /* Transform the raw expression tree */
3696  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_ROWS);
3697 
3698  /*
3699  * Like LIMIT clause, simply coerce to int8
3700  */
3701  constructName = "ROWS";
3702  node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3703  }
3704  else if (frameOptions & FRAMEOPTION_RANGE)
3705  {
3706  /*
3707  * We must look up the in_range support function that's to be used,
3708  * possibly choosing one of several, and coerce the "offset" value to
3709  * the appropriate input type.
3710  */
3711  Oid nodeType;
3712  Oid preferredType;
3713  int nfuncs = 0;
3714  int nmatches = 0;
3715  Oid selectedType = InvalidOid;
3716  Oid selectedFunc = InvalidOid;
3717  CatCList *proclist;
3718  int i;
3719 
3720  /* Transform the raw expression tree */
3721  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_RANGE);
3722  nodeType = exprType(node);
3723 
3724  /*
3725  * If there are multiple candidates, we'll prefer the one that exactly
3726  * matches nodeType; or if nodeType is as yet unknown, prefer the one
3727  * that exactly matches the sort column type. (The second rule is
3728  * like what we do for "known_type operator unknown".)
3729  */
3730  preferredType = (nodeType != UNKNOWNOID) ? nodeType : rangeopcintype;
3731 
3732  /* Find the in_range support functions applicable to this case */
3733  proclist = SearchSysCacheList2(AMPROCNUM,
3734  ObjectIdGetDatum(rangeopfamily),
3735  ObjectIdGetDatum(rangeopcintype));
3736  for (i = 0; i < proclist->n_members; i++)
3737  {
3738  HeapTuple proctup = &proclist->members[i]->tuple;
3739  Form_pg_amproc procform = (Form_pg_amproc) GETSTRUCT(proctup);
3740 
3741  /* The search will find all support proc types; ignore others */
3742  if (procform->amprocnum != BTINRANGE_PROC)
3743  continue;
3744  nfuncs++;
3745 
3746  /* Ignore function if given value can't be coerced to that type */
3747  if (!can_coerce_type(1, &nodeType, &procform->amprocrighttype,
3749  continue;
3750  nmatches++;
3751 
3752  /* Remember preferred match, or any match if didn't find that */
3753  if (selectedType != preferredType)
3754  {
3755  selectedType = procform->amprocrighttype;
3756  selectedFunc = procform->amproc;
3757  }
3758  }
3759  ReleaseCatCacheList(proclist);
3760 
3761  /*
3762  * Throw error if needed. It seems worth taking the trouble to
3763  * distinguish "no support at all" from "you didn't match any
3764  * available offset type".
3765  */
3766  if (nfuncs == 0)
3767  ereport(ERROR,
3768  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3769  errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s",
3770  format_type_be(rangeopcintype)),
3771  parser_errposition(pstate, exprLocation(node))));
3772  if (nmatches == 0)
3773  ereport(ERROR,
3774  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3775  errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s and offset type %s",
3776  format_type_be(rangeopcintype),
3777  format_type_be(nodeType)),
3778  errhint("Cast the offset value to an appropriate type."),
3779  parser_errposition(pstate, exprLocation(node))));
3780  if (nmatches != 1 && selectedType != preferredType)
3781  ereport(ERROR,
3782  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3783  errmsg("RANGE with offset PRECEDING/FOLLOWING has multiple interpretations for column type %s and offset type %s",
3784  format_type_be(rangeopcintype),
3785  format_type_be(nodeType)),
3786  errhint("Cast the offset value to the exact intended type."),
3787  parser_errposition(pstate, exprLocation(node))));
3788 
3789  /* OK, coerce the offset to the right type */
3790  constructName = "RANGE";
3791  node = coerce_to_specific_type(pstate, node,
3792  selectedType, constructName);
3793  *inRangeFunc = selectedFunc;
3794  }
3795  else if (frameOptions & FRAMEOPTION_GROUPS)
3796  {
3797  /* Transform the raw expression tree */
3798  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_GROUPS);
3799 
3800  /*
3801  * Like LIMIT clause, simply coerce to int8
3802  */
3803  constructName = "GROUPS";
3804  node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3805  }
3806  else
3807  {
3808  Assert(false);
3809  node = NULL;
3810  }
3811 
3812  /* Disallow variables in frame offsets */
3813  checkExprIsVarFree(pstate, node, constructName);
3814 
3815  return node;
3816 }
void ReleaseCatCacheList(CatCList *list)
Definition: catcache.c:1776
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
int i
Definition: isn.c:73
#define BTINRANGE_PROC
Definition: nbtree.h:710
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:580
#define FRAMEOPTION_GROUPS
Definition: parsenodes.h:582
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:581
FormData_pg_amproc * Form_pg_amproc
Definition: pg_amproc.h:68
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
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:220

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

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

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

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

References addRangeTableEntryForJoin(), Assert(), buildMergedJoinVar(), buildVarFromNSColumn(), check_stack_depth(), checkNameSpaceConflicts(), Alias::colnames, elog(), ereport, errcode(), errmsg(), ERROR, exprCollation(), exprLocation(), exprType(), exprTypmod(), extractRemainingColumns(), forboth, getNSItemForSpecialRelationTypes(), IsA, j, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, lappend(), lappend_int(), lfirst, lfirst_int, list_concat(), list_length(), list_make1, list_truncate(), makeNode, makeString(), markRelsAsNulledBy(), 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, ParseState::p_rtable, 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 2625 of file parse_clause.c.

2628 {
2629  List *result = NIL;
2630  List *flat_grouplist;
2631  List *gsets = NIL;
2632  ListCell *gl;
2633  bool hasGroupingSets = false;
2634  Bitmapset *seen_local = NULL;
2635 
2636  /*
2637  * Recursively flatten implicit RowExprs. (Technically this is only needed
2638  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2639  * anyway.)
2640  */
2641  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2642  true,
2643  &hasGroupingSets);
2644 
2645  /*
2646  * If the list is now empty, but hasGroupingSets is true, it's because we
2647  * elided redundant empty grouping sets. Restore a single empty grouping
2648  * set to leave a canonical form: GROUP BY ()
2649  */
2650 
2651  if (flat_grouplist == NIL && hasGroupingSets)
2652  {
2654  NIL,
2655  exprLocation((Node *) grouplist)));
2656  }
2657 
2658  foreach(gl, flat_grouplist)
2659  {
2660  Node *gexpr = (Node *) lfirst(gl);
2661 
2662  if (IsA(gexpr, GroupingSet))
2663  {
2664  GroupingSet *gset = (GroupingSet *) gexpr;
2665 
2666  switch (gset->kind)
2667  {
2668  case GROUPING_SET_EMPTY:
2669  gsets = lappend(gsets, gset);
2670  break;
2671  case GROUPING_SET_SIMPLE:
2672  /* can't happen */
2673  Assert(false);
2674  break;
2675  case GROUPING_SET_SETS:
2676  case GROUPING_SET_CUBE:
2677  case GROUPING_SET_ROLLUP:
2678  gsets = lappend(gsets,
2679  transformGroupingSet(&result,
2680  pstate, gset,
2681  targetlist, sortClause,
2682  exprKind, useSQL99, true));
2683  break;
2684  }
2685  }
2686  else
2687  {
2688  Index ref = transformGroupClauseExpr(&result, seen_local,
2689  pstate, gexpr,
2690  targetlist, sortClause,
2691  exprKind, useSQL99, true);
2692 
2693  if (ref > 0)
2694  {
2695  seen_local = bms_add_member(seen_local, ref);
2696  if (hasGroupingSets)
2697  gsets = lappend(gsets,
2699  list_make1_int(ref),
2700  exprLocation(gexpr)));
2701  }
2702  }
2703  }
2704 
2705  /* parser should prevent this */
2706  Assert(gsets == NIL || groupingSets != NULL);
2707 
2708  if (groupingSets)
2709  *groupingSets = gsets;
2710 
2711  return result;
2712 }
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:1456
@ GROUPING_SET_SIMPLE
Definition: parsenodes.h:1454
@ GROUPING_SET_ROLLUP
Definition: parsenodes.h:1455
#define list_make1_int(x1)
Definition: pg_list.h:227

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, 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 2360 of file parse_clause.c.

2364 {
2365  TargetEntry *tle;
2366  bool found = false;
2367 
2368  if (useSQL99)
2369  tle = findTargetlistEntrySQL99(pstate, gexpr,
2370  targetlist, exprKind);
2371  else
2372  tle = findTargetlistEntrySQL92(pstate, gexpr,
2373  targetlist, exprKind);
2374 
2375  if (tle->ressortgroupref > 0)
2376  {
2377  ListCell *sl;
2378 
2379  /*
2380  * Eliminate duplicates (GROUP BY x, x) but only at local level.
2381  * (Duplicates in grouping sets can affect the number of returned
2382  * rows, so can't be dropped indiscriminately.)
2383  *
2384  * Since we don't care about anything except the sortgroupref, we can
2385  * use a bitmapset rather than scanning lists.
2386  */
2387  if (bms_is_member(tle->ressortgroupref, seen_local))
2388  return 0;
2389 
2390  /*
2391  * If we're already in the flat clause list, we don't need to consider
2392  * adding ourselves again.
2393  */
2394  found = targetIsInSortList(tle, InvalidOid, *flatresult);
2395  if (found)
2396  return tle->ressortgroupref;
2397 
2398  /*
2399  * If the GROUP BY tlist entry also appears in ORDER BY, copy operator
2400  * info from the (first) matching ORDER BY item. This means that if
2401  * you write something like "GROUP BY foo ORDER BY foo USING <<<", the
2402  * GROUP BY operation silently takes on the equality semantics implied
2403  * by the ORDER BY. There are two reasons to do this: it improves the
2404  * odds that we can implement both GROUP BY and ORDER BY with a single
2405  * sort step, and it allows the user to choose the equality semantics
2406  * used by GROUP BY, should she be working with a datatype that has
2407  * more than one equality operator.
2408  *
2409  * If we're in a grouping set, though, we force our requested ordering
2410  * to be NULLS LAST, because if we have any hope of using a sorted agg
2411  * for the job, we're going to be tacking on generated NULL values
2412  * after the corresponding groups. If the user demands nulls first,
2413  * another sort step is going to be inevitable, but that's the
2414  * planner's problem.
2415  */
2416 
2417  foreach(sl, sortClause)
2418  {
2419  SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
2420 
2421  if (sc->tleSortGroupRef == tle->ressortgroupref)
2422  {
2423  SortGroupClause *grpc = copyObject(sc);
2424 
2425  if (!toplevel)
2426  grpc->nulls_first = false;
2427  *flatresult = lappend(*flatresult, grpc);
2428  found = true;
2429  break;
2430  }
2431  }
2432  }
2433 
2434  /*
2435  * If no match in ORDER BY, just add it to the result using default
2436  * sort/group semantics.
2437  */
2438  if (!found)
2439  *flatresult = addTargetToGroupList(pstate, tle,
2440  *flatresult, *targetlist,
2441  exprLocation(gexpr));
2442 
2443  /*
2444  * _something_ must have assigned us a sortgroupref by now...
2445  */
2446 
2447  return tle->ressortgroupref;
2448 }

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

2472 {
2473  Bitmapset *seen_local = NULL;
2474  List *result = NIL;
2475  ListCell *gl;
2476 
2477  foreach(gl, list)
2478  {
2479  Node *gexpr = (Node *) lfirst(gl);
2480 
2481  Index ref = transformGroupClauseExpr(flatresult,
2482  seen_local,
2483  pstate,
2484  gexpr,
2485  targetlist,
2486  sortClause,
2487  exprKind,
2488  useSQL99,
2489  toplevel);
2490 
2491  if (ref > 0)
2492  {
2493  seen_local = bms_add_member(seen_local, ref);
2494  result = lappend_int(result, ref);
2495  }
2496  }
2497 
2498  return result;
2499 }

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

2525 {
2526  ListCell *gl;
2527  List *content = NIL;
2528 
2529  Assert(toplevel || gset->kind != GROUPING_SET_SETS);
2530 
2531  foreach(gl, gset->content)
2532  {
2533  Node *n = lfirst(gl);
2534 
2535  if (IsA(n, List))
2536  {
2537  List *l = transformGroupClauseList(flatresult,
2538  pstate, (List *) n,
2539  targetlist, sortClause,
2540  exprKind, useSQL99, false);
2541 
2542  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2543  l,
2544  exprLocation(n)));
2545  }
2546  else if (IsA(n, GroupingSet))
2547  {
2548  GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
2549 
2550  content = lappend(content, transformGroupingSet(flatresult,
2551  pstate, gset2,
2552  targetlist, sortClause,
2553  exprKind, useSQL99, false));
2554  }
2555  else
2556  {
2557  Index ref = transformGroupClauseExpr(flatresult,
2558  NULL,
2559  pstate,
2560  n,
2561  targetlist,
2562  sortClause,
2563  exprKind,
2564  useSQL99,
2565  false);
2566 
2567  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2568  list_make1_int(ref),
2569  exprLocation(n)));
2570  }
2571  }
2572 
2573  /* Arbitrarily cap the size of CUBE, which has exponential growth */
2574  if (gset->kind == GROUPING_SET_CUBE)
2575  {
2576  if (list_length(content) > 12)
2577  ereport(ERROR,
2578  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2579  errmsg("CUBE is limited to 12 elements"),
2580  parser_errposition(pstate, gset->location)));
2581  }
2582 
2583  return (Node *) makeGroupingSet(gset->kind, content, gset->location);
2584 }
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, 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 369 of file parse_clause.c.

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

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

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

1877 {
1878  Node *qual;
1879 
1880  if (clause == NULL)
1881  return NULL;
1882 
1883  qual = transformExpr(pstate, clause, exprKind);
1884 
1885  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1886 
1887  /* LIMIT can't refer to any variables of the current query */
1888  checkExprIsVarFree(pstate, qual, constructName);
1889 
1890  /*
1891  * Don't allow NULLs in FETCH FIRST .. WITH TIES. This test is ugly and
1892  * extremely simplistic, in that you can pass a NULL anyway by hiding it
1893  * inside an expression -- but this protects ruleutils against emitting an
1894  * unadorned NULL that's not accepted back by the grammar.
1895  */
1896  if (exprKind == EXPR_KIND_LIMIT && limitOption == LIMIT_OPTION_WITH_TIES &&
1897  IsA(clause, A_Const) && castNode(A_Const, clause)->isnull)
1898  ereport(ERROR,
1899  (errcode(ERRCODE_INVALID_ROW_COUNT_IN_LIMIT_CLAUSE),
1900  errmsg("row count cannot be null in FETCH FIRST ... WITH TIES clause")));
1901 
1902  return qual;
1903 }
@ LIMIT_OPTION_WITH_TIES
Definition: nodes.h:440
@ 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 3291 of file parse_clause.c.

3295 {
3296  InferClause *infer = onConflictClause->infer;
3297 
3298  *arbiterExpr = NIL;
3299  *arbiterWhere = NULL;
3300  *constraint = InvalidOid;
3301 
3302  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3303  ereport(ERROR,
3304  (errcode(ERRCODE_SYNTAX_ERROR),
3305  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3306  errhint("For example, ON CONFLICT (column_name)."),
3307  parser_errposition(pstate,
3308  exprLocation((Node *) onConflictClause))));
3309 
3310  /*
3311  * To simplify certain aspects of its design, speculative insertion into
3312  * system catalogs is disallowed
3313  */
3314  if (IsCatalogRelation(pstate->p_target_relation))
3315  ereport(ERROR,
3316  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3317  errmsg("ON CONFLICT is not supported with system catalog tables"),
3318  parser_errposition(pstate,
3319  exprLocation((Node *) onConflictClause))));
3320 
3321  /* Same applies to table used by logical decoding as catalog table */
3323  ereport(ERROR,
3324  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3325  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3327  parser_errposition(pstate,
3328  exprLocation((Node *) onConflictClause))));
3329 
3330  /* ON CONFLICT DO NOTHING does not require an inference clause */
3331  if (infer)
3332  {
3333  if (infer->indexElems)
3334  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3335  pstate->p_target_relation);
3336 
3337  /*
3338  * Handling inference WHERE clause (for partial unique index
3339  * inference)
3340  */
3341  if (infer->whereClause)
3342  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3344 
3345  /*
3346  * If the arbiter is specified by constraint name, get the constraint
3347  * OID and mark the constrained columns as requiring SELECT privilege,
3348  * in the same way as would have happened if the arbiter had been
3349  * specified by explicit reference to the constraint's index columns.
3350  */
3351  if (infer->conname)
3352  {
3353  Oid relid = RelationGetRelid(pstate->p_target_relation);
3354  RTEPermissionInfo *perminfo = pstate->p_target_nsitem->p_perminfo;
3355  Bitmapset *conattnos;
3356 
3357  conattnos = get_relation_constraint_attnos(relid, infer->conname,
3358  false, constraint);
3359 
3360  /* Make sure the rel as a whole is marked for SELECT access */
3361  perminfo->requiredPerms |= ACL_SELECT;
3362  /* Mark the constrained columns as requiring SELECT access */
3363  perminfo->selectedCols = bms_add_members(perminfo->selectedCols,
3364  conattnos);
3365  }
3366  }
3367 
3368  /*
3369  * It's convenient to form a list of expressions based on the
3370  * representation used by CREATE INDEX, since the same restrictions are
3371  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3372  * primnode representation is used for inference elements, and so
3373  * assign_query_collations() can be trusted to do the right thing with the
3374  * post parse analysis query tree inference clause representation.
3375  */
3376 }
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:818
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:105
@ ONCONFLICT_UPDATE
Definition: nodes.h:428
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:503
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:384
#define RelationGetRelationName(relation)
Definition: rel.h:537
char * conname
Definition: parsenodes.h:1565
Node * whereClause
Definition: parsenodes.h:1564
InferClause * infer
Definition: parsenodes.h:1579
OnConflictAction action
Definition: parsenodes.h:1578
Bitmapset * selectedCols
Definition: parsenodes.h:1248

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_perminfo, ParseState::p_target_nsitem, ParseState::p_target_relation, parser_errposition(), RelationGetRelationName, RelationGetRelid, RelationIsUsedAsCatalogTable, RTEPermissionInfo::requiredPerms, resolve_unique_index_expr(), RTEPermissionInfo::selectedCols, transformExpr(), and InferClause::whereClause.

Referenced by transformOnConflictClause().

◆ transformRangeFunction()

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

Definition at line 467 of file parse_clause.c.

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

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

410 {
411  Query *query;
412 
413  /*
414  * Set p_expr_kind to show this parse level is recursing to a subselect.
415  * We can't be nested within any expression, so don't need save-restore
416  * logic here.
417  */
418  Assert(pstate->p_expr_kind == EXPR_KIND_NONE);
420 
421  /*
422  * If the subselect is LATERAL, make lateral_only names of this level
423  * visible to it. (LATERAL can't nest within a single pstate level, so we
424  * don't need save/restore logic here.)
425  */
426  Assert(!pstate->p_lateral_active);
427  pstate->p_lateral_active = r->lateral;
428 
429  /*
430  * Analyze and transform the subquery. Note that if the subquery doesn't
431  * have an alias, it can't be explicitly selected for locking, but locking
432  * might still be required (if there is an all-tables locking clause).
433  */
434  query = parse_sub_analyze(r->subquery, pstate, NULL,
435  isLockedRefname(pstate,
436  r->alias == NULL ? NULL :
437  r->alias->aliasname),
438  true);
439 
440  /* Restore state */
441  pstate->p_lateral_active = false;
442  pstate->p_expr_kind = EXPR_KIND_NONE;
443 
444  /*
445  * Check that we got a SELECT. Anything else should be impossible given
446  * restrictions of the grammar, but check anyway.
447  */
448  if (!IsA(query, Query) ||
449  query->commandType != CMD_SELECT)
450  elog(ERROR, "unexpected non-SELECT command in subquery in FROM");
451 
452  /*
453  * OK, build an RTE and nsitem for the subquery.
454  */
455  return addRangeTableEntryForSubquery(pstate,
456  query,
457  r->alias,
458  r->lateral,
459  true);
460 }
@ CMD_SELECT
Definition: nodes.h:276
@ 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:224
char * aliasname
Definition: primnodes.h:42
ParseExprKind p_expr_kind
Definition: parse_node.h:210
CmdType commandType
Definition: parsenodes.h:128
Node * subquery
Definition: parsenodes.h:617
Alias * alias
Definition: parsenodes.h:618

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

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

References addRangeTableEntryForTableFunc(), RangeTableFunc::alias, Assert(), assign_expr_collations(), bms_add_member(), coerce_to_specific_type(), coerce_to_specific_type_typmod(), RangeTableFuncCol::coldefexpr, RangeTableFuncCol::colexpr, TableFunc::colexprs, RangeTableFuncCol::colname, 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, 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 908 of file parse_clause.c.

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

2730 {
2731  List *sortlist = NIL;
2732  ListCell *olitem;
2733 
2734  foreach(olitem, orderlist)
2735  {
2736  SortBy *sortby = (SortBy *) lfirst(olitem);
2737  TargetEntry *tle;
2738 
2739  if (useSQL99)
2740  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2741  targetlist, exprKind);
2742  else
2743  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2744  targetlist, exprKind);
2745 
2746  sortlist = addTargetToSortList(pstate, tle,
2747  sortlist, *targetlist, sortby);
2748  }
2749 
2750  return sortlist;
2751 }
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 399 of file parse_clause.c.

400 {
401  /* addRangeTableEntry does all the work */
402  return addRangeTableEntry(pstate, r, r->alias, r->inh, true);
403 }
ParseNamespaceItem * addRangeTableEntry(ParseState *pstate, RangeVar *relation, Alias *alias, bool inh, bool inFromCl)
bool inh
Definition: primnodes.h:77

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

1849 {
1850  Node *qual;
1851 
1852  if (clause == NULL)
1853  return NULL;
1854 
1855  qual = transformExpr(pstate, clause, exprKind);
1856 
1857  qual = coerce_to_boolean(pstate, qual, constructName);
1858 
1859  return qual;
1860 }

References coerce_to_boolean(), and transformExpr().

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

◆ transformWindowDefinitions()

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

Definition at line 2758 of file parse_clause.c.

2761 {
2762  List *result = NIL;
2763  Index winref = 0;
2764  ListCell *lc;
2765 
2766  foreach(lc, windowdefs)
2767  {
2768  WindowDef *windef = (WindowDef *) lfirst(lc);
2769  WindowClause *refwc = NULL;
2770  List *partitionClause;
2771  List *orderClause;
2772  Oid rangeopfamily = InvalidOid;
2773  Oid rangeopcintype = InvalidOid;
2774  WindowClause *wc;
2775 
2776  winref++;
2777 
2778  /*
2779  * Check for duplicate window names.
2780  */
2781  if (windef->name &&
2782  findWindowClause(result, windef->name) != NULL)
2783  ereport(ERROR,
2784  (errcode(ERRCODE_WINDOWING_ERROR),
2785  errmsg("window \"%s\" is already defined", windef->name),
2786  parser_errposition(pstate, windef->location)));
2787 
2788  /*
2789  * If it references a previous window, look that up.
2790  */
2791  if (windef->refname)
2792  {
2793  refwc = findWindowClause(result, windef->refname);
2794  if (refwc == NULL)
2795  ereport(ERROR,
2796  (errcode(ERRCODE_UNDEFINED_OBJECT),
2797  errmsg("window \"%s\" does not exist",
2798  windef->refname),
2799  parser_errposition(pstate, windef->location)));
2800  }
2801 
2802  /*
2803  * Transform PARTITION and ORDER specs, if any. These are treated
2804  * almost exactly like top-level GROUP BY and ORDER BY clauses,
2805  * including the special handling of nondefault operator semantics.
2806  */
2807  orderClause = transformSortClause(pstate,
2808  windef->orderClause,
2809  targetlist,
2811  true /* force SQL99 rules */ );
2812  partitionClause = transformGroupClause(pstate,
2813  windef->partitionClause,
2814  NULL,
2815  targetlist,
2816  orderClause,
2818  true /* force SQL99 rules */ );
2819 
2820  /*
2821  * And prepare the new WindowClause.
2822  */
2823  wc = makeNode(WindowClause);
2824  wc->name = windef->name;
2825  wc->refname = windef->refname;
2826 
2827  /*
2828  * Per spec, a windowdef that references a previous one copies the
2829  * previous partition clause (and mustn't specify its own). It can
2830  * specify its own ordering clause, but only if the previous one had
2831  * none. It always specifies its own frame clause, and the previous
2832  * one must not have a frame clause. Yeah, it's bizarre that each of
2833  * these cases works differently, but SQL:2008 says so; see 7.11
2834  * <window clause> syntax rule 10 and general rule 1. The frame
2835  * clause rule is especially bizarre because it makes "OVER foo"
2836  * different from "OVER (foo)", and requires the latter to throw an
2837  * error if foo has a nondefault frame clause. Well, ours not to
2838  * reason why, but we do go out of our way to throw a useful error
2839  * message for such cases.
2840  */
2841  if (refwc)
2842  {
2843  if (partitionClause)
2844  ereport(ERROR,
2845  (errcode(ERRCODE_WINDOWING_ERROR),
2846  errmsg("cannot override PARTITION BY clause of window \"%s\"",
2847  windef->refname),
2848  parser_errposition(pstate, windef->location)));
2850  }
2851  else
2852  wc->partitionClause = partitionClause;
2853  if (refwc)
2854  {
2855  if (orderClause && refwc->orderClause)
2856  ereport(ERROR,
2857  (errcode(ERRCODE_WINDOWING_ERROR),
2858  errmsg("cannot override ORDER BY clause of window \"%s\"",
2859  windef->refname),
2860  parser_errposition(pstate, windef->location)));
2861  if (orderClause)
2862  {
2863  wc->orderClause = orderClause;
2864  wc->copiedOrder = false;
2865  }
2866  else
2867  {
2868  wc->orderClause = copyObject(refwc->orderClause);
2869  wc->copiedOrder = true;
2870  }
2871  }
2872  else
2873  {
2874  wc->orderClause = orderClause;
2875  wc->copiedOrder = false;
2876  }
2877  if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2878  {
2879  /*
2880  * Use this message if this is a WINDOW clause, or if it's an OVER
2881  * clause that includes ORDER BY or framing clauses. (We already
2882  * rejected PARTITION BY above, so no need to check that.)
2883  */
2884  if (windef->name ||
2885  orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2886  ereport(ERROR,
2887  (errcode(ERRCODE_WINDOWING_ERROR),
2888  errmsg("cannot copy window \"%s\" because it has a frame clause",
2889  windef->refname),
2890  parser_errposition(pstate, windef->location)));
2891  /* Else this clause is just OVER (foo), so say this: */
2892  ereport(ERROR,
2893  (errcode(ERRCODE_WINDOWING_ERROR),
2894  errmsg("cannot copy window \"%s\" because it has a frame clause",
2895  windef->refname),
2896  errhint("Omit the parentheses in this OVER clause."),
2897  parser_errposition(pstate, windef->location)));
2898  }
2899  wc->frameOptions = windef->frameOptions;
2900 
2901  /*
2902  * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
2903  * column; check that and get its sort opfamily info.
2904  */
2905  if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
2908  {
2909  SortGroupClause *sortcl;
2910  Node *sortkey;
2911  int16 rangestrategy;
2912 
2913  if (list_length(wc->orderClause) != 1)
2914  ereport(ERROR,
2915  (errcode(ERRCODE_WINDOWING_ERROR),
2916  errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
2917  parser_errposition(pstate, windef->location)));
2918  sortcl = linitial_node(SortGroupClause, wc->orderClause);
2919  sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
2920  /* Find the sort operator in pg_amop */
2921  if (!get_ordering_op_properties(sortcl->sortop,
2922  &rangeopfamily,
2923  &rangeopcintype,
2924  &rangestrategy))
2925  elog(ERROR, "operator %u is not a valid ordering operator",
2926  sortcl->sortop);
2927  /* Record properties of sort ordering */
2928  wc->inRangeColl = exprCollation(sortkey);
2929  wc->inRangeAsc = (rangestrategy == BTLessStrategyNumber);
2930  wc->inRangeNullsFirst = sortcl->nulls_first;
2931  }
2932 
2933  /* Per spec, GROUPS mode requires an ORDER BY clause */
2934  if (wc->frameOptions & FRAMEOPTION_GROUPS)
2935  {
2936  if (wc->orderClause == NIL)
2937  ereport(ERROR,
2938  (errcode(ERRCODE_WINDOWING_ERROR),
2939  errmsg("GROUPS mode requires an ORDER BY clause"),
2940  parser_errposition(pstate, windef->location)));
2941  }
2942 
2943  /* Process frame offset expressions */
2944  wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2945  rangeopfamily, rangeopcintype,
2946  &wc->startInRangeFunc,
2947  windef->startOffset);
2948  wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2949  rangeopfamily, rangeopcintype,
2950  &wc->endInRangeFunc,
2951  windef->endOffset);
2952  wc->runCondition = NIL;
2953  wc->winref = winref;
2954 
2955  result = lappend(result, wc);
2956  }
2957 
2958  return result;
2959 }
signed short int16
Definition: c.h:477
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:600
#define FRAMEOPTION_START_OFFSET
Definition: parsenodes.h:598
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:606
#define linitial_node(type, l)
Definition: pg_list.h:181
#define BTLessStrategyNumber
Definition: stratnum.h:29
Node * startOffset
Definition: parsenodes.h:1499
List * partitionClause
Definition: parsenodes.h:1495
Node * endOffset
Definition: parsenodes.h:1500
List * orderClause
Definition: parsenodes.h:1497
List * orderClause
Definition: parsenodes.h:565
List * partitionClause
Definition: parsenodes.h:564
Node * startOffset
Definition: parsenodes.h:567
char * refname
Definition: parsenodes.h:563
Node * endOffset
Definition: parsenodes.h:568
int frameOptions
Definition: parsenodes.h:566
int location
Definition: parsenodes.h:569
char * name
Definition: parsenodes.h:562
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:379

References BTLessStrategyNumber, copyObject, elog(), 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(), InvalidOid, lappend(), lfirst, linitial_node, list_length(), WindowDef::location, makeNode, WindowDef::name, NIL, SortGroupClause::nulls_first, WindowDef::orderClause, WindowClause::orderClause, parser_errposition(), WindowDef::partitionClause, WindowClause::partitionClause, WindowDef::refname, SortGroupClause::sortop, WindowDef::startOffset, WindowClause::startOffset, transformFrameOffset(), transformGroupClause(), transformSortClause(), and WindowClause::winref.

Referenced by transformPLAssignStmt(), and transformSelectStmt().