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

Go to the source code of this file.

Functions

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

Function Documentation

◆ addTargetToGroupList()

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

Definition at line 3411 of file parse_clause.c.

3413 {
3414  Oid restype = exprType((Node *) tle->expr);
3415 
3416  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3417  if (restype == UNKNOWNOID)
3418  {
3419  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3420  restype, TEXTOID, -1,
3423  -1);
3424  restype = TEXTOID;
3425  }
3426 
3427  /* avoid making duplicate grouplist entries */
3428  if (!targetIsInSortList(tle, InvalidOid, grouplist))
3429  {
3431  Oid sortop;
3432  Oid eqop;
3433  bool hashable;
3434  ParseCallbackState pcbstate;
3435 
3436  setup_parser_errposition_callback(&pcbstate, pstate, location);
3437 
3438  /* determine the eqop and optional sortop */
3439  get_sort_group_operators(restype,
3440  false, true, false,
3441  &sortop, &eqop, NULL,
3442  &hashable);
3443 
3445 
3446  grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3447  grpcl->eqop = eqop;
3448  grpcl->sortop = sortop;
3449  grpcl->nulls_first = false; /* OK with or without sortop */
3450  grpcl->hashable = hashable;
3451 
3452  grouplist = lappend(grouplist, grpcl);
3453  }
3454 
3455  return grouplist;
3456 }
List * lappend(List *list, void *datum)
Definition: list.c:336
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
#define makeNode(_type_)
Definition: nodes.h:621
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:157
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:192
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:494
@ COERCION_IMPLICIT
Definition: primnodes.h:472
Definition: nodes.h:574
Index tleSortGroupRef
Definition: parsenodes.h:1305
Expr * expr
Definition: primnodes.h:1716

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

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

◆ addTargetToSortList()

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

Definition at line 3268 of file parse_clause.c.

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

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

Referenced by transformAggregateCall(), and transformSortClause().

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3466 of file parse_clause.c.

3467 {
3468  Index maxRef;
3469  ListCell *l;
3470 
3471  if (tle->ressortgroupref) /* already has one? */
3472  return tle->ressortgroupref;
3473 
3474  /* easiest way to pick an unused refnumber: max used + 1 */
3475  maxRef = 0;
3476  foreach(l, tlist)
3477  {
3478  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3479 
3480  if (ref > maxRef)
3481  maxRef = ref;
3482  }
3483  tle->ressortgroupref = maxRef + 1;
3484  return tle->ressortgroupref;
3485 }
unsigned int Index
Definition: c.h:549
#define lfirst(lc)
Definition: pg_list.h:169
Index ressortgroupref
Definition: primnodes.h:1719

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

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

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

Referenced by transformFromClauseItem().

◆ buildVarFromNSColumn()

static Var * buildVarFromNSColumn ( ParseNamespaceColumn nscol)
static

Definition at line 1560 of file parse_clause.c.

1561 {
1562  Var *var;
1563 
1564  Assert(nscol->p_varno > 0); /* i.e., not deleted column */
1565  var = makeVar(nscol->p_varno,
1566  nscol->p_varattno,
1567  nscol->p_vartype,
1568  nscol->p_vartypmod,
1569  nscol->p_varcollid,
1570  0);
1571  /* makeVar doesn't offer parameters for these, so set by hand: */
1572  var->varnosyn = nscol->p_varnosyn;
1573  var->varattnosyn = nscol->p_varattnosyn;
1574  return var;
1575 }
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
AttrNumber p_varattno
Definition: parse_node.h:303
AttrNumber p_varattnosyn
Definition: parse_node.h:308
AttrNumber varattnosyn
Definition: primnodes.h:209
Index varnosyn
Definition: primnodes.h:208

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

Referenced by extractRemainingColumns(), and transformFromClauseItem().

◆ checkExprIsVarFree()

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

Definition at line 1800 of file parse_clause.c.

1801 {
1802  if (contain_vars_of_level(n, 0))
1803  {
1804  ereport(ERROR,
1805  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1806  /* translator: %s is name of a SQL construct, eg LIMIT */
1807  errmsg("argument of %s must not contain variables",
1808  constructName),
1809  parser_errposition(pstate,
1810  locate_var_of_level(n, 0))));
1811  }
1812 }
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:438
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:506

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

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

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

Referenced by findTargetlistEntrySQL92().

◆ extractRemainingColumns()

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

Definition at line 252 of file parse_clause.c.

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

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

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

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

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

◆ findTargetlistEntrySQL99()

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

Definition at line 2047 of file parse_clause.c.

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

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

3535 {
3536  ListCell *l;
3537 
3538  foreach(l, wclist)
3539  {
3540  WindowClause *wc = (WindowClause *) lfirst(l);
3541 
3542  if (wc->name && strcmp(wc->name, name) == 0)
3543  return wc;
3544  }
3545 
3546  return NULL;
3547 }

References lfirst, name, and WindowClause::name.

Referenced by transformWindowDefinitions().

◆ flatten_grouping_sets()

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

Definition at line 2133 of file parse_clause.c.

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

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

Referenced by transformGroupClause().

◆ get_matching_location()

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

Definition at line 3052 of file parse_clause.c.

3053 {
3054  ListCell *lcs;
3055  ListCell *lce;
3056 
3057  forboth(lcs, sortgrouprefs, lce, exprs)
3058  {
3059  if (lfirst_int(lcs) == sortgroupref)
3060  return exprLocation((Node *) lfirst(lce));
3061  }
3062  /* if no match, caller blew it */
3063  elog(ERROR, "get_matching_location: no matching sortgroupref");
3064  return -1; /* keep compiler quiet */
3065 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446

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

Referenced by transformDistinctOnClause().

◆ getNSItemForSpecialRelationTypes()

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

Definition at line 1012 of file parse_clause.c.

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

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

Referenced by transformFromClauseItem().

◆ resolve_unique_index_expr()

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

Definition at line 3077 of file parse_clause.c.

3079 {
3080  List *result = NIL;
3081  ListCell *l;
3082 
3083  foreach(l, infer->indexElems)
3084  {
3085  IndexElem *ielem = (IndexElem *) lfirst(l);
3087  Node *parse;
3088 
3089  /*
3090  * Raw grammar re-uses CREATE INDEX infrastructure for unique index
3091  * inference clause, and so will accept opclasses by name and so on.
3092  *
3093  * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
3094  * LAST ordering, since those are not significant for inference
3095  * purposes (any unique index matching the inference specification in
3096  * other regards is accepted indifferently). Actively reject this as
3097  * wrong-headed.
3098  */
3099  if (ielem->ordering != SORTBY_DEFAULT)
3100  ereport(ERROR,
3101  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3102  errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
3103  parser_errposition(pstate,
3104  exprLocation((Node *) infer))));
3105  if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
3106  ereport(ERROR,
3107  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3108  errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
3109  parser_errposition(pstate,
3110  exprLocation((Node *) infer))));
3111 
3112  if (!ielem->expr)
3113  {
3114  /* Simple index attribute */
3115  ColumnRef *n;
3116 
3117  /*
3118  * Grammar won't have built raw expression for us in event of
3119  * plain column reference. Create one directly, and perform
3120  * expression transformation. Planner expects this, and performs
3121  * its own normalization for the purposes of matching against
3122  * pg_index.
3123  */
3124  n = makeNode(ColumnRef);
3125  n->fields = list_make1(makeString(ielem->name));
3126  /* Location is approximately that of inference specification */
3127  n->location = infer->location;
3128  parse = (Node *) n;
3129  }
3130  else
3131  {
3132  /* Do parse transformation of the raw expression */
3133  parse = (Node *) ielem->expr;
3134  }
3135 
3136  /*
3137  * transformExpr() will reject subqueries, aggregates, window
3138  * functions, and SRFs, based on being passed
3139  * EXPR_KIND_INDEX_EXPRESSION. So we needn't worry about those
3140  * further ... not that they would match any available index
3141  * expression anyway.
3142  */
3143  pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
3144 
3145  /* Perform lookup of collation and operator class as required */
3146  if (!ielem->collation)
3147  pInfer->infercollid = InvalidOid;
3148  else
3149  pInfer->infercollid = LookupCollation(pstate, ielem->collation,
3150  exprLocation(pInfer->expr));
3151 
3152  if (!ielem->opclass)
3153  pInfer->inferopclass = InvalidOid;
3154  else
3155  pInfer->inferopclass = get_opclass_oid(BTREE_AM_OID,
3156  ielem->opclass, false);
3157 
3158  result = lappend(result, pInfer);
3159  }
3160 
3161  return result;
3162 }
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:517
#define list_make1(x1)
Definition: pg_list.h:206
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673
int location
Definition: parsenodes.h:253
List * fields
Definition: parsenodes.h:252
Node * expr
Definition: parsenodes.h:734
SortByDir ordering
Definition: parsenodes.h:739
SortByNulls nulls_ordering
Definition: parsenodes.h:740
List * opclass
Definition: parsenodes.h:737
char * name
Definition: parsenodes.h:733
List * collation
Definition: parsenodes.h:736
List * indexElems
Definition: parsenodes.h:1461
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 1690 of file parse_clause.c.

1691 {
1692  ListCell *lc;
1693 
1694  foreach(lc, namespace)
1695  {
1696  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1697 
1698  nsitem->p_cols_visible = cols_visible;
1699  }
1700 }

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

1708 {
1709  ListCell *lc;
1710 
1711  foreach(lc, namespace)
1712  {
1713  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1714 
1715  nsitem->p_lateral_only = lateral_only;
1716  nsitem->p_lateral_ok = lateral_ok;
1717  }
1718 }

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

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

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

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

◆ targetIsInSortList()

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

Definition at line 3507 of file parse_clause.c.

3508 {
3509  Index ref = tle->ressortgroupref;
3510  ListCell *l;
3511 
3512  /* no need to scan list if tle has no marker */
3513  if (ref == 0)
3514  return false;
3515 
3516  foreach(l, sortList)
3517  {
3518  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3519 
3520  if (scl->tleSortGroupRef == ref &&
3521  (sortop == InvalidOid ||
3522  sortop == scl->sortop ||
3523  sortop == get_commutator(scl->sortop)))
3524  return true;
3525  }
3526  return false;
3527 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1490

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

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

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

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

◆ transformDistinctOnClause()

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

Definition at line 2945 of file parse_clause.c.

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

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

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

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

Referenced by transformWindowDefinitions().

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 113 of file parse_clause.c.

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

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

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

◆ transformFromClauseItem()

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

Definition at line 1055 of file parse_clause.c.

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

References addRangeTableEntryForJoin(), Assert(), buildMergedJoinVar(), buildVarFromNSColumn(), checkNameSpaceConflicts(), Alias::colnames, elog, ereport, errcode(), errmsg(), ERROR, exprCollation(), exprLocation(), exprType(), exprTypmod(), extractRemainingColumns(), getNSItemForSpecialRelationTypes(), IsA, j, JOIN_INNER, JOIN_LEFT, lappend(), lappend_int(), lfirst, list_concat(), list_length(), list_make1, list_truncate(), makeNode, makeString(), NIL, nodeTag, ParseNamespaceItem::p_cols_visible, ParseState::p_joinexprs, ParseNamespaceItem::p_lateral_ok, ParseNamespaceItem::p_lateral_only, ParseNamespaceItem::p_names, ParseState::p_namespace, ParseNamespaceItem::p_nscolumns, ParseNamespaceItem::p_rel_visible, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, ParseNamespaceColumn::p_varattno, ParseNamespaceColumn::p_varattnosyn, ParseNamespaceColumn::p_varcollid, ParseNamespaceColumn::p_varno, ParseNamespaceColumn::p_varnosyn, ParseNamespaceColumn::p_vartype, ParseNamespaceColumn::p_vartypmod, palloc(), palloc0(), parser_errposition(), RangeTableSample::relation, RangeTblEntry::relkind, RTE_RELATION, RangeTblEntry::rtekind, RangeTblRef::rtindex, setNamespaceColumnVisibility(), setNamespaceLateralState(), strVal, RangeTblEntry::tablesample, transformJoinOnClause(), transformJoinUsingClause(), transformJsonTable(), 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 2507 of file parse_clause.c.

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

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

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

◆ transformGroupClauseExpr()

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

Definition at line 2242 of file parse_clause.c.

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

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

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

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

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

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

Referenced by transformGroupClause().

◆ transformJoinOnClause()

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

Definition at line 362 of file parse_clause.c.

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

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

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

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

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

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

Referenced by transformOnConflictClause().

◆ transformRangeFunction()

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

Definition at line 466 of file parse_clause.c.

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

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

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

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 t 
)
static

Definition at line 689 of file parse_clause.c.

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

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

Referenced by transformFromClauseItem().

◆ transformRangeTableSample()

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

Definition at line 909 of file parse_clause.c.

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

2612 {
2613  List *sortlist = NIL;
2614  ListCell *olitem;
2615 
2616  foreach(olitem, orderlist)
2617  {
2618  SortBy *sortby = (SortBy *) lfirst(olitem);
2619  TargetEntry *tle;
2620 
2621  if (useSQL99)
2622  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2623  targetlist, exprKind);
2624  else
2625  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2626  targetlist, exprKind);
2627 
2628  sortlist = addTargetToSortList(pstate, tle,
2629  sortlist, *targetlist, sortby);
2630  }
2631 
2632  return sortlist;
2633 }
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 392 of file parse_clause.c.

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

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

1731 {
1732  Node *qual;
1733 
1734  if (clause == NULL)
1735  return NULL;
1736 
1737  qual = transformExpr(pstate, clause, exprKind);
1738 
1739  qual = coerce_to_boolean(pstate, qual, constructName);
1740 
1741  return qual;
1742 }

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

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

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

Referenced by transformPLAssignStmt(), and transformSelectStmt().