PostgreSQL Source Code  git master
parse_clause.h File Reference
Include dependency graph for parse_clause.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void transformFromClause (ParseState *pstate, List *frmList)
 
int setTargetTable (ParseState *pstate, RangeVar *relation, bool inh, bool alsoSource, AclMode requiredPerms)
 
NodetransformWhereClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
 
NodetransformLimitClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName, LimitOption limitOption)
 
ListtransformGroupClause (ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
 
ListtransformSortClause (ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
 
ListtransformWindowDefinitions (ParseState *pstate, List *windowdefs, List **targetlist)
 
ListtransformDistinctClause (ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
 
ListtransformDistinctOnClause (ParseState *pstate, List *distinctlist, List **targetlist, List *sortClause)
 
void transformOnConflictArbiter (ParseState *pstate, OnConflictClause *onConflictClause, List **arbiterExpr, Node **arbiterWhere, Oid *constraint)
 
ListaddTargetToSortList (ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
 
Index assignSortGroupRef (TargetEntry *tle, List *tlist)
 
bool targetIsInSortList (TargetEntry *tle, Oid sortop, List *sortList)
 

Function Documentation

◆ addTargetToSortList()

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

Definition at line 3276 of file parse_clause.c.

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

Referenced by transformAggregateCall(), and transformSortClause().

3278 {
3279  Oid restype = exprType((Node *) tle->expr);
3280  Oid sortop;
3281  Oid eqop;
3282  bool hashable;
3283  bool reverse;
3284  int location;
3285  ParseCallbackState pcbstate;
3286 
3287  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3288  if (restype == UNKNOWNOID)
3289  {
3290  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3291  restype, TEXTOID, -1,
3294  -1);
3295  restype = TEXTOID;
3296  }
3297 
3298  /*
3299  * Rather than clutter the API of get_sort_group_operators and the other
3300  * functions we're about to use, make use of error context callback to
3301  * mark any error reports with a parse position. We point to the operator
3302  * location if present, else to the expression being sorted. (NB: use the
3303  * original untransformed expression here; the TLE entry might well point
3304  * at a duplicate expression in the regular SELECT list.)
3305  */
3306  location = sortby->location;
3307  if (location < 0)
3308  location = exprLocation(sortby->node);
3309  setup_parser_errposition_callback(&pcbstate, pstate, location);
3310 
3311  /* determine the sortop, eqop, and directionality */
3312  switch (sortby->sortby_dir)
3313  {
3314  case SORTBY_DEFAULT:
3315  case SORTBY_ASC:
3316  get_sort_group_operators(restype,
3317  true, true, false,
3318  &sortop, &eqop, NULL,
3319  &hashable);
3320  reverse = false;
3321  break;
3322  case SORTBY_DESC:
3323  get_sort_group_operators(restype,
3324  false, true, true,
3325  NULL, &eqop, &sortop,
3326  &hashable);
3327  reverse = true;
3328  break;
3329  case SORTBY_USING:
3330  Assert(sortby->useOp != NIL);
3331  sortop = compatible_oper_opid(sortby->useOp,
3332  restype,
3333  restype,
3334  false);
3335 
3336  /*
3337  * Verify it's a valid ordering operator, fetch the corresponding
3338  * equality operator, and determine whether to consider it like
3339  * ASC or DESC.
3340  */
3341  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3342  if (!OidIsValid(eqop))
3343  ereport(ERROR,
3344  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3345  errmsg("operator %s is not a valid ordering operator",
3346  strVal(llast(sortby->useOp))),
3347  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3348 
3349  /*
3350  * Also see if the equality operator is hashable.
3351  */
3352  hashable = op_hashjoinable(eqop, restype);
3353  break;
3354  default:
3355  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3356  sortop = InvalidOid; /* keep compiler quiet */
3357  eqop = InvalidOid;
3358  hashable = false;
3359  reverse = false;
3360  break;
3361  }
3362 
3364 
3365  /* avoid making duplicate sortlist entries */
3366  if (!targetIsInSortList(tle, sortop, sortlist))
3367  {
3369 
3370  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3371 
3372  sortcl->eqop = eqop;
3373  sortcl->sortop = sortop;
3374  sortcl->hashable = hashable;
3375 
3376  switch (sortby->sortby_nulls)
3377  {
3378  case SORTBY_NULLS_DEFAULT:
3379  /* NULLS FIRST is default for DESC; other way for ASC */
3380  sortcl->nulls_first = reverse;
3381  break;
3382  case SORTBY_NULLS_FIRST:
3383  sortcl->nulls_first = true;
3384  break;
3385  case SORTBY_NULLS_LAST:
3386  sortcl->nulls_first = false;
3387  break;
3388  default:
3389  elog(ERROR, "unrecognized sortby_nulls: %d",
3390  sortby->sortby_nulls);
3391  break;
3392  }
3393 
3394  sortlist = lappend(sortlist, sortcl);
3395  }
3396 
3397  return sortlist;
3398 }
#define NIL
Definition: pg_list.h:65
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
int errhint(const char *fmt,...)
Definition: elog.c:1156
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1250
SortByDir sortby_dir
Definition: parsenodes.h:494
List * useOp
Definition: parsenodes.h:496
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:265
#define llast(l)
Definition: pg_list.h:194
Index tleSortGroupRef
Definition: parsenodes.h:1295
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:157
Definition: nodes.h:537
#define strVal(v)
Definition: value.h:65
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1408
#define ERROR
Definition: elog.h:46
SortByNulls sortby_nulls
Definition: parsenodes.h:495
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:336
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define ereport(elevel,...)
Definition: elog.h:157
#define makeNode(_type_)
Definition: nodes.h:585
#define Assert(condition)
Definition: c.h:804
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:192
Expr * expr
Definition: primnodes.h:1455
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int errmsg(const char *fmt,...)
Definition: elog.c:909
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:499
#define elog(elevel,...)
Definition: elog.h:232
Node * node
Definition: parsenodes.h:493
int location
Definition: parsenodes.h:497

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3474 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

3475 {
3476  Index maxRef;
3477  ListCell *l;
3478 
3479  if (tle->ressortgroupref) /* already has one? */
3480  return tle->ressortgroupref;
3481 
3482  /* easiest way to pick an unused refnumber: max used + 1 */
3483  maxRef = 0;
3484  foreach(l, tlist)
3485  {
3486  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3487 
3488  if (ref > maxRef)
3489  maxRef = ref;
3490  }
3491  tle->ressortgroupref = maxRef + 1;
3492  return tle->ressortgroupref;
3493 }
unsigned int Index
Definition: c.h:549
#define lfirst(lc)
Definition: pg_list.h:169
Index ressortgroupref
Definition: primnodes.h:1458

◆ setTargetTable()

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

Definition at line 177 of file parse_clause.c.

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

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

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

◆ targetIsInSortList()

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

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

3516 {
3517  Index ref = tle->ressortgroupref;
3518  ListCell *l;
3519 
3520  /* no need to scan list if tle has no marker */
3521  if (ref == 0)
3522  return false;
3523 
3524  foreach(l, sortList)
3525  {
3526  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3527 
3528  if (scl->tleSortGroupRef == ref &&
3529  (sortop == InvalidOid ||
3530  sortop == scl->sortop ||
3531  sortop == get_commutator(scl->sortop)))
3532  return true;
3533  }
3534  return false;
3535 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1480
Index tleSortGroupRef
Definition: parsenodes.h:1295
unsigned int Index
Definition: c.h:549
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:169
Index ressortgroupref
Definition: primnodes.h:1458

◆ transformDistinctClause()

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

Definition at line 2869 of file parse_clause.c.

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

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

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

◆ transformDistinctOnClause()

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

Definition at line 2953 of file parse_clause.c.

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

Referenced by transformPLAssignStmt(), and transformSelectStmt().

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

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 113 of file parse_clause.c.

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

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

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

◆ transformGroupClause()

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

Definition at line 2516 of file parse_clause.c.

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

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

2519 {
2520  List *result = NIL;
2521  List *flat_grouplist;
2522  List *gsets = NIL;
2523  ListCell *gl;
2524  bool hasGroupingSets = false;
2525  Bitmapset *seen_local = NULL;
2526 
2527  /*
2528  * Recursively flatten implicit RowExprs. (Technically this is only needed
2529  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2530  * anyway.)
2531  */
2532  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2533  true,
2534  &hasGroupingSets);
2535 
2536  /*
2537  * If the list is now empty, but hasGroupingSets is true, it's because we
2538  * elided redundant empty grouping sets. Restore a single empty grouping
2539  * set to leave a canonical form: GROUP BY ()
2540  */
2541 
2542  if (flat_grouplist == NIL && hasGroupingSets)
2543  {
2545  NIL,
2546  exprLocation((Node *) grouplist)));
2547  }
2548 
2549  foreach(gl, flat_grouplist)
2550  {
2551  Node *gexpr = (Node *) lfirst(gl);
2552 
2553  if (IsA(gexpr, GroupingSet))
2554  {
2555  GroupingSet *gset = (GroupingSet *) gexpr;
2556 
2557  switch (gset->kind)
2558  {
2559  case GROUPING_SET_EMPTY:
2560  gsets = lappend(gsets, gset);
2561  break;
2562  case GROUPING_SET_SIMPLE:
2563  /* can't happen */
2564  Assert(false);
2565  break;
2566  case GROUPING_SET_SETS:
2567  case GROUPING_SET_CUBE:
2568  case GROUPING_SET_ROLLUP:
2569  gsets = lappend(gsets,
2570  transformGroupingSet(&result,
2571  pstate, gset,
2572  targetlist, sortClause,
2573  exprKind, useSQL99, true));
2574  break;
2575  }
2576  }
2577  else
2578  {
2579  Index ref = transformGroupClauseExpr(&result, seen_local,
2580  pstate, gexpr,
2581  targetlist, sortClause,
2582  exprKind, useSQL99, true);
2583 
2584  if (ref > 0)
2585  {
2586  seen_local = bms_add_member(seen_local, ref);
2587  if (hasGroupingSets)
2588  gsets = lappend(gsets,
2590  list_make1_int(ref),
2591  exprLocation(gexpr)));
2592  }
2593  }
2594  }
2595 
2596  /* parser should prevent this */
2597  Assert(gsets == NIL || groupingSets != NULL);
2598 
2599  if (groupingSets)
2600  *groupingSets = gsets;
2601 
2602  return result;
2603 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:588
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1250
Definition: nodes.h:537
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
GroupingSetKind kind
Definition: parsenodes.h:1364
#define list_make1(x1)
Definition: pg_list.h:206
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
#define list_make1_int(x1)
Definition: pg_list.h:221
List * lappend(List *list, void *datum)
Definition: list.c:336
unsigned int Index
Definition: c.h:549
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:794
Definition: pg_list.h:50
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)

◆ transformLimitClause()

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

Definition at line 1765 of file parse_clause.c.

References castNode, checkExprIsVarFree(), coerce_to_specific_type(), ereport, errcode(), errmsg(), ERROR, EXPR_KIND_LIMIT, IsA, LIMIT_OPTION_WITH_TIES, and transformExpr().

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

1768 {
1769  Node *qual;
1770 
1771  if (clause == NULL)
1772  return NULL;
1773 
1774  qual = transformExpr(pstate, clause, exprKind);
1775 
1776  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1777 
1778  /* LIMIT can't refer to any variables of the current query */
1779  checkExprIsVarFree(pstate, qual, constructName);
1780 
1781  /*
1782  * Don't allow NULLs in FETCH FIRST .. WITH TIES. This test is ugly and
1783  * extremely simplistic, in that you can pass a NULL anyway by hiding it
1784  * inside an expression -- but this protects ruleutils against emitting an
1785  * unadorned NULL that's not accepted back by the grammar.
1786  */
1787  if (exprKind == EXPR_KIND_LIMIT && limitOption == LIMIT_OPTION_WITH_TIES &&
1788  IsA(clause, A_Const) && castNode(A_Const, clause)->isnull)
1789  ereport(ERROR,
1790  (errcode(ERRCODE_INVALID_ROW_COUNT_IN_LIMIT_CLAUSE),
1791  errmsg("row count cannot be null in FETCH FIRST ... WITH TIES clause")));
1792 
1793  return qual;
1794 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
#define IsA(nodeptr, _type_)
Definition: nodes.h:588
#define castNode(_type_, nodeptr)
Definition: nodes.h:606
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
Definition: nodes.h:537
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)

◆ transformOnConflictArbiter()

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

Definition at line 3181 of file parse_clause.c.

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

Referenced by transformOnConflictClause().

3185 {
3186  InferClause *infer = onConflictClause->infer;
3187 
3188  *arbiterExpr = NIL;
3189  *arbiterWhere = NULL;
3190  *constraint = InvalidOid;
3191 
3192  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3193  ereport(ERROR,
3194  (errcode(ERRCODE_SYNTAX_ERROR),
3195  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3196  errhint("For example, ON CONFLICT (column_name)."),
3197  parser_errposition(pstate,
3198  exprLocation((Node *) onConflictClause))));
3199 
3200  /*
3201  * To simplify certain aspects of its design, speculative insertion into
3202  * system catalogs is disallowed
3203  */
3204  if (IsCatalogRelation(pstate->p_target_relation))
3205  ereport(ERROR,
3206  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3207  errmsg("ON CONFLICT is not supported with system catalog tables"),
3208  parser_errposition(pstate,
3209  exprLocation((Node *) onConflictClause))));
3210 
3211  /* Same applies to table used by logical decoding as catalog table */
3213  ereport(ERROR,
3214  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3215  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3217  parser_errposition(pstate,
3218  exprLocation((Node *) onConflictClause))));
3219 
3220  /* ON CONFLICT DO NOTHING does not require an inference clause */
3221  if (infer)
3222  {
3223  if (infer->indexElems)
3224  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3225  pstate->p_target_relation);
3226 
3227  /*
3228  * Handling inference WHERE clause (for partial unique index
3229  * inference)
3230  */
3231  if (infer->whereClause)
3232  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3234 
3235  /*
3236  * If the arbiter is specified by constraint name, get the constraint
3237  * OID and mark the constrained columns as requiring SELECT privilege,
3238  * in the same way as would have happened if the arbiter had been
3239  * specified by explicit reference to the constraint's index columns.
3240  */
3241  if (infer->conname)
3242  {
3243  Oid relid = RelationGetRelid(pstate->p_target_relation);
3244  RangeTblEntry *rte = pstate->p_target_nsitem->p_rte;
3245  Bitmapset *conattnos;
3246 
3247  conattnos = get_relation_constraint_attnos(relid, infer->conname,
3248  false, constraint);
3249 
3250  /* Make sure the rel as a whole is marked for SELECT access */
3251  rte->requiredPerms |= ACL_SELECT;
3252  /* Mark the constrained columns as requiring SELECT access */
3253  rte->selectedCols = bms_add_members(rte->selectedCols, conattnos);
3254  }
3255  }
3256 
3257  /*
3258  * It's convenient to form a list of expressions based on the
3259  * representation used by CREATE INDEX, since the same restrictions are
3260  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3261  * primnode representation is used for inference elements, and so
3262  * assign_query_collations() can be trusted to do the right thing with the
3263  * post parse analysis query tree inference clause representation.
3264  */
3265 }
#define NIL
Definition: pg_list.h:65
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:104
int errhint(const char *fmt,...)
Definition: elog.c:1156
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1250
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
List * indexElems
Definition: parsenodes.h:1450
Definition: nodes.h:537
int errcode(int sqlerrcode)
Definition: elog.c:698
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:193
AclMode requiredPerms
Definition: parsenodes.h:1157
unsigned int Oid
Definition: postgres_ext.h:31
RangeTblEntry * p_rte
Definition: parse_node.h:268
Bitmapset * selectedCols
Definition: parsenodes.h:1159
#define ERROR
Definition: elog.h:46
char * conname
Definition: parsenodes.h:1452
Bitmapset * get_relation_constraint_attnos(Oid relid, const char *conname, bool missing_ok, Oid *constraintOid)
#define RelationGetRelationName(relation)
Definition: rel.h:511
#define ACL_SELECT
Definition: parsenodes.h:83
InferClause * infer
Definition: parsenodes.h:1466
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:369
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Node * whereClause
Definition: parsenodes.h:1451
int errmsg(const char *fmt,...)
Definition: elog.c:909
Relation p_target_relation
Definition: parse_node.h:192
OnConflictAction action
Definition: parsenodes.h:1465
#define RelationGetRelid(relation)
Definition: rel.h:477
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:793
static List * resolve_unique_index_expr(ParseState *pstate, InferClause *infer, Relation heapRel)

◆ transformSortClause()

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

Definition at line 2616 of file parse_clause.c.

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

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

2621 {
2622  List *sortlist = NIL;
2623  ListCell *olitem;
2624 
2625  foreach(olitem, orderlist)
2626  {
2627  SortBy *sortby = (SortBy *) lfirst(olitem);
2628  TargetEntry *tle;
2629 
2630  if (useSQL99)
2631  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2632  targetlist, exprKind);
2633  else
2634  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2635  targetlist, exprKind);
2636 
2637  sortlist = addTargetToSortList(pstate, tle,
2638  sortlist, *targetlist, sortby);
2639  }
2640 
2641  return sortlist;
2642 }
#define NIL
Definition: pg_list.h:65
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:169
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Node * node
Definition: parsenodes.h:493
Definition: pg_list.h:50

◆ transformWhereClause()

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

Definition at line 1738 of file parse_clause.c.

References coerce_to_boolean(), and transformExpr().

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

1740 {
1741  Node *qual;
1742 
1743  if (clause == NULL)
1744  return NULL;
1745 
1746  qual = transformExpr(pstate, clause, exprKind);
1747 
1748  qual = coerce_to_boolean(pstate, qual, constructName);
1749 
1750  return qual;
1751 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
Definition: nodes.h:537
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

◆ transformWindowDefinitions()

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

Definition at line 2649 of file parse_clause.c.

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

Referenced by transformPLAssignStmt(), and transformSelectStmt().

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