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

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

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3476 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

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

◆ setTargetTable()

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

Definition at line 177 of file parse_clause.c.

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

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

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

◆ targetIsInSortList()

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

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

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

◆ transformDistinctClause()

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

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

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

◆ transformDistinctOnClause()

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

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

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

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 113 of file parse_clause.c.

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

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

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

◆ transformGroupClause()

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

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

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

◆ transformLimitClause()

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

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

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

◆ transformOnConflictArbiter()

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

Definition at line 3183 of file parse_clause.c.

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

Referenced by transformOnConflictClause().

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

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

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

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

◆ transformWhereClause()

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

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

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

◆ transformWindowDefinitions()

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

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

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