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

3210 {
3211  Oid restype = exprType((Node *) tle->expr);
3212  Oid sortop;
3213  Oid eqop;
3214  bool hashable;
3215  bool reverse;
3216  int location;
3217  ParseCallbackState pcbstate;
3218 
3219  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3220  if (restype == UNKNOWNOID)
3221  {
3222  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3223  restype, TEXTOID, -1,
3226  -1);
3227  restype = TEXTOID;
3228  }
3229 
3230  /*
3231  * Rather than clutter the API of get_sort_group_operators and the other
3232  * functions we're about to use, make use of error context callback to
3233  * mark any error reports with a parse position. We point to the operator
3234  * location if present, else to the expression being sorted. (NB: use the
3235  * original untransformed expression here; the TLE entry might well point
3236  * at a duplicate expression in the regular SELECT list.)
3237  */
3238  location = sortby->location;
3239  if (location < 0)
3240  location = exprLocation(sortby->node);
3241  setup_parser_errposition_callback(&pcbstate, pstate, location);
3242 
3243  /* determine the sortop, eqop, and directionality */
3244  switch (sortby->sortby_dir)
3245  {
3246  case SORTBY_DEFAULT:
3247  case SORTBY_ASC:
3248  get_sort_group_operators(restype,
3249  true, true, false,
3250  &sortop, &eqop, NULL,
3251  &hashable);
3252  reverse = false;
3253  break;
3254  case SORTBY_DESC:
3255  get_sort_group_operators(restype,
3256  false, true, true,
3257  NULL, &eqop, &sortop,
3258  &hashable);
3259  reverse = true;
3260  break;
3261  case SORTBY_USING:
3262  Assert(sortby->useOp != NIL);
3263  sortop = compatible_oper_opid(sortby->useOp,
3264  restype,
3265  restype,
3266  false);
3267 
3268  /*
3269  * Verify it's a valid ordering operator, fetch the corresponding
3270  * equality operator, and determine whether to consider it like
3271  * ASC or DESC.
3272  */
3273  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3274  if (!OidIsValid(eqop))
3275  ereport(ERROR,
3276  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3277  errmsg("operator %s is not a valid ordering operator",
3278  strVal(llast(sortby->useOp))),
3279  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3280 
3281  /*
3282  * Also see if the equality operator is hashable.
3283  */
3284  hashable = op_hashjoinable(eqop, restype);
3285  break;
3286  default:
3287  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3288  sortop = InvalidOid; /* keep compiler quiet */
3289  eqop = InvalidOid;
3290  hashable = false;
3291  reverse = false;
3292  break;
3293  }
3294 
3296 
3297  /* avoid making duplicate sortlist entries */
3298  if (!targetIsInSortList(tle, sortop, sortlist))
3299  {
3301 
3302  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3303 
3304  sortcl->eqop = eqop;
3305  sortcl->sortop = sortop;
3306  sortcl->hashable = hashable;
3307 
3308  switch (sortby->sortby_nulls)
3309  {
3310  case SORTBY_NULLS_DEFAULT:
3311  /* NULLS FIRST is default for DESC; other way for ASC */
3312  sortcl->nulls_first = reverse;
3313  break;
3314  case SORTBY_NULLS_FIRST:
3315  sortcl->nulls_first = true;
3316  break;
3317  case SORTBY_NULLS_LAST:
3318  sortcl->nulls_first = false;
3319  break;
3320  default:
3321  elog(ERROR, "unrecognized sortby_nulls: %d",
3322  sortby->sortby_nulls);
3323  break;
3324  }
3325 
3326  sortlist = lappend(sortlist, sortcl);
3327  }
3328 
3329  return sortlist;
3330 }
#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:1196
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:511
#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:576
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1246
#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:559
#define Assert(condition)
Definition: c.h:670
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 3406 of file parse_clause.c.

References lfirst, and TargetEntry::ressortgroupref.

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

3407 {
3408  Index maxRef;
3409  ListCell *l;
3410 
3411  if (tle->ressortgroupref) /* already has one? */
3412  return tle->ressortgroupref;
3413 
3414  /* easiest way to pick an unused refnumber: max used + 1 */
3415  maxRef = 0;
3416  foreach(l, tlist)
3417  {
3418  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3419 
3420  if (ref > maxRef)
3421  maxRef = ref;
3422  }
3423  tle->ressortgroupref = maxRef + 1;
3424  return tle->ressortgroupref;
3425 }
unsigned int Index
Definition: c.h:413
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1378

◆ interpretOidsOption()

bool interpretOidsOption ( List defList,
bool  allowOids 
)

Definition at line 255 of file parse_clause.c.

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

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

256 {
257  ListCell *cell;
258 
259  /* Scan list to see if OIDS was included */
260  foreach(cell, defList)
261  {
262  DefElem *def = (DefElem *) lfirst(cell);
263 
264  if (def->defnamespace == NULL &&
265  pg_strcasecmp(def->defname, "oids") == 0)
266  {
267  if (!allowOids)
268  ereport(ERROR,
269  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
270  errmsg("unrecognized parameter \"%s\"",
271  def->defname)));
272  return defGetBoolean(def);
273  }
274  }
275 
276  /* Force no-OIDS result if caller disallows OIDS. */
277  if (!allowOids)
278  return false;
279 
280  /* OIDS option was not specified, so use default. */
281  return default_with_oids;
282 }
char * defnamespace
Definition: parsenodes.h:718
int errcode(int sqlerrcode)
Definition: elog.c:575
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
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:719

◆ setTargetTable()

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

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

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

◆ targetIsInSortList()

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

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

3448 {
3449  Index ref = tle->ressortgroupref;
3450  ListCell *l;
3451 
3452  /* no need to scan list if tle has no marker */
3453  if (ref == 0)
3454  return false;
3455 
3456  foreach(l, sortList)
3457  {
3458  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3459 
3460  if (scl->tleSortGroupRef == ref &&
3461  (sortop == InvalidOid ||
3462  sortop == scl->sortop ||
3463  sortop == get_commutator(scl->sortop)))
3464  return true;
3465  }
3466  return false;
3467 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1313
Index tleSortGroupRef
Definition: parsenodes.h:1196
unsigned int Index
Definition: c.h:413
#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 2787 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().

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

◆ transformDistinctOnClause()

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

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

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

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

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

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

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

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

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

1744 {
1745  Node *qual;
1746 
1747  if (clause == NULL)
1748  return NULL;
1749 
1750  qual = transformExpr(pstate, clause, exprKind);
1751 
1752  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1753 
1754  /* LIMIT can't refer to any variables of the current query */
1755  checkExprIsVarFree(pstate, qual, constructName);
1756 
1757  return qual;
1758 }
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:511
#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 3100 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().

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

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

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

2588 {
2589  List *sortlist = NIL;
2590  ListCell *olitem;
2591 
2592  foreach(olitem, orderlist)
2593  {
2594  SortBy *sortby = (SortBy *) lfirst(olitem);
2595  TargetEntry *tle;
2596 
2597  if (useSQL99)
2598  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2599  targetlist, exprKind);
2600  else
2601  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2602  targetlist, exprKind);
2603 
2604  sortlist = addTargetToSortList(pstate, tle,
2605  sortlist, *targetlist, sortby);
2606  }
2607 
2608  return sortlist;
2609 }
#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 1715 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().

1717 {
1718  Node *qual;
1719 
1720  if (clause == NULL)
1721  return NULL;
1722 
1723  qual = transformExpr(pstate, clause, exprKind);
1724 
1725  qual = coerce_to_boolean(pstate, qual, constructName);
1726 
1727  return qual;
1728 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:511
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

◆ transformWindowDefinitions()

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

Definition at line 2616 of file parse_clause.c.

References WindowClause::copiedOrder, copyObject, WindowDef::endOffset, WindowClause::endOffset, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, findWindowClause(), FRAMEOPTION_DEFAULTS, WindowDef::frameOptions, WindowClause::frameOptions, lappend(), lfirst, WindowDef::location, makeNode, WindowDef::name, WindowClause::name, NIL, WindowDef::orderClause, WindowClause::orderClause, parser_errposition(), WindowDef::partitionClause, WindowClause::partitionClause, WindowDef::refname, WindowClause::refname, WindowDef::startOffset, WindowClause::startOffset, transformFrameOffset(), transformGroupClause(), transformSortClause(), and WindowClause::winref.

Referenced by transformSelectStmt().

2619 {
2620  List *result = NIL;
2621  Index winref = 0;
2622  ListCell *lc;
2623 
2624  foreach(lc, windowdefs)
2625  {
2626  WindowDef *windef = (WindowDef *) lfirst(lc);
2627  WindowClause *refwc = NULL;
2628  List *partitionClause;
2629  List *orderClause;
2630  WindowClause *wc;
2631 
2632  winref++;
2633 
2634  /*
2635  * Check for duplicate window names.
2636  */
2637  if (windef->name &&
2638  findWindowClause(result, windef->name) != NULL)
2639  ereport(ERROR,
2640  (errcode(ERRCODE_WINDOWING_ERROR),
2641  errmsg("window \"%s\" is already defined", windef->name),
2642  parser_errposition(pstate, windef->location)));
2643 
2644  /*
2645  * If it references a previous window, look that up.
2646  */
2647  if (windef->refname)
2648  {
2649  refwc = findWindowClause(result, windef->refname);
2650  if (refwc == NULL)
2651  ereport(ERROR,
2652  (errcode(ERRCODE_UNDEFINED_OBJECT),
2653  errmsg("window \"%s\" does not exist",
2654  windef->refname),
2655  parser_errposition(pstate, windef->location)));
2656  }
2657 
2658  /*
2659  * Transform PARTITION and ORDER specs, if any. These are treated
2660  * almost exactly like top-level GROUP BY and ORDER BY clauses,
2661  * including the special handling of nondefault operator semantics.
2662  */
2663  orderClause = transformSortClause(pstate,
2664  windef->orderClause,
2665  targetlist,
2667  true /* force SQL99 rules */ );
2668  partitionClause = transformGroupClause(pstate,
2669  windef->partitionClause,
2670  NULL,
2671  targetlist,
2672  orderClause,
2674  true /* force SQL99 rules */ );
2675 
2676  /*
2677  * And prepare the new WindowClause.
2678  */
2679  wc = makeNode(WindowClause);
2680  wc->name = windef->name;
2681  wc->refname = windef->refname;
2682 
2683  /*
2684  * Per spec, a windowdef that references a previous one copies the
2685  * previous partition clause (and mustn't specify its own). It can
2686  * specify its own ordering clause, but only if the previous one had
2687  * none. It always specifies its own frame clause, and the previous
2688  * one must not have a frame clause. Yeah, it's bizarre that each of
2689  * these cases works differently, but SQL:2008 says so; see 7.11
2690  * <window clause> syntax rule 10 and general rule 1. The frame
2691  * clause rule is especially bizarre because it makes "OVER foo"
2692  * different from "OVER (foo)", and requires the latter to throw an
2693  * error if foo has a nondefault frame clause. Well, ours not to
2694  * reason why, but we do go out of our way to throw a useful error
2695  * message for such cases.
2696  */
2697  if (refwc)
2698  {
2699  if (partitionClause)
2700  ereport(ERROR,
2701  (errcode(ERRCODE_WINDOWING_ERROR),
2702  errmsg("cannot override PARTITION BY clause of window \"%s\"",
2703  windef->refname),
2704  parser_errposition(pstate, windef->location)));
2706  }
2707  else
2708  wc->partitionClause = partitionClause;
2709  if (refwc)
2710  {
2711  if (orderClause && refwc->orderClause)
2712  ereport(ERROR,
2713  (errcode(ERRCODE_WINDOWING_ERROR),
2714  errmsg("cannot override ORDER BY clause of window \"%s\"",
2715  windef->refname),
2716  parser_errposition(pstate, windef->location)));
2717  if (orderClause)
2718  {
2719  wc->orderClause = orderClause;
2720  wc->copiedOrder = false;
2721  }
2722  else
2723  {
2724  wc->orderClause = copyObject(refwc->orderClause);
2725  wc->copiedOrder = true;
2726  }
2727  }
2728  else
2729  {
2730  wc->orderClause = orderClause;
2731  wc->copiedOrder = false;
2732  }
2733  if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2734  {
2735  /*
2736  * Use this message if this is a WINDOW clause, or if it's an OVER
2737  * clause that includes ORDER BY or framing clauses. (We already
2738  * rejected PARTITION BY above, so no need to check that.)
2739  */
2740  if (windef->name ||
2741  orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2742  ereport(ERROR,
2743  (errcode(ERRCODE_WINDOWING_ERROR),
2744  errmsg("cannot copy window \"%s\" because it has a frame clause",
2745  windef->refname),
2746  parser_errposition(pstate, windef->location)));
2747  /* Else this clause is just OVER (foo), so say this: */
2748  ereport(ERROR,
2749  (errcode(ERRCODE_WINDOWING_ERROR),
2750  errmsg("cannot copy window \"%s\" because it has a frame clause",
2751  windef->refname),
2752  errhint("Omit the parentheses in this OVER clause."),
2753  parser_errposition(pstate, windef->location)));
2754  }
2755  wc->frameOptions = windef->frameOptions;
2756  /* Process frame offset expressions */
2757  wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2758  windef->startOffset);
2759  wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2760  windef->endOffset);
2761  wc->winref = winref;
2762 
2763  result = lappend(result, wc);
2764  }
2765 
2766  return result;
2767 }
List * partitionClause
Definition: parsenodes.h:488
char * refname
Definition: parsenodes.h:1288
#define NIL
Definition: pg_list.h:69
bool copiedOrder
Definition: parsenodes.h:1295
int errhint(const char *fmt,...)
Definition: elog.c:987
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:524
int frameOptions
Definition: parsenodes.h:490
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
char * name
Definition: parsenodes.h:486
int errcode(int sqlerrcode)
Definition: elog.c:575
static Node * transformFrameOffset(ParseState *pstate, int frameOptions, Node *clause)
Node * startOffset
Definition: parsenodes.h:491
#define ERROR
Definition: elog.h:43
List * partitionClause
Definition: parsenodes.h:1289
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:1292
List * orderClause
Definition: parsenodes.h:489
unsigned int Index
Definition: c.h:413
#define makeNode(_type_)
Definition: nodes.h:559
#define lfirst(lc)
Definition: pg_list.h:106
Node * endOffset
Definition: parsenodes.h:1293
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
List * orderClause
Definition: parsenodes.h:1290
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * refname
Definition: parsenodes.h:487
#define copyObject(obj)
Definition: nodes.h:624
Definition: pg_list.h:45
static WindowClause * findWindowClause(List *wclist, const char *name)