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

3279 {
3280  Oid restype = exprType((Node *) tle->expr);
3281  Oid sortop;
3282  Oid eqop;
3283  bool hashable;
3284  bool reverse;
3285  int location;
3286  ParseCallbackState pcbstate;
3287 
3288  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3289  if (restype == UNKNOWNOID)
3290  {
3291  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3292  restype, TEXTOID, -1,
3295  -1);
3296  restype = TEXTOID;
3297  }
3298 
3299  /*
3300  * Rather than clutter the API of get_sort_group_operators and the other
3301  * functions we're about to use, make use of error context callback to
3302  * mark any error reports with a parse position. We point to the operator
3303  * location if present, else to the expression being sorted. (NB: use the
3304  * original untransformed expression here; the TLE entry might well point
3305  * at a duplicate expression in the regular SELECT list.)
3306  */
3307  location = sortby->location;
3308  if (location < 0)
3309  location = exprLocation(sortby->node);
3310  setup_parser_errposition_callback(&pcbstate, pstate, location);
3311 
3312  /* determine the sortop, eqop, and directionality */
3313  switch (sortby->sortby_dir)
3314  {
3315  case SORTBY_DEFAULT:
3316  case SORTBY_ASC:
3317  get_sort_group_operators(restype,
3318  true, true, false,
3319  &sortop, &eqop, NULL,
3320  &hashable);
3321  reverse = false;
3322  break;
3323  case SORTBY_DESC:
3324  get_sort_group_operators(restype,
3325  false, true, true,
3326  NULL, &eqop, &sortop,
3327  &hashable);
3328  reverse = true;
3329  break;
3330  case SORTBY_USING:
3331  Assert(sortby->useOp != NIL);
3332  sortop = compatible_oper_opid(sortby->useOp,
3333  restype,
3334  restype,
3335  false);
3336 
3337  /*
3338  * Verify it's a valid ordering operator, fetch the corresponding
3339  * equality operator, and determine whether to consider it like
3340  * ASC or DESC.
3341  */
3342  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3343  if (!OidIsValid(eqop))
3344  ereport(ERROR,
3345  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3346  errmsg("operator %s is not a valid ordering operator",
3347  strVal(llast(sortby->useOp))),
3348  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3349 
3350  /*
3351  * Also see if the equality operator is hashable.
3352  */
3353  hashable = op_hashjoinable(eqop, restype);
3354  break;
3355  default:
3356  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3357  sortop = InvalidOid; /* keep compiler quiet */
3358  eqop = InvalidOid;
3359  hashable = false;
3360  reverse = false;
3361  break;
3362  }
3363 
3365 
3366  /* avoid making duplicate sortlist entries */
3367  if (!targetIsInSortList(tle, sortop, sortlist))
3368  {
3370 
3371  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3372 
3373  sortcl->eqop = eqop;
3374  sortcl->sortop = sortop;
3375  sortcl->hashable = hashable;
3376 
3377  switch (sortby->sortby_nulls)
3378  {
3379  case SORTBY_NULLS_DEFAULT:
3380  /* NULLS FIRST is default for DESC; other way for ASC */
3381  sortcl->nulls_first = reverse;
3382  break;
3383  case SORTBY_NULLS_FIRST:
3384  sortcl->nulls_first = true;
3385  break;
3386  case SORTBY_NULLS_LAST:
3387  sortcl->nulls_first = false;
3388  break;
3389  default:
3390  elog(ERROR, "unrecognized sortby_nulls: %d",
3391  sortby->sortby_nulls);
3392  break;
3393  }
3394 
3395  sortlist = lappend(sortlist, sortcl);
3396  }
3397 
3398  return sortlist;
3399 }
#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:482
List * useOp
Definition: parsenodes.h:484
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:1283
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:539
#define strVal(v)
Definition: value.h:54
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:483
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:587
#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:1454
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:481
int location
Definition: parsenodes.h:485

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3475 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

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

◆ 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:1145
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 3516 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().

3517 {
3518  Index ref = tle->ressortgroupref;
3519  ListCell *l;
3520 
3521  /* no need to scan list if tle has no marker */
3522  if (ref == 0)
3523  return false;
3524 
3525  foreach(l, sortList)
3526  {
3527  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3528 
3529  if (scl->tleSortGroupRef == ref &&
3530  (sortop == InvalidOid ||
3531  sortop == scl->sortop ||
3532  sortop == get_commutator(scl->sortop)))
3533  return true;
3534  }
3535  return false;
3536 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1480
Index tleSortGroupRef
Definition: parsenodes.h:1283
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:1457

◆ transformDistinctClause()

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

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

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

◆ transformDistinctOnClause()

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

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

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

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

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) && ((A_Const *) clause)->val.type == T_Null)
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:590
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
Definition: nodes.h:300
int errmsg(const char *fmt,...)
Definition: elog.c:909
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
long val
Definition: informix.c:664

◆ transformOnConflictArbiter()

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

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

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

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

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

2622 {
2623  List *sortlist = NIL;
2624  ListCell *olitem;
2625 
2626  foreach(olitem, orderlist)
2627  {
2628  SortBy *sortby = (SortBy *) lfirst(olitem);
2629  TargetEntry *tle;
2630 
2631  if (useSQL99)
2632  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2633  targetlist, exprKind);
2634  else
2635  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2636  targetlist, exprKind);
2637 
2638  sortlist = addTargetToSortList(pstate, tle,
2639  sortlist, *targetlist, sortby);
2640  }
2641 
2642  return sortlist;
2643 }
#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:481
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:539
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

◆ transformWindowDefinitions()

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

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

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