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

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

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3470 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

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

◆ setTargetTable()

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

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

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

◆ targetIsInSortList()

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

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

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

◆ transformDistinctClause()

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

Definition at line 2852 of file parse_clause.c.

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

Referenced by transformAggregateCall(), and transformSelectStmt().

2854 {
2855  List *result = NIL;
2856  ListCell *slitem;
2857  ListCell *tlitem;
2858 
2859  /*
2860  * The distinctClause should consist of all ORDER BY items followed by all
2861  * other non-resjunk targetlist items. There must not be any resjunk
2862  * ORDER BY items --- that would imply that we are sorting by a value that
2863  * isn't necessarily unique within a DISTINCT group, so the results
2864  * wouldn't be well-defined. This construction ensures we follow the rule
2865  * that sortClause and distinctClause match; in fact the sortClause will
2866  * always be a prefix of distinctClause.
2867  *
2868  * Note a corner case: the same TLE could be in the ORDER BY list multiple
2869  * times with different sortops. We have to include it in the
2870  * distinctClause the same way to preserve the prefix property. The net
2871  * effect will be that the TLE value will be made unique according to both
2872  * sortops.
2873  */
2874  foreach(slitem, sortClause)
2875  {
2876  SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
2877  TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
2878 
2879  if (tle->resjunk)
2880  ereport(ERROR,
2881  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2882  is_agg ?
2883  errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
2884  errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
2885  parser_errposition(pstate,
2886  exprLocation((Node *) tle->expr))));
2887  result = lappend(result, copyObject(scl));
2888  }
2889 
2890  /*
2891  * Now add any remaining non-resjunk tlist items, using default sort/group
2892  * semantics for their data types.
2893  */
2894  foreach(tlitem, *targetlist)
2895  {
2896  TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
2897 
2898  if (tle->resjunk)
2899  continue; /* ignore junk */
2900  result = addTargetToGroupList(pstate, tle,
2901  result, *targetlist,
2902  exprLocation((Node *) tle->expr));
2903  }
2904 
2905  /*
2906  * Complain if we found nothing to make DISTINCT. Returning an empty list
2907  * would cause the parsed Query to look like it didn't have DISTINCT, with
2908  * results that would probably surprise the user. Note: this case is
2909  * presently impossible for aggregates because of grammar restrictions,
2910  * but we check anyway.
2911  */
2912  if (result == NIL)
2913  ereport(ERROR,
2914  (errcode(ERRCODE_SYNTAX_ERROR),
2915  is_agg ?
2916  errmsg("an aggregate with DISTINCT must have at least one argument") :
2917  errmsg("SELECT DISTINCT must have at least one column")));
2918 
2919  return result;
2920 }
#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:389
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
bool resjunk
Definition: primnodes.h:1414
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:321
#define ereport(elevel,...)
Definition: elog.h:144
#define lfirst(lc)
Definition: pg_list.h:190
Expr * expr
Definition: primnodes.h:1407
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define copyObject(obj)
Definition: nodes.h:645
Definition: pg_list.h:50

◆ transformDistinctOnClause()

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

Definition at line 2936 of file parse_clause.c.

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

Referenced by transformSelectStmt().

2938 {
2939  List *result = NIL;
2940  List *sortgrouprefs = NIL;
2941  bool skipped_sortitem;
2942  ListCell *lc;
2943  ListCell *lc2;
2944 
2945  /*
2946  * Add all the DISTINCT ON expressions to the tlist (if not already
2947  * present, they are added as resjunk items). Assign sortgroupref numbers
2948  * to them, and make a list of these numbers. (NB: we rely below on the
2949  * sortgrouprefs list being one-for-one with the original distinctlist.
2950  * Also notice that we could have duplicate DISTINCT ON expressions and
2951  * hence duplicate entries in sortgrouprefs.)
2952  */
2953  foreach(lc, distinctlist)
2954  {
2955  Node *dexpr = (Node *) lfirst(lc);
2956  int sortgroupref;
2957  TargetEntry *tle;
2958 
2959  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
2961  sortgroupref = assignSortGroupRef(tle, *targetlist);
2962  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
2963  }
2964 
2965  /*
2966  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
2967  * semantics from ORDER BY items that match DISTINCT ON items, and also
2968  * adopt their column sort order. We insist that the distinctClause and
2969  * sortClause match, so throw error if we find the need to add any more
2970  * distinctClause items after we've skipped an ORDER BY item that wasn't
2971  * in DISTINCT ON.
2972  */
2973  skipped_sortitem = false;
2974  foreach(lc, sortClause)
2975  {
2976  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
2977 
2978  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
2979  {
2980  if (skipped_sortitem)
2981  ereport(ERROR,
2982  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2983  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2984  parser_errposition(pstate,
2986  sortgrouprefs,
2987  distinctlist))));
2988  else
2989  result = lappend(result, copyObject(scl));
2990  }
2991  else
2992  skipped_sortitem = true;
2993  }
2994 
2995  /*
2996  * Now add any remaining DISTINCT ON items, using default sort/group
2997  * semantics for their data types. (Note: this is pretty questionable; if
2998  * the ORDER BY list doesn't include all the DISTINCT ON items and more
2999  * besides, you certainly aren't using DISTINCT ON in the intended way,
3000  * and you probably aren't going to get consistent results. It might be
3001  * better to throw an error or warning here. But historically we've
3002  * allowed it, so keep doing so.)
3003  */
3004  forboth(lc, distinctlist, lc2, sortgrouprefs)
3005  {
3006  Node *dexpr = (Node *) lfirst(lc);
3007  int sortgroupref = lfirst_int(lc2);
3008  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
3009 
3010  if (targetIsInSortList(tle, InvalidOid, result))
3011  continue; /* already in list (with some semantics) */
3012  if (skipped_sortitem)
3013  ereport(ERROR,
3014  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3015  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3016  parser_errposition(pstate, exprLocation(dexpr))));
3017  result = addTargetToGroupList(pstate, tle,
3018  result, *targetlist,
3019  exprLocation(dexpr));
3020  }
3021 
3022  /*
3023  * An empty result list is impossible here because of grammar
3024  * restrictions.
3025  */
3026  Assert(result != NIL);
3027 
3028  return result;
3029 }
#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:419
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Index tleSortGroupRef
Definition: parsenodes.h:1257
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
static int get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:191
bool list_member_int(const List *list, int datum)
Definition: list.c:654
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:367
List * lappend_int(List *list, int datum)
Definition: list.c:339
List * lappend(List *list, void *datum)
Definition: list.c:321
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:738
#define lfirst(lc)
Definition: pg_list.h:190
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define copyObject(obj)
Definition: nodes.h:645
Definition: pg_list.h:50

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 114 of file parse_clause.c.

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

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

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

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

Referenced by transformSelectStmt(), and transformWindowDefinitions().

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

1750 {
1751  Node *qual;
1752 
1753  if (clause == NULL)
1754  return NULL;
1755 
1756  qual = transformExpr(pstate, clause, exprKind);
1757 
1758  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1759 
1760  /* LIMIT can't refer to any variables of the current query */
1761  checkExprIsVarFree(pstate, qual, constructName);
1762 
1763  /*
1764  * Don't allow NULLs in FETCH FIRST .. WITH TIES. This test is ugly and
1765  * extremely simplistic, in that you can pass a NULL anyway by hiding it
1766  * inside an expression -- but this protects ruleutils against emitting an
1767  * unadorned NULL that's not accepted back by the grammar.
1768  */
1769  if (exprKind == EXPR_KIND_LIMIT && limitOption == LIMIT_OPTION_WITH_TIES &&
1770  IsA(clause, A_Const) && ((A_Const *) clause)->val.type == T_Null)
1771  ereport(ERROR,
1772  (errcode(ERRCODE_INVALID_ROW_COUNT_IN_LIMIT_CLAUSE),
1773  errmsg("row count cannot be NULL in FETCH FIRST ... WITH TIES clause")));
1774 
1775  return qual;
1776 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERROR
Definition: elog.h:43
#define ereport(elevel,...)
Definition: elog.h:144
Definition: nodes.h:295
int errmsg(const char *fmt,...)
Definition: elog.c:824
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 3164 of file parse_clause.c.

References ACL_SELECT, OnConflictClause::action, addNSItemToQuery(), bms_add_members(), InferClause::conname, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_INDEX_PREDICATE, exprLocation(), get_relation_constraint_attnos(), InferClause::indexElems, OnConflictClause::infer, InvalidOid, IsCatalogRelation(), NIL, ONCONFLICT_UPDATE, ParseState::p_namespace, 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().

3168 {
3169  InferClause *infer = onConflictClause->infer;
3170 
3171  *arbiterExpr = NIL;
3172  *arbiterWhere = NULL;
3173  *constraint = InvalidOid;
3174 
3175  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3176  ereport(ERROR,
3177  (errcode(ERRCODE_SYNTAX_ERROR),
3178  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3179  errhint("For example, ON CONFLICT (column_name)."),
3180  parser_errposition(pstate,
3181  exprLocation((Node *) onConflictClause))));
3182 
3183  /*
3184  * To simplify certain aspects of its design, speculative insertion into
3185  * system catalogs is disallowed
3186  */
3187  if (IsCatalogRelation(pstate->p_target_relation))
3188  ereport(ERROR,
3189  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3190  errmsg("ON CONFLICT is not supported with system catalog tables"),
3191  parser_errposition(pstate,
3192  exprLocation((Node *) onConflictClause))));
3193 
3194  /* Same applies to table used by logical decoding as catalog table */
3196  ereport(ERROR,
3197  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3198  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3200  parser_errposition(pstate,
3201  exprLocation((Node *) onConflictClause))));
3202 
3203  /* ON CONFLICT DO NOTHING does not require an inference clause */
3204  if (infer)
3205  {
3206  List *save_namespace;
3207 
3208  /*
3209  * While we process the arbiter expressions, accept only non-qualified
3210  * references to the target table. Hide any other relations.
3211  */
3212  save_namespace = pstate->p_namespace;
3213  pstate->p_namespace = NIL;
3214  addNSItemToQuery(pstate, pstate->p_target_nsitem,
3215  false, false, true);
3216 
3217  if (infer->indexElems)
3218  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3219  pstate->p_target_relation);
3220 
3221  /*
3222  * Handling inference WHERE clause (for partial unique index
3223  * inference)
3224  */
3225  if (infer->whereClause)
3226  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3228 
3229  pstate->p_namespace = save_namespace;
3230 
3231  /*
3232  * If the arbiter is specified by constraint name, get the constraint
3233  * OID and mark the constrained columns as requiring SELECT privilege,
3234  * in the same way as would have happened if the arbiter had been
3235  * specified by explicit reference to the constraint's index columns.
3236  */
3237  if (infer->conname)
3238  {
3239  Oid relid = RelationGetRelid(pstate->p_target_relation);
3240  RangeTblEntry *rte = pstate->p_target_nsitem->p_rte;
3241  Bitmapset *conattnos;
3242 
3243  conattnos = get_relation_constraint_attnos(relid, infer->conname,
3244  false, constraint);
3245 
3246  /* Make sure the rel as a whole is marked for SELECT access */
3247  rte->requiredPerms |= ACL_SELECT;
3248  /* Mark the constrained columns as requiring SELECT access */
3249  rte->selectedCols = bms_add_members(rte->selectedCols, conattnos);
3250  }
3251  }
3252 
3253  /*
3254  * It's convenient to form a list of expressions based on the
3255  * representation used by CREATE INDEX, since the same restrictions are
3256  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3257  * primnode representation is used for inference elements, and so
3258  * assign_query_collations() can be trusted to do the right thing with the
3259  * post parse analysis query tree inference clause representation.
3260  */
3261 }
#define NIL
Definition: pg_list.h:65
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:98
int errhint(const char *fmt,...)
Definition: elog.c:1071
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
List * indexElems
Definition: parsenodes.h:1412
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:191
AclMode requiredPerms
Definition: parsenodes.h:1119
unsigned int Oid
Definition: postgres_ext.h:31
RangeTblEntry * p_rte
Definition: parse_node.h:257
Bitmapset * selectedCols
Definition: parsenodes.h:1121
#define ERROR
Definition: elog.h:43
List * p_namespace
Definition: parse_node.h:184
char * conname
Definition: parsenodes.h:1414
Bitmapset * get_relation_constraint_attnos(Oid relid, const char *conname, bool missing_ok, Oid *constraintOid)
#define RelationGetRelationName(relation)
Definition: rel.h:490
#define ACL_SELECT
Definition: parsenodes.h:75
InferClause * infer
Definition: parsenodes.h:1428
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:348
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Node * whereClause
Definition: parsenodes.h:1413
int errmsg(const char *fmt,...)
Definition: elog.c:824
Relation p_target_relation
Definition: parse_node.h:190
OnConflictAction action
Definition: parsenodes.h:1427
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456
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 2599 of file parse_clause.c.

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

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

2604 {
2605  List *sortlist = NIL;
2606  ListCell *olitem;
2607 
2608  foreach(olitem, orderlist)
2609  {
2610  SortBy *sortby = (SortBy *) lfirst(olitem);
2611  TargetEntry *tle;
2612 
2613  if (useSQL99)
2614  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2615  targetlist, exprKind);
2616  else
2617  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2618  targetlist, exprKind);
2619 
2620  sortlist = addTargetToSortList(pstate, tle,
2621  sortlist, *targetlist, sortby);
2622  }
2623 
2624  return sortlist;
2625 }
#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:190
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Node * node
Definition: parsenodes.h:470
Definition: pg_list.h:50

◆ transformWhereClause()

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

Definition at line 1720 of file parse_clause.c.

References coerce_to_boolean(), and transformExpr().

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

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

◆ transformWindowDefinitions()

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

Definition at line 2632 of file parse_clause.c.

References BTLessStrategyNumber, castNode, WindowClause::copiedOrder, copyObject, elog, WindowClause::endInRangeFunc, WindowDef::endOffset, WindowClause::endOffset, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, exprCollation(), findWindowClause(), FRAMEOPTION_DEFAULTS, FRAMEOPTION_END_OFFSET, FRAMEOPTION_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, list_length(), WindowDef::location, makeNode, WindowDef::name, WindowClause::name, NIL, SortGroupClause::nulls_first, WindowDef::orderClause, WindowClause::orderClause, parser_errposition(), WindowDef::partitionClause, WindowClause::partitionClause, WindowDef::refname, WindowClause::refname, SortGroupClause::sortop, WindowClause::startInRangeFunc, WindowDef::startOffset, WindowClause::startOffset, transformFrameOffset(), transformGroupClause(), transformSortClause(), and WindowClause::winref.

Referenced by transformSelectStmt().

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