PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
parse_clause.c File Reference
#include "postgres.h"
#include "miscadmin.h"
#include "access/heapam.h"
#include "access/tsmapi.h"
#include "catalog/catalog.h"
#include "catalog/heap.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint_fn.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/guc.h"
#include "utils/lsyscache.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 RangeTblEntrytransformCTEReference (ParseState *pstate, RangeVar *r, CommonTableExpr *cte, Index levelsup)
 
static RangeTblEntrytransformENRReference (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, 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

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

Definition at line 52 of file parse_clause.c.

Function Documentation

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

Definition at line 3354 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, NULL, SortGroupClause::nulls_first, setup_parser_errposition_callback(), SortGroupClause::sortop, targetIsInSortList(), TEXTOID, SortGroupClause::tleSortGroupRef, and UNKNOWNOID.

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

3356 {
3357  Oid restype = exprType((Node *) tle->expr);
3358 
3359  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3360  if (restype == UNKNOWNOID)
3361  {
3362  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3363  restype, TEXTOID, -1,
3366  -1);
3367  restype = TEXTOID;
3368  }
3369 
3370  /* avoid making duplicate grouplist entries */
3371  if (!targetIsInSortList(tle, InvalidOid, grouplist))
3372  {
3374  Oid sortop;
3375  Oid eqop;
3376  bool hashable;
3377  ParseCallbackState pcbstate;
3378 
3379  setup_parser_errposition_callback(&pcbstate, pstate, location);
3380 
3381  /* determine the eqop and optional sortop */
3382  get_sort_group_operators(restype,
3383  false, true, false,
3384  &sortop, &eqop, NULL,
3385  &hashable);
3386 
3388 
3389  grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3390  grpcl->eqop = eqop;
3391  grpcl->sortop = sortop;
3392  grpcl->nulls_first = false; /* OK with or without sortop */
3393  grpcl->hashable = hashable;
3394 
3395  grouplist = lappend(grouplist, grpcl);
3396  }
3397 
3398  return grouplist;
3399 }
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
#define TEXTOID
Definition: pg_type.h:324
Index tleSortGroupRef
Definition: parsenodes.h:1184
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:509
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:557
#define NULL
Definition: c.h:229
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:1368
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
#define UNKNOWNOID
Definition: pg_type.h:431
List* addTargetToSortList ( ParseState pstate,
TargetEntry tle,
List sortlist,
List targetlist,
SortBy sortby 
)

Definition at line 3211 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, NULL, 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(), TEXTOID, SortGroupClause::tleSortGroupRef, UNKNOWNOID, and SortBy::useOp.

Referenced by transformAggregateCall(), and transformSortClause().

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

Definition at line 3409 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

3410 {
3411  Index maxRef;
3412  ListCell *l;
3413 
3414  if (tle->ressortgroupref) /* already has one? */
3415  return tle->ressortgroupref;
3416 
3417  /* easiest way to pick an unused refnumber: max used + 1 */
3418  maxRef = 0;
3419  foreach(l, tlist)
3420  {
3421  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3422 
3423  if (ref > maxRef)
3424  maxRef = ref;
3425  }
3426  tle->ressortgroupref = maxRef + 1;
3427  return tle->ressortgroupref;
3428 }
unsigned int Index
Definition: c.h:365
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1371
static Node * buildMergedJoinVar ( ParseState pstate,
JoinType  jointype,
Var l_colvar,
Var r_colvar 
)
static

Definition at line 1558 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(), NULL, select_common_type(), Var::vartype, and Var::vartypmod.

Referenced by transformFromClauseItem().

1560 {
1561  Oid outcoltype;
1562  int32 outcoltypmod;
1563  Node *l_node,
1564  *r_node,
1565  *res_node;
1566 
1567  /*
1568  * Choose output type if input types are dissimilar.
1569  */
1570  outcoltype = l_colvar->vartype;
1571  outcoltypmod = l_colvar->vartypmod;
1572  if (outcoltype != r_colvar->vartype)
1573  {
1574  outcoltype = select_common_type(pstate,
1575  list_make2(l_colvar, r_colvar),
1576  "JOIN/USING",
1577  NULL);
1578  outcoltypmod = -1; /* ie, unknown */
1579  }
1580  else if (outcoltypmod != r_colvar->vartypmod)
1581  {
1582  /* same type, but not same typmod */
1583  outcoltypmod = -1; /* ie, unknown */
1584  }
1585 
1586  /*
1587  * Insert coercion functions if needed. Note that a difference in typmod
1588  * can only happen if input has typmod but outcoltypmod is -1. In that
1589  * case we insert a RelabelType to clearly mark that result's typmod is
1590  * not same as input. We never need coerce_type_typmod.
1591  */
1592  if (l_colvar->vartype != outcoltype)
1593  l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
1594  outcoltype, outcoltypmod,
1596  else if (l_colvar->vartypmod != outcoltypmod)
1597  l_node = (Node *) makeRelabelType((Expr *) l_colvar,
1598  outcoltype, outcoltypmod,
1599  InvalidOid, /* fixed below */
1601  else
1602  l_node = (Node *) l_colvar;
1603 
1604  if (r_colvar->vartype != outcoltype)
1605  r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
1606  outcoltype, outcoltypmod,
1608  else if (r_colvar->vartypmod != outcoltypmod)
1609  r_node = (Node *) makeRelabelType((Expr *) r_colvar,
1610  outcoltype, outcoltypmod,
1611  InvalidOid, /* fixed below */
1613  else
1614  r_node = (Node *) r_colvar;
1615 
1616  /*
1617  * Choose what to emit
1618  */
1619  switch (jointype)
1620  {
1621  case JOIN_INNER:
1622 
1623  /*
1624  * We can use either var; prefer non-coerced one if available.
1625  */
1626  if (IsA(l_node, Var))
1627  res_node = l_node;
1628  else if (IsA(r_node, Var))
1629  res_node = r_node;
1630  else
1631  res_node = l_node;
1632  break;
1633  case JOIN_LEFT:
1634  /* Always use left var */
1635  res_node = l_node;
1636  break;
1637  case JOIN_RIGHT:
1638  /* Always use right var */
1639  res_node = r_node;
1640  break;
1641  case JOIN_FULL:
1642  {
1643  /*
1644  * Here we must build a COALESCE expression to ensure that the
1645  * join output is non-null if either input is.
1646  */
1648 
1649  c->coalescetype = outcoltype;
1650  /* coalescecollid will get set below */
1651  c->args = list_make2(l_node, r_node);
1652  c->location = -1;
1653  res_node = (Node *) c;
1654  break;
1655  }
1656  default:
1657  elog(ERROR, "unrecognized join type: %d", (int) jointype);
1658  res_node = NULL; /* keep compiler quiet */
1659  break;
1660  }
1661 
1662  /*
1663  * Apply assign_expr_collations to fix up the collation info in the
1664  * coercion and CoalesceExpr nodes, if we made any. This must be done now
1665  * so that the join node's alias vars show correct collation info.
1666  */
1667  assign_expr_collations(pstate, res_node);
1668 
1669  return res_node;
1670 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
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:509
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
signed int int32
Definition: c.h:256
void assign_expr_collations(ParseState *pstate, Node *expr)
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:170
List * args
Definition: primnodes.h:1047
char * c
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:399
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
Oid coalescetype
Definition: primnodes.h:1045
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:171
static void checkExprIsVarFree ( ParseState pstate,
Node n,
const char *  constructName 
)
static

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

1794 {
1795  if (contain_vars_of_level(n, 0))
1796  {
1797  ereport(ERROR,
1798  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1799  /* translator: %s is name of a SQL construct, eg LIMIT */
1800  errmsg("argument of %s must not contain variables",
1801  constructName),
1802  parser_errposition(pstate,
1803  locate_var_of_level(n, 0))));
1804  }
1805 }
int 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
static void checkTargetlistEntrySQL92 ( ParseState pstate,
TargetEntry tle,
ParseExprKind  exprKind 
)
static

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

1820 {
1821  switch (exprKind)
1822  {
1823  case EXPR_KIND_GROUP_BY:
1824  /* reject aggregates and window functions */
1825  if (pstate->p_hasAggs &&
1826  contain_aggs_of_level((Node *) tle->expr, 0))
1827  ereport(ERROR,
1828  (errcode(ERRCODE_GROUPING_ERROR),
1829  /* translator: %s is name of a SQL construct, eg GROUP BY */
1830  errmsg("aggregate functions are not allowed in %s",
1831  ParseExprKindName(exprKind)),
1832  parser_errposition(pstate,
1833  locate_agg_of_level((Node *) tle->expr, 0))));
1834  if (pstate->p_hasWindowFuncs &&
1835  contain_windowfuncs((Node *) tle->expr))
1836  ereport(ERROR,
1837  (errcode(ERRCODE_WINDOWING_ERROR),
1838  /* translator: %s is name of a SQL construct, eg GROUP BY */
1839  errmsg("window functions are not allowed in %s",
1840  ParseExprKindName(exprKind)),
1841  parser_errposition(pstate,
1842  locate_windowfunc((Node *) tle->expr))));
1843  break;
1844  case EXPR_KIND_ORDER_BY:
1845  /* no extra checks needed */
1846  break;
1847  case EXPR_KIND_DISTINCT_ON:
1848  /* no extra checks needed */
1849  break;
1850  default:
1851  elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
1852  break;
1853  }
1854 }
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
bool p_hasAggs
Definition: parse_node.h:198
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3393
bool p_hasWindowFuncs
Definition: parse_node.h:199
#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:1368
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
static void extractRemainingColumns ( List common_colnames,
List src_colnames,
List src_colvars,
List **  res_colnames,
List **  res_colvars 
)
static

Definition at line 288 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

291 {
292  List *new_colnames = NIL;
293  List *new_colvars = NIL;
294  ListCell *lnames,
295  *lvars;
296 
297  Assert(list_length(src_colnames) == list_length(src_colvars));
298 
299  forboth(lnames, src_colnames, lvars, src_colvars)
300  {
301  char *colname = strVal(lfirst(lnames));
302  bool match = false;
303  ListCell *cnames;
304 
305  foreach(cnames, common_colnames)
306  {
307  char *ccolname = strVal(lfirst(cnames));
308 
309  if (strcmp(colname, ccolname) == 0)
310  {
311  match = true;
312  break;
313  }
314  }
315 
316  if (!match)
317  {
318  new_colnames = lappend(new_colnames, lfirst(lnames));
319  new_colvars = lappend(new_colvars, lfirst(lvars));
320  }
321  }
322 
323  *res_colnames = new_colnames;
324  *res_colvars = new_colvars;
325 }
#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:676
#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
static TargetEntry * findTargetlistEntrySQL92 ( ParseState pstate,
Node node,
List **  tlist,
ParseExprKind  exprKind 
)
static

Definition at line 1874 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, NULL, ParseExprKindName(), parser_errposition(), TargetEntry::resjunk, TargetEntry::resname, strVal, and val.

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

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

Definition at line 2041 of file parse_clause.c.

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

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

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

Definition at line 3477 of file parse_clause.c.

References lfirst, WindowClause::name, and NULL.

Referenced by transformWindowDefinitions().

3478 {
3479  ListCell *l;
3480 
3481  foreach(l, wclist)
3482  {
3483  WindowClause *wc = (WindowClause *) lfirst(l);
3484 
3485  if (wc->name && strcmp(wc->name, name) == 0)
3486  return wc;
3487  }
3488 
3489  return NULL;
3490 }
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
const char * name
Definition: encode.c:521
static Node* flatten_grouping_sets ( Node expr,
bool  toplevel,
bool hasGroupingSets 
)
static

Definition at line 2127 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, NULL, result, RowExpr::row_format, T_GroupingSet, T_List, T_RowExpr, and Node::type.

Referenced by transformGroupClause().

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

Definition at line 2998 of file parse_clause.c.

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

Referenced by transformDistinctOnClause().

2999 {
3000  ListCell *lcs;
3001  ListCell *lce;
3002 
3003  forboth(lcs, sortgrouprefs, lce, exprs)
3004  {
3005  if (lfirst_int(lcs) == sortgroupref)
3006  return exprLocation((Node *) lfirst(lce));
3007  }
3008  /* if no match, caller blew it */
3009  elog(ERROR, "get_matching_location: no matching sortgroupref");
3010  return -1; /* keep compiler quiet */
3011 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
Definition: nodes.h:509
#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
static RangeTblEntry * getRTEForSpecialRelationTypes ( ParseState pstate,
RangeVar rv 
)
static

Definition at line 1076 of file parse_clause.c.

References NULL, RangeVar::relname, scanNameSpaceForCTE(), scanNameSpaceForENR(), transformCTEReference(), and transformENRReference().

Referenced by setTargetTable(), and transformFromClauseItem().

1077 {
1078  CommonTableExpr *cte;
1079  Index levelsup;
1080  RangeTblEntry *rte = NULL;
1081 
1082  cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
1083  if (cte)
1084  rte = transformCTEReference(pstate, rv, cte, levelsup);
1085  if (!rte && scanNameSpaceForENR(pstate, rv->relname))
1086  rte = transformENRReference(pstate, rv);
1087 
1088  return rte;
1089 }
char * relname
Definition: primnodes.h:68
bool scanNameSpaceForENR(ParseState *pstate, const char *refname)
static RangeTblEntry * transformCTEReference(ParseState *pstate, RangeVar *r, CommonTableExpr *cte, Index levelsup)
Definition: parse_clause.c:438
unsigned int Index
Definition: c.h:365
static RangeTblEntry * transformENRReference(ParseState *pstate, RangeVar *r)
Definition: parse_clause.c:453
CommonTableExpr * scanNameSpaceForCTE(ParseState *pstate, const char *refname, Index *ctelevelsup)
#define NULL
Definition: c.h:229
bool interpretOidsOption ( List defList,
bool  allowOids 
)

Definition at line 255 of file parse_clause.c.

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

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

256 {
257  ListCell *cell;
258 
259  /* Scan list to see if OIDS was included */
260  foreach(cell, defList)
261  {
262  DefElem *def = (DefElem *) lfirst(cell);
263 
264  if (def->defnamespace == NULL &&
265  pg_strcasecmp(def->defname, "oids") == 0)
266  {
267  if (!allowOids)
268  ereport(ERROR,
269  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
270  errmsg("unrecognized parameter \"%s\"",
271  def->defname)));
272  return defGetBoolean(def);
273  }
274  }
275 
276  /* Force no-OIDS result if caller disallows OIDS. */
277  if (!allowOids)
278  return false;
279 
280  /* OIDS option was not specified, so use default. */
281  return default_with_oids;
282 }
char * defnamespace
Definition: parsenodes.h:718
int errcode(int sqlerrcode)
Definition: elog.c:575
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
bool default_with_oids
Definition: guc.c:448
bool defGetBoolean(DefElem *def)
Definition: define.c:111
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * defname
Definition: parsenodes.h:719
static ParseNamespaceItem * makeNamespaceItem ( RangeTblEntry rte,
bool  rel_visible,
bool  cols_visible,
bool  lateral_only,
bool  lateral_ok 
)
static

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

1679 {
1680  ParseNamespaceItem *nsitem;
1681 
1682  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1683  nsitem->p_rte = rte;
1684  nsitem->p_rel_visible = rel_visible;
1685  nsitem->p_cols_visible = cols_visible;
1686  nsitem->p_lateral_only = lateral_only;
1687  nsitem->p_lateral_ok = lateral_ok;
1688  return nsitem;
1689 }
RangeTblEntry * p_rte
Definition: parse_node.h:246
void * palloc(Size size)
Definition: mcxt.c:849
static List * resolve_unique_index_expr ( ParseState pstate,
InferClause infer,
Relation  heapRel 
)
static

Definition at line 3023 of file parse_clause.c.

References BTREE_AM_OID, 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, InferClause::location, LookupCollation(), makeNode, makeString(), IndexElem::name, NIL, IndexElem::nulls_ordering, IndexElem::opclass, IndexElem::ordering, parse(), parser_errposition(), result, SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, and transformExpr().

Referenced by transformOnConflictArbiter().

3025 {
3026  List *result = NIL;
3027  ListCell *l;
3028 
3029  foreach(l, infer->indexElems)
3030  {
3031  IndexElem *ielem = (IndexElem *) lfirst(l);
3033  Node *parse;
3034 
3035  /*
3036  * Raw grammar re-uses CREATE INDEX infrastructure for unique index
3037  * inference clause, and so will accept opclasses by name and so on.
3038  *
3039  * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
3040  * LAST ordering, since those are not significant for inference
3041  * purposes (any unique index matching the inference specification in
3042  * other regards is accepted indifferently). Actively reject this as
3043  * wrong-headed.
3044  */
3045  if (ielem->ordering != SORTBY_DEFAULT)
3046  ereport(ERROR,
3047  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3048  errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
3049  parser_errposition(pstate,
3050  exprLocation((Node *) infer))));
3051  if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
3052  ereport(ERROR,
3053  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3054  errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
3055  parser_errposition(pstate,
3056  exprLocation((Node *) infer))));
3057 
3058  if (!ielem->expr)
3059  {
3060  /* Simple index attribute */
3061  ColumnRef *n;
3062 
3063  /*
3064  * Grammar won't have built raw expression for us in event of
3065  * plain column reference. Create one directly, and perform
3066  * expression transformation. Planner expects this, and performs
3067  * its own normalization for the purposes of matching against
3068  * pg_index.
3069  */
3070  n = makeNode(ColumnRef);
3071  n->fields = list_make1(makeString(ielem->name));
3072  /* Location is approximately that of inference specification */
3073  n->location = infer->location;
3074  parse = (Node *) n;
3075  }
3076  else
3077  {
3078  /* Do parse transformation of the raw expression */
3079  parse = (Node *) ielem->expr;
3080  }
3081 
3082  /*
3083  * transformExpr() should have already rejected subqueries,
3084  * aggregates, and window functions, based on the EXPR_KIND_ for an
3085  * index expression. Expressions returning sets won't have been
3086  * rejected, but don't bother doing so here; there should be no
3087  * available expression unique index to match any such expression
3088  * against anyway.
3089  */
3090  pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
3091 
3092  /* Perform lookup of collation and operator class as required */
3093  if (!ielem->collation)
3094  pInfer->infercollid = InvalidOid;
3095  else
3096  pInfer->infercollid = LookupCollation(pstate, ielem->collation,
3097  exprLocation(pInfer->expr));
3098 
3099  if (!ielem->opclass)
3100  pInfer->inferopclass = InvalidOid;
3101  else
3103  ielem->opclass, false);
3104 
3105  result = lappend(result, pInfer);
3106  }
3107 
3108  return result;
3109 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
SortByDir ordering
Definition: parsenodes.h:693
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
#define BTREE_AM_OID
Definition: pg_am.h:70
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
List * indexElems
Definition: parsenodes.h:1331
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1633
Oid get_opclass_oid(Oid amID, List *opclassname, bool missing_ok)
Definition: opclasscmds.c:220
int location
Definition: parsenodes.h:235
#define list_make1(x1)
Definition: pg_list.h:139
Node * expr
Definition: parsenodes.h:689
SortByNulls nulls_ordering
Definition: parsenodes.h:694
#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:692
#define makeNode(_type_)
Definition: nodes.h:557
#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:688
int errmsg(const char *fmt,...)
Definition: elog.c:797
List * collation
Definition: parsenodes.h:691
Definition: pg_list.h:45
List * fields
Definition: parsenodes.h:234
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
static void setNamespaceColumnVisibility ( List namespace,
bool  cols_visible 
)
static

Definition at line 1696 of file parse_clause.c.

References lfirst, and ParseNamespaceItem::p_cols_visible.

Referenced by transformFromClauseItem().

1697 {
1698  ListCell *lc;
1699 
1700  foreach(lc, namespace)
1701  {
1702  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1703 
1704  nsitem->p_cols_visible = cols_visible;
1705  }
1706 }
#define lfirst(lc)
Definition: pg_list.h:106
static void setNamespaceLateralState ( List namespace,
bool  lateral_only,
bool  lateral_ok 
)
static

Definition at line 1713 of file parse_clause.c.

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

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

1714 {
1715  ListCell *lc;
1716 
1717  foreach(lc, namespace)
1718  {
1719  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1720 
1721  nsitem->p_lateral_only = lateral_only;
1722  nsitem->p_lateral_ok = lateral_ok;
1723  }
1724 }
#define lfirst(lc)
Definition: pg_list.h:106
int setTargetTable ( ParseState pstate,
RangeVar relation,
bool  inh,
bool  alsoSource,
AclMode  requiredPerms 
)

Definition at line 181 of file parse_clause.c.

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

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

183 {
184  RangeTblEntry *rte;
185  int rtindex;
186 
187  /* So far special relations are immutable; so they cannot be targets. */
188  rte = getRTEForSpecialRelationTypes(pstate, relation);
189  if (rte != NULL)
190  ereport(ERROR,
191  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
192  errmsg("relation \"%s\" cannot be the target of a modifying statement",
193  relation->relname)));
194 
195  /* Close old target; this could only happen for multi-action rules */
196  if (pstate->p_target_relation != NULL)
198 
199  /*
200  * Open target rel and grab suitable lock (which we will hold till end of
201  * transaction).
202  *
203  * free_parsestate() will eventually do the corresponding heap_close(),
204  * but *not* release the lock.
205  */
206  pstate->p_target_relation = parserOpenTable(pstate, relation,
208 
209  /*
210  * Now build an RTE.
211  */
212  rte = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
213  relation->alias, inh, false);
214  pstate->p_target_rangetblentry = rte;
215 
216  /* assume new rte is at end */
217  rtindex = list_length(pstate->p_rtable);
218  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
219 
220  /*
221  * Override addRangeTableEntry's default ACL_SELECT permissions check, and
222  * instead mark target table as requiring exactly the specified
223  * permissions.
224  *
225  * If we find an explicit reference to the rel later during parse
226  * analysis, we will add the ACL_SELECT bit back again; see
227  * markVarForSelectPriv and its callers.
228  */
229  rte->requiredPerms = requiredPerms;
230 
231  /*
232  * If UPDATE/DELETE, add table to joinlist and namespace.
233  *
234  * Note: some callers know that they can find the new ParseNamespaceItem
235  * at the end of the pstate->p_namespace list. This is a bit ugly but not
236  * worth complicating this function's signature for.
237  */
238  if (alsoSource)
239  addRTEtoQuery(pstate, rte, true, true, true);
240 
241  return rtindex;
242 }
Relation parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
int errcode(int sqlerrcode)
Definition: elog.c:575
AclMode requiredPerms
Definition: parsenodes.h:1047
#define heap_close(r, l)
Definition: heapam.h:97
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#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:183
static RangeTblEntry * getRTEForSpecialRelationTypes(ParseState *pstate, RangeVar *rv)
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
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:182
Alias * alias
Definition: primnodes.h:72
List * p_rtable
Definition: parse_node.h:172
bool targetIsInSortList ( TargetEntry tle,
Oid  sortop,
List sortList 
)

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

3451 {
3452  Index ref = tle->ressortgroupref;
3453  ListCell *l;
3454 
3455  /* no need to scan list if tle has no marker */
3456  if (ref == 0)
3457  return false;
3458 
3459  foreach(l, sortList)
3460  {
3461  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3462 
3463  if (scl->tleSortGroupRef == ref &&
3464  (sortop == InvalidOid ||
3465  sortop == scl->sortop ||
3466  sortop == get_commutator(scl->sortop)))
3467  return true;
3468  }
3469  return false;
3470 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1313
Index tleSortGroupRef
Definition: parsenodes.h:1184
unsigned int Index
Definition: c.h:365
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1371
static RangeTblEntry * transformCTEReference ( ParseState pstate,
RangeVar r,
CommonTableExpr cte,
Index  levelsup 
)
static

Definition at line 438 of file parse_clause.c.

References addRangeTableEntryForCTE().

Referenced by getRTEForSpecialRelationTypes().

440 {
441  RangeTblEntry *rte;
442 
443  rte = addRangeTableEntryForCTE(pstate, cte, levelsup, r, true);
444 
445  return rte;
446 }
RangeTblEntry * addRangeTableEntryForCTE(ParseState *pstate, CommonTableExpr *cte, Index levelsup, RangeVar *rv, bool inFromCl)
List* transformDistinctClause ( ParseState pstate,
List **  targetlist,
List sortClause,
bool  is_agg 
)

Definition at line 2807 of file parse_clause.c.

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

Referenced by transformAggregateCall(), and transformSelectStmt().

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

Definition at line 2891 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(), result, targetIsInSortList(), and SortGroupClause::tleSortGroupRef.

Referenced by transformSelectStmt().

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

Definition at line 453 of file parse_clause.c.

References addRangeTableEntryForENR().

Referenced by getRTEForSpecialRelationTypes().

454 {
455  RangeTblEntry *rte;
456 
457  rte = addRangeTableEntryForENR(pstate, r, true);
458 
459  return rte;
460 }
RangeTblEntry * addRangeTableEntryForENR(ParseState *pstate, RangeVar *rv, bool inFromCl)
static Node * transformFrameOffset ( ParseState pstate,
int  frameOptions,
Node clause 
)
static

Definition at line 3497 of file parse_clause.c.

References Assert, checkExprIsVarFree(), coerce_to_specific_type(), elog, ERROR, EXPR_KIND_WINDOW_FRAME_RANGE, EXPR_KIND_WINDOW_FRAME_ROWS, FRAMEOPTION_RANGE, FRAMEOPTION_ROWS, INT8OID, NULL, and transformExpr().

Referenced by transformWindowDefinitions().

3498 {
3499  const char *constructName = NULL;
3500  Node *node;
3501 
3502  /* Quick exit if no offset expression */
3503  if (clause == NULL)
3504  return NULL;
3505 
3506  if (frameOptions & FRAMEOPTION_ROWS)
3507  {
3508  /* Transform the raw expression tree */
3509  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_ROWS);
3510 
3511  /*
3512  * Like LIMIT clause, simply coerce to int8
3513  */
3514  constructName = "ROWS";
3515  node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3516  }
3517  else if (frameOptions & FRAMEOPTION_RANGE)
3518  {
3519  /* Transform the raw expression tree */
3520  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_RANGE);
3521 
3522  /*
3523  * this needs a lot of thought to decide how to support in the context
3524  * of Postgres' extensible datatype framework
3525  */
3526  constructName = "RANGE";
3527  /* error was already thrown by gram.y, this is just a backstop */
3528  elog(ERROR, "window frame with value offset is not implemented");
3529  }
3530  else
3531  {
3532  Assert(false);
3533  node = NULL;
3534  }
3535 
3536  /* Disallow variables in frame offsets */
3537  checkExprIsVarFree(pstate, node, constructName);
3538 
3539  return node;
3540 }
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:509
#define ERROR
Definition: elog.h:43
#define INT8OID
Definition: pg_type.h:304
#define NULL
Definition: c.h:229
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:505
#define Assert(condition)
Definition: c.h:676
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:506
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
#define elog
Definition: elog.h:219
void transformFromClause ( ParseState pstate,
List frmList 
)

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

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

Definition at line 1113 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, NULL, ParseState::p_joinexprs, ParseState::p_namespace, ParseState::p_rtable, parser_errposition(), JoinExpr::quals, JoinExpr::rarg, RangeTableSample::relation, RangeTblEntry::relkind, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, rt_fetch, RangeTblRef::rtindex, JoinExpr::rtindex, RangeVar::schemaname, setNamespaceColumnVisibility(), setNamespaceLateralState(), strVal, RangeTblEntry::tablesample, transformJoinOnClause(), transformJoinUsingClause(), transformRangeFunction(), transformRangeSubselect(), transformRangeTableFunc(), transformRangeTableSample(), transformTableEntry(), and JoinExpr::usingClause.

Referenced by transformFromClause().

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

Definition at line 2503 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, NULL, result, transformGroupClauseExpr(), and transformGroupingSet().

Referenced by transformSelectStmt(), and transformWindowDefinitions().

2506 {
2507  List *result = NIL;
2508  List *flat_grouplist;
2509  List *gsets = NIL;
2510  ListCell *gl;
2511  bool hasGroupingSets = false;
2512  Bitmapset *seen_local = NULL;
2513 
2514  /*
2515  * Recursively flatten implicit RowExprs. (Technically this is only needed
2516  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2517  * anyway.)
2518  */
2519  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2520  true,
2521  &hasGroupingSets);
2522 
2523  /*
2524  * If the list is now empty, but hasGroupingSets is true, it's because we
2525  * elided redundant empty grouping sets. Restore a single empty grouping
2526  * set to leave a canonical form: GROUP BY ()
2527  */
2528 
2529  if (flat_grouplist == NIL && hasGroupingSets)
2530  {
2532  NIL,
2533  exprLocation((Node *) grouplist)));
2534  }
2535 
2536  foreach(gl, flat_grouplist)
2537  {
2538  Node *gexpr = (Node *) lfirst(gl);
2539 
2540  if (IsA(gexpr, GroupingSet))
2541  {
2542  GroupingSet *gset = (GroupingSet *) gexpr;
2543 
2544  switch (gset->kind)
2545  {
2546  case GROUPING_SET_EMPTY:
2547  gsets = lappend(gsets, gset);
2548  break;
2549  case GROUPING_SET_SIMPLE:
2550  /* can't happen */
2551  Assert(false);
2552  break;
2553  case GROUPING_SET_SETS:
2554  case GROUPING_SET_CUBE:
2555  case GROUPING_SET_ROLLUP:
2556  gsets = lappend(gsets,
2557  transformGroupingSet(&result,
2558  pstate, gset,
2559  targetlist, sortClause,
2560  exprKind, useSQL99, true));
2561  break;
2562  }
2563  }
2564  else
2565  {
2566  Index ref = transformGroupClauseExpr(&result, seen_local,
2567  pstate, gexpr,
2568  targetlist, sortClause,
2569  exprKind, useSQL99, true);
2570 
2571  if (ref > 0)
2572  {
2573  seen_local = bms_add_member(seen_local, ref);
2574  if (hasGroupingSets)
2575  gsets = lappend(gsets,
2577  list_make1_int(ref),
2578  exprLocation(gexpr)));
2579  }
2580  }
2581  }
2582 
2583  /* parser should prevent this */
2584  Assert(gsets == NIL || groupingSets != NULL);
2585 
2586  if (groupingSets)
2587  *groupingSets = gsets;
2588 
2589  return result;
2590 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
Definition: nodes.h:509
return result
Definition: formatting.c:1633
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
GroupingSetKind kind
Definition: parsenodes.h:1253
#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:365
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:605
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)
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 2238 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().

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

Definition at line 2346 of file parse_clause.c.

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

Referenced by transformGroupingSet().

2350 {
2351  Bitmapset *seen_local = NULL;
2352  List *result = NIL;
2353  ListCell *gl;
2354 
2355  foreach(gl, list)
2356  {
2357  Node *gexpr = (Node *) lfirst(gl);
2358 
2359  Index ref = transformGroupClauseExpr(flatresult,
2360  seen_local,
2361  pstate,
2362  gexpr,
2363  targetlist,
2364  sortClause,
2365  exprKind,
2366  useSQL99,
2367  toplevel);
2368 
2369  if (ref > 0)
2370  {
2371  seen_local = bms_add_member(seen_local, ref);
2372  result = lappend_int(result, ref);
2373  }
2374  }
2375 
2376  return result;
2377 }
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:509
return result
Definition: formatting.c:1633
List * lappend_int(List *list, int datum)
Definition: list.c:146
unsigned int Index
Definition: c.h:365
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
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)
static Node* transformGroupingSet ( List **  flatresult,
ParseState pstate,
GroupingSet gset,
List **  targetlist,
List sortClause,
ParseExprKind  exprKind,
bool  useSQL99,
bool  toplevel 
)
static

Definition at line 2399 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, NULL, parser_errposition(), transformGroupClauseExpr(), and transformGroupClauseList().

Referenced by transformGroupClause().

2403 {
2404  ListCell *gl;
2405  List *content = NIL;
2406 
2407  Assert(toplevel || gset->kind != GROUPING_SET_SETS);
2408 
2409  foreach(gl, gset->content)
2410  {
2411  Node *n = lfirst(gl);
2412 
2413  if (IsA(n, List))
2414  {
2415  List *l = transformGroupClauseList(flatresult,
2416  pstate, (List *) n,
2417  targetlist, sortClause,
2418  exprKind, useSQL99, false);
2419 
2420  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2421  l,
2422  exprLocation(n)));
2423  }
2424  else if (IsA(n, GroupingSet))
2425  {
2426  GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
2427 
2428  content = lappend(content, transformGroupingSet(flatresult,
2429  pstate, gset2,
2430  targetlist, sortClause,
2431  exprKind, useSQL99, false));
2432  }
2433  else
2434  {
2435  Index ref = transformGroupClauseExpr(flatresult,
2436  NULL,
2437  pstate,
2438  n,
2439  targetlist,
2440  sortClause,
2441  exprKind,
2442  useSQL99,
2443  false);
2444 
2445  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2446  list_make1_int(ref),
2447  exprLocation(n)));
2448  }
2449  }
2450 
2451  /* Arbitrarily cap the size of CUBE, which has exponential growth */
2452  if (gset->kind == GROUPING_SET_CUBE)
2453  {
2454  if (list_length(content) > 12)
2455  ereport(ERROR,
2456  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2457  errmsg("CUBE is limited to 12 elements"),
2458  parser_errposition(pstate, gset->location)));
2459  }
2460 
2461  return (Node *) makeGroupingSet(gset->kind, content, gset->location);
2462 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
List * content
Definition: parsenodes.h:1254
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
Definition: nodes.h:509
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:1253
#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:365
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#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:605
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)
static Node * transformJoinOnClause ( ParseState pstate,
JoinExpr j,
List namespace 
)
static

Definition at line 393 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

394 {
395  Node *result;
396  List *save_namespace;
397 
398  /*
399  * The namespace that the join expression should see is just the two
400  * subtrees of the JOIN plus any outer references from upper pstate
401  * levels. Temporarily set this pstate's namespace accordingly. (We need
402  * not check for refname conflicts, because transformFromClauseItem()
403  * already did.) All namespace items are marked visible regardless of
404  * LATERAL state.
405  */
406  setNamespaceLateralState(namespace, false, true);
407 
408  save_namespace = pstate->p_namespace;
409  pstate->p_namespace = namespace;
410 
411  result = transformWhereClause(pstate, j->quals,
412  EXPR_KIND_JOIN_ON, "JOIN/ON");
413 
414  pstate->p_namespace = save_namespace;
415 
416  return result;
417 }
Definition: nodes.h:509
return result
Definition: formatting.c:1633
List * p_namespace
Definition: parse_node.h:176
static void setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
Node * quals
Definition: primnodes.h:1454
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Definition: pg_list.h:45
static Node * transformJoinUsingClause ( ParseState pstate,
RangeTblEntry leftRTE,
RangeTblEntry rightRTE,
List leftVars,
List rightVars 
)
static

Definition at line 333 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, result, and transformExpr().

Referenced by transformFromClauseItem().

336 {
337  Node *result;
338  List *andargs = NIL;
339  ListCell *lvars,
340  *rvars;
341 
342  /*
343  * We cheat a little bit here by building an untransformed operator tree
344  * whose leaves are the already-transformed Vars. This requires collusion
345  * from transformExpr(), which normally could be expected to complain
346  * about already-transformed subnodes. However, this does mean that we
347  * have to mark the columns as requiring SELECT privilege for ourselves;
348  * transformExpr() won't do it.
349  */
350  forboth(lvars, leftVars, rvars, rightVars)
351  {
352  Var *lvar = (Var *) lfirst(lvars);
353  Var *rvar = (Var *) lfirst(rvars);
354  A_Expr *e;
355 
356  /* Require read access to the join variables */
357  markVarForSelectPriv(pstate, lvar, leftRTE);
358  markVarForSelectPriv(pstate, rvar, rightRTE);
359 
360  /* Now create the lvar = rvar join condition */
361  e = makeSimpleA_Expr(AEXPR_OP, "=",
362  (Node *) copyObject(lvar), (Node *) copyObject(rvar),
363  -1);
364 
365  /* Prepare to combine into an AND clause, if multiple join columns */
366  andargs = lappend(andargs, e);
367  }
368 
369  /* Only need an AND if there's more than one join column */
370  if (list_length(andargs) == 1)
371  result = (Node *) linitial(andargs);
372  else
373  result = (Node *) makeBoolExpr(AND_EXPR, andargs, -1);
374 
375  /*
376  * Since the references are already Vars, and are certainly from the input
377  * relations, we don't have to go through the same pushups that
378  * transformJoinOnClause() does. Just invoke transformExpr() to fix up
379  * the operators, and we're done.
380  */
381  result = transformExpr(pstate, result, EXPR_KIND_JOIN_USING);
382 
383  result = coerce_to_boolean(pstate, result, "JOIN/USING");
384 
385  return result;
386 }
#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:509
return result
Definition: formatting.c:1633
A_Expr * makeSimpleA_Expr(A_Expr_Kind kind, char *name, Node *lexpr, Node *rexpr, int location)
Definition: makefuncs.c:49
Definition: primnodes.h:163
Expr * makeBoolExpr(BoolExprType boolop, List *args, int location)
Definition: makefuncs.c:366
#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:622
Definition: pg_list.h:45
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)
Node* transformLimitClause ( ParseState pstate,
Node clause,
ParseExprKind  exprKind,
const char *  constructName 
)

Definition at line 1762 of file parse_clause.c.

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

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

1764 {
1765  Node *qual;
1766 
1767  if (clause == NULL)
1768  return NULL;
1769 
1770  qual = transformExpr(pstate, clause, exprKind);
1771 
1772  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1773 
1774  /* LIMIT can't refer to any variables of the current query */
1775  checkExprIsVarFree(pstate, qual, constructName);
1776 
1777  return qual;
1778 }
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:509
#define INT8OID
Definition: pg_type.h:304
#define NULL
Definition: c.h:229
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
void transformOnConflictArbiter ( ParseState pstate,
OnConflictClause onConflictClause,
List **  arbiterExpr,
Node **  arbiterWhere,
Oid constraint 
)

Definition at line 3120 of file parse_clause.c.

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

Referenced by transformOnConflictClause().

3124 {
3125  InferClause *infer = onConflictClause->infer;
3126 
3127  *arbiterExpr = NIL;
3128  *arbiterWhere = NULL;
3129  *constraint = InvalidOid;
3130 
3131  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3132  ereport(ERROR,
3133  (errcode(ERRCODE_SYNTAX_ERROR),
3134  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3135  errhint("For example, ON CONFLICT (column_name)."),
3136  parser_errposition(pstate,
3137  exprLocation((Node *) onConflictClause))));
3138 
3139  /*
3140  * To simplify certain aspects of its design, speculative insertion into
3141  * system catalogs is disallowed
3142  */
3143  if (IsCatalogRelation(pstate->p_target_relation))
3144  ereport(ERROR,
3145  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3146  errmsg("ON CONFLICT is not supported with system catalog tables"),
3147  parser_errposition(pstate,
3148  exprLocation((Node *) onConflictClause))));
3149 
3150  /* Same applies to table used by logical decoding as catalog table */
3152  ereport(ERROR,
3153  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3154  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3156  parser_errposition(pstate,
3157  exprLocation((Node *) onConflictClause))));
3158 
3159  /* ON CONFLICT DO NOTHING does not require an inference clause */
3160  if (infer)
3161  {
3162  List *save_namespace;
3163 
3164  /*
3165  * While we process the arbiter expressions, accept only non-qualified
3166  * references to the target table. Hide any other relations.
3167  */
3168  save_namespace = pstate->p_namespace;
3169  pstate->p_namespace = NIL;
3170  addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
3171  false, false, true);
3172 
3173  if (infer->indexElems)
3174  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3175  pstate->p_target_relation);
3176 
3177  /*
3178  * Handling inference WHERE clause (for partial unique index
3179  * inference)
3180  */
3181  if (infer->whereClause)
3182  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3184 
3185  pstate->p_namespace = save_namespace;
3186 
3187  if (infer->conname)
3189  infer->conname, false);
3190  }
3191 
3192  /*
3193  * It's convenient to form a list of expressions based on the
3194  * representation used by CREATE INDEX, since the same restrictions are
3195  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3196  * primnode representation is used for inference elements, and so
3197  * assign_query_collations() can be trusted to do the right thing with the
3198  * post parse analysis query tree inference clause representation.
3199  */
3200 }
#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
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
List * indexElems
Definition: parsenodes.h:1331
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
List * p_namespace
Definition: parse_node.h:176
char * conname
Definition: parsenodes.h:1333
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:183
InferClause * infer
Definition: parsenodes.h:1347
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:315
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Node * whereClause
Definition: parsenodes.h:1332
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation p_target_relation
Definition: parse_node.h:182
OnConflictAction action
Definition: parsenodes.h:1346
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:416
static List * resolve_unique_index_expr(ParseState *pstate, InferClause *infer, Relation heapRel)
static RangeTblEntry * transformRangeFunction ( ParseState pstate,
RangeFunction r 
)
static

Definition at line 533 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, NULL, RangeFunction::ordinality, FuncCall::over, ParseState::p_last_srf, ParseState::p_lateral_active, parser_errposition(), strVal, SystemFuncName(), and transformExpr().

Referenced by transformFromClauseItem().

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

Definition at line 466 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, NULL, ParseState::p_expr_kind, ParseState::p_lateral_active, parse_sub_analyze(), and RangeSubselect::subquery.

Referenced by transformFromClauseItem().

467 {
468  Query *query;
469  RangeTblEntry *rte;
470 
471  /*
472  * We require user to supply an alias for a subselect, per SQL92. To relax
473  * this, we'd have to be prepared to gin up a unique alias for an
474  * unlabeled subselect. (This is just elog, not ereport, because the
475  * grammar should have enforced it already. It'd probably be better to
476  * report the error here, but we don't have a good error location here.)
477  */
478  if (r->alias == NULL)
479  elog(ERROR, "subquery in FROM must have an alias");
480 
481  /*
482  * Set p_expr_kind to show this parse level is recursing to a subselect.
483  * We can't be nested within any expression, so don't need save-restore
484  * logic here.
485  */
486  Assert(pstate->p_expr_kind == EXPR_KIND_NONE);
488 
489  /*
490  * If the subselect is LATERAL, make lateral_only names of this level
491  * visible to it. (LATERAL can't nest within a single pstate level, so we
492  * don't need save/restore logic here.)
493  */
494  Assert(!pstate->p_lateral_active);
495  pstate->p_lateral_active = r->lateral;
496 
497  /*
498  * Analyze and transform the subquery.
499  */
500  query = parse_sub_analyze(r->subquery, pstate, NULL,
501  isLockedRefname(pstate, r->alias->aliasname),
502  true);
503 
504  /* Restore state */
505  pstate->p_lateral_active = false;
506  pstate->p_expr_kind = EXPR_KIND_NONE;
507 
508  /*
509  * Check that we got a SELECT. Anything else should be impossible given
510  * restrictions of the grammar, but check anyway.
511  */
512  if (!IsA(query, Query) ||
513  query->commandType != CMD_SELECT)
514  elog(ERROR, "unexpected non-SELECT command in subquery in FROM");
515 
516  /*
517  * OK, build an RTE for the subquery.
518  */
519  rte = addRangeTableEntryForSubquery(pstate,
520  query,
521  r->alias,
522  r->lateral,
523  true);
524 
525  return rte;
526 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Node * subquery
Definition: parsenodes.h:535
#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:186
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:160
bool p_lateral_active
Definition: parse_node.h:178
CmdType commandType
Definition: parsenodes.h:110
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
char * aliasname
Definition: primnodes.h:42
Alias * alias
Definition: parsenodes.h:536
bool isLockedRefname(ParseState *pstate, const char *refname)
#define elog
Definition: elog.h:219
static RangeTblEntry * transformRangeTableFunc ( ParseState pstate,
RangeTableFunc t 
)
static

Definition at line 758 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(), DEFAULT_COLLATION_OID, TableFunc::docexpr, RangeTableFunc::docexpr, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_FROM_FUNCTION, RangeTableFuncCol::for_ordinality, INT4OID, 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, NULL, TableFunc::ordinalitycol, ParseState::p_lateral_active, palloc(), parser_errposition(), pfree(), pstrdup(), TableFunc::rowexpr, RangeTableFunc::rowexpr, TypeName::setof, strVal, TEXTOID, transformExpr(), type_is_collatable(), RangeTableFuncCol::typeName, typenameTypeIdAndMod(), ResTarget::val, and XMLOID.

Referenced by transformFromClauseItem().

759 {
761  const char *constructName;
762  Oid docType;
763  RangeTblEntry *rte;
764  bool is_lateral;
765  ListCell *col;
766  char **names;
767  int colno;
768 
769  /* Currently only XMLTABLE is supported */
770  constructName = "XMLTABLE";
771  docType = XMLOID;
772 
773  /*
774  * We make lateral_only names of this level visible, whether or not the
775  * RangeTableFunc is explicitly marked LATERAL. This is needed for SQL
776  * spec compliance and seems useful on convenience grounds for all
777  * functions in FROM.
778  *
779  * (LATERAL can't nest within a single pstate level, so we don't need
780  * save/restore logic here.)
781  */
782  Assert(!pstate->p_lateral_active);
783  pstate->p_lateral_active = true;
784 
785  /* Transform and apply typecast to the row-generating expression ... */
786  Assert(rtf->rowexpr != NULL);
787  tf->rowexpr = coerce_to_specific_type(pstate,
788  transformExpr(pstate, rtf->rowexpr, EXPR_KIND_FROM_FUNCTION),
789  TEXTOID,
790  constructName);
791  assign_expr_collations(pstate, tf->rowexpr);
792 
793  /* ... and to the document itself */
794  Assert(rtf->docexpr != NULL);
795  tf->docexpr = coerce_to_specific_type(pstate,
796  transformExpr(pstate, rtf->docexpr, EXPR_KIND_FROM_FUNCTION),
797  docType,
798  constructName);
799  assign_expr_collations(pstate, tf->docexpr);
800 
801  /* undef ordinality column number */
802  tf->ordinalitycol = -1;
803 
804 
805  names = palloc(sizeof(char *) * list_length(rtf->columns));
806 
807  colno = 0;
808  foreach(col, rtf->columns)
809  {
810  RangeTableFuncCol *rawc = (RangeTableFuncCol *) lfirst(col);
811  Oid typid;
812  int32 typmod;
813  Node *colexpr;
814  Node *coldefexpr;
815  int j;
816 
817  tf->colnames = lappend(tf->colnames,
818  makeString(pstrdup(rawc->colname)));
819 
820  /*
821  * Determine the type and typmod for the new column. FOR ORDINALITY
822  * columns are INTEGER per spec; the others are user-specified.
823  */
824  if (rawc->for_ordinality)
825  {
826  if (tf->ordinalitycol != -1)
827  ereport(ERROR,
828  (errcode(ERRCODE_SYNTAX_ERROR),
829  errmsg("only one FOR ORDINALITY column is allowed"),
830  parser_errposition(pstate, rawc->location)));
831 
832  typid = INT4OID;
833  typmod = -1;
834  tf->ordinalitycol = colno;
835  }
836  else
837  {
838  if (rawc->typeName->setof)
839  ereport(ERROR,
840  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
841  errmsg("column \"%s\" cannot be declared SETOF",
842  rawc->colname),
843  parser_errposition(pstate, rawc->location)));
844 
845  typenameTypeIdAndMod(pstate, rawc->typeName,
846  &typid, &typmod);
847  }
848 
849  tf->coltypes = lappend_oid(tf->coltypes, typid);
850  tf->coltypmods = lappend_int(tf->coltypmods, typmod);
853 
854  /* Transform the PATH and DEFAULT expressions */
855  if (rawc->colexpr)
856  {
857  colexpr = coerce_to_specific_type(pstate,
858  transformExpr(pstate, rawc->colexpr,
860  TEXTOID,
861  constructName);
862  assign_expr_collations(pstate, colexpr);
863  }
864  else
865  colexpr = NULL;
866 
867  if (rawc->coldefexpr)
868  {
869  coldefexpr = coerce_to_specific_type_typmod(pstate,
870  transformExpr(pstate, rawc->coldefexpr,
872  typid, typmod,
873  constructName);
874  assign_expr_collations(pstate, coldefexpr);
875  }
876  else
877  coldefexpr = NULL;
878 
879  tf->colexprs = lappend(tf->colexprs, colexpr);
880  tf->coldefexprs = lappend(tf->coldefexprs, coldefexpr);
881 
882  if (rawc->is_not_null)
883  tf->notnulls = bms_add_member(tf->notnulls, colno);
884 
885  /* make sure column names are unique */
886  for (j = 0; j < colno; j++)
887  if (strcmp(names[j], rawc->colname) == 0)
888  ereport(ERROR,
889  (errcode(ERRCODE_SYNTAX_ERROR),
890  errmsg("column name \"%s\" is not unique",
891  rawc->colname),
892  parser_errposition(pstate, rawc->location)));
893  names[colno] = rawc->colname;
894 
895  colno++;
896  }
897  pfree(names);
898 
899  /* Namespaces, if any, also need to be transformed */
900  if (rtf->namespaces != NIL)
901  {
902  ListCell *ns;
903  ListCell *lc2;
904  List *ns_uris = NIL;
905  List *ns_names = NIL;
906  bool default_ns_seen = false;
907 
908  foreach(ns, rtf->namespaces)
909  {
910  ResTarget *r = (ResTarget *) lfirst(ns);
911  Node *ns_uri;
912 
913  Assert(IsA(r, ResTarget));
914  ns_uri = transformExpr(pstate, r->val, EXPR_KIND_FROM_FUNCTION);
915  ns_uri = coerce_to_specific_type(pstate, ns_uri,
916  TEXTOID, constructName);
917  assign_expr_collations(pstate, ns_uri);
918  ns_uris = lappend(ns_uris, ns_uri);
919 
920  /* Verify consistency of name list: no dupes, only one DEFAULT */
921  if (r->name != NULL)
922  {
923  foreach(lc2, ns_names)
924  {
925  char *name = strVal(lfirst(lc2));
926 
927  if (name == NULL)
928  continue;
929  if (strcmp(name, r->name) == 0)
930  ereport(ERROR,
931  (errcode(ERRCODE_SYNTAX_ERROR),
932  errmsg("namespace name \"%s\" is not unique",
933  name),
934  parser_errposition(pstate, r->location)));
935  }
936  }
937  else
938  {
939  if (default_ns_seen)
940  ereport(ERROR,
941  (errcode(ERRCODE_SYNTAX_ERROR),
942  errmsg("only one default namespace is allowed"),
943  parser_errposition(pstate, r->location)));
944  default_ns_seen = true;
945  }
946 
947  /* Note the string may be NULL */
948  ns_names = lappend(ns_names, makeString(r->name));
949  }
950 
951  tf->ns_uris = ns_uris;
952  tf->ns_names = ns_names;
953  }
954 
955  tf->location = rtf->location;
956 
957  pstate->p_lateral_active = false;
958 
959  /*
960  * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
961  * there are any lateral cross-references in it.
962  */
963  is_lateral = rtf->lateral || contain_vars_of_level((Node *) tf, 0);
964 
965  rte = addRangeTableEntryForTableFunc(pstate,
966  tf, rtf->alias, is_lateral, true);
967 
968  return rte;
969 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Node * docexpr
Definition: primnodes.h:84
Node * val
Definition: parsenodes.h:441
List * colnames
Definition: primnodes.h:86
char * name
Definition: parsenodes.h:439
List * coltypmods
Definition: primnodes.h:88
#define TEXTOID
Definition: pg_type.h:324
char * pstrdup(const char *in)
Definition: mcxt.c:1077
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
#define INT4OID
Definition: pg_type.h:316
Definition: nodes.h:509
#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:89
signed int int32
Definition: c.h:256
int location
Definition: parsenodes.h:442
void assign_expr_collations(ParseState *pstate, Node *expr)
void pfree(void *pointer)
Definition: mcxt.c:950
#define ERROR
Definition: elog.h:43
bool setof
Definition: parsenodes.h:210
List * coldefexprs
Definition: primnodes.h:91
List * ns_names
Definition: primnodes.h:83
Node * rowexpr
Definition: primnodes.h:85
#define XMLOID
Definition: pg_type.h:359
TypeName * typeName
Definition: parsenodes.h:590
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:75
Bitmapset * notnulls
Definition: primnodes.h:92
#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:93
List * coltypes
Definition: primnodes.h:87
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:90
bool p_lateral_active
Definition: parse_node.h:178
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
List * ns_uris
Definition: primnodes.h:82
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:698
const char * name
Definition: encode.c:521
void * palloc(Size size)
Definition: mcxt.c:849
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:94
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:2806
Definition: pg_list.h:45
Node * coerce_to_specific_type_typmod(ParseState *pstate, Node *node, Oid targetTypeId, int32 targetTypmod, const char *constructName)
static TableSampleClause * transformRangeTableSample ( ParseState pstate,
RangeTableSample rts 
)
static

Definition at line 978 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, FLOAT8OID, forboth, get_func_rettype(), GetTsmRoutine(), INTERNALOID, lappend(), lfirst, lfirst_oid, list_length(), RangeTableSample::location, LookupFuncName(), makeNode, RangeTableSample::method, NameListToString(), NIL, NULL, OidIsValid, TsmRoutine::parameterTypes, parser_errposition(), RangeTableSample::repeatable, TableSampleClause::repeatable, TsmRoutine::repeatable_across_queries, transformExpr(), TSM_HANDLEROID, and TableSampleClause::tsmhandler.

Referenced by transformFromClauseItem().

979 {
980  TableSampleClause *tablesample;
981  Oid handlerOid;
982  Oid funcargtypes[1];
983  TsmRoutine *tsm;
984  List *fargs;
985  ListCell *larg,
986  *ltyp;
987 
988  /*
989  * To validate the sample method name, look up the handler function, which
990  * has the same name, one dummy INTERNAL argument, and a result type of
991  * tsm_handler. (Note: tablesample method names are not schema-qualified
992  * in the SQL standard; but since they are just functions to us, we allow
993  * schema qualification to resolve any potential ambiguity.)
994  */
995  funcargtypes[0] = INTERNALOID;
996 
997  handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true);
998 
999  /* we want error to complain about no-such-method, not no-such-function */
1000  if (!OidIsValid(handlerOid))
1001  ereport(ERROR,
1002  (errcode(ERRCODE_UNDEFINED_OBJECT),
1003  errmsg("tablesample method %s does not exist",
1004  NameListToString(rts->method)),
1005  parser_errposition(pstate, rts->location)));
1006 
1007  /* check that handler has correct return type */
1008  if (get_func_rettype(handlerOid) != TSM_HANDLEROID)
1009  ereport(ERROR,
1010  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1011  errmsg("function %s must return type %s",
1012  NameListToString(rts->method), "tsm_handler"),
1013  parser_errposition(pstate, rts->location)));
1014 
1015  /* OK, run the handler to get TsmRoutine, for argument type info */
1016  tsm = GetTsmRoutine(handlerOid);
1017 
1018  tablesample = makeNode(TableSampleClause);
1019  tablesample->tsmhandler = handlerOid;
1020 
1021  /* check user provided the expected number of arguments */
1022  if (list_length(rts->args) != list_length(tsm->parameterTypes))
1023  ereport(ERROR,
1024  (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
1025  errmsg_plural("tablesample method %s requires %d argument, not %d",
1026  "tablesample method %s requires %d arguments, not %d",
1028  NameListToString(rts->method),
1030  list_length(rts->args)),
1031  parser_errposition(pstate, rts->location)));
1032 
1033  /*
1034  * Transform the arguments, typecasting them as needed. Note we must also
1035  * assign collations now, because assign_query_collations() doesn't
1036  * examine any substructure of RTEs.
1037  */
1038  fargs = NIL;
1039  forboth(larg, rts->args, ltyp, tsm->parameterTypes)
1040  {
1041  Node *arg = (Node *) lfirst(larg);
1042  Oid argtype = lfirst_oid(ltyp);
1043 
1044  arg = transformExpr(pstate, arg, EXPR_KIND_FROM_FUNCTION);
1045  arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE");
1046  assign_expr_collations(pstate, arg);
1047  fargs = lappend(fargs, arg);
1048  }
1049  tablesample->args = fargs;
1050 
1051  /* Process REPEATABLE (seed) */
1052  if (rts->repeatable != NULL)
1053  {
1054  Node *arg;
1055 
1056  if (!tsm->repeatable_across_queries)
1057  ereport(ERROR,
1058  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1059  errmsg("tablesample method %s does not support REPEATABLE",
1060  NameListToString(rts->method)),
1061  parser_errposition(pstate, rts->location)));
1062 
1063  arg = transformExpr(pstate, rts->repeatable, EXPR_KIND_FROM_FUNCTION);
1064  arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE");
1065  assign_expr_collations(pstate, arg);
1066  tablesample->repeatable = (Expr *) arg;
1067  }
1068  else
1069  tablesample->repeatable = NULL;
1070 
1071  return tablesample;
1072 }
#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
#define TSM_HANDLEROID
Definition: pg_type.h:712
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1459
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:3063
#define INTERNALOID
Definition: pg_type.h:698
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
#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
#define FLOAT8OID
Definition: pg_type.h:419
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
Definition: parse_func.c:1929
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
List* transformSortClause ( ParseState pstate,
List orderlist,
List **  targetlist,
ParseExprKind  exprKind,
bool  useSQL99 
)

Definition at line 2603 of file parse_clause.c.

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

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

2608 {
2609  List *sortlist = NIL;
2610  ListCell *olitem;
2611 
2612  foreach(olitem, orderlist)
2613  {
2614  SortBy *sortby = (SortBy *) lfirst(olitem);
2615  TargetEntry *tle;
2616 
2617  if (useSQL99)
2618  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2619  targetlist, exprKind);
2620  else
2621  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2622  targetlist, exprKind);
2623 
2624  sortlist = addTargetToSortList(pstate, tle,
2625  sortlist, *targetlist, sortby);
2626  }
2627 
2628  return sortlist;
2629 }
#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:468
Definition: pg_list.h:45
static RangeTblEntry * transformTableEntry ( ParseState pstate,
RangeVar r 
)
static

Definition at line 423 of file parse_clause.c.

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

Referenced by transformFromClauseItem().

424 {
425  RangeTblEntry *rte;
426 
427  /* We need only build a range table entry */
428  rte = addRangeTableEntry(pstate, r, r->alias, r->inh, true);
429 
430  return rte;
431 }
RangeTblEntry * addRangeTableEntry(ParseState *pstate, RangeVar *relation, Alias *alias, bool inh, bool inFromCl)
bool inh
Definition: primnodes.h:69
Alias * alias
Definition: primnodes.h:72
Node* transformWhereClause ( ParseState pstate,
Node clause,
ParseExprKind  exprKind,
const char *  constructName 
)

Definition at line 1735 of file parse_clause.c.

References coerce_to_boolean(), NULL, and transformExpr().

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

1737 {
1738  Node *qual;
1739 
1740  if (clause == NULL)
1741  return NULL;
1742 
1743  qual = transformExpr(pstate, clause, exprKind);
1744 
1745  qual = coerce_to_boolean(pstate, qual, constructName);
1746 
1747  return qual;
1748 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:509
#define NULL
Definition: c.h:229
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)
List* transformWindowDefinitions ( ParseState pstate,
List windowdefs,
List **  targetlist 
)

Definition at line 2636 of file parse_clause.c.

References WindowClause::copiedOrder, copyObject, WindowDef::endOffset, WindowClause::endOffset, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, findWindowClause(), FRAMEOPTION_DEFAULTS, WindowDef::frameOptions, WindowClause::frameOptions, lappend(), lfirst, WindowDef::location, makeNode, WindowDef::name, WindowClause::name, NIL, NULL, WindowDef::orderClause, WindowClause::orderClause, parser_errposition(), WindowDef::partitionClause, WindowClause::partitionClause, WindowDef::refname, WindowClause::refname, result, WindowDef::startOffset, WindowClause::startOffset, transformFrameOffset(), transformGroupClause(), transformSortClause(), and WindowClause::winref.

Referenced by transformSelectStmt().

2639 {
2640  List *result = NIL;
2641  Index winref = 0;
2642  ListCell *lc;
2643 
2644  foreach(lc, windowdefs)
2645  {
2646  WindowDef *windef = (WindowDef *) lfirst(lc);
2647  WindowClause *refwc = NULL;
2648  List *partitionClause;
2649  List *orderClause;
2650  WindowClause *wc;
2651 
2652  winref++;
2653 
2654  /*
2655  * Check for duplicate window names.
2656  */
2657  if (windef->name &&
2658  findWindowClause(result, windef->name) != NULL)
2659  ereport(ERROR,
2660  (errcode(ERRCODE_WINDOWING_ERROR),
2661  errmsg("window \"%s\" is already defined", windef->name),
2662  parser_errposition(pstate, windef->location)));
2663 
2664  /*
2665  * If it references a previous window, look that up.
2666  */
2667  if (windef->refname)
2668  {
2669  refwc = findWindowClause(result, windef->refname);
2670  if (refwc == NULL)
2671  ereport(ERROR,
2672  (errcode(ERRCODE_UNDEFINED_OBJECT),
2673  errmsg("window \"%s\" does not exist",
2674  windef->refname),
2675  parser_errposition(pstate, windef->location)));
2676  }
2677 
2678  /*
2679  * Transform PARTITION and ORDER specs, if any. These are treated
2680  * almost exactly like top-level GROUP BY and ORDER BY clauses,
2681  * including the special handling of nondefault operator semantics.
2682  */
2683  orderClause = transformSortClause(pstate,
2684  windef->orderClause,
2685  targetlist,
2687  true /* force SQL99 rules */ );
2688  partitionClause = transformGroupClause(pstate,
2689  windef->partitionClause,
2690  NULL,
2691  targetlist,
2692  orderClause,
2694  true /* force SQL99 rules */ );
2695 
2696  /*
2697  * And prepare the new WindowClause.
2698  */
2699  wc = makeNode(WindowClause);
2700  wc->name = windef->name;
2701  wc->refname = windef->refname;
2702 
2703  /*
2704  * Per spec, a windowdef that references a previous one copies the
2705  * previous partition clause (and mustn't specify its own). It can
2706  * specify its own ordering clause, but only if the previous one had
2707  * none. It always specifies its own frame clause, and the previous
2708  * one must not have a frame clause. Yeah, it's bizarre that each of
2709  * these cases works differently, but SQL:2008 says so; see 7.11
2710  * <window clause> syntax rule 10 and general rule 1. The frame
2711  * clause rule is especially bizarre because it makes "OVER foo"
2712  * different from "OVER (foo)", and requires the latter to throw an
2713  * error if foo has a nondefault frame clause. Well, ours not to
2714  * reason why, but we do go out of our way to throw a useful error
2715  * message for such cases.
2716  */
2717  if (refwc)
2718  {
2719  if (partitionClause)
2720  ereport(ERROR,
2721  (errcode(ERRCODE_WINDOWING_ERROR),
2722  errmsg("cannot override PARTITION BY clause of window \"%s\"",
2723  windef->refname),
2724  parser_errposition(pstate, windef->location)));
2726  }
2727  else
2728  wc->partitionClause = partitionClause;
2729  if (refwc)
2730  {
2731  if (orderClause && refwc->orderClause)
2732  ereport(ERROR,
2733  (errcode(ERRCODE_WINDOWING_ERROR),
2734  errmsg("cannot override ORDER BY clause of window \"%s\"",
2735  windef->refname),
2736  parser_errposition(pstate, windef->location)));
2737  if (orderClause)
2738  {
2739  wc->orderClause = orderClause;
2740  wc->copiedOrder = false;
2741  }
2742  else
2743  {
2744  wc->orderClause = copyObject(refwc->orderClause);
2745  wc->copiedOrder = true;
2746  }
2747  }
2748  else
2749  {
2750  wc->orderClause = orderClause;
2751  wc->copiedOrder = false;
2752  }
2753  if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2754  {
2755  /*
2756  * Use this message if this is a WINDOW clause, or if it's an OVER
2757  * clause that includes ORDER BY or framing clauses. (We already
2758  * rejected PARTITION BY above, so no need to check that.)
2759  */
2760  if (windef->name ||
2761  orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2762  ereport(ERROR,
2763  (errcode(ERRCODE_WINDOWING_ERROR),
2764  errmsg("cannot copy window \"%s\" because it has a frame clause",
2765  windef->refname),
2766  parser_errposition(pstate, windef->location)));
2767  /* Else this clause is just OVER (foo), so say this: */
2768  ereport(ERROR,
2769  (errcode(ERRCODE_WINDOWING_ERROR),
2770  errmsg("cannot copy window \"%s\" because it has a frame clause",
2771  windef->refname),
2772  errhint("Omit the parentheses in this OVER clause."),
2773  parser_errposition(pstate, windef->location)));
2774  }
2775  wc->frameOptions = windef->frameOptions;
2776  /* Process frame offset expressions */
2777  wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2778  windef->startOffset);
2779  wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2780  windef->endOffset);
2781  wc->winref = winref;
2782 
2783  result = lappend(result, wc);
2784  }
2785 
2786  return result;
2787 }
List * partitionClause
Definition: parsenodes.h:488
char * refname
Definition: parsenodes.h:1276
#define NIL
Definition: pg_list.h:69
bool copiedOrder
Definition: parsenodes.h:1283
int errhint(const char *fmt,...)
Definition: elog.c:987
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:524
int frameOptions
Definition: parsenodes.h:490
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
char * name
Definition: parsenodes.h:486
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1633
static Node * transformFrameOffset(ParseState *pstate, int frameOptions, Node *clause)
Node * startOffset
Definition: parsenodes.h:491
#define ERROR
Definition: elog.h:43
List * partitionClause
Definition: parsenodes.h:1277
int location
Definition: parsenodes.h:493
Node * endOffset
Definition: parsenodes.h:492
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:1280
List * orderClause
Definition: parsenodes.h:489
unsigned int Index
Definition: c.h:365
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
Node * endOffset
Definition: parsenodes.h:1281
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
List * orderClause
Definition: parsenodes.h:1278
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * refname
Definition: parsenodes.h:487
#define copyObject(obj)
Definition: nodes.h:622
Definition: pg_list.h:45
static WindowClause * findWindowClause(List *wclist, const char *name)