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

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

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3461 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

3462 {
3463  Index maxRef;
3464  ListCell *l;
3465 
3466  if (tle->ressortgroupref) /* already has one? */
3467  return tle->ressortgroupref;
3468 
3469  /* easiest way to pick an unused refnumber: max used + 1 */
3470  maxRef = 0;
3471  foreach(l, tlist)
3472  {
3473  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3474 
3475  if (ref > maxRef)
3476  maxRef = ref;
3477  }
3478  tle->ressortgroupref = maxRef + 1;
3479  return tle->ressortgroupref;
3480 }
unsigned int Index
Definition: c.h:537
#define lfirst(lc)
Definition: pg_list.h:169
Index ressortgroupref
Definition: primnodes.h:1434

◆ 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: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:704
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:191
AclMode requiredPerms
Definition: parsenodes.h:1124
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:45
#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:155
int errmsg(const char *fmt,...)
Definition: elog.c:915
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 3502 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().

3503 {
3504  Index ref = tle->ressortgroupref;
3505  ListCell *l;
3506 
3507  /* no need to scan list if tle has no marker */
3508  if (ref == 0)
3509  return false;
3510 
3511  foreach(l, sortList)
3512  {
3513  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3514 
3515  if (scl->tleSortGroupRef == ref &&
3516  (sortop == InvalidOid ||
3517  sortop == scl->sortop ||
3518  sortop == get_commutator(scl->sortop)))
3519  return true;
3520  }
3521  return false;
3522 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1453
Index tleSortGroupRef
Definition: parsenodes.h:1262
unsigned int Index
Definition: c.h:537
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:169
Index ressortgroupref
Definition: primnodes.h:1434

◆ transformDistinctClause()

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

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

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

◆ transformDistinctOnClause()

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

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

2929 {
2930  List *result = NIL;
2931  List *sortgrouprefs = NIL;
2932  bool skipped_sortitem;
2933  ListCell *lc;
2934  ListCell *lc2;
2935 
2936  /*
2937  * Add all the DISTINCT ON expressions to the tlist (if not already
2938  * present, they are added as resjunk items). Assign sortgroupref numbers
2939  * to them, and make a list of these numbers. (NB: we rely below on the
2940  * sortgrouprefs list being one-for-one with the original distinctlist.
2941  * Also notice that we could have duplicate DISTINCT ON expressions and
2942  * hence duplicate entries in sortgrouprefs.)
2943  */
2944  foreach(lc, distinctlist)
2945  {
2946  Node *dexpr = (Node *) lfirst(lc);
2947  int sortgroupref;
2948  TargetEntry *tle;
2949 
2950  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
2952  sortgroupref = assignSortGroupRef(tle, *targetlist);
2953  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
2954  }
2955 
2956  /*
2957  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
2958  * semantics from ORDER BY items that match DISTINCT ON items, and also
2959  * adopt their column sort order. We insist that the distinctClause and
2960  * sortClause match, so throw error if we find the need to add any more
2961  * distinctClause items after we've skipped an ORDER BY item that wasn't
2962  * in DISTINCT ON.
2963  */
2964  skipped_sortitem = false;
2965  foreach(lc, sortClause)
2966  {
2967  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
2968 
2969  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
2970  {
2971  if (skipped_sortitem)
2972  ereport(ERROR,
2973  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2974  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2975  parser_errposition(pstate,
2977  sortgrouprefs,
2978  distinctlist))));
2979  else
2980  result = lappend(result, copyObject(scl));
2981  }
2982  else
2983  skipped_sortitem = true;
2984  }
2985 
2986  /*
2987  * Now add any remaining DISTINCT ON items, using default sort/group
2988  * semantics for their data types. (Note: this is pretty questionable; if
2989  * the ORDER BY list doesn't include all the DISTINCT ON items and more
2990  * besides, you certainly aren't using DISTINCT ON in the intended way,
2991  * and you probably aren't going to get consistent results. It might be
2992  * better to throw an error or warning here. But historically we've
2993  * allowed it, so keep doing so.)
2994  */
2995  forboth(lc, distinctlist, lc2, sortgrouprefs)
2996  {
2997  Node *dexpr = (Node *) lfirst(lc);
2998  int sortgroupref = lfirst_int(lc2);
2999  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
3000 
3001  if (targetIsInSortList(tle, InvalidOid, result))
3002  continue; /* already in list (with some semantics) */
3003  if (skipped_sortitem)
3004  ereport(ERROR,
3005  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3006  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3007  parser_errposition(pstate, exprLocation(dexpr))));
3008  result = addTargetToGroupList(pstate, tle,
3009  result, *targetlist,
3010  exprLocation(dexpr));
3011  }
3012 
3013  /*
3014  * An empty result list is impossible here because of grammar
3015  * restrictions.
3016  */
3017  Assert(result != NIL);
3018 
3019  return result;
3020 }
#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:1231
Index tleSortGroupRef
Definition: parsenodes.h:1262
Definition: nodes.h:528
int errcode(int sqlerrcode)
Definition: elog.c:704
static int get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
#define ERROR
Definition: elog.h:45
#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:362
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:155
#define Assert(condition)
Definition: c.h:792
#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:915
#define copyObject(obj)
Definition: nodes.h:644
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(), transformPLAssignStmt(), 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:528
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: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:336
#define lfirst(lc)
Definition: pg_list.h:169
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 2490 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().

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

1741 {
1742  Node *qual;
1743 
1744  if (clause == NULL)
1745  return NULL;
1746 
1747  qual = transformExpr(pstate, clause, exprKind);
1748 
1749  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1750 
1751  /* LIMIT can't refer to any variables of the current query */
1752  checkExprIsVarFree(pstate, qual, constructName);
1753 
1754  /*
1755  * Don't allow NULLs in FETCH FIRST .. WITH TIES. This test is ugly and
1756  * extremely simplistic, in that you can pass a NULL anyway by hiding it
1757  * inside an expression -- but this protects ruleutils against emitting an
1758  * unadorned NULL that's not accepted back by the grammar.
1759  */
1760  if (exprKind == EXPR_KIND_LIMIT && limitOption == LIMIT_OPTION_WITH_TIES &&
1761  IsA(clause, A_Const) && ((A_Const *) clause)->val.type == T_Null)
1762  ereport(ERROR,
1763  (errcode(ERRCODE_INVALID_ROW_COUNT_IN_LIMIT_CLAUSE),
1764  errmsg("row count cannot be null in FETCH FIRST ... WITH TIES clause")));
1765 
1766  return qual;
1767 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
Definition: nodes.h:528
int errcode(int sqlerrcode)
Definition: elog.c:704
#define ERROR
Definition: elog.h:45
#define ereport(elevel,...)
Definition: elog.h:155
Definition: nodes.h:293
int errmsg(const char *fmt,...)
Definition: elog.c:915
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 3155 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().

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

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

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

2595 {
2596  List *sortlist = NIL;
2597  ListCell *olitem;
2598 
2599  foreach(olitem, orderlist)
2600  {
2601  SortBy *sortby = (SortBy *) lfirst(olitem);
2602  TargetEntry *tle;
2603 
2604  if (useSQL99)
2605  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2606  targetlist, exprKind);
2607  else
2608  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2609  targetlist, exprKind);
2610 
2611  sortlist = addTargetToSortList(pstate, tle,
2612  sortlist, *targetlist, sortby);
2613  }
2614 
2615  return sortlist;
2616 }
#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:470
Definition: pg_list.h:50

◆ transformWhereClause()

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

Definition at line 1711 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(), transformPLAssignStmt(), transformRuleStmt(), transformSelectStmt(), and transformUpdateStmt().

1713 {
1714  Node *qual;
1715 
1716  if (clause == NULL)
1717  return NULL;
1718 
1719  qual = transformExpr(pstate, clause, exprKind);
1720 
1721  qual = coerce_to_boolean(pstate, qual, constructName);
1722 
1723  return qual;
1724 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
Definition: nodes.h:528
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

◆ transformWindowDefinitions()

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

Definition at line 2623 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 transformPLAssignStmt(), and transformSelectStmt().

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