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

3219 {
3220  Oid restype = exprType((Node *) tle->expr);
3221  Oid sortop;
3222  Oid eqop;
3223  bool hashable;
3224  bool reverse;
3225  int location;
3226  ParseCallbackState pcbstate;
3227 
3228  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3229  if (restype == UNKNOWNOID)
3230  {
3231  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3232  restype, TEXTOID, -1,
3235  -1);
3236  restype = TEXTOID;
3237  }
3238 
3239  /*
3240  * Rather than clutter the API of get_sort_group_operators and the other
3241  * functions we're about to use, make use of error context callback to
3242  * mark any error reports with a parse position. We point to the operator
3243  * location if present, else to the expression being sorted. (NB: use the
3244  * original untransformed expression here; the TLE entry might well point
3245  * at a duplicate expression in the regular SELECT list.)
3246  */
3247  location = sortby->location;
3248  if (location < 0)
3249  location = exprLocation(sortby->node);
3250  setup_parser_errposition_callback(&pcbstate, pstate, location);
3251 
3252  /* determine the sortop, eqop, and directionality */
3253  switch (sortby->sortby_dir)
3254  {
3255  case SORTBY_DEFAULT:
3256  case SORTBY_ASC:
3257  get_sort_group_operators(restype,
3258  true, true, false,
3259  &sortop, &eqop, NULL,
3260  &hashable);
3261  reverse = false;
3262  break;
3263  case SORTBY_DESC:
3264  get_sort_group_operators(restype,
3265  false, true, true,
3266  NULL, &eqop, &sortop,
3267  &hashable);
3268  reverse = true;
3269  break;
3270  case SORTBY_USING:
3271  Assert(sortby->useOp != NIL);
3272  sortop = compatible_oper_opid(sortby->useOp,
3273  restype,
3274  restype,
3275  false);
3276 
3277  /*
3278  * Verify it's a valid ordering operator, fetch the corresponding
3279  * equality operator, and determine whether to consider it like
3280  * ASC or DESC.
3281  */
3282  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3283  if (!OidIsValid(eqop))
3284  ereport(ERROR,
3285  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3286  errmsg("operator %s is not a valid ordering operator",
3287  strVal(llast(sortby->useOp))),
3288  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3289 
3290  /*
3291  * Also see if the equality operator is hashable.
3292  */
3293  hashable = op_hashjoinable(eqop, restype);
3294  break;
3295  default:
3296  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3297  sortop = InvalidOid; /* keep compiler quiet */
3298  eqop = InvalidOid;
3299  hashable = false;
3300  reverse = false;
3301  break;
3302  }
3303 
3305 
3306  /* avoid making duplicate sortlist entries */
3307  if (!targetIsInSortList(tle, sortop, sortlist))
3308  {
3310 
3311  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3312 
3313  sortcl->eqop = eqop;
3314  sortcl->sortop = sortop;
3315  sortcl->hashable = hashable;
3316 
3317  switch (sortby->sortby_nulls)
3318  {
3319  case SORTBY_NULLS_DEFAULT:
3320  /* NULLS FIRST is default for DESC; other way for ASC */
3321  sortcl->nulls_first = reverse;
3322  break;
3323  case SORTBY_NULLS_FIRST:
3324  sortcl->nulls_first = true;
3325  break;
3326  case SORTBY_NULLS_LAST:
3327  sortcl->nulls_first = false;
3328  break;
3329  default:
3330  elog(ERROR, "unrecognized sortby_nulls: %d",
3331  sortby->sortby_nulls);
3332  break;
3333  }
3334 
3335  sortlist = lappend(sortlist, sortcl);
3336  }
3337 
3338  return sortlist;
3339 }
#define NIL
Definition: pg_list.h:65
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
int errhint(const char *fmt,...)
Definition: elog.c:1071
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
SortByDir sortby_dir
Definition: parsenodes.h:470
List * useOp
Definition: parsenodes.h:472
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:264
#define llast(l)
Definition: pg_list.h:215
Index tleSortGroupRef
Definition: parsenodes.h:1234
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:525
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:639
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1244
#define ERROR
Definition: elog.h:43
SortByNulls sortby_nulls
Definition: parsenodes.h:471
#define ereport(elevel, rest)
Definition: elog.h:141
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
List * lappend(List *list, void *datum)
Definition: list.c:322
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define makeNode(_type_)
Definition: nodes.h:573
#define Assert(condition)
Definition: c.h:733
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:187
Expr * expr
Definition: primnodes.h:1393
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int errmsg(const char *fmt,...)
Definition: elog.c:822
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:494
#define elog(elevel,...)
Definition: elog.h:228
Node * node
Definition: parsenodes.h:469
int location
Definition: parsenodes.h:473

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3415 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

3416 {
3417  Index maxRef;
3418  ListCell *l;
3419 
3420  if (tle->ressortgroupref) /* already has one? */
3421  return tle->ressortgroupref;
3422 
3423  /* easiest way to pick an unused refnumber: max used + 1 */
3424  maxRef = 0;
3425  foreach(l, tlist)
3426  {
3427  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3428 
3429  if (ref > maxRef)
3430  maxRef = ref;
3431  }
3432  tle->ressortgroupref = maxRef + 1;
3433  return tle->ressortgroupref;
3434 }
unsigned int Index
Definition: c.h:476
#define lfirst(lc)
Definition: pg_list.h:190
Index ressortgroupref
Definition: primnodes.h:1396

◆ setTargetTable()

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

Definition at line 182 of file parse_clause.c.

References addRangeTableEntryForRelation(), addRTEtoQuery(), RangeVar::alias, Assert, ereport, errcode(), errmsg(), ERROR, list_length(), NoLock, ParseState::p_rtable, ParseState::p_target_rangetblentry, ParseState::p_target_relation, parserOpenTable(), RangeVar::relname, RangeTblEntry::requiredPerms, RowExclusiveLock, rt_fetch, scanNameSpaceForENR(), RangeVar::schemaname, and table_close().

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

184 {
185  RangeTblEntry *rte;
186  int rtindex;
187 
188  /*
189  * ENRs hide tables of the same name, so we need to check for them first.
190  * In contrast, CTEs don't hide tables (for this purpose).
191  */
192  if (relation->schemaname == NULL &&
193  scanNameSpaceForENR(pstate, relation->relname))
194  ereport(ERROR,
195  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
196  errmsg("relation \"%s\" cannot be the target of a modifying statement",
197  relation->relname)));
198 
199  /* Close old target; this could only happen for multi-action rules */
200  if (pstate->p_target_relation != NULL)
202 
203  /*
204  * Open target rel and grab suitable lock (which we will hold till end of
205  * transaction).
206  *
207  * free_parsestate() will eventually do the corresponding table_close(),
208  * but *not* release the lock.
209  */
210  pstate->p_target_relation = parserOpenTable(pstate, relation,
212 
213  /*
214  * Now build an RTE.
215  */
216  rte = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
218  relation->alias, inh, false);
219  pstate->p_target_rangetblentry = rte;
220 
221  /* assume new rte is at end */
222  rtindex = list_length(pstate->p_rtable);
223  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
224 
225  /*
226  * Override addRangeTableEntry's default ACL_SELECT permissions check, and
227  * instead mark target table as requiring exactly the specified
228  * permissions.
229  *
230  * If we find an explicit reference to the rel later during parse
231  * analysis, we will add the ACL_SELECT bit back again; see
232  * markVarForSelectPriv and its callers.
233  */
234  rte->requiredPerms = requiredPerms;
235 
236  /*
237  * If UPDATE/DELETE, add table to joinlist and namespace.
238  *
239  * Note: some callers know that they can find the new ParseNamespaceItem
240  * at the end of the pstate->p_namespace list. This is a bit ugly but not
241  * worth complicating this function's signature for.
242  */
243  if (alsoSource)
244  addRTEtoQuery(pstate, rte, true, true, true);
245 
246  return rtindex;
247 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Relation parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
int errcode(int sqlerrcode)
Definition: elog.c:608
AclMode requiredPerms
Definition: parsenodes.h:1096
char * schemaname
Definition: primnodes.h:67
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
bool scanNameSpaceForENR(ParseState *pstate, const char *refname)
#define RowExclusiveLock
Definition: lockdefs.h:38
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
#define ereport(elevel, rest)
Definition: elog.h:141
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:188
#define Assert(condition)
Definition: c.h:733
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:822
Relation p_target_relation
Definition: parse_node.h:187
Alias * alias
Definition: primnodes.h:72
List * p_rtable
Definition: parse_node.h:177

◆ targetIsInSortList()

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

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

3457 {
3458  Index ref = tle->ressortgroupref;
3459  ListCell *l;
3460 
3461  /* no need to scan list if tle has no marker */
3462  if (ref == 0)
3463  return false;
3464 
3465  foreach(l, sortList)
3466  {
3467  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3468 
3469  if (scl->tleSortGroupRef == ref &&
3470  (sortop == InvalidOid ||
3471  sortop == scl->sortop ||
3472  sortop == get_commutator(scl->sortop)))
3473  return true;
3474  }
3475  return false;
3476 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1311
Index tleSortGroupRef
Definition: parsenodes.h:1234
unsigned int Index
Definition: c.h:476
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:190
Index ressortgroupref
Definition: primnodes.h:1396

◆ transformDistinctClause()

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

Definition at line 2797 of file parse_clause.c.

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

Referenced by transformAggregateCall(), and transformSelectStmt().

2799 {
2800  List *result = NIL;
2801  ListCell *slitem;
2802  ListCell *tlitem;
2803 
2804  /*
2805  * The distinctClause should consist of all ORDER BY items followed by all
2806  * other non-resjunk targetlist items. There must not be any resjunk
2807  * ORDER BY items --- that would imply that we are sorting by a value that
2808  * isn't necessarily unique within a DISTINCT group, so the results
2809  * wouldn't be well-defined. This construction ensures we follow the rule
2810  * that sortClause and distinctClause match; in fact the sortClause will
2811  * always be a prefix of distinctClause.
2812  *
2813  * Note a corner case: the same TLE could be in the ORDER BY list multiple
2814  * times with different sortops. We have to include it in the
2815  * distinctClause the same way to preserve the prefix property. The net
2816  * effect will be that the TLE value will be made unique according to both
2817  * sortops.
2818  */
2819  foreach(slitem, sortClause)
2820  {
2821  SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
2822  TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
2823 
2824  if (tle->resjunk)
2825  ereport(ERROR,
2826  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2827  is_agg ?
2828  errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
2829  errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
2830  parser_errposition(pstate,
2831  exprLocation((Node *) tle->expr))));
2832  result = lappend(result, copyObject(scl));
2833  }
2834 
2835  /*
2836  * Now add any remaining non-resjunk tlist items, using default sort/group
2837  * semantics for their data types.
2838  */
2839  foreach(tlitem, *targetlist)
2840  {
2841  TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
2842 
2843  if (tle->resjunk)
2844  continue; /* ignore junk */
2845  result = addTargetToGroupList(pstate, tle,
2846  result, *targetlist,
2847  exprLocation((Node *) tle->expr));
2848  }
2849 
2850  /*
2851  * Complain if we found nothing to make DISTINCT. Returning an empty list
2852  * would cause the parsed Query to look like it didn't have DISTINCT, with
2853  * results that would probably surprise the user. Note: this case is
2854  * presently impossible for aggregates because of grammar restrictions,
2855  * but we check anyway.
2856  */
2857  if (result == NIL)
2858  ereport(ERROR,
2859  (errcode(ERRCODE_SYNTAX_ERROR),
2860  is_agg ?
2861  errmsg("an aggregate with DISTINCT must have at least one argument") :
2862  errmsg("SELECT DISTINCT must have at least one column")));
2863 
2864  return result;
2865 }
#define NIL
Definition: pg_list.h:65
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:389
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
bool resjunk
Definition: primnodes.h:1400
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
#define lfirst(lc)
Definition: pg_list.h:190
Expr * expr
Definition: primnodes.h:1393
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50

◆ transformDistinctOnClause()

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

Definition at line 2881 of file parse_clause.c.

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

Referenced by transformSelectStmt().

2883 {
2884  List *result = NIL;
2885  List *sortgrouprefs = NIL;
2886  bool skipped_sortitem;
2887  ListCell *lc;
2888  ListCell *lc2;
2889 
2890  /*
2891  * Add all the DISTINCT ON expressions to the tlist (if not already
2892  * present, they are added as resjunk items). Assign sortgroupref numbers
2893  * to them, and make a list of these numbers. (NB: we rely below on the
2894  * sortgrouprefs list being one-for-one with the original distinctlist.
2895  * Also notice that we could have duplicate DISTINCT ON expressions and
2896  * hence duplicate entries in sortgrouprefs.)
2897  */
2898  foreach(lc, distinctlist)
2899  {
2900  Node *dexpr = (Node *) lfirst(lc);
2901  int sortgroupref;
2902  TargetEntry *tle;
2903 
2904  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
2906  sortgroupref = assignSortGroupRef(tle, *targetlist);
2907  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
2908  }
2909 
2910  /*
2911  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
2912  * semantics from ORDER BY items that match DISTINCT ON items, and also
2913  * adopt their column sort order. We insist that the distinctClause and
2914  * sortClause match, so throw error if we find the need to add any more
2915  * distinctClause items after we've skipped an ORDER BY item that wasn't
2916  * in DISTINCT ON.
2917  */
2918  skipped_sortitem = false;
2919  foreach(lc, sortClause)
2920  {
2921  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
2922 
2923  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
2924  {
2925  if (skipped_sortitem)
2926  ereport(ERROR,
2927  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2928  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2929  parser_errposition(pstate,
2931  sortgrouprefs,
2932  distinctlist))));
2933  else
2934  result = lappend(result, copyObject(scl));
2935  }
2936  else
2937  skipped_sortitem = true;
2938  }
2939 
2940  /*
2941  * Now add any remaining DISTINCT ON items, using default sort/group
2942  * semantics for their data types. (Note: this is pretty questionable; if
2943  * the ORDER BY list doesn't include all the DISTINCT ON items and more
2944  * besides, you certainly aren't using DISTINCT ON in the intended way,
2945  * and you probably aren't going to get consistent results. It might be
2946  * better to throw an error or warning here. But historically we've
2947  * allowed it, so keep doing so.)
2948  */
2949  forboth(lc, distinctlist, lc2, sortgrouprefs)
2950  {
2951  Node *dexpr = (Node *) lfirst(lc);
2952  int sortgroupref = lfirst_int(lc2);
2953  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
2954 
2955  if (targetIsInSortList(tle, InvalidOid, result))
2956  continue; /* already in list (with some semantics) */
2957  if (skipped_sortitem)
2958  ereport(ERROR,
2959  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2960  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
2961  parser_errposition(pstate, exprLocation(dexpr))));
2962  result = addTargetToGroupList(pstate, tle,
2963  result, *targetlist,
2964  exprLocation(dexpr));
2965  }
2966 
2967  /*
2968  * An empty result list is impossible here because of grammar
2969  * restrictions.
2970  */
2971  Assert(result != NIL);
2972 
2973  return result;
2974 }
#define NIL
Definition: pg_list.h:65
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Index tleSortGroupRef
Definition: parsenodes.h:1234
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
static int get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:191
bool list_member_int(const List *list, int datum)
Definition: list.c:655
#define ereport(elevel, rest)
Definition: elog.h:141
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:367
List * lappend_int(List *list, int datum)
Definition: list.c:340
List * lappend(List *list, void *datum)
Definition: list.c:322
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define Assert(condition)
Definition: c.h:733
#define lfirst(lc)
Definition: pg_list.h:190
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 116 of file parse_clause.c.

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

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

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

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

Referenced by transformSelectStmt(), and transformWindowDefinitions().

2447 {
2448  List *result = NIL;
2449  List *flat_grouplist;
2450  List *gsets = NIL;
2451  ListCell *gl;
2452  bool hasGroupingSets = false;
2453  Bitmapset *seen_local = NULL;
2454 
2455  /*
2456  * Recursively flatten implicit RowExprs. (Technically this is only needed
2457  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2458  * anyway.)
2459  */
2460  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2461  true,
2462  &hasGroupingSets);
2463 
2464  /*
2465  * If the list is now empty, but hasGroupingSets is true, it's because we
2466  * elided redundant empty grouping sets. Restore a single empty grouping
2467  * set to leave a canonical form: GROUP BY ()
2468  */
2469 
2470  if (flat_grouplist == NIL && hasGroupingSets)
2471  {
2473  NIL,
2474  exprLocation((Node *) grouplist)));
2475  }
2476 
2477  foreach(gl, flat_grouplist)
2478  {
2479  Node *gexpr = (Node *) lfirst(gl);
2480 
2481  if (IsA(gexpr, GroupingSet))
2482  {
2483  GroupingSet *gset = (GroupingSet *) gexpr;
2484 
2485  switch (gset->kind)
2486  {
2487  case GROUPING_SET_EMPTY:
2488  gsets = lappend(gsets, gset);
2489  break;
2490  case GROUPING_SET_SIMPLE:
2491  /* can't happen */
2492  Assert(false);
2493  break;
2494  case GROUPING_SET_SETS:
2495  case GROUPING_SET_CUBE:
2496  case GROUPING_SET_ROLLUP:
2497  gsets = lappend(gsets,
2498  transformGroupingSet(&result,
2499  pstate, gset,
2500  targetlist, sortClause,
2501  exprKind, useSQL99, true));
2502  break;
2503  }
2504  }
2505  else
2506  {
2507  Index ref = transformGroupClauseExpr(&result, seen_local,
2508  pstate, gexpr,
2509  targetlist, sortClause,
2510  exprKind, useSQL99, true);
2511 
2512  if (ref > 0)
2513  {
2514  seen_local = bms_add_member(seen_local, ref);
2515  if (hasGroupingSets)
2516  gsets = lappend(gsets,
2518  list_make1_int(ref),
2519  exprLocation(gexpr)));
2520  }
2521  }
2522  }
2523 
2524  /* parser should prevent this */
2525  Assert(gsets == NIL || groupingSets != NULL);
2526 
2527  if (groupingSets)
2528  *groupingSets = gsets;
2529 
2530  return result;
2531 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Definition: nodes.h:525
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
GroupingSetKind kind
Definition: parsenodes.h:1303
#define list_make1(x1)
Definition: pg_list.h:227
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
#define list_make1_int(x1)
Definition: pg_list.h:238
List * lappend(List *list, void *datum)
Definition: list.c:322
unsigned int Index
Definition: c.h:476
#define Assert(condition)
Definition: c.h:733
#define lfirst(lc)
Definition: pg_list.h:190
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:788
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 
)

Definition at line 1705 of file parse_clause.c.

References checkExprIsVarFree(), coerce_to_specific_type(), and transformExpr().

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

1707 {
1708  Node *qual;
1709 
1710  if (clause == NULL)
1711  return NULL;
1712 
1713  qual = transformExpr(pstate, clause, exprKind);
1714 
1715  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1716 
1717  /* LIMIT can't refer to any variables of the current query */
1718  checkExprIsVarFree(pstate, qual, constructName);
1719 
1720  return qual;
1721 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Definition: nodes.h:525
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)

◆ transformOnConflictArbiter()

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

Definition at line 3109 of file parse_clause.c.

References ACL_SELECT, OnConflictClause::action, addRTEtoQuery(), 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, ParseState::p_target_rangetblentry, ParseState::p_target_relation, parser_errposition(), RelationGetRelationName, RelationGetRelid, RelationIsUsedAsCatalogTable, RangeTblEntry::requiredPerms, resolve_unique_index_expr(), RangeTblEntry::selectedCols, transformExpr(), and InferClause::whereClause.

Referenced by transformOnConflictClause().

3113 {
3114  InferClause *infer = onConflictClause->infer;
3115 
3116  *arbiterExpr = NIL;
3117  *arbiterWhere = NULL;
3118  *constraint = InvalidOid;
3119 
3120  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3121  ereport(ERROR,
3122  (errcode(ERRCODE_SYNTAX_ERROR),
3123  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3124  errhint("For example, ON CONFLICT (column_name)."),
3125  parser_errposition(pstate,
3126  exprLocation((Node *) onConflictClause))));
3127 
3128  /*
3129  * To simplify certain aspects of its design, speculative insertion into
3130  * system catalogs is disallowed
3131  */
3132  if (IsCatalogRelation(pstate->p_target_relation))
3133  ereport(ERROR,
3134  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3135  errmsg("ON CONFLICT is not supported with system catalog tables"),
3136  parser_errposition(pstate,
3137  exprLocation((Node *) onConflictClause))));
3138 
3139  /* Same applies to table used by logical decoding as catalog table */
3141  ereport(ERROR,
3142  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3143  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3145  parser_errposition(pstate,
3146  exprLocation((Node *) onConflictClause))));
3147 
3148  /* ON CONFLICT DO NOTHING does not require an inference clause */
3149  if (infer)
3150  {
3151  List *save_namespace;
3152 
3153  /*
3154  * While we process the arbiter expressions, accept only non-qualified
3155  * references to the target table. Hide any other relations.
3156  */
3157  save_namespace = pstate->p_namespace;
3158  pstate->p_namespace = NIL;
3159  addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
3160  false, false, true);
3161 
3162  if (infer->indexElems)
3163  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3164  pstate->p_target_relation);
3165 
3166  /*
3167  * Handling inference WHERE clause (for partial unique index
3168  * inference)
3169  */
3170  if (infer->whereClause)
3171  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3173 
3174  pstate->p_namespace = save_namespace;
3175 
3176  /*
3177  * If the arbiter is specified by constraint name, get the constraint
3178  * OID and mark the constrained columns as requiring SELECT privilege,
3179  * in the same way as would have happened if the arbiter had been
3180  * specified by explicit reference to the constraint's index columns.
3181  */
3182  if (infer->conname)
3183  {
3184  Oid relid = RelationGetRelid(pstate->p_target_relation);
3185  RangeTblEntry *rte = pstate->p_target_rangetblentry;
3186  Bitmapset *conattnos;
3187 
3188  conattnos = get_relation_constraint_attnos(relid, infer->conname,
3189  false, constraint);
3190 
3191  /* Make sure the rel as a whole is marked for SELECT access */
3192  rte->requiredPerms |= ACL_SELECT;
3193  /* Mark the constrained columns as requiring SELECT access */
3194  rte->selectedCols = bms_add_members(rte->selectedCols, conattnos);
3195  }
3196  }
3197 
3198  /*
3199  * It's convenient to form a list of expressions based on the
3200  * representation used by CREATE INDEX, since the same restrictions are
3201  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3202  * primnode representation is used for inference elements, and so
3203  * assign_query_collations() can be trusted to do the right thing with the
3204  * post parse analysis query tree inference clause representation.
3205  */
3206 }
#define NIL
Definition: pg_list.h:65
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:99
int errhint(const char *fmt,...)
Definition: elog.c:1071
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
List * indexElems
Definition: parsenodes.h:1389
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
AclMode requiredPerms
Definition: parsenodes.h:1096
unsigned int Oid
Definition: postgres_ext.h:31
Bitmapset * selectedCols
Definition: parsenodes.h:1098
#define ERROR
Definition: elog.h:43
List * p_namespace
Definition: parse_node.h:181
char * conname
Definition: parsenodes.h:1391
Bitmapset * get_relation_constraint_attnos(Oid relid, const char *conname, bool missing_ok, Oid *constraintOid)
#define RelationGetRelationName(relation)
Definition: rel.h:457
#define ereport(elevel, rest)
Definition: elog.h:141
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define ACL_SELECT
Definition: parsenodes.h:75
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:188
InferClause * infer
Definition: parsenodes.h:1405
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:315
#define InvalidOid
Definition: postgres_ext.h:36
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Node * whereClause
Definition: parsenodes.h:1390
int errmsg(const char *fmt,...)
Definition: elog.c:822
Relation p_target_relation
Definition: parse_node.h:187
OnConflictAction action
Definition: parsenodes.h:1404
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:423
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 2544 of file parse_clause.c.

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

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

2549 {
2550  List *sortlist = NIL;
2551  ListCell *olitem;
2552 
2553  foreach(olitem, orderlist)
2554  {
2555  SortBy *sortby = (SortBy *) lfirst(olitem);
2556  TargetEntry *tle;
2557 
2558  if (useSQL99)
2559  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2560  targetlist, exprKind);
2561  else
2562  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2563  targetlist, exprKind);
2564 
2565  sortlist = addTargetToSortList(pstate, tle,
2566  sortlist, *targetlist, sortby);
2567  }
2568 
2569  return sortlist;
2570 }
#define NIL
Definition: pg_list.h:65
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
#define lfirst(lc)
Definition: pg_list.h:190
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
Node * node
Definition: parsenodes.h:469
Definition: pg_list.h:50

◆ transformWhereClause()

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

Definition at line 1678 of file parse_clause.c.

References coerce_to_boolean(), and transformExpr().

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

1680 {
1681  Node *qual;
1682 
1683  if (clause == NULL)
1684  return NULL;
1685 
1686  qual = transformExpr(pstate, clause, exprKind);
1687 
1688  qual = coerce_to_boolean(pstate, qual, constructName);
1689 
1690  return qual;
1691 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Definition: nodes.h:525
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

◆ transformWindowDefinitions()

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

Definition at line 2577 of file parse_clause.c.

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

Referenced by transformSelectStmt().

2580 {
2581  List *result = NIL;
2582  Index winref = 0;
2583  ListCell *lc;
2584 
2585  foreach(lc, windowdefs)
2586  {
2587  WindowDef *windef = (WindowDef *) lfirst(lc);
2588  WindowClause *refwc = NULL;
2589  List *partitionClause;
2590  List *orderClause;
2591  Oid rangeopfamily = InvalidOid;
2592  Oid rangeopcintype = InvalidOid;
2593  WindowClause *wc;
2594 
2595  winref++;
2596 
2597  /*
2598  * Check for duplicate window names.
2599  */
2600  if (windef->name &&
2601  findWindowClause(result, windef->name) != NULL)
2602  ereport(ERROR,
2603  (errcode(ERRCODE_WINDOWING_ERROR),
2604  errmsg("window \"%s\" is already defined", windef->name),
2605  parser_errposition(pstate, windef->location)));
2606 
2607  /*
2608  * If it references a previous window, look that up.
2609  */
2610  if (windef->refname)
2611  {
2612  refwc = findWindowClause(result, windef->refname);
2613  if (refwc == NULL)
2614  ereport(ERROR,
2615  (errcode(ERRCODE_UNDEFINED_OBJECT),
2616  errmsg("window \"%s\" does not exist",
2617  windef->refname),
2618  parser_errposition(pstate, windef->location)));
2619  }
2620 
2621  /*
2622  * Transform PARTITION and ORDER specs, if any. These are treated
2623  * almost exactly like top-level GROUP BY and ORDER BY clauses,
2624  * including the special handling of nondefault operator semantics.
2625  */
2626  orderClause = transformSortClause(pstate,
2627  windef->orderClause,
2628  targetlist,
2630  true /* force SQL99 rules */ );
2631  partitionClause = transformGroupClause(pstate,
2632  windef->partitionClause,
2633  NULL,
2634  targetlist,
2635  orderClause,
2637  true /* force SQL99 rules */ );
2638 
2639  /*
2640  * And prepare the new WindowClause.
2641  */
2642  wc = makeNode(WindowClause);
2643  wc->name = windef->name;
2644  wc->refname = windef->refname;
2645 
2646  /*
2647  * Per spec, a windowdef that references a previous one copies the
2648  * previous partition clause (and mustn't specify its own). It can
2649  * specify its own ordering clause, but only if the previous one had
2650  * none. It always specifies its own frame clause, and the previous
2651  * one must not have a frame clause. Yeah, it's bizarre that each of
2652  * these cases works differently, but SQL:2008 says so; see 7.11
2653  * <window clause> syntax rule 10 and general rule 1. The frame
2654  * clause rule is especially bizarre because it makes "OVER foo"
2655  * different from "OVER (foo)", and requires the latter to throw an
2656  * error if foo has a nondefault frame clause. Well, ours not to
2657  * reason why, but we do go out of our way to throw a useful error
2658  * message for such cases.
2659  */
2660  if (refwc)
2661  {
2662  if (partitionClause)
2663  ereport(ERROR,
2664  (errcode(ERRCODE_WINDOWING_ERROR),
2665  errmsg("cannot override PARTITION BY clause of window \"%s\"",
2666  windef->refname),
2667  parser_errposition(pstate, windef->location)));
2669  }
2670  else
2671  wc->partitionClause = partitionClause;
2672  if (refwc)
2673  {
2674  if (orderClause && refwc->orderClause)
2675  ereport(ERROR,
2676  (errcode(ERRCODE_WINDOWING_ERROR),
2677  errmsg("cannot override ORDER BY clause of window \"%s\"",
2678  windef->refname),
2679  parser_errposition(pstate, windef->location)));
2680  if (orderClause)
2681  {
2682  wc->orderClause = orderClause;
2683  wc->copiedOrder = false;
2684  }
2685  else
2686  {
2687  wc->orderClause = copyObject(refwc->orderClause);
2688  wc->copiedOrder = true;
2689  }
2690  }
2691  else
2692  {
2693  wc->orderClause = orderClause;
2694  wc->copiedOrder = false;
2695  }
2696  if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2697  {
2698  /*
2699  * Use this message if this is a WINDOW clause, or if it's an OVER
2700  * clause that includes ORDER BY or framing clauses. (We already
2701  * rejected PARTITION BY above, so no need to check that.)
2702  */
2703  if (windef->name ||
2704  orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2705  ereport(ERROR,
2706  (errcode(ERRCODE_WINDOWING_ERROR),
2707  errmsg("cannot copy window \"%s\" because it has a frame clause",
2708  windef->refname),
2709  parser_errposition(pstate, windef->location)));
2710  /* Else this clause is just OVER (foo), so say this: */
2711  ereport(ERROR,
2712  (errcode(ERRCODE_WINDOWING_ERROR),
2713  errmsg("cannot copy window \"%s\" because it has a frame clause",
2714  windef->refname),
2715  errhint("Omit the parentheses in this OVER clause."),
2716  parser_errposition(pstate, windef->location)));
2717  }
2718  wc->frameOptions = windef->frameOptions;
2719 
2720  /*
2721  * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
2722  * column; check that and get its sort opfamily info.
2723  */
2724  if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
2727  {
2728  SortGroupClause *sortcl;
2729  Node *sortkey;
2730  int16 rangestrategy;
2731 
2732  if (list_length(wc->orderClause) != 1)
2733  ereport(ERROR,
2734  (errcode(ERRCODE_WINDOWING_ERROR),
2735  errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
2736  parser_errposition(pstate, windef->location)));
2737  sortcl = castNode(SortGroupClause, linitial(wc->orderClause));
2738  sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
2739  /* Find the sort operator in pg_amop */
2740  if (!get_ordering_op_properties(sortcl->sortop,
2741  &rangeopfamily,
2742  &rangeopcintype,
2743  &rangestrategy))
2744  elog(ERROR, "operator %u is not a valid ordering operator",
2745  sortcl->sortop);
2746  /* Record properties of sort ordering */
2747  wc->inRangeColl = exprCollation(sortkey);
2748  wc->inRangeAsc = (rangestrategy == BTLessStrategyNumber);
2749  wc->inRangeNullsFirst = sortcl->nulls_first;
2750  }
2751 
2752  /* Per spec, GROUPS mode requires an ORDER BY clause */
2753  if (wc->frameOptions & FRAMEOPTION_GROUPS)
2754  {
2755  if (wc->orderClause == NIL)
2756  ereport(ERROR,
2757  (errcode(ERRCODE_WINDOWING_ERROR),
2758  errmsg("GROUPS mode requires an ORDER BY clause"),
2759  parser_errposition(pstate, windef->location)));
2760  }
2761 
2762  /* Process frame offset expressions */
2763  wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2764  rangeopfamily, rangeopcintype,
2765  &wc->startInRangeFunc,
2766  windef->startOffset);
2767  wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2768  rangeopfamily, rangeopcintype,
2769  &wc->endInRangeFunc,
2770  windef->endOffset);
2771  wc->winref = winref;
2772 
2773  result = lappend(result, wc);
2774  }
2775 
2776  return result;
2777 }
signed short int16
Definition: c.h:346
List * partitionClause
Definition: parsenodes.h:489
char * refname
Definition: parsenodes.h:1329
#define NIL
Definition: pg_list.h:65
bool copiedOrder
Definition: parsenodes.h:1341
int errhint(const char *fmt,...)
Definition: elog.c:1071
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:531
bool inRangeNullsFirst
Definition: parsenodes.h:1339
int frameOptions
Definition: parsenodes.h:491
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
char * name
Definition: parsenodes.h:487
Oid endInRangeFunc
Definition: parsenodes.h:1336
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:401
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
#define FRAMEOPTION_START_OFFSET
Definition: parsenodes.h:523
Node * startOffset
Definition: parsenodes.h:492
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
List * partitionClause
Definition: parsenodes.h:1330
int location
Definition: parsenodes.h:494
Node * endOffset
Definition: parsenodes.h:493
List * transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
Node * startOffset
Definition: parsenodes.h:1333
List * orderClause
Definition: parsenodes.h:490
unsigned int Index
Definition: c.h:476
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:573
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:505
#define lfirst(lc)
Definition: pg_list.h:190
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:204
Node * endOffset
Definition: parsenodes.h:1334
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:719
#define FRAMEOPTION_END_OFFSET
Definition: parsenodes.h:525
List * orderClause
Definition: parsenodes.h:1331
int errmsg(const char *fmt,...)
Definition: elog.c:822
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:507
char * refname
Definition: parsenodes.h:488
#define copyObject(obj)
Definition: nodes.h:641
#define BTLessStrategyNumber
Definition: stratnum.h:29
Definition: pg_list.h:50
Oid startInRangeFunc
Definition: parsenodes.h:1335
static WindowClause * findWindowClause(List *wclist, const char *name)