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

Go to the source code of this file.

Macros

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

Functions

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

Macro Definition Documentation

◆ makeDefaultNSItem

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

Definition at line 58 of file parse_clause.c.

Function Documentation

◆ addTargetToGroupList()

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

Definition at line 3396 of file parse_clause.c.

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

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

3398 {
3399  Oid restype = exprType((Node *) tle->expr);
3400 
3401  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3402  if (restype == UNKNOWNOID)
3403  {
3404  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3405  restype, TEXTOID, -1,
3408  -1);
3409  restype = TEXTOID;
3410  }
3411 
3412  /* avoid making duplicate grouplist entries */
3413  if (!targetIsInSortList(tle, InvalidOid, grouplist))
3414  {
3416  Oid sortop;
3417  Oid eqop;
3418  bool hashable;
3419  ParseCallbackState pcbstate;
3420 
3421  setup_parser_errposition_callback(&pcbstate, pstate, location);
3422 
3423  /* determine the eqop and optional sortop */
3424  get_sort_group_operators(restype,
3425  false, true, false,
3426  &sortop, &eqop, NULL,
3427  &hashable);
3428 
3430 
3431  grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3432  grpcl->eqop = eqop;
3433  grpcl->sortop = sortop;
3434  grpcl->nulls_first = false; /* OK with or without sortop */
3435  grpcl->hashable = hashable;
3436 
3437  grouplist = lappend(grouplist, grpcl);
3438  }
3439 
3440  return grouplist;
3441 }
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
Index tleSortGroupRef
Definition: parsenodes.h:1207
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:517
unsigned int Oid
Definition: postgres_ext.h:31
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define makeNode(_type_)
Definition: nodes.h:565
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:187
Expr * expr
Definition: primnodes.h:1376
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42

◆ addTargetToSortList()

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

Definition at line 3253 of file parse_clause.c.

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

Referenced by transformAggregateCall(), and transformSortClause().

3255 {
3256  Oid restype = exprType((Node *) tle->expr);
3257  Oid sortop;
3258  Oid eqop;
3259  bool hashable;
3260  bool reverse;
3261  int location;
3262  ParseCallbackState pcbstate;
3263 
3264  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3265  if (restype == UNKNOWNOID)
3266  {
3267  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3268  restype, TEXTOID, -1,
3271  -1);
3272  restype = TEXTOID;
3273  }
3274 
3275  /*
3276  * Rather than clutter the API of get_sort_group_operators and the other
3277  * functions we're about to use, make use of error context callback to
3278  * mark any error reports with a parse position. We point to the operator
3279  * location if present, else to the expression being sorted. (NB: use the
3280  * original untransformed expression here; the TLE entry might well point
3281  * at a duplicate expression in the regular SELECT list.)
3282  */
3283  location = sortby->location;
3284  if (location < 0)
3285  location = exprLocation(sortby->node);
3286  setup_parser_errposition_callback(&pcbstate, pstate, location);
3287 
3288  /* determine the sortop, eqop, and directionality */
3289  switch (sortby->sortby_dir)
3290  {
3291  case SORTBY_DEFAULT:
3292  case SORTBY_ASC:
3293  get_sort_group_operators(restype,
3294  true, true, false,
3295  &sortop, &eqop, NULL,
3296  &hashable);
3297  reverse = false;
3298  break;
3299  case SORTBY_DESC:
3300  get_sort_group_operators(restype,
3301  false, true, true,
3302  NULL, &eqop, &sortop,
3303  &hashable);
3304  reverse = true;
3305  break;
3306  case SORTBY_USING:
3307  Assert(sortby->useOp != NIL);
3308  sortop = compatible_oper_opid(sortby->useOp,
3309  restype,
3310  restype,
3311  false);
3312 
3313  /*
3314  * Verify it's a valid ordering operator, fetch the corresponding
3315  * equality operator, and determine whether to consider it like
3316  * ASC or DESC.
3317  */
3318  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3319  if (!OidIsValid(eqop))
3320  ereport(ERROR,
3321  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3322  errmsg("operator %s is not a valid ordering operator",
3323  strVal(llast(sortby->useOp))),
3324  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3325 
3326  /*
3327  * Also see if the equality operator is hashable.
3328  */
3329  hashable = op_hashjoinable(eqop, restype);
3330  break;
3331  default:
3332  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3333  sortop = InvalidOid; /* keep compiler quiet */
3334  eqop = InvalidOid;
3335  hashable = false;
3336  reverse = false;
3337  break;
3338  }
3339 
3341 
3342  /* avoid making duplicate sortlist entries */
3343  if (!targetIsInSortList(tle, sortop, sortlist))
3344  {
3346 
3347  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3348 
3349  sortcl->eqop = eqop;
3350  sortcl->sortop = sortop;
3351  sortcl->hashable = hashable;
3352 
3353  switch (sortby->sortby_nulls)
3354  {
3355  case SORTBY_NULLS_DEFAULT:
3356  /* NULLS FIRST is default for DESC; other way for ASC */
3357  sortcl->nulls_first = reverse;
3358  break;
3359  case SORTBY_NULLS_FIRST:
3360  sortcl->nulls_first = true;
3361  break;
3362  case SORTBY_NULLS_LAST:
3363  sortcl->nulls_first = false;
3364  break;
3365  default:
3366  elog(ERROR, "unrecognized sortby_nulls: %d",
3367  sortby->sortby_nulls);
3368  break;
3369  }
3370 
3371  sortlist = lappend(sortlist, sortcl);
3372  }
3373 
3374  return sortlist;
3375 }
#define NIL
Definition: pg_list.h:69
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
int errhint(const char *fmt,...)
Definition: elog.c:987
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
SortByDir sortby_dir
Definition: parsenodes.h:471
List * useOp
Definition: parsenodes.h:473
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:264
#define llast(l)
Definition: pg_list.h:131
Index tleSortGroupRef
Definition: parsenodes.h:1207
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:517
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:605
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1231
#define ERROR
Definition: elog.h:43
SortByNulls sortby_nulls
Definition: parsenodes.h:472
#define ereport(elevel, rest)
Definition: elog.h:122
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define makeNode(_type_)
Definition: nodes.h:565
#define Assert(condition)
Definition: c.h:699
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:187
Expr * expr
Definition: primnodes.h:1376
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:494
#define elog
Definition: elog.h:219
Node * node
Definition: parsenodes.h:470
int location
Definition: parsenodes.h:474

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3451 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

3452 {
3453  Index maxRef;
3454  ListCell *l;
3455 
3456  if (tle->ressortgroupref) /* already has one? */
3457  return tle->ressortgroupref;
3458 
3459  /* easiest way to pick an unused refnumber: max used + 1 */
3460  maxRef = 0;
3461  foreach(l, tlist)
3462  {
3463  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3464 
3465  if (ref > maxRef)
3466  maxRef = ref;
3467  }
3468  tle->ressortgroupref = maxRef + 1;
3469  return tle->ressortgroupref;
3470 }
unsigned int Index
Definition: c.h:442
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1379

◆ buildMergedJoinVar()

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

Definition at line 1545 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

1547 {
1548  Oid outcoltype;
1549  int32 outcoltypmod;
1550  Node *l_node,
1551  *r_node,
1552  *res_node;
1553 
1554  /*
1555  * Choose output type if input types are dissimilar.
1556  */
1557  outcoltype = l_colvar->vartype;
1558  outcoltypmod = l_colvar->vartypmod;
1559  if (outcoltype != r_colvar->vartype)
1560  {
1561  outcoltype = select_common_type(pstate,
1562  list_make2(l_colvar, r_colvar),
1563  "JOIN/USING",
1564  NULL);
1565  outcoltypmod = -1; /* ie, unknown */
1566  }
1567  else if (outcoltypmod != r_colvar->vartypmod)
1568  {
1569  /* same type, but not same typmod */
1570  outcoltypmod = -1; /* ie, unknown */
1571  }
1572 
1573  /*
1574  * Insert coercion functions if needed. Note that a difference in typmod
1575  * can only happen if input has typmod but outcoltypmod is -1. In that
1576  * case we insert a RelabelType to clearly mark that result's typmod is
1577  * not same as input. We never need coerce_type_typmod.
1578  */
1579  if (l_colvar->vartype != outcoltype)
1580  l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
1581  outcoltype, outcoltypmod,
1583  else if (l_colvar->vartypmod != outcoltypmod)
1584  l_node = (Node *) makeRelabelType((Expr *) l_colvar,
1585  outcoltype, outcoltypmod,
1586  InvalidOid, /* fixed below */
1588  else
1589  l_node = (Node *) l_colvar;
1590 
1591  if (r_colvar->vartype != outcoltype)
1592  r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
1593  outcoltype, outcoltypmod,
1595  else if (r_colvar->vartypmod != outcoltypmod)
1596  r_node = (Node *) makeRelabelType((Expr *) r_colvar,
1597  outcoltype, outcoltypmod,
1598  InvalidOid, /* fixed below */
1600  else
1601  r_node = (Node *) r_colvar;
1602 
1603  /*
1604  * Choose what to emit
1605  */
1606  switch (jointype)
1607  {
1608  case JOIN_INNER:
1609 
1610  /*
1611  * We can use either var; prefer non-coerced one if available.
1612  */
1613  if (IsA(l_node, Var))
1614  res_node = l_node;
1615  else if (IsA(r_node, Var))
1616  res_node = r_node;
1617  else
1618  res_node = l_node;
1619  break;
1620  case JOIN_LEFT:
1621  /* Always use left var */
1622  res_node = l_node;
1623  break;
1624  case JOIN_RIGHT:
1625  /* Always use right var */
1626  res_node = r_node;
1627  break;
1628  case JOIN_FULL:
1629  {
1630  /*
1631  * Here we must build a COALESCE expression to ensure that the
1632  * join output is non-null if either input is.
1633  */
1635 
1636  c->coalescetype = outcoltype;
1637  /* coalescecollid will get set below */
1638  c->args = list_make2(l_node, r_node);
1639  c->location = -1;
1640  res_node = (Node *) c;
1641  break;
1642  }
1643  default:
1644  elog(ERROR, "unrecognized join type: %d", (int) jointype);
1645  res_node = NULL; /* keep compiler quiet */
1646  break;
1647  }
1648 
1649  /*
1650  * Apply assign_expr_collations to fix up the collation info in the
1651  * coercion and CoalesceExpr nodes, if we made any. This must be done now
1652  * so that the join node's alias vars show correct collation info.
1653  */
1654  assign_expr_collations(pstate, res_node);
1655 
1656  return res_node;
1657 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:517
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:164
signed int int32
Definition: c.h:313
void assign_expr_collations(ParseState *pstate, Node *expr)
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:171
List * args
Definition: primnodes.h:1055
char * c
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:401
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:565
Oid coalescetype
Definition: primnodes.h:1053
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
#define elog
Definition: elog.h:219
int32 vartypmod
Definition: primnodes.h:172

◆ checkExprIsVarFree()

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

Definition at line 1780 of file parse_clause.c.

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

Referenced by transformFrameOffset(), and transformLimitClause().

1781 {
1782  if (contain_vars_of_level(n, 0))
1783  {
1784  ereport(ERROR,
1785  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1786  /* translator: %s is name of a SQL construct, eg LIMIT */
1787  errmsg("argument of %s must not contain variables",
1788  constructName),
1789  parser_errposition(pstate,
1790  locate_var_of_level(n, 0))));
1791  }
1792 }
int errcode(int sqlerrcode)
Definition: elog.c:575
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:437
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:369
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ checkTargetlistEntrySQL92()

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

Definition at line 1805 of file parse_clause.c.

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

Referenced by findTargetlistEntrySQL92().

1807 {
1808  switch (exprKind)
1809  {
1810  case EXPR_KIND_GROUP_BY:
1811  /* reject aggregates and window functions */
1812  if (pstate->p_hasAggs &&
1813  contain_aggs_of_level((Node *) tle->expr, 0))
1814  ereport(ERROR,
1815  (errcode(ERRCODE_GROUPING_ERROR),
1816  /* translator: %s is name of a SQL construct, eg GROUP BY */
1817  errmsg("aggregate functions are not allowed in %s",
1818  ParseExprKindName(exprKind)),
1819  parser_errposition(pstate,
1820  locate_agg_of_level((Node *) tle->expr, 0))));
1821  if (pstate->p_hasWindowFuncs &&
1822  contain_windowfuncs((Node *) tle->expr))
1823  ereport(ERROR,
1824  (errcode(ERRCODE_WINDOWING_ERROR),
1825  /* translator: %s is name of a SQL construct, eg GROUP BY */
1826  errmsg("window functions are not allowed in %s",
1827  ParseExprKindName(exprKind)),
1828  parser_errposition(pstate,
1829  locate_windowfunc((Node *) tle->expr))));
1830  break;
1831  case EXPR_KIND_ORDER_BY:
1832  /* no extra checks needed */
1833  break;
1834  case EXPR_KIND_DISTINCT_ON:
1835  /* no extra checks needed */
1836  break;
1837  default:
1838  elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
1839  break;
1840  }
1841 }
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
bool p_hasAggs
Definition: parse_node.h:200
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3402
bool p_hasWindowFuncs
Definition: parse_node.h:201
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
Expr * expr
Definition: primnodes.h:1376
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
bool contain_aggs_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:67
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197

◆ extractRemainingColumns()

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

Definition at line 295 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

298 {
299  List *new_colnames = NIL;
300  List *new_colvars = NIL;
301  ListCell *lnames,
302  *lvars;
303 
304  Assert(list_length(src_colnames) == list_length(src_colvars));
305 
306  forboth(lnames, src_colnames, lvars, src_colvars)
307  {
308  char *colname = strVal(lfirst(lnames));
309  bool match = false;
310  ListCell *cnames;
311 
312  foreach(cnames, common_colnames)
313  {
314  char *ccolname = strVal(lfirst(cnames));
315 
316  if (strcmp(colname, ccolname) == 0)
317  {
318  match = true;
319  break;
320  }
321  }
322 
323  if (!match)
324  {
325  new_colnames = lappend(new_colnames, lfirst(lnames));
326  new_colvars = lappend(new_colvars, lfirst(lvars));
327  }
328  }
329 
330  *res_colnames = new_colnames;
331  *res_colvars = new_colvars;
332 }
#define NIL
Definition: pg_list.h:69
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
#define strVal(v)
Definition: value.h:54
List * lappend(List *list, void *datum)
Definition: list.c:128
HashCompareFunc match
Definition: dynahash.c:213
static const struct cname cnames[]
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
Definition: pg_list.h:45

◆ findTargetlistEntrySQL92()

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

Definition at line 1861 of file parse_clause.c.

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

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

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

◆ findTargetlistEntrySQL99()

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

Definition at line 2028 of file parse_clause.c.

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

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

2030 {
2031  TargetEntry *target_result;
2032  ListCell *tl;
2033  Node *expr;
2034 
2035  /*
2036  * Convert the untransformed node to a transformed expression, and search
2037  * for a match in the tlist. NOTE: it doesn't really matter whether there
2038  * is more than one match. Also, we are willing to match an existing
2039  * resjunk target here, though the SQL92 cases above must ignore resjunk
2040  * targets.
2041  */
2042  expr = transformExpr(pstate, node, exprKind);
2043 
2044  foreach(tl, *tlist)
2045  {
2046  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2047  Node *texpr;
2048 
2049  /*
2050  * Ignore any implicit cast on the existing tlist expression.
2051  *
2052  * This essentially allows the ORDER/GROUP/etc item to adopt the same
2053  * datatype previously selected for a textually-equivalent tlist item.
2054  * There can't be any implicit cast at top level in an ordinary SELECT
2055  * tlist at this stage, but the case does arise with ORDER BY in an
2056  * aggregate function.
2057  */
2058  texpr = strip_implicit_coercions((Node *) tle->expr);
2059 
2060  if (equal(expr, texpr))
2061  return tle;
2062  }
2063 
2064  /*
2065  * If no matches, construct a new target entry which is appended to the
2066  * end of the target list. This target is given resjunk = true so that it
2067  * will not be projected into the final tuple.
2068  */
2069  target_result = transformTargetEntry(pstate, node, expr, exprKind,
2070  NULL, true);
2071 
2072  *tlist = lappend(*tlist, target_result);
2073 
2074  return target_result;
2075 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:517
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1376
TargetEntry * transformTargetEntry(ParseState *pstate, Node *node, Node *expr, ParseExprKind exprKind, char *colname, bool resjunk)
Definition: parse_target.c:85
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:612

◆ findWindowClause()

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

Definition at line 3519 of file parse_clause.c.

References lfirst, and WindowClause::name.

Referenced by transformWindowDefinitions().

3520 {
3521  ListCell *l;
3522 
3523  foreach(l, wclist)
3524  {
3525  WindowClause *wc = (WindowClause *) lfirst(l);
3526 
3527  if (wc->name && strcmp(wc->name, name) == 0)
3528  return wc;
3529  }
3530 
3531  return NULL;
3532 }
#define lfirst(lc)
Definition: pg_list.h:106
const char * name
Definition: encode.c:521

◆ flatten_grouping_sets()

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

Definition at line 2114 of file parse_clause.c.

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

Referenced by transformGroupClause().

2115 {
2116  /* just in case of pathological input */
2118 
2119  if (expr == (Node *) NIL)
2120  return (Node *) NIL;
2121 
2122  switch (expr->type)
2123  {
2124  case T_RowExpr:
2125  {
2126  RowExpr *r = (RowExpr *) expr;
2127 
2128  if (r->row_format == COERCE_IMPLICIT_CAST)
2129  return flatten_grouping_sets((Node *) r->args,
2130  false, NULL);
2131  }
2132  break;
2133  case T_GroupingSet:
2134  {
2135  GroupingSet *gset = (GroupingSet *) expr;
2136  ListCell *l2;
2137  List *result_set = NIL;
2138 
2139  if (hasGroupingSets)
2140  *hasGroupingSets = true;
2141 
2142  /*
2143  * at the top level, we skip over all empty grouping sets; the
2144  * caller can supply the canonical GROUP BY () if nothing is
2145  * left.
2146  */
2147 
2148  if (toplevel && gset->kind == GROUPING_SET_EMPTY)
2149  return (Node *) NIL;
2150 
2151  foreach(l2, gset->content)
2152  {
2153  Node *n1 = lfirst(l2);
2154  Node *n2 = flatten_grouping_sets(n1, false, NULL);
2155 
2156  if (IsA(n1, GroupingSet) &&
2157  ((GroupingSet *) n1)->kind == GROUPING_SET_SETS)
2158  {
2159  result_set = list_concat(result_set, (List *) n2);
2160  }
2161  else
2162  result_set = lappend(result_set, n2);
2163  }
2164 
2165  /*
2166  * At top level, keep the grouping set node; but if we're in a
2167  * nested grouping set, then we need to concat the flattened
2168  * result into the outer list if it's simply nested.
2169  */
2170 
2171  if (toplevel || (gset->kind != GROUPING_SET_SETS))
2172  {
2173  return (Node *) makeGroupingSet(gset->kind, result_set, gset->location);
2174  }
2175  else
2176  return (Node *) result_set;
2177  }
2178  case T_List:
2179  {
2180  List *result = NIL;
2181  ListCell *l;
2182 
2183  foreach(l, (List *) expr)
2184  {
2185  Node *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets);
2186 
2187  if (n != (Node *) NIL)
2188  {
2189  if (IsA(n, List))
2190  result = list_concat(result, (List *) n);
2191  else
2192  result = lappend(result, n);
2193  }
2194  }
2195 
2196  return (Node *) result;
2197  }
2198  default:
2199  break;
2200  }
2201 
2202  return expr;
2203 }
#define NIL
Definition: pg_list.h:69
List * args
Definition: primnodes.h:991
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
List * content
Definition: parsenodes.h:1277
Definition: nodes.h:517
List * list_concat(List *list1, List *list2)
Definition: list.c:321
GroupingSetKind kind
Definition: parsenodes.h:1276
NodeTag type
Definition: nodes.h:519
void check_stack_depth(void)
Definition: postgres.c:3155
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
Definition: nodes.h:296
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:607
CoercionForm row_format
Definition: primnodes.h:1006
Definition: pg_list.h:45

◆ get_matching_location()

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

Definition at line 3024 of file parse_clause.c.

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

Referenced by transformDistinctOnClause().

3025 {
3026  ListCell *lcs;
3027  ListCell *lce;
3028 
3029  forboth(lcs, sortgrouprefs, lce, exprs)
3030  {
3031  if (lfirst_int(lcs) == sortgroupref)
3032  return exprLocation((Node *) lfirst(lce));
3033  }
3034  /* if no match, caller blew it */
3035  elog(ERROR, "get_matching_location: no matching sortgroupref");
3036  return -1; /* keep compiler quiet */
3037 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
Definition: nodes.h:517
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:107
#define lfirst(lc)
Definition: pg_list.h:106
#define elog
Definition: elog.h:219

◆ getRTEForSpecialRelationTypes()

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

Definition at line 1059 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

1060 {
1061  CommonTableExpr *cte;
1062  Index levelsup;
1063  RangeTblEntry *rte;
1064 
1065  /*
1066  * if it is a qualified name, it can't be a CTE or tuplestore reference
1067  */
1068  if (rv->schemaname)
1069  return NULL;
1070 
1071  cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
1072  if (cte)
1073  rte = addRangeTableEntryForCTE(pstate, cte, levelsup, rv, true);
1074  else if (scanNameSpaceForENR(pstate, rv->relname))
1075  rte = addRangeTableEntryForENR(pstate, rv, true);
1076  else
1077  rte = NULL;
1078 
1079  return rte;
1080 }
RangeTblEntry * addRangeTableEntryForENR(ParseState *pstate, RangeVar *rv, bool inFromCl)
char * schemaname
Definition: primnodes.h:68
char * relname
Definition: primnodes.h:69
bool scanNameSpaceForENR(ParseState *pstate, const char *refname)
unsigned int Index
Definition: c.h:442
CommonTableExpr * scanNameSpaceForCTE(ParseState *pstate, const char *refname, Index *ctelevelsup)
RangeTblEntry * addRangeTableEntryForCTE(ParseState *pstate, CommonTableExpr *cte, Index levelsup, RangeVar *rv, bool inFromCl)

◆ interpretOidsOption()

bool interpretOidsOption ( List defList,
bool  allowOids 
)

Definition at line 262 of file parse_clause.c.

References default_with_oids, defGetBoolean(), DefElem::defname, DefElem::defnamespace, ereport, errcode(), errmsg(), ERROR, and lfirst.

Referenced by DefineRelation(), GetIntoRelEFlags(), and transformCreateStmt().

263 {
264  ListCell *cell;
265 
266  /* Scan list to see if OIDS was included */
267  foreach(cell, defList)
268  {
269  DefElem *def = (DefElem *) lfirst(cell);
270 
271  if (def->defnamespace == NULL &&
272  strcmp(def->defname, "oids") == 0)
273  {
274  if (!allowOids)
275  ereport(ERROR,
276  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
277  errmsg("unrecognized parameter \"%s\"",
278  def->defname)));
279  return defGetBoolean(def);
280  }
281  }
282 
283  /* Force no-OIDS result if caller disallows OIDS. */
284  if (!allowOids)
285  return false;
286 
287  /* OIDS option was not specified, so use default. */
288  return default_with_oids;
289 }
char * defnamespace
Definition: parsenodes.h:729
int errcode(int sqlerrcode)
Definition: elog.c:575
bool default_with_oids
Definition: guc.c:450
bool defGetBoolean(DefElem *def)
Definition: define.c:111
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define lfirst(lc)
Definition: pg_list.h:106
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * defname
Definition: parsenodes.h:730

◆ makeNamespaceItem()

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

Definition at line 1664 of file parse_clause.c.

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

1666 {
1667  ParseNamespaceItem *nsitem;
1668 
1669  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1670  nsitem->p_rte = rte;
1671  nsitem->p_rel_visible = rel_visible;
1672  nsitem->p_cols_visible = cols_visible;
1673  nsitem->p_lateral_only = lateral_only;
1674  nsitem->p_lateral_ok = lateral_ok;
1675  return nsitem;
1676 }
RangeTblEntry * p_rte
Definition: parse_node.h:248
void * palloc(Size size)
Definition: mcxt.c:924

◆ resolve_unique_index_expr()

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

Definition at line 3049 of file parse_clause.c.

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

Referenced by transformOnConflictArbiter().

3051 {
3052  List *result = NIL;
3053  ListCell *l;
3054 
3055  foreach(l, infer->indexElems)
3056  {
3057  IndexElem *ielem = (IndexElem *) lfirst(l);
3059  Node *parse;
3060 
3061  /*
3062  * Raw grammar re-uses CREATE INDEX infrastructure for unique index
3063  * inference clause, and so will accept opclasses by name and so on.
3064  *
3065  * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
3066  * LAST ordering, since those are not significant for inference
3067  * purposes (any unique index matching the inference specification in
3068  * other regards is accepted indifferently). Actively reject this as
3069  * wrong-headed.
3070  */
3071  if (ielem->ordering != SORTBY_DEFAULT)
3072  ereport(ERROR,
3073  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3074  errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
3075  parser_errposition(pstate,
3076  exprLocation((Node *) infer))));
3077  if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
3078  ereport(ERROR,
3079  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3080  errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
3081  parser_errposition(pstate,
3082  exprLocation((Node *) infer))));
3083 
3084  if (!ielem->expr)
3085  {
3086  /* Simple index attribute */
3087  ColumnRef *n;
3088 
3089  /*
3090  * Grammar won't have built raw expression for us in event of
3091  * plain column reference. Create one directly, and perform
3092  * expression transformation. Planner expects this, and performs
3093  * its own normalization for the purposes of matching against
3094  * pg_index.
3095  */
3096  n = makeNode(ColumnRef);
3097  n->fields = list_make1(makeString(ielem->name));
3098  /* Location is approximately that of inference specification */
3099  n->location = infer->location;
3100  parse = (Node *) n;
3101  }
3102  else
3103  {
3104  /* Do parse transformation of the raw expression */
3105  parse = (Node *) ielem->expr;
3106  }
3107 
3108  /*
3109  * transformExpr() will reject subqueries, aggregates, window
3110  * functions, and SRFs, based on being passed
3111  * EXPR_KIND_INDEX_EXPRESSION. So we needn't worry about those
3112  * further ... not that they would match any available index
3113  * expression anyway.
3114  */
3115  pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
3116 
3117  /* Perform lookup of collation and operator class as required */
3118  if (!ielem->collation)
3119  pInfer->infercollid = InvalidOid;
3120  else
3121  pInfer->infercollid = LookupCollation(pstate, ielem->collation,
3122  exprLocation(pInfer->expr));
3123 
3124  if (!ielem->opclass)
3125  pInfer->inferopclass = InvalidOid;
3126  else
3127  pInfer->inferopclass = get_opclass_oid(BTREE_AM_OID,
3128  ielem->opclass, false);
3129 
3130  result = lappend(result, pInfer);
3131  }
3132 
3133  return result;
3134 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
SortByDir ordering
Definition: parsenodes.h:704
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
List * indexElems
Definition: parsenodes.h:1362
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
Oid get_opclass_oid(Oid amID, List *opclassname, bool missing_ok)
Definition: opclasscmds.c:221
int location
Definition: parsenodes.h:237
#define list_make1(x1)
Definition: pg_list.h:139
Node * expr
Definition: parsenodes.h:700
SortByNulls nulls_ordering
Definition: parsenodes.h:705
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:496
#define InvalidOid
Definition: postgres_ext.h:36
List * opclass
Definition: parsenodes.h:703
#define makeNode(_type_)
Definition: nodes.h:565
#define lfirst(lc)
Definition: pg_list.h:106
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
char * name
Definition: parsenodes.h:699
int errmsg(const char *fmt,...)
Definition: elog.c:797
List * collation
Definition: parsenodes.h:702
Definition: pg_list.h:45
List * fields
Definition: parsenodes.h:236
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ setNamespaceColumnVisibility()

static void setNamespaceColumnVisibility ( List namespace,
bool  cols_visible 
)
static

Definition at line 1683 of file parse_clause.c.

References lfirst, and ParseNamespaceItem::p_cols_visible.

Referenced by transformFromClauseItem().

1684 {
1685  ListCell *lc;
1686 
1687  foreach(lc, namespace)
1688  {
1689  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1690 
1691  nsitem->p_cols_visible = cols_visible;
1692  }
1693 }
#define lfirst(lc)
Definition: pg_list.h:106

◆ setNamespaceLateralState()

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

Definition at line 1700 of file parse_clause.c.

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

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

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

◆ setTargetTable()

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

Definition at line 185 of file parse_clause.c.

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

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

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

◆ targetIsInSortList()

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

Definition at line 3492 of file parse_clause.c.

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

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

3493 {
3494  Index ref = tle->ressortgroupref;
3495  ListCell *l;
3496 
3497  /* no need to scan list if tle has no marker */
3498  if (ref == 0)
3499  return false;
3500 
3501  foreach(l, sortList)
3502  {
3503  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3504 
3505  if (scl->tleSortGroupRef == ref &&
3506  (sortop == InvalidOid ||
3507  sortop == scl->sortop ||
3508  sortop == get_commutator(scl->sortop)))
3509  return true;
3510  }
3511  return false;
3512 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1298
Index tleSortGroupRef
Definition: parsenodes.h:1207
unsigned int Index
Definition: c.h:442
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1379

◆ transformDistinctClause()

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

Definition at line 2833 of file parse_clause.c.

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

Referenced by transformAggregateCall(), and transformSelectStmt().

2835 {
2836  List *result = NIL;
2837  ListCell *slitem;
2838  ListCell *tlitem;
2839 
2840  /*
2841  * The distinctClause should consist of all ORDER BY items followed by all
2842  * other non-resjunk targetlist items. There must not be any resjunk
2843  * ORDER BY items --- that would imply that we are sorting by a value that
2844  * isn't necessarily unique within a DISTINCT group, so the results
2845  * wouldn't be well-defined. This construction ensures we follow the rule
2846  * that sortClause and distinctClause match; in fact the sortClause will
2847  * always be a prefix of distinctClause.
2848  *
2849  * Note a corner case: the same TLE could be in the ORDER BY list multiple
2850  * times with different sortops. We have to include it in the
2851  * distinctClause the same way to preserve the prefix property. The net
2852  * effect will be that the TLE value will be made unique according to both
2853  * sortops.
2854  */
2855  foreach(slitem, sortClause)
2856  {
2857  SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
2858  TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
2859 
2860  if (tle->resjunk)
2861  ereport(ERROR,
2862  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2863  is_agg ?
2864  errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
2865  errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
2866  parser_errposition(pstate,
2867  exprLocation((Node *) tle->expr))));
2868  result = lappend(result, copyObject(scl));
2869  }
2870 
2871  /*
2872  * Now add any remaining non-resjunk tlist items, using default sort/group
2873  * semantics for their data types.
2874  */
2875  foreach(tlitem, *targetlist)
2876  {
2877  TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
2878 
2879  if (tle->resjunk)
2880  continue; /* ignore junk */
2881  result = addTargetToGroupList(pstate, tle,
2882  result, *targetlist,
2883  exprLocation((Node *) tle->expr));
2884  }
2885 
2886  /*
2887  * Complain if we found nothing to make DISTINCT. Returning an empty list
2888  * would cause the parsed Query to look like it didn't have DISTINCT, with
2889  * results that would probably surprise the user. Note: this case is
2890  * presently impossible for aggregates because of grammar restrictions,
2891  * but we check anyway.
2892  */
2893  if (result == NIL)
2894  ereport(ERROR,
2895  (errcode(ERRCODE_SYNTAX_ERROR),
2896  is_agg ?
2897  errmsg("an aggregate with DISTINCT must have at least one argument") :
2898  errmsg("SELECT DISTINCT must have at least one column")));
2899 
2900  return result;
2901 }
#define NIL
Definition: pg_list.h:69
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:370
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
bool resjunk
Definition: primnodes.h:1383
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1376
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define copyObject(obj)
Definition: nodes.h:630
Definition: pg_list.h:45

◆ transformDistinctOnClause()

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

Definition at line 2917 of file parse_clause.c.

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

Referenced by transformSelectStmt().

2919 {
2920  List *result = NIL;
2921  List *sortgrouprefs = NIL;
2922  bool skipped_sortitem;
2923  ListCell *lc;
2924  ListCell *lc2;
2925 
2926  /*
2927  * Add all the DISTINCT ON expressions to the tlist (if not already
2928  * present, they are added as resjunk items). Assign sortgroupref numbers
2929  * to them, and make a list of these numbers. (NB: we rely below on the
2930  * sortgrouprefs list being one-for-one with the original distinctlist.
2931  * Also notice that we could have duplicate DISTINCT ON expressions and
2932  * hence duplicate entries in sortgrouprefs.)
2933  */
2934  foreach(lc, distinctlist)
2935  {
2936  Node *dexpr = (Node *) lfirst(lc);
2937  int sortgroupref;
2938  TargetEntry *tle;
2939 
2940  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
2942  sortgroupref = assignSortGroupRef(tle, *targetlist);
2943  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
2944  }
2945 
2946  /*
2947  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
2948  * semantics from ORDER BY items that match DISTINCT ON items, and also
2949  * adopt their column sort order. We insist that the distinctClause and
2950  * sortClause match, so throw error if we find the need to add any more
2951  * distinctClause items after we've skipped an ORDER BY item that wasn't
2952  * in DISTINCT ON.
2953  */
2954  skipped_sortitem = false;
2955  foreach(lc, sortClause)
2956  {
2957  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
2958 
2959  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
2960  {
2961  if (skipped_sortitem)
2962  ereport(ERROR,
2963  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2964  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2965  parser_errposition(pstate,
2967  sortgrouprefs,
2968  distinctlist))));
2969  else
2970  result = lappend(result, copyObject(scl));
2971  }
2972  else
2973  skipped_sortitem = true;
2974  }
2975 
2976  /*
2977  * Now add any remaining DISTINCT ON items, using default sort/group
2978  * semantics for their data types. (Note: this is pretty questionable; if
2979  * the ORDER BY list doesn't include all the DISTINCT ON items and more
2980  * besides, you certainly aren't using DISTINCT ON in the intended way,
2981  * and you probably aren't going to get consistent results. It might be
2982  * better to throw an error or warning here. But historically we've
2983  * allowed it, so keep doing so.)
2984  */
2985  forboth(lc, distinctlist, lc2, sortgrouprefs)
2986  {
2987  Node *dexpr = (Node *) lfirst(lc);
2988  int sortgroupref = lfirst_int(lc2);
2989  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
2990 
2991  if (targetIsInSortList(tle, InvalidOid, result))
2992  continue; /* already in list (with some semantics) */
2993  if (skipped_sortitem)
2994  ereport(ERROR,
2995  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2996  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2997  parser_errposition(pstate, exprLocation(dexpr))));
2998  result = addTargetToGroupList(pstate, tle,
2999  result, *targetlist,
3000  exprLocation(dexpr));
3001  }
3002 
3003  /*
3004  * An empty result list is impossible here because of grammar
3005  * restrictions.
3006  */
3007  Assert(result != NIL);
3008 
3009  return result;
3010 }
#define NIL
Definition: pg_list.h:69
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
Index tleSortGroupRef
Definition: parsenodes.h:1207
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
static int get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:107
bool list_member_int(const List *list, int datum)
Definition: list.c:485
#define ereport(elevel, rest)
Definition: elog.h:122
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:348
List * lappend_int(List *list, int datum)
Definition: list.c:146
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define copyObject(obj)
Definition: nodes.h:630
Definition: pg_list.h:45

◆ transformFrameOffset()

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

Definition at line 3546 of file parse_clause.c.

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

Referenced by transformWindowDefinitions().

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

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 119 of file parse_clause.c.

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

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

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

◆ transformFromClauseItem()

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

Definition at line 1104 of file parse_clause.c.

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

Referenced by transformFromClause().

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

◆ transformGroupClause()

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

Definition at line 2490 of file parse_clause.c.

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

Referenced by transformSelectStmt(), and transformWindowDefinitions().

2493 {
2494  List *result = NIL;
2495  List *flat_grouplist;
2496  List *gsets = NIL;
2497  ListCell *gl;
2498  bool hasGroupingSets = false;
2499  Bitmapset *seen_local = NULL;
2500 
2501  /*
2502  * Recursively flatten implicit RowExprs. (Technically this is only needed
2503  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2504  * anyway.)
2505  */
2506  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2507  true,
2508  &hasGroupingSets);
2509 
2510  /*
2511  * If the list is now empty, but hasGroupingSets is true, it's because we
2512  * elided redundant empty grouping sets. Restore a single empty grouping
2513  * set to leave a canonical form: GROUP BY ()
2514  */
2515 
2516  if (flat_grouplist == NIL && hasGroupingSets)
2517  {
2519  NIL,
2520  exprLocation((Node *) grouplist)));
2521  }
2522 
2523  foreach(gl, flat_grouplist)
2524  {
2525  Node *gexpr = (Node *) lfirst(gl);
2526 
2527  if (IsA(gexpr, GroupingSet))
2528  {
2529  GroupingSet *gset = (GroupingSet *) gexpr;
2530 
2531  switch (gset->kind)
2532  {
2533  case GROUPING_SET_EMPTY:
2534  gsets = lappend(gsets, gset);
2535  break;
2536  case GROUPING_SET_SIMPLE:
2537  /* can't happen */
2538  Assert(false);
2539  break;
2540  case GROUPING_SET_SETS:
2541  case GROUPING_SET_CUBE:
2542  case GROUPING_SET_ROLLUP:
2543  gsets = lappend(gsets,
2544  transformGroupingSet(&result,
2545  pstate, gset,
2546  targetlist, sortClause,
2547  exprKind, useSQL99, true));
2548  break;
2549  }
2550  }
2551  else
2552  {
2553  Index ref = transformGroupClauseExpr(&result, seen_local,
2554  pstate, gexpr,
2555  targetlist, sortClause,
2556  exprKind, useSQL99, true);
2557 
2558  if (ref > 0)
2559  {
2560  seen_local = bms_add_member(seen_local, ref);
2561  if (hasGroupingSets)
2562  gsets = lappend(gsets,
2564  list_make1_int(ref),
2565  exprLocation(gexpr)));
2566  }
2567  }
2568  }
2569 
2570  /* parser should prevent this */
2571  Assert(gsets == NIL || groupingSets != NULL);
2572 
2573  if (groupingSets)
2574  *groupingSets = gsets;
2575 
2576  return result;
2577 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
Definition: nodes.h:517
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
GroupingSetKind kind
Definition: parsenodes.h:1276
#define list_make1(x1)
Definition: pg_list.h:139
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
#define list_make1_int(x1)
Definition: pg_list.h:145
List * lappend(List *list, void *datum)
Definition: list.c:128
unsigned int Index
Definition: c.h:442
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:764
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:607
Definition: pg_list.h:45
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)

◆ transformGroupClauseExpr()

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

Definition at line 2225 of file parse_clause.c.

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

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

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

◆ transformGroupClauseList()

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

Definition at line 2333 of file parse_clause.c.

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

Referenced by transformGroupingSet().

2337 {
2338  Bitmapset *seen_local = NULL;
2339  List *result = NIL;
2340  ListCell *gl;
2341 
2342  foreach(gl, list)
2343  {
2344  Node *gexpr = (Node *) lfirst(gl);
2345 
2346  Index ref = transformGroupClauseExpr(flatresult,
2347  seen_local,
2348  pstate,
2349  gexpr,
2350  targetlist,
2351  sortClause,
2352  exprKind,
2353  useSQL99,
2354  toplevel);
2355 
2356  if (ref > 0)
2357  {
2358  seen_local = bms_add_member(seen_local, ref);
2359  result = lappend_int(result, ref);
2360  }
2361  }
2362 
2363  return result;
2364 }
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:517
List * lappend_int(List *list, int datum)
Definition: list.c:146
unsigned int Index
Definition: c.h:442
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:764
Definition: pg_list.h:45
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)

◆ transformGroupingSet()

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

Definition at line 2386 of file parse_clause.c.

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

Referenced by transformGroupClause().

2390 {
2391  ListCell *gl;
2392  List *content = NIL;
2393 
2394  Assert(toplevel || gset->kind != GROUPING_SET_SETS);
2395 
2396  foreach(gl, gset->content)
2397  {
2398  Node *n = lfirst(gl);
2399 
2400  if (IsA(n, List))
2401  {
2402  List *l = transformGroupClauseList(flatresult,
2403  pstate, (List *) n,
2404  targetlist, sortClause,
2405  exprKind, useSQL99, false);
2406 
2407  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2408  l,
2409  exprLocation(n)));
2410  }
2411  else if (IsA(n, GroupingSet))
2412  {
2413  GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
2414 
2415  content = lappend(content, transformGroupingSet(flatresult,
2416  pstate, gset2,
2417  targetlist, sortClause,
2418  exprKind, useSQL99, false));
2419  }
2420  else
2421  {
2422  Index ref = transformGroupClauseExpr(flatresult,
2423  NULL,
2424  pstate,
2425  n,
2426  targetlist,
2427  sortClause,
2428  exprKind,
2429  useSQL99,
2430  false);
2431 
2432  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2433  list_make1_int(ref),
2434  exprLocation(n)));
2435  }
2436  }
2437 
2438  /* Arbitrarily cap the size of CUBE, which has exponential growth */
2439  if (gset->kind == GROUPING_SET_CUBE)
2440  {
2441  if (list_length(content) > 12)
2442  ereport(ERROR,
2443  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2444  errmsg("CUBE is limited to 12 elements"),
2445  parser_errposition(pstate, gset->location)));
2446  }
2447 
2448  return (Node *) makeGroupingSet(gset->kind, content, gset->location);
2449 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
List * content
Definition: parsenodes.h:1277
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
GroupingSetKind kind
Definition: parsenodes.h:1276
#define ERROR
Definition: elog.h:43
static List * transformGroupClauseList(List **flatresult, ParseState *pstate, List *list, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
#define list_make1_int(x1)
Definition: pg_list.h:145
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
unsigned int Index
Definition: c.h:442
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:607
Definition: pg_list.h:45
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)

◆ transformJoinOnClause()

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

Definition at line 400 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

401 {
402  Node *result;
403  List *save_namespace;
404 
405  /*
406  * The namespace that the join expression should see is just the two
407  * subtrees of the JOIN plus any outer references from upper pstate
408  * levels. Temporarily set this pstate's namespace accordingly. (We need
409  * not check for refname conflicts, because transformFromClauseItem()
410  * already did.) All namespace items are marked visible regardless of
411  * LATERAL state.
412  */
413  setNamespaceLateralState(namespace, false, true);
414 
415  save_namespace = pstate->p_namespace;
416  pstate->p_namespace = namespace;
417 
418  result = transformWhereClause(pstate, j->quals,
419  EXPR_KIND_JOIN_ON, "JOIN/ON");
420 
421  pstate->p_namespace = save_namespace;
422 
423  return result;
424 }
Definition: nodes.h:517
List * p_namespace
Definition: parse_node.h:178
static void setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
Node * quals
Definition: primnodes.h:1462
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Definition: pg_list.h:45

◆ transformJoinUsingClause()

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

Definition at line 340 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

343 {
344  Node *result;
345  List *andargs = NIL;
346  ListCell *lvars,
347  *rvars;
348 
349  /*
350  * We cheat a little bit here by building an untransformed operator tree
351  * whose leaves are the already-transformed Vars. This requires collusion
352  * from transformExpr(), which normally could be expected to complain
353  * about already-transformed subnodes. However, this does mean that we
354  * have to mark the columns as requiring SELECT privilege for ourselves;
355  * transformExpr() won't do it.
356  */
357  forboth(lvars, leftVars, rvars, rightVars)
358  {
359  Var *lvar = (Var *) lfirst(lvars);
360  Var *rvar = (Var *) lfirst(rvars);
361  A_Expr *e;
362 
363  /* Require read access to the join variables */
364  markVarForSelectPriv(pstate, lvar, leftRTE);
365  markVarForSelectPriv(pstate, rvar, rightRTE);
366 
367  /* Now create the lvar = rvar join condition */
368  e = makeSimpleA_Expr(AEXPR_OP, "=",
369  (Node *) copyObject(lvar), (Node *) copyObject(rvar),
370  -1);
371 
372  /* Prepare to combine into an AND clause, if multiple join columns */
373  andargs = lappend(andargs, e);
374  }
375 
376  /* Only need an AND if there's more than one join column */
377  if (list_length(andargs) == 1)
378  result = (Node *) linitial(andargs);
379  else
380  result = (Node *) makeBoolExpr(AND_EXPR, andargs, -1);
381 
382  /*
383  * Since the references are already Vars, and are certainly from the input
384  * relations, we don't have to go through the same pushups that
385  * transformJoinOnClause() does. Just invoke transformExpr() to fix up
386  * the operators, and we're done.
387  */
388  result = transformExpr(pstate, result, EXPR_KIND_JOIN_USING);
389 
390  result = coerce_to_boolean(pstate, result, "JOIN/USING");
391 
392  return result;
393 }
#define NIL
Definition: pg_list.h:69
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
void markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:517
A_Expr * makeSimpleA_Expr(A_Expr_Kind kind, char *name, Node *lexpr, Node *rexpr, int location)
Definition: makefuncs.c:49
Definition: primnodes.h:164
Expr * makeBoolExpr(BoolExprType boolop, List *args, int location)
Definition: makefuncs.c:368
#define linitial(l)
Definition: pg_list.h:111
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
e
Definition: preproc-init.c:82
#define copyObject(obj)
Definition: nodes.h:630
Definition: pg_list.h:45
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

◆ transformLimitClause()

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

Definition at line 1749 of file parse_clause.c.

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

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

1751 {
1752  Node *qual;
1753 
1754  if (clause == NULL)
1755  return NULL;
1756 
1757  qual = transformExpr(pstate, clause, exprKind);
1758 
1759  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1760 
1761  /* LIMIT can't refer to any variables of the current query */
1762  checkExprIsVarFree(pstate, qual, constructName);
1763 
1764  return qual;
1765 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:517
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)

◆ transformOnConflictArbiter()

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

Definition at line 3145 of file parse_clause.c.

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

Referenced by transformOnConflictClause().

3149 {
3150  InferClause *infer = onConflictClause->infer;
3151 
3152  *arbiterExpr = NIL;
3153  *arbiterWhere = NULL;
3154  *constraint = InvalidOid;
3155 
3156  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3157  ereport(ERROR,
3158  (errcode(ERRCODE_SYNTAX_ERROR),
3159  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3160  errhint("For example, ON CONFLICT (column_name)."),
3161  parser_errposition(pstate,
3162  exprLocation((Node *) onConflictClause))));
3163 
3164  /*
3165  * To simplify certain aspects of its design, speculative insertion into
3166  * system catalogs is disallowed
3167  */
3168  if (IsCatalogRelation(pstate->p_target_relation))
3169  ereport(ERROR,
3170  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3171  errmsg("ON CONFLICT is not supported with system catalog tables"),
3172  parser_errposition(pstate,
3173  exprLocation((Node *) onConflictClause))));
3174 
3175  /* Same applies to table used by logical decoding as catalog table */
3177  ereport(ERROR,
3178  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3179  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3181  parser_errposition(pstate,
3182  exprLocation((Node *) onConflictClause))));
3183 
3184  /* ON CONFLICT DO NOTHING does not require an inference clause */
3185  if (infer)
3186  {
3187  List *save_namespace;
3188 
3189  /*
3190  * While we process the arbiter expressions, accept only non-qualified
3191  * references to the target table. Hide any other relations.
3192  */
3193  save_namespace = pstate->p_namespace;
3194  pstate->p_namespace = NIL;
3195  addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
3196  false, false, true);
3197 
3198  if (infer->indexElems)
3199  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3200  pstate->p_target_relation);
3201 
3202  /*
3203  * Handling inference WHERE clause (for partial unique index
3204  * inference)
3205  */
3206  if (infer->whereClause)
3207  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3209 
3210  pstate->p_namespace = save_namespace;
3211 
3212  /*
3213  * If the arbiter is specified by constraint name, get the constraint
3214  * OID and mark the constrained columns as requiring SELECT privilege,
3215  * in the same way as would have happened if the arbiter had been
3216  * specified by explicit reference to the constraint's index columns.
3217  */
3218  if (infer->conname)
3219  {
3220  Oid relid = RelationGetRelid(pstate->p_target_relation);
3221  RangeTblEntry *rte = pstate->p_target_rangetblentry;
3222  Bitmapset *conattnos;
3223 
3224  conattnos = get_relation_constraint_attnos(relid, infer->conname,
3225  false, constraint);
3226 
3227  /* Make sure the rel as a whole is marked for SELECT access */
3228  rte->requiredPerms |= ACL_SELECT;
3229  /* Mark the constrained columns as requiring SELECT access */
3230  rte->selectedCols = bms_add_members(rte->selectedCols, conattnos);
3231  }
3232  }
3233 
3234  /*
3235  * It's convenient to form a list of expressions based on the
3236  * representation used by CREATE INDEX, since the same restrictions are
3237  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3238  * primnode representation is used for inference elements, and so
3239  * assign_query_collations() can be trusted to do the right thing with the
3240  * post parse analysis query tree inference clause representation.
3241  */
3242 }
#define NIL
Definition: pg_list.h:69
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:92
int errhint(const char *fmt,...)
Definition: elog.c:987
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
List * indexElems
Definition: parsenodes.h:1362
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
AclMode requiredPerms
Definition: parsenodes.h:1070
unsigned int Oid
Definition: postgres_ext.h:31
Bitmapset * selectedCols
Definition: parsenodes.h:1072
#define ERROR
Definition: elog.h:43
List * p_namespace
Definition: parse_node.h:178
char * conname
Definition: parsenodes.h:1364
Bitmapset * get_relation_constraint_attnos(Oid relid, const char *conname, bool missing_ok, Oid *constraintOid)
#define RelationGetRelationName(relation)
Definition: rel.h:441
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define ACL_SELECT
Definition: parsenodes.h:75
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:185
InferClause * infer
Definition: parsenodes.h:1378
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:306
#define InvalidOid
Definition: postgres_ext.h:36
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Node * whereClause
Definition: parsenodes.h:1363
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation p_target_relation
Definition: parse_node.h:184
OnConflictAction action
Definition: parsenodes.h:1377
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:407
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:821
static List * resolve_unique_index_expr(ParseState *pstate, InferClause *infer, Relation heapRel)

◆ transformRangeFunction()

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

Definition at line 511 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

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

◆ transformRangeSubselect()

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

Definition at line 444 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

445 {
446  Query *query;
447  RangeTblEntry *rte;
448 
449  /*
450  * We require user to supply an alias for a subselect, per SQL92. To relax
451  * this, we'd have to be prepared to gin up a unique alias for an
452  * unlabeled subselect. (This is just elog, not ereport, because the
453  * grammar should have enforced it already. It'd probably be better to
454  * report the error here, but we don't have a good error location here.)
455  */
456  if (r->alias == NULL)
457  elog(ERROR, "subquery in FROM must have an alias");
458 
459  /*
460  * Set p_expr_kind to show this parse level is recursing to a subselect.
461  * We can't be nested within any expression, so don't need save-restore
462  * logic here.
463  */
464  Assert(pstate->p_expr_kind == EXPR_KIND_NONE);
466 
467  /*
468  * If the subselect is LATERAL, make lateral_only names of this level
469  * visible to it. (LATERAL can't nest within a single pstate level, so we
470  * don't need save/restore logic here.)
471  */
472  Assert(!pstate->p_lateral_active);
473  pstate->p_lateral_active = r->lateral;
474 
475  /*
476  * Analyze and transform the subquery.
477  */
478  query = parse_sub_analyze(r->subquery, pstate, NULL,
479  isLockedRefname(pstate, r->alias->aliasname),
480  true);
481 
482  /* Restore state */
483  pstate->p_lateral_active = false;
484  pstate->p_expr_kind = EXPR_KIND_NONE;
485 
486  /*
487  * Check that we got a SELECT. Anything else should be impossible given
488  * restrictions of the grammar, but check anyway.
489  */
490  if (!IsA(query, Query) ||
491  query->commandType != CMD_SELECT)
492  elog(ERROR, "unexpected non-SELECT command in subquery in FROM");
493 
494  /*
495  * OK, build an RTE for the subquery.
496  */
497  rte = addRangeTableEntryForSubquery(pstate,
498  query,
499  r->alias,
500  r->lateral,
501  true);
502 
503  return rte;
504 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
Node * subquery
Definition: parsenodes.h:543
#define ERROR
Definition: elog.h:43
RangeTblEntry * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
ParseExprKind p_expr_kind
Definition: parse_node.h:188
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:164
bool p_lateral_active
Definition: parse_node.h:180
CmdType commandType
Definition: parsenodes.h:112
#define Assert(condition)
Definition: c.h:699
char * aliasname
Definition: primnodes.h:43
Alias * alias
Definition: parsenodes.h:544
bool isLockedRefname(ParseState *pstate, const char *refname)
#define elog
Definition: elog.h:219

◆ transformRangeTableFunc()

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

Definition at line 736 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

737 {
739  const char *constructName;
740  Oid docType;
741  RangeTblEntry *rte;
742  bool is_lateral;
743  ListCell *col;
744  char **names;
745  int colno;
746 
747  /* Currently only XMLTABLE is supported */
748  constructName = "XMLTABLE";
749  docType = XMLOID;
750 
751  /*
752  * We make lateral_only names of this level visible, whether or not the
753  * RangeTableFunc is explicitly marked LATERAL. This is needed for SQL
754  * spec compliance and seems useful on convenience grounds for all
755  * functions in FROM.
756  *
757  * (LATERAL can't nest within a single pstate level, so we don't need
758  * save/restore logic here.)
759  */
760  Assert(!pstate->p_lateral_active);
761  pstate->p_lateral_active = true;
762 
763  /* Transform and apply typecast to the row-generating expression ... */
764  Assert(rtf->rowexpr != NULL);
765  tf->rowexpr = coerce_to_specific_type(pstate,
766  transformExpr(pstate, rtf->rowexpr, EXPR_KIND_FROM_FUNCTION),
767  TEXTOID,
768  constructName);
769  assign_expr_collations(pstate, tf->rowexpr);
770 
771  /* ... and to the document itself */
772  Assert(rtf->docexpr != NULL);
773  tf->docexpr = coerce_to_specific_type(pstate,
774  transformExpr(pstate, rtf->docexpr, EXPR_KIND_FROM_FUNCTION),
775  docType,
776  constructName);
777  assign_expr_collations(pstate, tf->docexpr);
778 
779  /* undef ordinality column number */
780  tf->ordinalitycol = -1;
781 
782 
783  names = palloc(sizeof(char *) * list_length(rtf->columns));
784 
785  colno = 0;
786  foreach(col, rtf->columns)
787  {
788  RangeTableFuncCol *rawc = (RangeTableFuncCol *) lfirst(col);
789  Oid typid;
790  int32 typmod;
791  Node *colexpr;
792  Node *coldefexpr;
793  int j;
794 
795  tf->colnames = lappend(tf->colnames,
796  makeString(pstrdup(rawc->colname)));
797 
798  /*
799  * Determine the type and typmod for the new column. FOR ORDINALITY
800  * columns are INTEGER per spec; the others are user-specified.
801  */
802  if (rawc->for_ordinality)
803  {
804  if (tf->ordinalitycol != -1)
805  ereport(ERROR,
806  (errcode(ERRCODE_SYNTAX_ERROR),
807  errmsg("only one FOR ORDINALITY column is allowed"),
808  parser_errposition(pstate, rawc->location)));
809 
810  typid = INT4OID;
811  typmod = -1;
812  tf->ordinalitycol = colno;
813  }
814  else
815  {
816  if (rawc->typeName->setof)
817  ereport(ERROR,
818  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
819  errmsg("column \"%s\" cannot be declared SETOF",
820  rawc->colname),
821  parser_errposition(pstate, rawc->location)));
822 
823  typenameTypeIdAndMod(pstate, rawc->typeName,
824  &typid, &typmod);
825  }
826 
827  tf->coltypes = lappend_oid(tf->coltypes, typid);
828  tf->coltypmods = lappend_int(tf->coltypmods, typmod);
830  type_is_collatable(typid) ? DEFAULT_COLLATION_OID : InvalidOid);
831 
832  /* Transform the PATH and DEFAULT expressions */
833  if (rawc->colexpr)
834  {
835  colexpr = coerce_to_specific_type(pstate,
836  transformExpr(pstate, rawc->colexpr,
838  TEXTOID,
839  constructName);
840  assign_expr_collations(pstate, colexpr);
841  }
842  else
843  colexpr = NULL;
844 
845  if (rawc->coldefexpr)
846  {
847  coldefexpr = coerce_to_specific_type_typmod(pstate,
848  transformExpr(pstate, rawc->coldefexpr,
850  typid, typmod,
851  constructName);
852  assign_expr_collations(pstate, coldefexpr);
853  }
854  else
855  coldefexpr = NULL;
856 
857  tf->colexprs = lappend(tf->colexprs, colexpr);
858  tf->coldefexprs = lappend(tf->coldefexprs, coldefexpr);
859 
860  if (rawc->is_not_null)
861  tf->notnulls = bms_add_member(tf->notnulls, colno);
862 
863  /* make sure column names are unique */
864  for (j = 0; j < colno; j++)
865  if (strcmp(names[j], rawc->colname) == 0)
866  ereport(ERROR,
867  (errcode(ERRCODE_SYNTAX_ERROR),
868  errmsg("column name \"%s\" is not unique",
869  rawc->colname),
870  parser_errposition(pstate, rawc->location)));
871  names[colno] = rawc->colname;
872 
873  colno++;
874  }
875  pfree(names);
876 
877  /* Namespaces, if any, also need to be transformed */
878  if (rtf->namespaces != NIL)
879  {
880  ListCell *ns;
881  ListCell *lc2;
882  List *ns_uris = NIL;
883  List *ns_names = NIL;
884  bool default_ns_seen = false;
885 
886  foreach(ns, rtf->namespaces)
887  {
888  ResTarget *r = (ResTarget *) lfirst(ns);
889  Node *ns_uri;
890 
891  Assert(IsA(r, ResTarget));
892  ns_uri = transformExpr(pstate, r->val, EXPR_KIND_FROM_FUNCTION);
893  ns_uri = coerce_to_specific_type(pstate, ns_uri,
894  TEXTOID, constructName);
895  assign_expr_collations(pstate, ns_uri);
896  ns_uris = lappend(ns_uris, ns_uri);
897 
898  /* Verify consistency of name list: no dupes, only one DEFAULT */
899  if (r->name != NULL)
900  {
901  foreach(lc2, ns_names)
902  {
903  char *name = strVal(lfirst(lc2));
904 
905  if (name == NULL)
906  continue;
907  if (strcmp(name, r->name) == 0)
908  ereport(ERROR,
909  (errcode(ERRCODE_SYNTAX_ERROR),
910  errmsg("namespace name \"%s\" is not unique",
911  name),
912  parser_errposition(pstate, r->location)));
913  }
914  }
915  else
916  {
917  if (default_ns_seen)
918  ereport(ERROR,
919  (errcode(ERRCODE_SYNTAX_ERROR),
920  errmsg("only one default namespace is allowed"),
921  parser_errposition(pstate, r->location)));
922  default_ns_seen = true;
923  }
924 
925  /* Note the string may be NULL */
926  ns_names = lappend(ns_names, makeString(r->name));
927  }
928 
929  tf->ns_uris = ns_uris;
930  tf->ns_names = ns_names;
931  }
932 
933  tf->location = rtf->location;
934 
935  pstate->p_lateral_active = false;
936 
937  /*
938  * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
939  * there are any lateral cross-references in it.
940  */
941  is_lateral = rtf->lateral || contain_vars_of_level((Node *) tf, 0);
942 
943  rte = addRangeTableEntryForTableFunc(pstate,
944  tf, rtf->alias, is_lateral, true);
945 
946  return rte;
947 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
Node * docexpr
Definition: primnodes.h:85
Node * val
Definition: parsenodes.h:443
List * colnames
Definition: primnodes.h:87
char * name
Definition: parsenodes.h:441
List * coltypmods
Definition: primnodes.h:89
char * pstrdup(const char *in)
Definition: mcxt.c:1161
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:517
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
List * colcollations
Definition: primnodes.h:90
signed int int32
Definition: c.h:313
int location
Definition: parsenodes.h:444
void assign_expr_collations(ParseState *pstate, Node *expr)
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
bool setof
Definition: parsenodes.h:212
List * coldefexprs
Definition: primnodes.h:92
List * ns_names
Definition: primnodes.h:84
Node * rowexpr
Definition: primnodes.h:86
TypeName * typeName
Definition: parsenodes.h:598
Bitmapset * notnulls
Definition: primnodes.h:93
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend_int(List *list, int datum)
Definition: list.c:146
List * lappend(List *list, void *datum)
Definition: list.c:128
int ordinalitycol
Definition: primnodes.h:94
List * coltypes
Definition: primnodes.h:88
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:293
#define InvalidOid
Definition: postgres_ext.h:36
List * colexprs
Definition: primnodes.h:91
bool p_lateral_active
Definition: parse_node.h:180
#define makeNode(_type_)
Definition: nodes.h:565
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
List * ns_uris
Definition: primnodes.h:83
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:369
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
RangeTblEntry * addRangeTableEntryForTableFunc(ParseState *pstate, TableFunc *tf, Alias *alias, bool lateral, bool inFromCl)
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:764
const char * name
Definition: encode.c:521
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:797
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
int location
Definition: primnodes.h:95
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:2824
Definition: pg_list.h:45
Node * coerce_to_specific_type_typmod(ParseState *pstate, Node *node, Oid targetTypeId, int32 targetTypmod, const char *constructName)

◆ transformRangeTableSample()

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

Definition at line 956 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

957 {
958  TableSampleClause *tablesample;
959  Oid handlerOid;
960  Oid funcargtypes[1];
961  TsmRoutine *tsm;
962  List *fargs;
963  ListCell *larg,
964  *ltyp;
965 
966  /*
967  * To validate the sample method name, look up the handler function, which
968  * has the same name, one dummy INTERNAL argument, and a result type of
969  * tsm_handler. (Note: tablesample method names are not schema-qualified
970  * in the SQL standard; but since they are just functions to us, we allow
971  * schema qualification to resolve any potential ambiguity.)
972  */
973  funcargtypes[0] = INTERNALOID;
974 
975  handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true);
976 
977  /* we want error to complain about no-such-method, not no-such-function */
978  if (!OidIsValid(handlerOid))
979  ereport(ERROR,
980  (errcode(ERRCODE_UNDEFINED_OBJECT),
981  errmsg("tablesample method %s does not exist",
982  NameListToString(rts->method)),
983  parser_errposition(pstate, rts->location)));
984 
985  /* check that handler has correct return type */
986  if (get_func_rettype(handlerOid) != TSM_HANDLEROID)
987  ereport(ERROR,
988  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
989  errmsg("function %s must return type %s",
990  NameListToString(rts->method), "tsm_handler"),
991  parser_errposition(pstate, rts->location)));
992 
993  /* OK, run the handler to get TsmRoutine, for argument type info */
994  tsm = GetTsmRoutine(handlerOid);
995 
996  tablesample = makeNode(TableSampleClause);
997  tablesample->tsmhandler = handlerOid;
998 
999  /* check user provided the expected number of arguments */
1000  if (list_length(rts->args) != list_length(tsm->parameterTypes))
1001  ereport(ERROR,
1002  (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
1003  errmsg_plural("tablesample method %s requires %d argument, not %d",
1004  "tablesample method %s requires %d arguments, not %d",
1006  NameListToString(rts->method),
1008  list_length(rts->args)),
1009  parser_errposition(pstate, rts->location)));
1010 
1011  /*
1012  * Transform the arguments, typecasting them as needed. Note we must also
1013  * assign collations now, because assign_query_collations() doesn't
1014  * examine any substructure of RTEs.
1015  */
1016  fargs = NIL;
1017  forboth(larg, rts->args, ltyp, tsm->parameterTypes)
1018  {
1019  Node *arg = (Node *) lfirst(larg);
1020  Oid argtype = lfirst_oid(ltyp);
1021 
1022  arg = transformExpr(pstate, arg, EXPR_KIND_FROM_FUNCTION);
1023  arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE");
1024  assign_expr_collations(pstate, arg);
1025  fargs = lappend(fargs, arg);
1026  }
1027  tablesample->args = fargs;
1028 
1029  /* Process REPEATABLE (seed) */
1030  if (rts->repeatable != NULL)
1031  {
1032  Node *arg;
1033 
1034  if (!tsm->repeatable_across_queries)
1035  ereport(ERROR,
1036  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1037  errmsg("tablesample method %s does not support REPEATABLE",
1038  NameListToString(rts->method)),
1039  parser_errposition(pstate, rts->location)));
1040 
1041  arg = transformExpr(pstate, rts->repeatable, EXPR_KIND_FROM_FUNCTION);
1042  arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE");
1043  assign_expr_collations(pstate, arg);
1044  tablesample->repeatable = (Expr *) arg;
1045  }
1046  else
1047  tablesample->repeatable = NULL;
1048 
1049  return tablesample;
1050 }
#define NIL
Definition: pg_list.h:69
bool repeatable_across_queries
Definition: tsmapi.h:63
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:850
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:605
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1444
void assign_expr_collations(ParseState *pstate, Node *expr)
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
char * NameListToString(List *names)
Definition: namespace.c:3082
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
#define makeNode(_type_)
Definition: nodes.h:565
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
Definition: parse_func.c:1974
int errmsg(const char *fmt,...)
Definition: elog.c:797
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
void * arg
List * parameterTypes
Definition: tsmapi.h:60
Definition: pg_list.h:45
#define lfirst_oid(lc)
Definition: pg_list.h:108

◆ transformSortClause()

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

Definition at line 2590 of file parse_clause.c.

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

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

2595 {
2596  List *sortlist = NIL;
2597  ListCell *olitem;
2598 
2599  foreach(olitem, orderlist)
2600  {
2601  SortBy *sortby = (SortBy *) lfirst(olitem);
2602  TargetEntry *tle;
2603 
2604  if (useSQL99)
2605  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2606  targetlist, exprKind);
2607  else
2608  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2609  targetlist, exprKind);
2610 
2611  sortlist = addTargetToSortList(pstate, tle,
2612  sortlist, *targetlist, sortby);
2613  }
2614 
2615  return sortlist;
2616 }
#define NIL
Definition: pg_list.h:69
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
#define lfirst(lc)
Definition: pg_list.h:106
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Node * node
Definition: parsenodes.h:470
Definition: pg_list.h:45

◆ transformTableEntry()

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

Definition at line 430 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

431 {
432  RangeTblEntry *rte;
433 
434  /* We need only build a range table entry */
435  rte = addRangeTableEntry(pstate, r, r->alias, r->inh, true);
436 
437  return rte;
438 }
RangeTblEntry * addRangeTableEntry(ParseState *pstate, RangeVar *relation, Alias *alias, bool inh, bool inFromCl)
bool inh
Definition: primnodes.h:70
Alias * alias
Definition: primnodes.h:73

◆ transformWhereClause()

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

Definition at line 1722 of file parse_clause.c.

References coerce_to_boolean(), and transformExpr().

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

1724 {
1725  Node *qual;
1726 
1727  if (clause == NULL)
1728  return NULL;
1729 
1730  qual = transformExpr(pstate, clause, exprKind);
1731 
1732  qual = coerce_to_boolean(pstate, qual, constructName);
1733 
1734  return qual;
1735 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:517
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

◆ transformWindowDefinitions()

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

Definition at line 2623 of file parse_clause.c.

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

Referenced by transformSelectStmt().

2626 {
2627  List *result = NIL;
2628  Index winref = 0;
2629  ListCell *lc;
2630 
2631  foreach(lc, windowdefs)
2632  {
2633  WindowDef *windef = (WindowDef *) lfirst(lc);
2634  WindowClause *refwc = NULL;
2635  List *partitionClause;
2636  List *orderClause;
2637  Oid rangeopfamily = InvalidOid;
2638  Oid rangeopcintype = InvalidOid;
2639  WindowClause *wc;
2640 
2641  winref++;
2642 
2643  /*
2644  * Check for duplicate window names.
2645  */
2646  if (windef->name &&
2647  findWindowClause(result, windef->name) != NULL)
2648  ereport(ERROR,
2649  (errcode(ERRCODE_WINDOWING_ERROR),
2650  errmsg("window \"%s\" is already defined", windef->name),
2651  parser_errposition(pstate, windef->location)));
2652 
2653  /*
2654  * If it references a previous window, look that up.
2655  */
2656  if (windef->refname)
2657  {
2658  refwc = findWindowClause(result, windef->refname);
2659  if (refwc == NULL)
2660  ereport(ERROR,
2661  (errcode(ERRCODE_UNDEFINED_OBJECT),
2662  errmsg("window \"%s\" does not exist",
2663  windef->refname),
2664  parser_errposition(pstate, windef->location)));
2665  }
2666 
2667  /*
2668  * Transform PARTITION and ORDER specs, if any. These are treated
2669  * almost exactly like top-level GROUP BY and ORDER BY clauses,
2670  * including the special handling of nondefault operator semantics.
2671  */
2672  orderClause = transformSortClause(pstate,
2673  windef->orderClause,
2674  targetlist,
2676  true /* force SQL99 rules */ );
2677  partitionClause = transformGroupClause(pstate,
2678  windef->partitionClause,
2679  NULL,
2680  targetlist,
2681  orderClause,
2683  true /* force SQL99 rules */ );
2684 
2685  /*
2686  * And prepare the new WindowClause.
2687  */
2688  wc = makeNode(WindowClause);
2689  wc->name = windef->name;
2690  wc->refname = windef->refname;
2691 
2692  /*
2693  * Per spec, a windowdef that references a previous one copies the
2694  * previous partition clause (and mustn't specify its own). It can
2695  * specify its own ordering clause, but only if the previous one had
2696  * none. It always specifies its own frame clause, and the previous
2697  * one must not have a frame clause. Yeah, it's bizarre that each of
2698  * these cases works differently, but SQL:2008 says so; see 7.11
2699  * <window clause> syntax rule 10 and general rule 1. The frame
2700  * clause rule is especially bizarre because it makes "OVER foo"
2701  * different from "OVER (foo)", and requires the latter to throw an
2702  * error if foo has a nondefault frame clause. Well, ours not to
2703  * reason why, but we do go out of our way to throw a useful error
2704  * message for such cases.
2705  */
2706  if (refwc)
2707  {
2708  if (partitionClause)
2709  ereport(ERROR,
2710  (errcode(ERRCODE_WINDOWING_ERROR),
2711  errmsg("cannot override PARTITION BY clause of window \"%s\"",
2712  windef->refname),
2713  parser_errposition(pstate, windef->location)));
2715  }
2716  else
2717  wc->partitionClause = partitionClause;
2718  if (refwc)
2719  {
2720  if (orderClause && refwc->orderClause)
2721  ereport(ERROR,
2722  (errcode(ERRCODE_WINDOWING_ERROR),
2723  errmsg("cannot override ORDER BY clause of window \"%s\"",
2724  windef->refname),
2725  parser_errposition(pstate, windef->location)));
2726  if (orderClause)
2727  {
2728  wc->orderClause = orderClause;
2729  wc->copiedOrder = false;
2730  }
2731  else
2732  {
2733  wc->orderClause = copyObject(refwc->orderClause);
2734  wc->copiedOrder = true;
2735  }
2736  }
2737  else
2738  {
2739  wc->orderClause = orderClause;
2740  wc->copiedOrder = false;
2741  }
2742  if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2743  {
2744  /*
2745  * Use this message if this is a WINDOW clause, or if it's an OVER
2746  * clause that includes ORDER BY or framing clauses. (We already
2747  * rejected PARTITION BY above, so no need to check that.)
2748  */
2749  if (windef->name ||
2750  orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2751  ereport(ERROR,
2752  (errcode(ERRCODE_WINDOWING_ERROR),
2753  errmsg("cannot copy window \"%s\" because it has a frame clause",
2754  windef->refname),
2755  parser_errposition(pstate, windef->location)));
2756  /* Else this clause is just OVER (foo), so say this: */
2757  ereport(ERROR,
2758  (errcode(ERRCODE_WINDOWING_ERROR),
2759  errmsg("cannot copy window \"%s\" because it has a frame clause",
2760  windef->refname),
2761  errhint("Omit the parentheses in this OVER clause."),
2762  parser_errposition(pstate, windef->location)));
2763  }
2764  wc->frameOptions = windef->frameOptions;
2765 
2766  /*
2767  * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
2768  * column; check that and get its sort opfamily info.
2769  */
2770  if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
2773  {
2774  SortGroupClause *sortcl;
2775  Node *sortkey;
2776  int16 rangestrategy;
2777 
2778  if (list_length(wc->orderClause) != 1)
2779  ereport(ERROR,
2780  (errcode(ERRCODE_WINDOWING_ERROR),
2781  errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
2782  parser_errposition(pstate, windef->location)));
2783  sortcl = castNode(SortGroupClause, linitial(wc->orderClause));
2784  sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
2785  /* Find the sort operator in pg_amop */
2786  if (!get_ordering_op_properties(sortcl->sortop,
2787  &rangeopfamily,
2788  &rangeopcintype,
2789  &rangestrategy))
2790  elog(ERROR, "operator %u is not a valid ordering operator",
2791  sortcl->sortop);
2792  /* Record properties of sort ordering */
2793  wc->inRangeColl = exprCollation(sortkey);
2794  wc->inRangeAsc = (rangestrategy == BTLessStrategyNumber);
2795  wc->inRangeNullsFirst = sortcl->nulls_first;
2796  }
2797 
2798  /* Process frame offset expressions */
2799  wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2800  rangeopfamily, rangeopcintype,
2801  &wc->startInRangeFunc,
2802  windef->startOffset);
2803  wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2804  rangeopfamily, rangeopcintype,
2805  &wc->endInRangeFunc,
2806  windef->endOffset);
2807  wc->winref = winref;
2808 
2809  result = lappend(result, wc);
2810  }
2811 
2812  return result;
2813 }
signed short int16
Definition: c.h:312
List * partitionClause
Definition: parsenodes.h:490
char * refname
Definition: parsenodes.h:1302
#define NIL
Definition: pg_list.h:69
bool copiedOrder
Definition: parsenodes.h:1314
int errhint(const char *fmt,...)
Definition: elog.c:987
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:532
bool inRangeNullsFirst
Definition: parsenodes.h:1312
int frameOptions
Definition: parsenodes.h:492
#define castNode(_type_, nodeptr)
Definition: nodes.h:586
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
char * name
Definition: parsenodes.h:488
Oid endInRangeFunc
Definition: parsenodes.h:1309
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:382
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define FRAMEOPTION_START_OFFSET
Definition: parsenodes.h:524
Node * startOffset
Definition: parsenodes.h:493
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
List * partitionClause
Definition: parsenodes.h:1303
int location
Definition: parsenodes.h:495
Node * endOffset
Definition: parsenodes.h:494
List * transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
Node * startOffset
Definition: parsenodes.h:1306
List * orderClause
Definition: parsenodes.h:491
unsigned int Index
Definition: c.h:442
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:565
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:506
#define lfirst(lc)
Definition: pg_list.h:106
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:204
Node * endOffset
Definition: parsenodes.h:1307
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
#define FRAMEOPTION_END_OFFSET
Definition: parsenodes.h:526
List * orderClause
Definition: parsenodes.h:1304
int errmsg(const char *fmt,...)
Definition: elog.c:797
static Node * transformFrameOffset(ParseState *pstate, int frameOptions, Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc, Node *clause)
#define elog
Definition: elog.h:219
char * refname
Definition: parsenodes.h:489
#define copyObject(obj)
Definition: nodes.h:630
#define BTLessStrategyNumber
Definition: stratnum.h:29
Definition: pg_list.h:45
Oid startInRangeFunc
Definition: parsenodes.h:1308
static WindowClause * findWindowClause(List *wclist, const char *name)