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

3332 {
3333  Oid restype = exprType((Node *) tle->expr);
3334 
3335  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3336  if (restype == UNKNOWNOID)
3337  {
3338  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3339  restype, TEXTOID, -1,
3342  -1);
3343  restype = TEXTOID;
3344  }
3345 
3346  /* avoid making duplicate grouplist entries */
3347  if (!targetIsInSortList(tle, InvalidOid, grouplist))
3348  {
3350  Oid sortop;
3351  Oid eqop;
3352  bool hashable;
3353  ParseCallbackState pcbstate;
3354 
3355  setup_parser_errposition_callback(&pcbstate, pstate, location);
3356 
3357  /* determine the eqop and optional sortop */
3358  get_sort_group_operators(restype,
3359  false, true, false,
3360  &sortop, &eqop, NULL,
3361  &hashable);
3362 
3364 
3365  grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3366  grpcl->eqop = eqop;
3367  grpcl->sortop = sortop;
3368  grpcl->nulls_first = false; /* OK with or without sortop */
3369  grpcl->hashable = hashable;
3370 
3371  grouplist = lappend(grouplist, grpcl);
3372  }
3373 
3374  return grouplist;
3375 }
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
#define TEXTOID
Definition: pg_type.h:324
Index tleSortGroupRef
Definition: parsenodes.h:1156
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:1367
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 3187 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().

3189 {
3190  Oid restype = exprType((Node *) tle->expr);
3191  Oid sortop;
3192  Oid eqop;
3193  bool hashable;
3194  bool reverse;
3195  int location;
3196  ParseCallbackState pcbstate;
3197 
3198  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3199  if (restype == UNKNOWNOID)
3200  {
3201  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3202  restype, TEXTOID, -1,
3205  -1);
3206  restype = TEXTOID;
3207  }
3208 
3209  /*
3210  * Rather than clutter the API of get_sort_group_operators and the other
3211  * functions we're about to use, make use of error context callback to
3212  * mark any error reports with a parse position. We point to the operator
3213  * location if present, else to the expression being sorted. (NB: use the
3214  * original untransformed expression here; the TLE entry might well point
3215  * at a duplicate expression in the regular SELECT list.)
3216  */
3217  location = sortby->location;
3218  if (location < 0)
3219  location = exprLocation(sortby->node);
3220  setup_parser_errposition_callback(&pcbstate, pstate, location);
3221 
3222  /* determine the sortop, eqop, and directionality */
3223  switch (sortby->sortby_dir)
3224  {
3225  case SORTBY_DEFAULT:
3226  case SORTBY_ASC:
3227  get_sort_group_operators(restype,
3228  true, true, false,
3229  &sortop, &eqop, NULL,
3230  &hashable);
3231  reverse = false;
3232  break;
3233  case SORTBY_DESC:
3234  get_sort_group_operators(restype,
3235  false, true, true,
3236  NULL, &eqop, &sortop,
3237  &hashable);
3238  reverse = true;
3239  break;
3240  case SORTBY_USING:
3241  Assert(sortby->useOp != NIL);
3242  sortop = compatible_oper_opid(sortby->useOp,
3243  restype,
3244  restype,
3245  false);
3246 
3247  /*
3248  * Verify it's a valid ordering operator, fetch the corresponding
3249  * equality operator, and determine whether to consider it like
3250  * ASC or DESC.
3251  */
3252  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3253  if (!OidIsValid(eqop))
3254  ereport(ERROR,
3255  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3256  errmsg("operator %s is not a valid ordering operator",
3257  strVal(llast(sortby->useOp))),
3258  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3259 
3260  /*
3261  * Also see if the equality operator is hashable.
3262  */
3263  hashable = op_hashjoinable(eqop, restype);
3264  break;
3265  default:
3266  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3267  sortop = InvalidOid; /* keep compiler quiet */
3268  eqop = InvalidOid;
3269  hashable = false;
3270  reverse = false;
3271  break;
3272  }
3273 
3275 
3276  /* avoid making duplicate sortlist entries */
3277  if (!targetIsInSortList(tle, sortop, sortlist))
3278  {
3280 
3281  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3282 
3283  sortcl->eqop = eqop;
3284  sortcl->sortop = sortop;
3285  sortcl->hashable = hashable;
3286 
3287  switch (sortby->sortby_nulls)
3288  {
3289  case SORTBY_NULLS_DEFAULT:
3290  /* NULLS FIRST is default for DESC; other way for ASC */
3291  sortcl->nulls_first = reverse;
3292  break;
3293  case SORTBY_NULLS_FIRST:
3294  sortcl->nulls_first = true;
3295  break;
3296  case SORTBY_NULLS_LAST:
3297  sortcl->nulls_first = false;
3298  break;
3299  default:
3300  elog(ERROR, "unrecognized sortby_nulls: %d",
3301  sortby->sortby_nulls);
3302  break;
3303  }
3304 
3305  sortlist = lappend(sortlist, sortcl);
3306  }
3307 
3308  return sortlist;
3309 }
#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:1213
SortByDir sortby_dir
Definition: parsenodes.h:470
#define TEXTOID
Definition: pg_type.h:324
List * useOp
Definition: parsenodes.h:472
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:1156
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:471
#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:675
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:1367
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:469
int location
Definition: parsenodes.h:473
Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3385 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

3386 {
3387  Index maxRef;
3388  ListCell *l;
3389 
3390  if (tle->ressortgroupref) /* already has one? */
3391  return tle->ressortgroupref;
3392 
3393  /* easiest way to pick an unused refnumber: max used + 1 */
3394  maxRef = 0;
3395  foreach(l, tlist)
3396  {
3397  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3398 
3399  if (ref > maxRef)
3400  maxRef = ref;
3401  }
3402  tle->ressortgroupref = maxRef + 1;
3403  return tle->ressortgroupref;
3404 }
unsigned int Index
Definition: c.h:365
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1370
static Node * buildMergedJoinVar ( ParseState pstate,
JoinType  jointype,
Var l_colvar,
Var r_colvar 
)
static

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

1536 {
1537  Oid outcoltype;
1538  int32 outcoltypmod;
1539  Node *l_node,
1540  *r_node,
1541  *res_node;
1542 
1543  /*
1544  * Choose output type if input types are dissimilar.
1545  */
1546  outcoltype = l_colvar->vartype;
1547  outcoltypmod = l_colvar->vartypmod;
1548  if (outcoltype != r_colvar->vartype)
1549  {
1550  outcoltype = select_common_type(pstate,
1551  list_make2(l_colvar, r_colvar),
1552  "JOIN/USING",
1553  NULL);
1554  outcoltypmod = -1; /* ie, unknown */
1555  }
1556  else if (outcoltypmod != r_colvar->vartypmod)
1557  {
1558  /* same type, but not same typmod */
1559  outcoltypmod = -1; /* ie, unknown */
1560  }
1561 
1562  /*
1563  * Insert coercion functions if needed. Note that a difference in typmod
1564  * can only happen if input has typmod but outcoltypmod is -1. In that
1565  * case we insert a RelabelType to clearly mark that result's typmod is
1566  * not same as input. We never need coerce_type_typmod.
1567  */
1568  if (l_colvar->vartype != outcoltype)
1569  l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
1570  outcoltype, outcoltypmod,
1572  else if (l_colvar->vartypmod != outcoltypmod)
1573  l_node = (Node *) makeRelabelType((Expr *) l_colvar,
1574  outcoltype, outcoltypmod,
1575  InvalidOid, /* fixed below */
1577  else
1578  l_node = (Node *) l_colvar;
1579 
1580  if (r_colvar->vartype != outcoltype)
1581  r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
1582  outcoltype, outcoltypmod,
1584  else if (r_colvar->vartypmod != outcoltypmod)
1585  r_node = (Node *) makeRelabelType((Expr *) r_colvar,
1586  outcoltype, outcoltypmod,
1587  InvalidOid, /* fixed below */
1589  else
1590  r_node = (Node *) r_colvar;
1591 
1592  /*
1593  * Choose what to emit
1594  */
1595  switch (jointype)
1596  {
1597  case JOIN_INNER:
1598 
1599  /*
1600  * We can use either var; prefer non-coerced one if available.
1601  */
1602  if (IsA(l_node, Var))
1603  res_node = l_node;
1604  else if (IsA(r_node, Var))
1605  res_node = r_node;
1606  else
1607  res_node = l_node;
1608  break;
1609  case JOIN_LEFT:
1610  /* Always use left var */
1611  res_node = l_node;
1612  break;
1613  case JOIN_RIGHT:
1614  /* Always use right var */
1615  res_node = r_node;
1616  break;
1617  case JOIN_FULL:
1618  {
1619  /*
1620  * Here we must build a COALESCE expression to ensure that the
1621  * join output is non-null if either input is.
1622  */
1624 
1625  c->coalescetype = outcoltype;
1626  /* coalescecollid will get set below */
1627  c->args = list_make2(l_node, r_node);
1628  c->location = -1;
1629  res_node = (Node *) c;
1630  break;
1631  }
1632  default:
1633  elog(ERROR, "unrecognized join type: %d", (int) jointype);
1634  res_node = NULL; /* keep compiler quiet */
1635  break;
1636  }
1637 
1638  /*
1639  * Apply assign_expr_collations to fix up the collation info in the
1640  * coercion and CoalesceExpr nodes, if we made any. This must be done now
1641  * so that the join node's alias vars show correct collation info.
1642  */
1643  assign_expr_collations(pstate, res_node);
1644 
1645  return res_node;
1646 }
#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:1046
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:1044
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 1769 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().

1770 {
1771  if (contain_vars_of_level(n, 0))
1772  {
1773  ereport(ERROR,
1774  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1775  /* translator: %s is name of a SQL construct, eg LIMIT */
1776  errmsg("argument of %s must not contain variables",
1777  constructName),
1778  parser_errposition(pstate,
1779  locate_var_of_level(n, 0))));
1780  }
1781 }
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 1794 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().

1796 {
1797  switch (exprKind)
1798  {
1799  case EXPR_KIND_GROUP_BY:
1800  /* reject aggregates and window functions */
1801  if (pstate->p_hasAggs &&
1802  contain_aggs_of_level((Node *) tle->expr, 0))
1803  ereport(ERROR,
1804  (errcode(ERRCODE_GROUPING_ERROR),
1805  /* translator: %s is name of a SQL construct, eg GROUP BY */
1806  errmsg("aggregate functions are not allowed in %s",
1807  ParseExprKindName(exprKind)),
1808  parser_errposition(pstate,
1809  locate_agg_of_level((Node *) tle->expr, 0))));
1810  if (pstate->p_hasWindowFuncs &&
1811  contain_windowfuncs((Node *) tle->expr))
1812  ereport(ERROR,
1813  (errcode(ERRCODE_WINDOWING_ERROR),
1814  /* translator: %s is name of a SQL construct, eg GROUP BY */
1815  errmsg("window functions are not allowed in %s",
1816  ParseExprKindName(exprKind)),
1817  parser_errposition(pstate,
1818  locate_windowfunc((Node *) tle->expr))));
1819  break;
1820  case EXPR_KIND_ORDER_BY:
1821  /* no extra checks needed */
1822  break;
1823  case EXPR_KIND_DISTINCT_ON:
1824  /* no extra checks needed */
1825  break;
1826  default:
1827  elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
1828  break;
1829  }
1830 }
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
bool p_hasAggs
Definition: parse_node.h:195
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3352
bool p_hasWindowFuncs
Definition: parse_node.h:196
#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:1367
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:198
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
static const struct cname cnames[]
Definition: pg_list.h:45
static TargetEntry * findTargetlistEntrySQL92 ( ParseState pstate,
Node node,
List **  tlist,
ParseExprKind  exprKind 
)
static

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

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

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

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

2019 {
2020  TargetEntry *target_result;
2021  ListCell *tl;
2022  Node *expr;
2023 
2024  /*
2025  * Convert the untransformed node to a transformed expression, and search
2026  * for a match in the tlist. NOTE: it doesn't really matter whether there
2027  * is more than one match. Also, we are willing to match an existing
2028  * resjunk target here, though the SQL92 cases above must ignore resjunk
2029  * targets.
2030  */
2031  expr = transformExpr(pstate, node, exprKind);
2032 
2033  foreach(tl, *tlist)
2034  {
2035  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2036  Node *texpr;
2037 
2038  /*
2039  * Ignore any implicit cast on the existing tlist expression.
2040  *
2041  * This essentially allows the ORDER/GROUP/etc item to adopt the same
2042  * datatype previously selected for a textually-equivalent tlist item.
2043  * There can't be any implicit cast at top level in an ordinary SELECT
2044  * tlist at this stage, but the case does arise with ORDER BY in an
2045  * aggregate function.
2046  */
2047  texpr = strip_implicit_coercions((Node *) tle->expr);
2048 
2049  if (equal(expr, texpr))
2050  return tle;
2051  }
2052 
2053  /*
2054  * If no matches, construct a new target entry which is appended to the
2055  * end of the target list. This target is given resjunk = TRUE so that it
2056  * will not be projected into the final tuple.
2057  */
2058  target_result = transformTargetEntry(pstate, node, expr, exprKind,
2059  NULL, true);
2060 
2061  *tlist = lappend(*tlist, target_result);
2062 
2063  return target_result;
2064 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2961
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
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:1367
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 3453 of file parse_clause.c.

References lfirst, WindowClause::name, and NULL.

Referenced by transformWindowDefinitions().

3454 {
3455  ListCell *l;
3456 
3457  foreach(l, wclist)
3458  {
3459  WindowClause *wc = (WindowClause *) lfirst(l);
3460 
3461  if (wc->name && strcmp(wc->name, name) == 0)
3462  return wc;
3463  }
3464 
3465  return NULL;
3466 }
#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 2103 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().

2104 {
2105  /* just in case of pathological input */
2107 
2108  if (expr == (Node *) NIL)
2109  return (Node *) NIL;
2110 
2111  switch (expr->type)
2112  {
2113  case T_RowExpr:
2114  {
2115  RowExpr *r = (RowExpr *) expr;
2116 
2117  if (r->row_format == COERCE_IMPLICIT_CAST)
2118  return flatten_grouping_sets((Node *) r->args,
2119  false, NULL);
2120  }
2121  break;
2122  case T_GroupingSet:
2123  {
2124  GroupingSet *gset = (GroupingSet *) expr;
2125  ListCell *l2;
2126  List *result_set = NIL;
2127 
2128  if (hasGroupingSets)
2129  *hasGroupingSets = true;
2130 
2131  /*
2132  * at the top level, we skip over all empty grouping sets; the
2133  * caller can supply the canonical GROUP BY () if nothing is
2134  * left.
2135  */
2136 
2137  if (toplevel && gset->kind == GROUPING_SET_EMPTY)
2138  return (Node *) NIL;
2139 
2140  foreach(l2, gset->content)
2141  {
2142  Node *n1 = lfirst(l2);
2143  Node *n2 = flatten_grouping_sets(n1, false, NULL);
2144 
2145  if (IsA(n1, GroupingSet) &&
2146  ((GroupingSet *) n1)->kind == GROUPING_SET_SETS)
2147  {
2148  result_set = list_concat(result_set, (List *) n2);
2149  }
2150  else
2151  result_set = lappend(result_set, n2);
2152  }
2153 
2154  /*
2155  * At top level, keep the grouping set node; but if we're in a
2156  * nested grouping set, then we need to concat the flattened
2157  * result into the outer list if it's simply nested.
2158  */
2159 
2160  if (toplevel || (gset->kind != GROUPING_SET_SETS))
2161  {
2162  return (Node *) makeGroupingSet(gset->kind, result_set, gset->location);
2163  }
2164  else
2165  return (Node *) result_set;
2166  }
2167  case T_List:
2168  {
2169  List *result = NIL;
2170  ListCell *l;
2171 
2172  foreach(l, (List *) expr)
2173  {
2174  Node *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets);
2175 
2176  if (n != (Node *) NIL)
2177  {
2178  if (IsA(n, List))
2179  result = list_concat(result, (List *) n);
2180  else
2181  result = lappend(result, n);
2182  }
2183  }
2184 
2185  return (Node *) result;
2186  }
2187  default:
2188  break;
2189  }
2190 
2191  return expr;
2192 }
#define NIL
Definition: pg_list.h:69
List * args
Definition: primnodes.h:985
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
List * content
Definition: parsenodes.h:1226
Definition: nodes.h:509
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1618
GroupingSetKind kind
Definition: parsenodes.h:1225
NodeTag type
Definition: nodes.h:511
void check_stack_depth(void)
Definition: postgres.c:3102
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:604
CoercionForm row_format
Definition: primnodes.h:997
Definition: pg_list.h:45
static int get_matching_location ( int  sortgroupref,
List sortgrouprefs,
List exprs 
)
static

Definition at line 2974 of file parse_clause.c.

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

Referenced by transformDistinctOnClause().

2975 {
2976  ListCell *lcs;
2977  ListCell *lce;
2978 
2979  forboth(lcs, sortgrouprefs, lce, exprs)
2980  {
2981  if (lfirst_int(lcs) == sortgroupref)
2982  return exprLocation((Node *) lfirst(lce));
2983  }
2984  /* if no match, caller blew it */
2985  elog(ERROR, "get_matching_location: no matching sortgroupref");
2986  return -1; /* keep compiler quiet */
2987 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1213
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 1051 of file parse_clause.c.

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

Referenced by setTargetTable(), and transformFromClauseItem().

1052 {
1053 
1054  CommonTableExpr *cte;
1055  Index levelsup;
1056  RangeTblEntry *rte = NULL;
1057 
1058  cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
1059  if (cte)
1060  rte = transformCTEReference(pstate, rv, cte, levelsup);
1061  if (!rte && scanNameSpaceForENR(pstate, rv->relname))
1062  rte = transformENRReference(pstate, rv);
1063 
1064  return rte;
1065 }
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:452
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 1653 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().

1655 {
1656  ParseNamespaceItem *nsitem;
1657 
1658  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1659  nsitem->p_rte = rte;
1660  nsitem->p_rel_visible = rel_visible;
1661  nsitem->p_cols_visible = cols_visible;
1662  nsitem->p_lateral_only = lateral_only;
1663  nsitem->p_lateral_ok = lateral_ok;
1664  return nsitem;
1665 }
RangeTblEntry * p_rte
Definition: parse_node.h:241
void * palloc(Size size)
Definition: mcxt.c:849
static List * resolve_unique_index_expr ( ParseState pstate,
InferClause infer,
Relation  heapRel 
)
static

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

3001 {
3002  List *result = NIL;
3003  ListCell *l;
3004 
3005  foreach(l, infer->indexElems)
3006  {
3007  IndexElem *ielem = (IndexElem *) lfirst(l);
3009  Node *parse;
3010 
3011  /*
3012  * Raw grammar re-uses CREATE INDEX infrastructure for unique index
3013  * inference clause, and so will accept opclasses by name and so on.
3014  *
3015  * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
3016  * LAST ordering, since those are not significant for inference
3017  * purposes (any unique index matching the inference specification in
3018  * other regards is accepted indifferently). Actively reject this as
3019  * wrong-headed.
3020  */
3021  if (ielem->ordering != SORTBY_DEFAULT)
3022  ereport(ERROR,
3023  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3024  errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
3025  parser_errposition(pstate,
3026  exprLocation((Node *) infer))));
3027  if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
3028  ereport(ERROR,
3029  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3030  errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
3031  parser_errposition(pstate,
3032  exprLocation((Node *) infer))));
3033 
3034  if (!ielem->expr)
3035  {
3036  /* Simple index attribute */
3037  ColumnRef *n;
3038 
3039  /*
3040  * Grammar won't have built raw expression for us in event of
3041  * plain column reference. Create one directly, and perform
3042  * expression transformation. Planner expects this, and performs
3043  * its own normalization for the purposes of matching against
3044  * pg_index.
3045  */
3046  n = makeNode(ColumnRef);
3047  n->fields = list_make1(makeString(ielem->name));
3048  /* Location is approximately that of inference specification */
3049  n->location = infer->location;
3050  parse = (Node *) n;
3051  }
3052  else
3053  {
3054  /* Do parse transformation of the raw expression */
3055  parse = (Node *) ielem->expr;
3056  }
3057 
3058  /*
3059  * transformExpr() should have already rejected subqueries,
3060  * aggregates, and window functions, based on the EXPR_KIND_ for an
3061  * index expression. Expressions returning sets won't have been
3062  * rejected, but don't bother doing so here; there should be no
3063  * available expression unique index to match any such expression
3064  * against anyway.
3065  */
3066  pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
3067 
3068  /* Perform lookup of collation and operator class as required */
3069  if (!ielem->collation)
3070  pInfer->infercollid = InvalidOid;
3071  else
3072  pInfer->infercollid = LookupCollation(pstate, ielem->collation,
3073  exprLocation(pInfer->expr));
3074 
3075  if (!ielem->opclass)
3076  pInfer->inferopclass = InvalidOid;
3077  else
3079  ielem->opclass, false);
3080 
3081  result = lappend(result, pInfer);
3082  }
3083 
3084  return result;
3085 }
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:1213
#define BTREE_AM_OID
Definition: pg_am.h:70
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
List * indexElems
Definition: parsenodes.h:1303
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
Oid get_opclass_oid(Oid amID, List *opclassname, bool missing_ok)
Definition: opclasscmds.c:220
int location
Definition: parsenodes.h:236
#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:235
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 1672 of file parse_clause.c.

References lfirst, and ParseNamespaceItem::p_cols_visible.

Referenced by transformFromClauseItem().

1673 {
1674  ListCell *lc;
1675 
1676  foreach(lc, namespace)
1677  {
1678  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1679 
1680  nsitem->p_cols_visible = cols_visible;
1681  }
1682 }
#define lfirst(lc)
Definition: pg_list.h:106
static void setNamespaceLateralState ( List namespace,
bool  lateral_only,
bool  lateral_ok 
)
static

Definition at line 1689 of file parse_clause.c.

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

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

1690 {
1691  ListCell *lc;
1692 
1693  foreach(lc, namespace)
1694  {
1695  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
1696 
1697  nsitem->p_lateral_only = lateral_only;
1698  nsitem->p_lateral_ok = lateral_ok;
1699  }
1700 }
#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:1019
#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:180
static RangeTblEntry * getRTEForSpecialRelationTypes(ParseState *pstate, RangeVar *rv)
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
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:179
Alias * alias
Definition: primnodes.h:72
List * p_rtable
Definition: parse_node.h:169
bool targetIsInSortList ( TargetEntry tle,
Oid  sortop,
List sortList 
)

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

3427 {
3428  Index ref = tle->ressortgroupref;
3429  ListCell *l;
3430 
3431  /* no need to scan list if tle has no marker */
3432  if (ref == 0)
3433  return false;
3434 
3435  foreach(l, sortList)
3436  {
3437  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3438 
3439  if (scl->tleSortGroupRef == ref &&
3440  (sortop == InvalidOid ||
3441  sortop == scl->sortop ||
3442  sortop == get_commutator(scl->sortop)))
3443  return true;
3444  }
3445  return false;
3446 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1313
Index tleSortGroupRef
Definition: parsenodes.h:1156
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:1370
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 2783 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().

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

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

2869 {
2870  List *result = NIL;
2871  List *sortgrouprefs = NIL;
2872  bool skipped_sortitem;
2873  ListCell *lc;
2874  ListCell *lc2;
2875 
2876  /*
2877  * Add all the DISTINCT ON expressions to the tlist (if not already
2878  * present, they are added as resjunk items). Assign sortgroupref numbers
2879  * to them, and make a list of these numbers. (NB: we rely below on the
2880  * sortgrouprefs list being one-for-one with the original distinctlist.
2881  * Also notice that we could have duplicate DISTINCT ON expressions and
2882  * hence duplicate entries in sortgrouprefs.)
2883  */
2884  foreach(lc, distinctlist)
2885  {
2886  Node *dexpr = (Node *) lfirst(lc);
2887  int sortgroupref;
2888  TargetEntry *tle;
2889 
2890  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
2892  sortgroupref = assignSortGroupRef(tle, *targetlist);
2893  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
2894  }
2895 
2896  /*
2897  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
2898  * semantics from ORDER BY items that match DISTINCT ON items, and also
2899  * adopt their column sort order. We insist that the distinctClause and
2900  * sortClause match, so throw error if we find the need to add any more
2901  * distinctClause items after we've skipped an ORDER BY item that wasn't
2902  * in DISTINCT ON.
2903  */
2904  skipped_sortitem = false;
2905  foreach(lc, sortClause)
2906  {
2907  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
2908 
2909  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
2910  {
2911  if (skipped_sortitem)
2912  ereport(ERROR,
2913  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2914  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2915  parser_errposition(pstate,
2917  sortgrouprefs,
2918  distinctlist))));
2919  else
2920  result = lappend(result, copyObject(scl));
2921  }
2922  else
2923  skipped_sortitem = true;
2924  }
2925 
2926  /*
2927  * Now add any remaining DISTINCT ON items, using default sort/group
2928  * semantics for their data types. (Note: this is pretty questionable; if
2929  * the ORDER BY list doesn't include all the DISTINCT ON items and more
2930  * besides, you certainly aren't using DISTINCT ON in the intended way,
2931  * and you probably aren't going to get consistent results. It might be
2932  * better to throw an error or warning here. But historically we've
2933  * allowed it, so keep doing so.)
2934  */
2935  forboth(lc, distinctlist, lc2, sortgrouprefs)
2936  {
2937  Node *dexpr = (Node *) lfirst(lc);
2938  int sortgroupref = lfirst_int(lc2);
2939  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
2940 
2941  if (targetIsInSortList(tle, InvalidOid, result))
2942  continue; /* already in list (with some semantics) */
2943  if (skipped_sortitem)
2944  ereport(ERROR,
2945  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2946  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2947  parser_errposition(pstate, exprLocation(dexpr))));
2948  result = addTargetToGroupList(pstate, tle,
2949  result, *targetlist,
2950  exprLocation(dexpr));
2951  }
2952 
2953  /*
2954  * An empty result list is impossible here because of grammar
2955  * restrictions.
2956  */
2957  Assert(result != NIL);
2958 
2959  return result;
2960 }
#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:1213
Index tleSortGroupRef
Definition: parsenodes.h:1156
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
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:675
#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:621
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 3473 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().

3474 {
3475  const char *constructName = NULL;
3476  Node *node;
3477 
3478  /* Quick exit if no offset expression */
3479  if (clause == NULL)
3480  return NULL;
3481 
3482  if (frameOptions & FRAMEOPTION_ROWS)
3483  {
3484  /* Transform the raw expression tree */
3485  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_ROWS);
3486 
3487  /*
3488  * Like LIMIT clause, simply coerce to int8
3489  */
3490  constructName = "ROWS";
3491  node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
3492  }
3493  else if (frameOptions & FRAMEOPTION_RANGE)
3494  {
3495  /* Transform the raw expression tree */
3496  node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_RANGE);
3497 
3498  /*
3499  * this needs a lot of thought to decide how to support in the context
3500  * of Postgres' extensible datatype framework
3501  */
3502  constructName = "RANGE";
3503  /* error was already thrown by gram.y, this is just a backstop */
3504  elog(ERROR, "window frame with value offset is not implemented");
3505  }
3506  else
3507  {
3508  Assert(false);
3509  node = NULL;
3510  }
3511 
3512  /* Disallow variables in frame offsets */
3513  checkExprIsVarFree(pstate, node, constructName);
3514 
3515  return node;
3516 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
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:506
#define Assert(condition)
Definition: c.h:675
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:507
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:173
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:171
Definition: pg_list.h:45
static Node * transformFromClauseItem ( ParseState pstate,
Node n,
RangeTblEntry **  top_rte,
int *  top_rti,
List **  namespace 
)
static

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

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

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

2482 {
2483  List *result = NIL;
2484  List *flat_grouplist;
2485  List *gsets = NIL;
2486  ListCell *gl;
2487  bool hasGroupingSets = false;
2488  Bitmapset *seen_local = NULL;
2489 
2490  /*
2491  * Recursively flatten implicit RowExprs. (Technically this is only needed
2492  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2493  * anyway.)
2494  */
2495  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2496  true,
2497  &hasGroupingSets);
2498 
2499  /*
2500  * If the list is now empty, but hasGroupingSets is true, it's because we
2501  * elided redundant empty grouping sets. Restore a single empty grouping
2502  * set to leave a canonical form: GROUP BY ()
2503  */
2504 
2505  if (flat_grouplist == NIL && hasGroupingSets)
2506  {
2508  NIL,
2509  exprLocation((Node *) grouplist)));
2510  }
2511 
2512  foreach(gl, flat_grouplist)
2513  {
2514  Node *gexpr = (Node *) lfirst(gl);
2515 
2516  if (IsA(gexpr, GroupingSet))
2517  {
2518  GroupingSet *gset = (GroupingSet *) gexpr;
2519 
2520  switch (gset->kind)
2521  {
2522  case GROUPING_SET_EMPTY:
2523  gsets = lappend(gsets, gset);
2524  break;
2525  case GROUPING_SET_SIMPLE:
2526  /* can't happen */
2527  Assert(false);
2528  break;
2529  case GROUPING_SET_SETS:
2530  case GROUPING_SET_CUBE:
2531  case GROUPING_SET_ROLLUP:
2532  gsets = lappend(gsets,
2533  transformGroupingSet(&result,
2534  pstate, gset,
2535  targetlist, sortClause,
2536  exprKind, useSQL99, true));
2537  break;
2538  }
2539  }
2540  else
2541  {
2542  Index ref = transformGroupClauseExpr(&result, seen_local,
2543  pstate, gexpr,
2544  targetlist, sortClause,
2545  exprKind, useSQL99, true);
2546 
2547  if (ref > 0)
2548  {
2549  seen_local = bms_add_member(seen_local, ref);
2550  if (hasGroupingSets)
2551  gsets = lappend(gsets,
2553  list_make1_int(ref),
2554  exprLocation(gexpr)));
2555  }
2556  }
2557  }
2558 
2559  /* parser should prevent this */
2560  Assert(gsets == NIL || groupingSets != NULL);
2561 
2562  if (groupingSets)
2563  *groupingSets = gsets;
2564 
2565  return result;
2566 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1213
Definition: nodes.h:509
return result
Definition: formatting.c:1618
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
GroupingSetKind kind
Definition: parsenodes.h:1225
#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:675
#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:604
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 2214 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().

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

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

Referenced by transformGroupingSet().

2326 {
2327  Bitmapset *seen_local = NULL;
2328  List *result = NIL;
2329  ListCell *gl;
2330 
2331  foreach(gl, list)
2332  {
2333  Node *gexpr = (Node *) lfirst(gl);
2334 
2335  Index ref = transformGroupClauseExpr(flatresult,
2336  seen_local,
2337  pstate,
2338  gexpr,
2339  targetlist,
2340  sortClause,
2341  exprKind,
2342  useSQL99,
2343  toplevel);
2344 
2345  if (ref > 0)
2346  {
2347  seen_local = bms_add_member(seen_local, ref);
2348  result = lappend_int(result, ref);
2349  }
2350  }
2351 
2352  return result;
2353 }
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:509
return result
Definition: formatting.c:1618
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 2375 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().

2379 {
2380  ListCell *gl;
2381  List *content = NIL;
2382 
2383  Assert(toplevel || gset->kind != GROUPING_SET_SETS);
2384 
2385  foreach(gl, gset->content)
2386  {
2387  Node *n = lfirst(gl);
2388 
2389  if (IsA(n, List))
2390  {
2391  List *l = transformGroupClauseList(flatresult,
2392  pstate, (List *) n,
2393  targetlist, sortClause,
2394  exprKind, useSQL99, false);
2395 
2396  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2397  l,
2398  exprLocation(n)));
2399  }
2400  else if (IsA(n, GroupingSet))
2401  {
2402  GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
2403 
2404  content = lappend(content, transformGroupingSet(flatresult,
2405  pstate, gset2,
2406  targetlist, sortClause,
2407  exprKind, useSQL99, false));
2408  }
2409  else
2410  {
2411  Index ref = transformGroupClauseExpr(flatresult,
2412  NULL,
2413  pstate,
2414  n,
2415  targetlist,
2416  sortClause,
2417  exprKind,
2418  useSQL99,
2419  false);
2420 
2421  content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
2422  list_make1_int(ref),
2423  exprLocation(n)));
2424  }
2425  }
2426 
2427  /* Arbitrarily cap the size of CUBE, which has exponential growth */
2428  if (gset->kind == GROUPING_SET_CUBE)
2429  {
2430  if (list_length(content) > 12)
2431  ereport(ERROR,
2432  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2433  errmsg("CUBE is limited to 12 elements"),
2434  parser_errposition(pstate, gset->location)));
2435  }
2436 
2437  return (Node *) makeGroupingSet(gset->kind, content, gset->location);
2438 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
List * content
Definition: parsenodes.h:1226
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1213
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:1225
#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:675
#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:604
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:1618
List * p_namespace
Definition: parse_node.h:173
static void setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
Node * quals
Definition: primnodes.h:1453
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:147
Definition: nodes.h:509
return result
Definition: formatting.c:1618
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:621
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 1738 of file parse_clause.c.

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

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

1740 {
1741  Node *qual;
1742 
1743  if (clause == NULL)
1744  return NULL;
1745 
1746  qual = transformExpr(pstate, clause, exprKind);
1747 
1748  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1749 
1750  /* LIMIT can't refer to any variables of the current query */
1751  checkExprIsVarFree(pstate, qual, constructName);
1752 
1753  return qual;
1754 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
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 3096 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().

3100 {
3101  InferClause *infer = onConflictClause->infer;
3102 
3103  *arbiterExpr = NIL;
3104  *arbiterWhere = NULL;
3105  *constraint = InvalidOid;
3106 
3107  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3108  ereport(ERROR,
3109  (errcode(ERRCODE_SYNTAX_ERROR),
3110  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3111  errhint("For example, ON CONFLICT (column_name)."),
3112  parser_errposition(pstate,
3113  exprLocation((Node *) onConflictClause))));
3114 
3115  /*
3116  * To simplify certain aspects of its design, speculative insertion into
3117  * system catalogs is disallowed
3118  */
3119  if (IsCatalogRelation(pstate->p_target_relation))
3120  ereport(ERROR,
3121  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3122  errmsg("ON CONFLICT is not supported with system catalog tables"),
3123  parser_errposition(pstate,
3124  exprLocation((Node *) onConflictClause))));
3125 
3126  /* Same applies to table used by logical decoding as catalog table */
3128  ereport(ERROR,
3129  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3130  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3132  parser_errposition(pstate,
3133  exprLocation((Node *) onConflictClause))));
3134 
3135  /* ON CONFLICT DO NOTHING does not require an inference clause */
3136  if (infer)
3137  {
3138  List *save_namespace;
3139 
3140  /*
3141  * While we process the arbiter expressions, accept only non-qualified
3142  * references to the target table. Hide any other relations.
3143  */
3144  save_namespace = pstate->p_namespace;
3145  pstate->p_namespace = NIL;
3146  addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
3147  false, false, true);
3148 
3149  if (infer->indexElems)
3150  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3151  pstate->p_target_relation);
3152 
3153  /*
3154  * Handling inference WHERE clause (for partial unique index
3155  * inference)
3156  */
3157  if (infer->whereClause)
3158  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3160 
3161  pstate->p_namespace = save_namespace;
3162 
3163  if (infer->conname)
3165  infer->conname, false);
3166  }
3167 
3168  /*
3169  * It's convenient to form a list of expressions based on the
3170  * representation used by CREATE INDEX, since the same restrictions are
3171  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3172  * primnode representation is used for inference elements, and so
3173  * assign_query_collations() can be trusted to do the right thing with the
3174  * post parse analysis query tree inference clause representation.
3175  */
3176 }
#define NIL
Definition: pg_list.h:69
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:91
int errhint(const char *fmt,...)
Definition: elog.c:987
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1213
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:147
List * indexElems
Definition: parsenodes.h:1303
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:173
char * conname
Definition: parsenodes.h:1305
#define RelationGetRelationName(relation)
Definition: rel.h:437
#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:180
InferClause * infer
Definition: parsenodes.h:1319
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:316
#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:1304
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation p_target_relation
Definition: parse_node.h:179
OnConflictAction action
Definition: parsenodes.h:1318
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:417
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_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 
576  /* Disassemble the function-call/column-def-list pairs */
577  Assert(list_length(pair) == 2);
578  fexpr = (Node *) linitial(pair);
579  coldeflist = (List *) lsecond(pair);
580 
581  /*
582  * If we find a function call unnest() with more than one argument and
583  * no special decoration, transform it into separate unnest() calls on
584  * each argument. This is a kluge, for sure, but it's less nasty than
585  * other ways of implementing the SQL-standard UNNEST() syntax.
586  *
587  * If there is any decoration (including a coldeflist), we don't
588  * transform, which probably means a no-such-function error later. We
589  * could alternatively throw an error right now, but that doesn't seem
590  * tremendously helpful. If someone is using any such decoration,
591  * then they're not using the SQL-standard syntax, and they're more
592  * likely expecting an un-tweaked function call.
593  *
594  * Note: the transformation changes a non-schema-qualified unnest()
595  * function name into schema-qualified pg_catalog.unnest(). This
596  * choice is also a bit debatable, but it seems reasonable to force
597  * use of built-in unnest() when we make this transformation.
598  */
599  if (IsA(fexpr, FuncCall))
600  {
601  FuncCall *fc = (FuncCall *) fexpr;
602 
603  if (list_length(fc->funcname) == 1 &&
604  strcmp(strVal(linitial(fc->funcname)), "unnest") == 0 &&
605  list_length(fc->args) > 1 &&
606  fc->agg_order == NIL &&
607  fc->agg_filter == NULL &&
608  !fc->agg_star &&
609  !fc->agg_distinct &&
610  !fc->func_variadic &&
611  fc->over == NULL &&
612  coldeflist == NIL)
613  {
614  ListCell *lc;
615 
616  foreach(lc, fc->args)
617  {
618  Node *arg = (Node *) lfirst(lc);
619  FuncCall *newfc;
620 
621  newfc = makeFuncCall(SystemFuncName("unnest"),
622  list_make1(arg),
623  fc->location);
624 
625  funcexprs = lappend(funcexprs,
626  transformExpr(pstate, (Node *) newfc,
628 
629  funcnames = lappend(funcnames,
630  FigureColname((Node *) newfc));
631 
632  /* coldeflist is empty, so no error is possible */
633 
634  coldeflists = lappend(coldeflists, coldeflist);
635  }
636  continue; /* done with this function item */
637  }
638  }
639 
640  /* normal case ... */
641  funcexprs = lappend(funcexprs,
642  transformExpr(pstate, fexpr,
644 
645  funcnames = lappend(funcnames,
646  FigureColname(fexpr));
647 
648  if (coldeflist && r->coldeflist)
649  ereport(ERROR,
650  (errcode(ERRCODE_SYNTAX_ERROR),
651  errmsg("multiple column definition lists are not allowed for the same function"),
652  parser_errposition(pstate,
653  exprLocation((Node *) r->coldeflist))));
654 
655  coldeflists = lappend(coldeflists, coldeflist);
656  }
657 
658  pstate->p_lateral_active = false;
659 
660  /*
661  * We must assign collations now so that the RTE exposes correct collation
662  * info for Vars created from it.
663  */
664  assign_list_collations(pstate, funcexprs);
665 
666  /*
667  * Install the top-level coldeflist if there was one (we already checked
668  * that there was no conflicting per-function coldeflist).
669  *
670  * We only allow this when there's a single function (even after UNNEST
671  * expansion) and no WITH ORDINALITY. The reason for the latter
672  * restriction is that it's not real clear whether the ordinality column
673  * should be in the coldeflist, and users are too likely to make mistakes
674  * in one direction or the other. Putting the coldeflist inside ROWS
675  * FROM() is much clearer in this case.
676  */
677  if (r->coldeflist)
678  {
679  if (list_length(funcexprs) != 1)
680  {
681  if (r->is_rowsfrom)
682  ereport(ERROR,
683  (errcode(ERRCODE_SYNTAX_ERROR),
684  errmsg("ROWS FROM() with multiple functions cannot have a column definition list"),
685  errhint("Put a separate column definition list for each function inside ROWS FROM()."),
686  parser_errposition(pstate,
687  exprLocation((Node *) r->coldeflist))));
688  else
689  ereport(ERROR,
690  (errcode(ERRCODE_SYNTAX_ERROR),
691  errmsg("UNNEST() with multiple arguments cannot have a column definition list"),
692  errhint("Use separate UNNEST() calls inside ROWS FROM(), and attach a column definition list to each one."),
693  parser_errposition(pstate,
694  exprLocation((Node *) r->coldeflist))));
695  }
696  if (r->ordinality)
697  ereport(ERROR,
698  (errcode(ERRCODE_SYNTAX_ERROR),
699  errmsg("WITH ORDINALITY cannot be used with a column definition list"),
700  errhint("Put the column definition list inside ROWS FROM()."),
701  parser_errposition(pstate,
702  exprLocation((Node *) r->coldeflist))));
703 
704  coldeflists = list_make1(r->coldeflist);
705  }
706 
707  /*
708  * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
709  * there are any lateral cross-references in it.
710  */
711  is_lateral = r->lateral || contain_vars_of_level((Node *) funcexprs, 0);
712 
713  /*
714  * OK, build an RTE for the function.
715  */
716  rte = addRangeTableEntryForFunction(pstate,
717  funcnames, funcexprs, coldeflists,
718  r, is_lateral, true);
719 
720  return rte;
721 }
#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:1213
Node * agg_filter
Definition: parsenodes.h:353
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
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:359
List * agg_order
Definition: parsenodes.h:352
#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:358
List * coldeflist
Definition: parsenodes.h:562
char * FigureColname(Node *node)
void assign_list_collations(ParseState *pstate, List *exprs)
List * functions
Definition: parsenodes.h:560
#define ereport(elevel, rest)
Definition: elog.h:122
bool is_rowsfrom
Definition: parsenodes.h:559
List * lappend(List *list, void *datum)
Definition: list.c:128
bool func_variadic
Definition: parsenodes.h:357
FuncCall * makeFuncCall(List *name, List *args, int location)
Definition: makefuncs.c:582
bool p_lateral_active
Definition: parse_node.h:175
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:675
#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:351
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:350
bool agg_distinct
Definition: parsenodes.h:356
bool agg_star
Definition: parsenodes.h:355
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:536
#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:183
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:175
CmdType commandType
Definition: parsenodes.h:110
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
char * aliasname
Definition: primnodes.h:42
Alias * alias
Definition: parsenodes.h:537
bool isLockedRefname(ParseState *pstate, const char *refname)
#define elog
Definition: elog.h:219
static RangeTblEntry * transformRangeTableFunc ( ParseState pstate,
RangeTableFunc t 
)
static

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

733 {
735  const char *constructName;
736  Oid docType;
737  RangeTblEntry *rte;
738  bool is_lateral;
739  ListCell *col;
740  char **names;
741  int colno;
742 
743  /* Currently only XMLTABLE is supported */
744  constructName = "XMLTABLE";
745  docType = XMLOID;
746 
747  /*
748  * We make lateral_only names of this level visible, whether or not the
749  * RangeTableFunc is explicitly marked LATERAL. This is needed for SQL
750  * spec compliance and seems useful on convenience grounds for all
751  * functions in FROM.
752  *
753  * (LATERAL can't nest within a single pstate level, so we don't need
754  * save/restore logic here.)
755  */
756  Assert(!pstate->p_lateral_active);
757  pstate->p_lateral_active = true;
758 
759  /* Transform and apply typecast to the row-generating expression ... */
760  Assert(rtf->rowexpr != NULL);
761  tf->rowexpr = coerce_to_specific_type(pstate,
762  transformExpr(pstate, rtf->rowexpr, EXPR_KIND_FROM_FUNCTION),
763  TEXTOID,
764  constructName);
765  assign_expr_collations(pstate, tf->rowexpr);
766 
767  /* ... and to the document itself */
768  Assert(rtf->docexpr != NULL);
769  tf->docexpr = coerce_to_specific_type(pstate,
770  transformExpr(pstate, rtf->docexpr, EXPR_KIND_FROM_FUNCTION),
771  docType,
772  constructName);
773  assign_expr_collations(pstate, tf->docexpr);
774 
775  /* undef ordinality column number */
776  tf->ordinalitycol = -1;
777 
778 
779  names = palloc(sizeof(char *) * list_length(rtf->columns));
780 
781  colno = 0;
782  foreach(col, rtf->columns)
783  {
784  RangeTableFuncCol *rawc = (RangeTableFuncCol *) lfirst(col);
785  Oid typid;
786  int32 typmod;
787  Node *colexpr;
788  Node *coldefexpr;
789  int j;
790 
791  tf->colnames = lappend(tf->colnames,
792  makeString(pstrdup(rawc->colname)));
793 
794  /*
795  * Determine the type and typmod for the new column. FOR
796  * ORDINALITY columns are INTEGER per spec; the others are
797  * user-specified.
798  */
799  if (rawc->for_ordinality)
800  {
801  if (tf->ordinalitycol != -1)
802  ereport(ERROR,
803  (errcode(ERRCODE_SYNTAX_ERROR),
804  errmsg("only one FOR ORDINALITY column is allowed"),
805  parser_errposition(pstate, rawc->location)));
806 
807  typid = INT4OID;
808  typmod = -1;
809  tf->ordinalitycol = colno;
810  }
811  else
812  {
813  if (rawc->typeName->setof)
814  ereport(ERROR,
815  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
816  errmsg("column \"%s\" cannot be declared SETOF",
817  rawc->colname),
818  parser_errposition(pstate, rawc->location)));
819 
820  typenameTypeIdAndMod(pstate, rawc->typeName,
821  &typid, &typmod);
822  }
823 
824  tf->coltypes = lappend_oid(tf->coltypes, typid);
825  tf->coltypmods = lappend_int(tf->coltypmods, typmod);
828 
829  /* Transform the PATH and DEFAULT expressions */
830  if (rawc->colexpr)
831  {
832  colexpr = coerce_to_specific_type(pstate,
833  transformExpr(pstate, rawc->colexpr,
835  TEXTOID,
836  constructName);
837  assign_expr_collations(pstate, colexpr);
838  }
839  else
840  colexpr = NULL;
841 
842  if (rawc->coldefexpr)
843  {
844  coldefexpr = coerce_to_specific_type_typmod(pstate,
845  transformExpr(pstate, rawc->coldefexpr,
847  typid, typmod,
848  constructName);
849  assign_expr_collations(pstate, coldefexpr);
850  }
851  else
852  coldefexpr = NULL;
853 
854  tf->colexprs = lappend(tf->colexprs, colexpr);
855  tf->coldefexprs = lappend(tf->coldefexprs, coldefexpr);
856 
857  if (rawc->is_not_null)
858  tf->notnulls = bms_add_member(tf->notnulls, colno);
859 
860  /* make sure column names are unique */
861  for (j = 0; j < colno; j++)
862  if (strcmp(names[j], rawc->colname) == 0)
863  ereport(ERROR,
864  (errcode(ERRCODE_SYNTAX_ERROR),
865  errmsg("column name \"%s\" is not unique",
866  rawc->colname),
867  parser_errposition(pstate, rawc->location)));
868  names[colno] = rawc->colname;
869 
870  colno++;
871  }
872  pfree(names);
873 
874  /* Namespaces, if any, also need to be transformed */
875  if (rtf->namespaces != NIL)
876  {
877  ListCell *ns;
878  ListCell *lc2;
879  List *ns_uris = NIL;
880  List *ns_names = NIL;
881  bool default_ns_seen = false;
882 
883  foreach(ns, rtf->namespaces)
884  {
885  ResTarget *r = (ResTarget *) lfirst(ns);
886  Node *ns_uri;
887 
888  Assert(IsA(r, ResTarget));
889  ns_uri = transformExpr(pstate, r->val, EXPR_KIND_FROM_FUNCTION);
890  ns_uri = coerce_to_specific_type(pstate, ns_uri,
891  TEXTOID, constructName);
892  assign_expr_collations(pstate, ns_uri);
893  ns_uris = lappend(ns_uris, ns_uri);
894 
895  /* Verify consistency of name list: no dupes, only one DEFAULT */
896  if (r->name != NULL)
897  {
898  foreach(lc2, ns_names)
899  {
900  char *name = strVal(lfirst(lc2));
901 
902  if (name == NULL)
903  continue;
904  if (strcmp(name, r->name) == 0)
905  ereport(ERROR,
906  (errcode(ERRCODE_SYNTAX_ERROR),
907  errmsg("namespace name \"%s\" is not unique",
908  name),
909  parser_errposition(pstate, r->location)));
910  }
911  }
912  else
913  {
914  if (default_ns_seen)
915  ereport(ERROR,
916  (errcode(ERRCODE_SYNTAX_ERROR),
917  errmsg("only one default namespace is allowed"),
918  parser_errposition(pstate, r->location)));
919  default_ns_seen = true;
920  }
921 
922  /* Note the string may be NULL */
923  ns_names = lappend(ns_names, makeString(r->name));
924  }
925 
926  tf->ns_uris = ns_uris;
927  tf->ns_names = ns_names;
928  }
929 
930  tf->location = rtf->location;
931 
932  pstate->p_lateral_active = false;
933 
934  /*
935  * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
936  * there are any lateral cross-references in it.
937  */
938  is_lateral = rtf->lateral || contain_vars_of_level((Node *) tf, 0);
939 
940  rte = addRangeTableEntryForTableFunc(pstate,
941  tf, rtf->alias, is_lateral, true);
942 
943  return rte;
944 }
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:442
List * colnames
Definition: primnodes.h:86
char * name
Definition: parsenodes.h:440
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:147
#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:443
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:211
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:591
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:74
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:175
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#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 953 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().

954 {
955  TableSampleClause *tablesample;
956  Oid handlerOid;
957  Oid funcargtypes[1];
958  TsmRoutine *tsm;
959  List *fargs;
960  ListCell *larg,
961  *ltyp;
962 
963  /*
964  * To validate the sample method name, look up the handler function, which
965  * has the same name, one dummy INTERNAL argument, and a result type of
966  * tsm_handler. (Note: tablesample method names are not schema-qualified
967  * in the SQL standard; but since they are just functions to us, we allow
968  * schema qualification to resolve any potential ambiguity.)
969  */
970  funcargtypes[0] = INTERNALOID;
971 
972  handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true);
973 
974  /* we want error to complain about no-such-method, not no-such-function */
975  if (!OidIsValid(handlerOid))
976  ereport(ERROR,
977  (errcode(ERRCODE_UNDEFINED_OBJECT),
978  errmsg("tablesample method %s does not exist",
979  NameListToString(rts->method)),
980  parser_errposition(pstate, rts->location)));
981 
982  /* check that handler has correct return type */
983  if (get_func_rettype(handlerOid) != TSM_HANDLEROID)
984  ereport(ERROR,
985  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
986  errmsg("function %s must return type %s",
987  NameListToString(rts->method), "tsm_handler"),
988  parser_errposition(pstate, rts->location)));
989 
990  /* OK, run the handler to get TsmRoutine, for argument type info */
991  tsm = GetTsmRoutine(handlerOid);
992 
993  tablesample = makeNode(TableSampleClause);
994  tablesample->tsmhandler = handlerOid;
995 
996  /* check user provided the expected number of arguments */
997  if (list_length(rts->args) != list_length(tsm->parameterTypes))
998  ereport(ERROR,
999  (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
1000  errmsg_plural("tablesample method %s requires %d argument, not %d",
1001  "tablesample method %s requires %d arguments, not %d",
1003  NameListToString(rts->method),
1005  list_length(rts->args)),
1006  parser_errposition(pstate, rts->location)));
1007 
1008  /*
1009  * Transform the arguments, typecasting them as needed. Note we must also
1010  * assign collations now, because assign_query_collations() doesn't
1011  * examine any substructure of RTEs.
1012  */
1013  fargs = NIL;
1014  forboth(larg, rts->args, ltyp, tsm->parameterTypes)
1015  {
1016  Node *arg = (Node *) lfirst(larg);
1017  Oid argtype = lfirst_oid(ltyp);
1018 
1019  arg = transformExpr(pstate, arg, EXPR_KIND_FROM_FUNCTION);
1020  arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE");
1021  assign_expr_collations(pstate, arg);
1022  fargs = lappend(fargs, arg);
1023  }
1024  tablesample->args = fargs;
1025 
1026  /* Process REPEATABLE (seed) */
1027  if (rts->repeatable != NULL)
1028  {
1029  Node *arg;
1030 
1031  if (!tsm->repeatable_across_queries)
1032  ereport(ERROR,
1033  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1034  errmsg("tablesample method %s does not support REPEATABLE",
1035  NameListToString(rts->method)),
1036  parser_errposition(pstate, rts->location)));
1037 
1038  arg = transformExpr(pstate, rts->repeatable, EXPR_KIND_FROM_FUNCTION);
1039  arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE");
1040  assign_expr_collations(pstate, arg);
1041  tablesample->repeatable = (Expr *) arg;
1042  }
1043  else
1044  tablesample->repeatable = NULL;
1045 
1046  return tablesample;
1047 }
#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:147
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:2953
#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:1910
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 2579 of file parse_clause.c.

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

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

2584 {
2585  List *sortlist = NIL;
2586  ListCell *olitem;
2587 
2588  foreach(olitem, orderlist)
2589  {
2590  SortBy *sortby = (SortBy *) lfirst(olitem);
2591  TargetEntry *tle;
2592 
2593  if (useSQL99)
2594  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2595  targetlist, exprKind);
2596  else
2597  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2598  targetlist, exprKind);
2599 
2600  sortlist = addTargetToSortList(pstate, tle,
2601  sortlist, *targetlist, sortby);
2602  }
2603 
2604  return sortlist;
2605 }
#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:469
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 1711 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().

1713 {
1714  Node *qual;
1715 
1716  if (clause == NULL)
1717  return NULL;
1718 
1719  qual = transformExpr(pstate, clause, exprKind);
1720 
1721  qual = coerce_to_boolean(pstate, qual, constructName);
1722 
1723  return qual;
1724 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
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 2612 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().

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