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

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

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3417 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

3418 {
3419  Index maxRef;
3420  ListCell *l;
3421 
3422  if (tle->ressortgroupref) /* already has one? */
3423  return tle->ressortgroupref;
3424 
3425  /* easiest way to pick an unused refnumber: max used + 1 */
3426  maxRef = 0;
3427  foreach(l, tlist)
3428  {
3429  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3430 
3431  if (ref > maxRef)
3432  maxRef = ref;
3433  }
3434  tle->ressortgroupref = maxRef + 1;
3435  return tle->ressortgroupref;
3436 }
unsigned int Index
Definition: c.h:475
#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 184 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().

186 {
187  RangeTblEntry *rte;
188  int rtindex;
189 
190  /*
191  * ENRs hide tables of the same name, so we need to check for them first.
192  * In contrast, CTEs don't hide tables (for this purpose).
193  */
194  if (relation->schemaname == NULL &&
195  scanNameSpaceForENR(pstate, relation->relname))
196  ereport(ERROR,
197  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
198  errmsg("relation \"%s\" cannot be the target of a modifying statement",
199  relation->relname)));
200 
201  /* Close old target; this could only happen for multi-action rules */
202  if (pstate->p_target_relation != NULL)
204 
205  /*
206  * Open target rel and grab suitable lock (which we will hold till end of
207  * transaction).
208  *
209  * free_parsestate() will eventually do the corresponding table_close(),
210  * but *not* release the lock.
211  */
212  pstate->p_target_relation = parserOpenTable(pstate, relation,
214 
215  /*
216  * Now build an RTE.
217  */
218  rte = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
220  relation->alias, inh, false);
221  pstate->p_target_rangetblentry = rte;
222 
223  /* assume new rte is at end */
224  rtindex = list_length(pstate->p_rtable);
225  Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
226 
227  /*
228  * Override addRangeTableEntry's default ACL_SELECT permissions check, and
229  * instead mark target table as requiring exactly the specified
230  * permissions.
231  *
232  * If we find an explicit reference to the rel later during parse
233  * analysis, we will add the ACL_SELECT bit back again; see
234  * markVarForSelectPriv and its callers.
235  */
236  rte->requiredPerms = requiredPerms;
237 
238  /*
239  * If UPDATE/DELETE, add table to joinlist and namespace.
240  *
241  * Note: some callers know that they can find the new ParseNamespaceItem
242  * at the end of the pstate->p_namespace list. This is a bit ugly but not
243  * worth complicating this function's signature for.
244  */
245  if (alsoSource)
246  addRTEtoQuery(pstate, rte, true, true, true);
247 
248  return rtindex;
249 }
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:570
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:732
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:784
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 3458 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().

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

◆ transformDistinctClause()

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

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

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

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

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

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

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

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

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

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

1709 {
1710  Node *qual;
1711 
1712  if (clause == NULL)
1713  return NULL;
1714 
1715  qual = transformExpr(pstate, clause, exprKind);
1716 
1717  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1718 
1719  /* LIMIT can't refer to any variables of the current query */
1720  checkExprIsVarFree(pstate, qual, constructName);
1721 
1722  return qual;
1723 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
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 3111 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().

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

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

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

2551 {
2552  List *sortlist = NIL;
2553  ListCell *olitem;
2554 
2555  foreach(olitem, orderlist)
2556  {
2557  SortBy *sortby = (SortBy *) lfirst(olitem);
2558  TargetEntry *tle;
2559 
2560  if (useSQL99)
2561  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2562  targetlist, exprKind);
2563  else
2564  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2565  targetlist, exprKind);
2566 
2567  sortlist = addTargetToSortList(pstate, tle,
2568  sortlist, *targetlist, sortby);
2569  }
2570 
2571  return sortlist;
2572 }
#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 1680 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().

1682 {
1683  Node *qual;
1684 
1685  if (clause == NULL)
1686  return NULL;
1687 
1688  qual = transformExpr(pstate, clause, exprKind);
1689 
1690  qual = coerce_to_boolean(pstate, qual, constructName);
1691 
1692  return qual;
1693 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
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 2579 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().

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