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)
 
bool interpretOidsOption (List *defList, bool allowOids)
 
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 3253 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(), TEXTOID, SortGroupClause::tleSortGroupRef, UNKNOWNOID, and SortBy::useOp.

Referenced by transformAggregateCall(), and transformSortClause().

3255 {
3256  Oid restype = exprType((Node *) tle->expr);
3257  Oid sortop;
3258  Oid eqop;
3259  bool hashable;
3260  bool reverse;
3261  int location;
3262  ParseCallbackState pcbstate;
3263 
3264  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3265  if (restype == UNKNOWNOID)
3266  {
3267  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3268  restype, TEXTOID, -1,
3271  -1);
3272  restype = TEXTOID;
3273  }
3274 
3275  /*
3276  * Rather than clutter the API of get_sort_group_operators and the other
3277  * functions we're about to use, make use of error context callback to
3278  * mark any error reports with a parse position. We point to the operator
3279  * location if present, else to the expression being sorted. (NB: use the
3280  * original untransformed expression here; the TLE entry might well point
3281  * at a duplicate expression in the regular SELECT list.)
3282  */
3283  location = sortby->location;
3284  if (location < 0)
3285  location = exprLocation(sortby->node);
3286  setup_parser_errposition_callback(&pcbstate, pstate, location);
3287 
3288  /* determine the sortop, eqop, and directionality */
3289  switch (sortby->sortby_dir)
3290  {
3291  case SORTBY_DEFAULT:
3292  case SORTBY_ASC:
3293  get_sort_group_operators(restype,
3294  true, true, false,
3295  &sortop, &eqop, NULL,
3296  &hashable);
3297  reverse = false;
3298  break;
3299  case SORTBY_DESC:
3300  get_sort_group_operators(restype,
3301  false, true, true,
3302  NULL, &eqop, &sortop,
3303  &hashable);
3304  reverse = true;
3305  break;
3306  case SORTBY_USING:
3307  Assert(sortby->useOp != NIL);
3308  sortop = compatible_oper_opid(sortby->useOp,
3309  restype,
3310  restype,
3311  false);
3312 
3313  /*
3314  * Verify it's a valid ordering operator, fetch the corresponding
3315  * equality operator, and determine whether to consider it like
3316  * ASC or DESC.
3317  */
3318  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3319  if (!OidIsValid(eqop))
3320  ereport(ERROR,
3321  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3322  errmsg("operator %s is not a valid ordering operator",
3323  strVal(llast(sortby->useOp))),
3324  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3325 
3326  /*
3327  * Also see if the equality operator is hashable.
3328  */
3329  hashable = op_hashjoinable(eqop, restype);
3330  break;
3331  default:
3332  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3333  sortop = InvalidOid; /* keep compiler quiet */
3334  eqop = InvalidOid;
3335  hashable = false;
3336  reverse = false;
3337  break;
3338  }
3339 
3341 
3342  /* avoid making duplicate sortlist entries */
3343  if (!targetIsInSortList(tle, sortop, sortlist))
3344  {
3346 
3347  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3348 
3349  sortcl->eqop = eqop;
3350  sortcl->sortop = sortop;
3351  sortcl->hashable = hashable;
3352 
3353  switch (sortby->sortby_nulls)
3354  {
3355  case SORTBY_NULLS_DEFAULT:
3356  /* NULLS FIRST is default for DESC; other way for ASC */
3357  sortcl->nulls_first = reverse;
3358  break;
3359  case SORTBY_NULLS_FIRST:
3360  sortcl->nulls_first = true;
3361  break;
3362  case SORTBY_NULLS_LAST:
3363  sortcl->nulls_first = false;
3364  break;
3365  default:
3366  elog(ERROR, "unrecognized sortby_nulls: %d",
3367  sortby->sortby_nulls);
3368  break;
3369  }
3370 
3371  sortlist = lappend(sortlist, sortcl);
3372  }
3373 
3374  return sortlist;
3375 }
#define NIL
Definition: pg_list.h:69
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
int errhint(const char *fmt,...)
Definition: elog.c:987
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
SortByDir sortby_dir
Definition: parsenodes.h:469
#define TEXTOID
Definition: pg_type.h:324
List * useOp
Definition: parsenodes.h:471
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:264
#define llast(l)
Definition: pg_list.h:131
Index tleSortGroupRef
Definition: parsenodes.h:1204
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:513
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:594
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1231
#define ERROR
Definition: elog.h:43
SortByNulls sortby_nulls
Definition: parsenodes.h:470
#define ereport(elevel, rest)
Definition: elog.h:122
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:128
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define makeNode(_type_)
Definition: nodes.h:561
#define Assert(condition)
Definition: c.h:688
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:1375
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
#define UNKNOWNOID
Definition: pg_type.h:431
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:494
#define elog
Definition: elog.h:219
Node * node
Definition: parsenodes.h:468
int location
Definition: parsenodes.h:472

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3451 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

3452 {
3453  Index maxRef;
3454  ListCell *l;
3455 
3456  if (tle->ressortgroupref) /* already has one? */
3457  return tle->ressortgroupref;
3458 
3459  /* easiest way to pick an unused refnumber: max used + 1 */
3460  maxRef = 0;
3461  foreach(l, tlist)
3462  {
3463  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3464 
3465  if (ref > maxRef)
3466  maxRef = ref;
3467  }
3468  tle->ressortgroupref = maxRef + 1;
3469  return tle->ressortgroupref;
3470 }
unsigned int Index
Definition: c.h:431
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1378

◆ interpretOidsOption()

bool interpretOidsOption ( List defList,
bool  allowOids 
)

Definition at line 262 of file parse_clause.c.

References default_with_oids, defGetBoolean(), DefElem::defname, DefElem::defnamespace, ereport, errcode(), errmsg(), ERROR, and lfirst.

Referenced by DefineRelation(), GetIntoRelEFlags(), and transformCreateStmt().

263 {
264  ListCell *cell;
265 
266  /* Scan list to see if OIDS was included */
267  foreach(cell, defList)
268  {
269  DefElem *def = (DefElem *) lfirst(cell);
270 
271  if (def->defnamespace == NULL &&
272  strcmp(def->defname, "oids") == 0)
273  {
274  if (!allowOids)
275  ereport(ERROR,
276  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
277  errmsg("unrecognized parameter \"%s\"",
278  def->defname)));
279  return defGetBoolean(def);
280  }
281  }
282 
283  /* Force no-OIDS result if caller disallows OIDS. */
284  if (!allowOids)
285  return false;
286 
287  /* OIDS option was not specified, so use default. */
288  return default_with_oids;
289 }
char * defnamespace
Definition: parsenodes.h:726
int errcode(int sqlerrcode)
Definition: elog.c:575
bool default_with_oids
Definition: guc.c:448
bool defGetBoolean(DefElem *def)
Definition: define.c:111
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define lfirst(lc)
Definition: pg_list.h:106
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * defname
Definition: parsenodes.h:727

◆ setTargetTable()

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

Definition at line 185 of file parse_clause.c.

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

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

187 {
188  RangeTblEntry *rte;
189  int rtindex;
190 
191  /*
192  * ENRs hide tables of the same name, so we need to check for them first.
193  * In contrast, CTEs don't hide tables (for this purpose).
194  */
195  if (relation->schemaname == NULL &&
196  scanNameSpaceForENR(pstate, relation->relname))
197  ereport(ERROR,
198  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
199  errmsg("relation \"%s\" cannot be the target of a modifying statement",
200  relation->relname)));
201 
202  /* Close old target; this could only happen for multi-action rules */
203  if (pstate->p_target_relation != NULL)
205 
206  /*
207  * Open target rel and grab suitable lock (which we will hold till end of
208  * transaction).
209  *
210  * free_parsestate() will eventually do the corresponding heap_close(),
211  * but *not* release the lock.
212  */
213  pstate->p_target_relation = parserOpenTable(pstate, relation,
215 
216  /*
217  * Now build an RTE.
218  */
219  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 }
Relation parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
int errcode(int sqlerrcode)
Definition: elog.c:575
AclMode requiredPerms
Definition: parsenodes.h:1067
#define heap_close(r, l)
Definition: heapam.h:97
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
#define ereport(elevel, rest)
Definition: elog.h:122
#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:185
#define Assert(condition)
Definition: c.h:688
static int list_length(const List *l)
Definition: pg_list.h:89
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation p_target_relation
Definition: parse_node.h:184
Alias * alias
Definition: primnodes.h:72
List * p_rtable
Definition: parse_node.h:174

◆ targetIsInSortList()

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

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

3493 {
3494  Index ref = tle->ressortgroupref;
3495  ListCell *l;
3496 
3497  /* no need to scan list if tle has no marker */
3498  if (ref == 0)
3499  return false;
3500 
3501  foreach(l, sortList)
3502  {
3503  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3504 
3505  if (scl->tleSortGroupRef == ref &&
3506  (sortop == InvalidOid ||
3507  sortop == scl->sortop ||
3508  sortop == get_commutator(scl->sortop)))
3509  return true;
3510  }
3511  return false;
3512 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1298
Index tleSortGroupRef
Definition: parsenodes.h:1204
unsigned int Index
Definition: c.h:431
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1378

◆ transformDistinctClause()

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

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

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

◆ transformDistinctOnClause()

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

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

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

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

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

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

◆ transformGroupClause()

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

Definition at line 2490 of file parse_clause.c.

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

Referenced by transformSelectStmt(), and transformWindowDefinitions().

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

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

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

1751 {
1752  Node *qual;
1753 
1754  if (clause == NULL)
1755  return NULL;
1756 
1757  qual = transformExpr(pstate, clause, exprKind);
1758 
1759  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1760 
1761  /* LIMIT can't refer to any variables of the current query */
1762  checkExprIsVarFree(pstate, qual, constructName);
1763 
1764  return qual;
1765 }
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:513
#define INT8OID
Definition: pg_type.h:304
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 3145 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().

3149 {
3150  InferClause *infer = onConflictClause->infer;
3151 
3152  *arbiterExpr = NIL;
3153  *arbiterWhere = NULL;
3154  *constraint = InvalidOid;
3155 
3156  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3157  ereport(ERROR,
3158  (errcode(ERRCODE_SYNTAX_ERROR),
3159  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3160  errhint("For example, ON CONFLICT (column_name)."),
3161  parser_errposition(pstate,
3162  exprLocation((Node *) onConflictClause))));
3163 
3164  /*
3165  * To simplify certain aspects of its design, speculative insertion into
3166  * system catalogs is disallowed
3167  */
3168  if (IsCatalogRelation(pstate->p_target_relation))
3169  ereport(ERROR,
3170  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3171  errmsg("ON CONFLICT is not supported with system catalog tables"),
3172  parser_errposition(pstate,
3173  exprLocation((Node *) onConflictClause))));
3174 
3175  /* Same applies to table used by logical decoding as catalog table */
3177  ereport(ERROR,
3178  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3179  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3181  parser_errposition(pstate,
3182  exprLocation((Node *) onConflictClause))));
3183 
3184  /* ON CONFLICT DO NOTHING does not require an inference clause */
3185  if (infer)
3186  {
3187  List *save_namespace;
3188 
3189  /*
3190  * While we process the arbiter expressions, accept only non-qualified
3191  * references to the target table. Hide any other relations.
3192  */
3193  save_namespace = pstate->p_namespace;
3194  pstate->p_namespace = NIL;
3195  addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
3196  false, false, true);
3197 
3198  if (infer->indexElems)
3199  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3200  pstate->p_target_relation);
3201 
3202  /*
3203  * Handling inference WHERE clause (for partial unique index
3204  * inference)
3205  */
3206  if (infer->whereClause)
3207  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3209 
3210  pstate->p_namespace = save_namespace;
3211 
3212  /*
3213  * If the arbiter is specified by constraint name, get the constraint
3214  * OID and mark the constrained columns as requiring SELECT privilege,
3215  * in the same way as would have happened if the arbiter had been
3216  * specified by explicit reference to the constraint's index columns.
3217  */
3218  if (infer->conname)
3219  {
3220  Oid relid = RelationGetRelid(pstate->p_target_relation);
3221  RangeTblEntry *rte = pstate->p_target_rangetblentry;
3222  Bitmapset *conattnos;
3223 
3224  conattnos = get_relation_constraint_attnos(relid, infer->conname,
3225  false, constraint);
3226 
3227  /* Make sure the rel as a whole is marked for SELECT access */
3228  rte->requiredPerms |= ACL_SELECT;
3229  /* Mark the constrained columns as requiring SELECT access */
3230  rte->selectedCols = bms_add_members(rte->selectedCols, conattnos);
3231  }
3232  }
3233 
3234  /*
3235  * It's convenient to form a list of expressions based on the
3236  * representation used by CREATE INDEX, since the same restrictions are
3237  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3238  * primnode representation is used for inference elements, and so
3239  * assign_query_collations() can be trusted to do the right thing with the
3240  * post parse analysis query tree inference clause representation.
3241  */
3242 }
#define NIL
Definition: pg_list.h:69
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:92
int errhint(const char *fmt,...)
Definition: elog.c:987
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
List * indexElems
Definition: parsenodes.h:1359
Definition: nodes.h:513
int errcode(int sqlerrcode)
Definition: elog.c:575
AclMode requiredPerms
Definition: parsenodes.h:1067
unsigned int Oid
Definition: postgres_ext.h:31
Bitmapset * selectedCols
Definition: parsenodes.h:1069
#define ERROR
Definition: elog.h:43
List * p_namespace
Definition: parse_node.h:178
char * conname
Definition: parsenodes.h:1361
Bitmapset * get_relation_constraint_attnos(Oid relid, const char *conname, bool missing_ok, Oid *constraintOid)
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define ACL_SELECT
Definition: parsenodes.h:73
RangeTblEntry * p_target_rangetblentry
Definition: parse_node.h:185
InferClause * infer
Definition: parsenodes.h:1375
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:324
#define InvalidOid
Definition: postgres_ext.h:36
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Node * whereClause
Definition: parsenodes.h:1360
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation p_target_relation
Definition: parse_node.h:184
OnConflictAction action
Definition: parsenodes.h:1374
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:425
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:799
static List * resolve_unique_index_expr(ParseState *pstate, InferClause *infer, Relation heapRel)

◆ transformSortClause()

List* transformSortClause ( ParseState pstate,
List orderlist,
List **  targetlist,
ParseExprKind  exprKind,
bool  useSQL99 
)

Definition at line 2590 of file parse_clause.c.

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

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

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

◆ transformWhereClause()

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

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

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

◆ transformWindowDefinitions()

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

Definition at line 2623 of file parse_clause.c.

References BTLessStrategyNumber, castNode, WindowClause::copiedOrder, copyObject, elog, WindowClause::endInRangeFunc, WindowDef::endOffset, WindowClause::endOffset, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, exprCollation(), findWindowClause(), FRAMEOPTION_DEFAULTS, FRAMEOPTION_END_OFFSET, FRAMEOPTION_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().

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