PostgreSQL Source Code  git master
parse_clause.h File Reference
Include dependency graph for parse_clause.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void transformFromClause (ParseState *pstate, List *frmList)
 
int setTargetTable (ParseState *pstate, RangeVar *relation, bool inh, bool alsoSource, AclMode requiredPerms)
 
NodetransformWhereClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
 
NodetransformLimitClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName, LimitOption limitOption)
 
ListtransformGroupClause (ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
 
ListtransformSortClause (ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
 
ListtransformWindowDefinitions (ParseState *pstate, List *windowdefs, List **targetlist)
 
ListtransformDistinctClause (ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
 
ListtransformDistinctOnClause (ParseState *pstate, List *distinctlist, List **targetlist, List *sortClause)
 
void transformOnConflictArbiter (ParseState *pstate, OnConflictClause *onConflictClause, List **arbiterExpr, Node **arbiterWhere, Oid *constraint)
 
ListaddTargetToSortList (ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
 
Index assignSortGroupRef (TargetEntry *tle, List *tlist)
 
bool targetIsInSortList (TargetEntry *tle, Oid sortop, List *sortList)
 
ParseNamespaceItemtransformJsonTable (ParseState *pstate, JsonTable *jt)
 

Function Documentation

◆ addTargetToSortList()

List* addTargetToSortList ( ParseState pstate,
TargetEntry tle,
List sortlist,
List targetlist,
SortBy sortby 
)

Definition at line 3391 of file parse_clause.c.

3393 {
3394  Oid restype = exprType((Node *) tle->expr);
3395  Oid sortop;
3396  Oid eqop;
3397  bool hashable;
3398  bool reverse;
3399  int location;
3400  ParseCallbackState pcbstate;
3401 
3402  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3403  if (restype == UNKNOWNOID)
3404  {
3405  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3406  restype, TEXTOID, -1,
3409  -1);
3410  restype = TEXTOID;
3411  }
3412 
3413  /*
3414  * Rather than clutter the API of get_sort_group_operators and the other
3415  * functions we're about to use, make use of error context callback to
3416  * mark any error reports with a parse position. We point to the operator
3417  * location if present, else to the expression being sorted. (NB: use the
3418  * original untransformed expression here; the TLE entry might well point
3419  * at a duplicate expression in the regular SELECT list.)
3420  */
3421  location = sortby->location;
3422  if (location < 0)
3423  location = exprLocation(sortby->node);
3424  setup_parser_errposition_callback(&pcbstate, pstate, location);
3425 
3426  /* determine the sortop, eqop, and directionality */
3427  switch (sortby->sortby_dir)
3428  {
3429  case SORTBY_DEFAULT:
3430  case SORTBY_ASC:
3431  get_sort_group_operators(restype,
3432  true, true, false,
3433  &sortop, &eqop, NULL,
3434  &hashable);
3435  reverse = false;
3436  break;
3437  case SORTBY_DESC:
3438  get_sort_group_operators(restype,
3439  false, true, true,
3440  NULL, &eqop, &sortop,
3441  &hashable);
3442  reverse = true;
3443  break;
3444  case SORTBY_USING:
3445  Assert(sortby->useOp != NIL);
3446  sortop = compatible_oper_opid(sortby->useOp,
3447  restype,
3448  restype,
3449  false);
3450 
3451  /*
3452  * Verify it's a valid ordering operator, fetch the corresponding
3453  * equality operator, and determine whether to consider it like
3454  * ASC or DESC.
3455  */
3456  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3457  if (!OidIsValid(eqop))
3458  ereport(ERROR,
3459  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3460  errmsg("operator %s is not a valid ordering operator",
3461  strVal(llast(sortby->useOp))),
3462  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3463 
3464  /*
3465  * Also see if the equality operator is hashable.
3466  */
3467  hashable = op_hashjoinable(eqop, restype);
3468  break;
3469  default:
3470  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3471  sortop = InvalidOid; /* keep compiler quiet */
3472  eqop = InvalidOid;
3473  hashable = false;
3474  reverse = false;
3475  break;
3476  }
3477 
3479 
3480  /* avoid making duplicate sortlist entries */
3481  if (!targetIsInSortList(tle, sortop, sortlist))
3482  {
3484 
3485  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3486 
3487  sortcl->eqop = eqop;
3488  sortcl->sortop = sortop;
3489  sortcl->hashable = hashable;
3490  sortcl->reverse_sort = reverse;
3491 
3492  switch (sortby->sortby_nulls)
3493  {
3494  case SORTBY_NULLS_DEFAULT:
3495  /* NULLS FIRST is default for DESC; other way for ASC */
3496  sortcl->nulls_first = reverse;
3497  break;
3498  case SORTBY_NULLS_FIRST:
3499  sortcl->nulls_first = true;
3500  break;
3501  case SORTBY_NULLS_LAST:
3502  sortcl->nulls_first = false;
3503  break;
3504  default:
3505  elog(ERROR, "unrecognized sortby_nulls: %d",
3506  sortby->sortby_nulls);
3507  break;
3508  }
3509 
3510  sortlist = lappend(sortlist, sortcl);
3511  }
3512 
3513  return sortlist;
3514 }
#define Assert(condition)
Definition: c.h:812
#define OidIsValid(objectId)
Definition: c.h:729
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
List * lappend(List *list, void *datum)
Definition: list.c:339
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:267
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1437
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1380
#define makeNode(_type_)
Definition: nodes.h:155
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:157
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:156
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:140
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:180
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:487
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:54
@ SORTBY_NULLS_LAST
Definition: parsenodes.h:56
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:55
@ SORTBY_USING
Definition: parsenodes.h:49
@ SORTBY_DESC
Definition: parsenodes.h:48
@ SORTBY_ASC
Definition: parsenodes.h:47
@ SORTBY_DEFAULT
Definition: parsenodes.h:46
#define llast(l)
Definition: pg_list.h:198
#define NIL
Definition: pg_list.h:68
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:736
@ COERCION_IMPLICIT
Definition: primnodes.h:714
Definition: nodes.h:129
SortByNulls sortby_nulls
Definition: parsenodes.h:550
Node * node
Definition: parsenodes.h:548
List * useOp
Definition: parsenodes.h:551
SortByDir sortby_dir
Definition: parsenodes.h:549
ParseLoc location
Definition: parsenodes.h:552
Index tleSortGroupRef
Definition: parsenodes.h:1438
Expr * expr
Definition: primnodes.h:2190
#define strVal(v)
Definition: value.h:82

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(), InvalidOid, lappend(), llast, SortBy::location, makeNode, NIL, SortBy::node, SortGroupClause::nulls_first, OidIsValid, op_hashjoinable(), SortGroupClause::reverse_sort, setup_parser_errposition_callback(), SORTBY_ASC, SORTBY_DEFAULT, SORTBY_DESC, SortBy::sortby_dir, SortBy::sortby_nulls, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, SORTBY_USING, SortGroupClause::sortop, strVal, targetIsInSortList(), SortGroupClause::tleSortGroupRef, and SortBy::useOp.

Referenced by transformAggregateCall(), and transformSortClause().

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3592 of file parse_clause.c.

3593 {
3594  Index maxRef;
3595  ListCell *l;
3596 
3597  if (tle->ressortgroupref) /* already has one? */
3598  return tle->ressortgroupref;
3599 
3600  /* easiest way to pick an unused refnumber: max used + 1 */
3601  maxRef = 0;
3602  foreach(l, tlist)
3603  {
3604  Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3605 
3606  if (ref > maxRef)
3607  maxRef = ref;
3608  }
3609  tle->ressortgroupref = maxRef + 1;
3610  return tle->ressortgroupref;
3611 }
unsigned int Index
Definition: c.h:568
#define lfirst(lc)
Definition: pg_list.h:172
Index ressortgroupref
Definition: primnodes.h:2196

References lfirst, and TargetEntry::ressortgroupref.

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

◆ setTargetTable()

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

Definition at line 178 of file parse_clause.c.

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

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

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

◆ targetIsInSortList()

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

Definition at line 3633 of file parse_clause.c.

3634 {
3635  Index ref = tle->ressortgroupref;
3636  ListCell *l;
3637 
3638  /* no need to scan list if tle has no marker */
3639  if (ref == 0)
3640  return false;
3641 
3642  foreach(l, sortList)
3643  {
3644  SortGroupClause *scl = (SortGroupClause *) lfirst(l);
3645 
3646  if (scl->tleSortGroupRef == ref &&
3647  (sortop == InvalidOid ||
3648  sortop == scl->sortop ||
3649  sortop == get_commutator(scl->sortop)))
3650  return true;
3651  }
3652  return false;
3653 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1509

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

◆ transformDistinctClause()

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

Definition at line 2983 of file parse_clause.c.

2985 {
2986  List *result = NIL;
2987  ListCell *slitem;
2988  ListCell *tlitem;
2989 
2990  /*
2991  * The distinctClause should consist of all ORDER BY items followed by all
2992  * other non-resjunk targetlist items. There must not be any resjunk
2993  * ORDER BY items --- that would imply that we are sorting by a value that
2994  * isn't necessarily unique within a DISTINCT group, so the results
2995  * wouldn't be well-defined. This construction ensures we follow the rule
2996  * that sortClause and distinctClause match; in fact the sortClause will
2997  * always be a prefix of distinctClause.
2998  *
2999  * Note a corner case: the same TLE could be in the ORDER BY list multiple
3000  * times with different sortops. We have to include it in the
3001  * distinctClause the same way to preserve the prefix property. The net
3002  * effect will be that the TLE value will be made unique according to both
3003  * sortops.
3004  */
3005  foreach(slitem, sortClause)
3006  {
3007  SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
3008  TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
3009 
3010  if (tle->resjunk)
3011  ereport(ERROR,
3012  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3013  is_agg ?
3014  errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
3015  errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
3016  parser_errposition(pstate,
3017  exprLocation((Node *) tle->expr))));
3018  result = lappend(result, copyObject(scl));
3019  }
3020 
3021  /*
3022  * Now add any remaining non-resjunk tlist items, using default sort/group
3023  * semantics for their data types.
3024  */
3025  foreach(tlitem, *targetlist)
3026  {
3027  TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
3028 
3029  if (tle->resjunk)
3030  continue; /* ignore junk */
3031  result = addTargetToGroupList(pstate, tle,
3032  result, *targetlist,
3033  exprLocation((Node *) tle->expr));
3034  }
3035 
3036  /*
3037  * Complain if we found nothing to make DISTINCT. Returning an empty list
3038  * would cause the parsed Query to look like it didn't have DISTINCT, with
3039  * results that would probably surprise the user. Note: this case is
3040  * presently impossible for aggregates because of grammar restrictions,
3041  * but we check anyway.
3042  */
3043  if (result == NIL)
3044  ereport(ERROR,
3045  (errcode(ERRCODE_SYNTAX_ERROR),
3046  is_agg ?
3047  errmsg("an aggregate with DISTINCT must have at least one argument") :
3048  errmsg("SELECT DISTINCT must have at least one column")));
3049 
3050  return result;
3051 }
#define copyObject(obj)
Definition: nodes.h:224
static List * addTargetToGroupList(ParseState *pstate, TargetEntry *tle, List *grouplist, List *targetlist, int location)
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
Definition: pg_list.h:54
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:367

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

Referenced by transformAggregateCall(), transformPLAssignStmt(), and transformSelectStmt().

◆ transformDistinctOnClause()

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

Definition at line 3067 of file parse_clause.c.

3069 {
3070  List *result = NIL;
3071  List *sortgrouprefs = NIL;
3072  bool skipped_sortitem;
3073  ListCell *lc;
3074  ListCell *lc2;
3075 
3076  /*
3077  * Add all the DISTINCT ON expressions to the tlist (if not already
3078  * present, they are added as resjunk items). Assign sortgroupref numbers
3079  * to them, and make a list of these numbers. (NB: we rely below on the
3080  * sortgrouprefs list being one-for-one with the original distinctlist.
3081  * Also notice that we could have duplicate DISTINCT ON expressions and
3082  * hence duplicate entries in sortgrouprefs.)
3083  */
3084  foreach(lc, distinctlist)
3085  {
3086  Node *dexpr = (Node *) lfirst(lc);
3087  int sortgroupref;
3088  TargetEntry *tle;
3089 
3090  tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
3092  sortgroupref = assignSortGroupRef(tle, *targetlist);
3093  sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
3094  }
3095 
3096  /*
3097  * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
3098  * semantics from ORDER BY items that match DISTINCT ON items, and also
3099  * adopt their column sort order. We insist that the distinctClause and
3100  * sortClause match, so throw error if we find the need to add any more
3101  * distinctClause items after we've skipped an ORDER BY item that wasn't
3102  * in DISTINCT ON.
3103  */
3104  skipped_sortitem = false;
3105  foreach(lc, sortClause)
3106  {
3107  SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
3108 
3109  if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
3110  {
3111  if (skipped_sortitem)
3112  ereport(ERROR,
3113  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3114  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3115  parser_errposition(pstate,
3117  sortgrouprefs,
3118  distinctlist))));
3119  else
3120  result = lappend(result, copyObject(scl));
3121  }
3122  else
3123  skipped_sortitem = true;
3124  }
3125 
3126  /*
3127  * Now add any remaining DISTINCT ON items, using default sort/group
3128  * semantics for their data types. (Note: this is pretty questionable; if
3129  * the ORDER BY list doesn't include all the DISTINCT ON items and more
3130  * besides, you certainly aren't using DISTINCT ON in the intended way,
3131  * and you probably aren't going to get consistent results. It might be
3132  * better to throw an error or warning here. But historically we've
3133  * allowed it, so keep doing so.)
3134  */
3135  forboth(lc, distinctlist, lc2, sortgrouprefs)
3136  {
3137  Node *dexpr = (Node *) lfirst(lc);
3138  int sortgroupref = lfirst_int(lc2);
3139  TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
3140 
3141  if (targetIsInSortList(tle, InvalidOid, result))
3142  continue; /* already in list (with some semantics) */
3143  if (skipped_sortitem)
3144  ereport(ERROR,
3145  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3146  errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3147  parser_errposition(pstate, exprLocation(dexpr))));
3148  result = addTargetToGroupList(pstate, tle,
3149  result, *targetlist,
3150  exprLocation(dexpr));
3151  }
3152 
3153  /*
3154  * An empty result list is impossible here because of grammar
3155  * restrictions.
3156  */
3157  Assert(result != NIL);
3158 
3159  return result;
3160 }
List * lappend_int(List *list, int datum)
Definition: list.c:357
bool list_member_int(const List *list, int datum)
Definition: list.c:702
static int get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
static TargetEntry * findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
@ EXPR_KIND_DISTINCT_ON
Definition: parse_node.h:61
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#define lfirst_int(lc)
Definition: pg_list.h:173
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:345

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

Referenced by transformPLAssignStmt(), and transformSelectStmt().

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 112 of file parse_clause.c.

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  ParseNamespaceItem *nsitem;
129  List *namespace;
130 
131  n = transformFromClauseItem(pstate, n,
132  &nsitem,
133  &namespace);
134 
135  checkNameSpaceConflicts(pstate, pstate->p_namespace, namespace);
136 
137  /* Mark the new namespace items as visible only to LATERAL */
138  setNamespaceLateralState(namespace, true, true);
139 
140  pstate->p_joinlist = lappend(pstate->p_joinlist, n);
141  pstate->p_namespace = list_concat(pstate->p_namespace, namespace);
142  }
143 
144  /*
145  * We're done parsing the FROM list, so make all namespace items
146  * unconditionally visible. Note that this will also reset lateral_only
147  * for any namespace items that were already present when we were called;
148  * but those should have been that way already.
149  */
150  setNamespaceLateralState(pstate->p_namespace, false, true);
151 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
static void setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
static Node * transformFromClauseItem(ParseState *pstate, Node *n, ParseNamespaceItem **top_nsitem, List **namespace)
void checkNameSpaceConflicts(ParseState *pstate, List *namespace1, List *namespace2)
List * p_namespace
Definition: parse_node.h:219
List * p_joinlist
Definition: parse_node.h:217

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

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

◆ transformGroupClause()

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

Definition at line 2630 of file parse_clause.c.

2633 {
2634  List *result = NIL;
2635  List *flat_grouplist;
2636  List *gsets = NIL;
2637  ListCell *gl;
2638  bool hasGroupingSets = false;
2639  Bitmapset *seen_local = NULL;
2640 
2641  /*
2642  * Recursively flatten implicit RowExprs. (Technically this is only needed
2643  * for GROUP BY, per the syntax rules for grouping sets, but we do it
2644  * anyway.)
2645  */
2646  flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
2647  true,
2648  &hasGroupingSets);
2649 
2650  /*
2651  * If the list is now empty, but hasGroupingSets is true, it's because we
2652  * elided redundant empty grouping sets. Restore a single empty grouping
2653  * set to leave a canonical form: GROUP BY ()
2654  */
2655 
2656  if (flat_grouplist == NIL && hasGroupingSets)
2657  {
2659  NIL,
2660  exprLocation((Node *) grouplist)));
2661  }
2662 
2663  foreach(gl, flat_grouplist)
2664  {
2665  Node *gexpr = (Node *) lfirst(gl);
2666 
2667  if (IsA(gexpr, GroupingSet))
2668  {
2669  GroupingSet *gset = (GroupingSet *) gexpr;
2670 
2671  switch (gset->kind)
2672  {
2673  case GROUPING_SET_EMPTY:
2674  gsets = lappend(gsets, gset);
2675  break;
2676  case GROUPING_SET_SIMPLE:
2677  /* can't happen */
2678  Assert(false);
2679  break;
2680  case GROUPING_SET_SETS:
2681  case GROUPING_SET_CUBE:
2682  case GROUPING_SET_ROLLUP:
2683  gsets = lappend(gsets,
2684  transformGroupingSet(&result,
2685  pstate, gset,
2686  targetlist, sortClause,
2687  exprKind, useSQL99, true));
2688  break;
2689  }
2690  }
2691  else
2692  {
2693  Index ref = transformGroupClauseExpr(&result, seen_local,
2694  pstate, gexpr,
2695  targetlist, sortClause,
2696  exprKind, useSQL99, true);
2697 
2698  if (ref > 0)
2699  {
2700  seen_local = bms_add_member(seen_local, ref);
2701  if (hasGroupingSets)
2702  gsets = lappend(gsets,
2704  list_make1_int(ref),
2705  exprLocation(gexpr)));
2706  }
2707  }
2708  }
2709 
2710  /* parser should prevent this */
2711  Assert(gsets == NIL || groupingSets != NULL);
2712 
2713  if (groupingSets)
2714  *groupingSets = gsets;
2715 
2716  return result;
2717 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition: makefuncs.c:842
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
static Node * flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
static Index transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, ParseState *pstate, Node *gexpr, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
@ GROUPING_SET_CUBE
Definition: parsenodes.h:1502
@ GROUPING_SET_SIMPLE
Definition: parsenodes.h:1500
@ GROUPING_SET_ROLLUP
Definition: parsenodes.h:1501
@ GROUPING_SET_SETS
Definition: parsenodes.h:1503
@ GROUPING_SET_EMPTY
Definition: parsenodes.h:1499
#define list_make1(x1)
Definition: pg_list.h:212
#define list_make1_int(x1)
Definition: pg_list.h:227

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, lappend(), lfirst, list_make1, list_make1_int, makeGroupingSet(), NIL, transformGroupClauseExpr(), and transformGroupingSet().

Referenced by transformPLAssignStmt(), transformSelectStmt(), and transformWindowDefinitions().

◆ transformJsonTable()

ParseNamespaceItem* transformJsonTable ( ParseState pstate,
JsonTable jt 
)

Definition at line 74 of file parse_jsontable.c.

75 {
76  TableFunc *tf;
77  JsonFuncExpr *jfe;
78  JsonExpr *je;
79  JsonTablePathSpec *rootPathSpec = jt->pathspec;
80  bool is_lateral;
81  JsonTableParseContext cxt = {pstate};
82 
83  Assert(IsA(rootPathSpec->string, A_Const) &&
84  castNode(A_Const, rootPathSpec->string)->val.node.type == T_String);
85 
86  if (jt->on_error &&
90  ereport(ERROR,
91  errcode(ERRCODE_SYNTAX_ERROR),
92  errmsg("invalid %s behavior", "ON ERROR"),
93  errdetail("Only EMPTY [ ARRAY ] or ERROR is allowed in the top-level ON ERROR clause."),
94  parser_errposition(pstate, jt->on_error->location));
95 
96  cxt.pathNameId = 0;
97  if (rootPathSpec->name == NULL)
98  rootPathSpec->name = generateJsonTablePathName(&cxt);
99  cxt.pathNames = list_make1(rootPathSpec->name);
101 
102  /*
103  * We make lateral_only names of this level visible, whether or not the
104  * RangeTableFunc is explicitly marked LATERAL. This is needed for SQL
105  * spec compliance and seems useful on convenience grounds for all
106  * functions in FROM.
107  *
108  * (LATERAL can't nest within a single pstate level, so we don't need
109  * save/restore logic here.)
110  */
111  Assert(!pstate->p_lateral_active);
112  pstate->p_lateral_active = true;
113 
114  tf = makeNode(TableFunc);
115  tf->functype = TFT_JSON_TABLE;
116 
117  /*
118  * Transform JsonFuncExpr representing the top JSON_TABLE context_item and
119  * pathspec into a dummy JSON_TABLE_OP JsonExpr.
120  */
121  jfe = makeNode(JsonFuncExpr);
122  jfe->op = JSON_TABLE_OP;
123  jfe->context_item = jt->context_item;
124  jfe->pathspec = (Node *) rootPathSpec->string;
125  jfe->passing = jt->passing;
126  jfe->on_empty = NULL;
127  jfe->on_error = jt->on_error;
128  jfe->location = jt->location;
129  tf->docexpr = transformExpr(pstate, (Node *) jfe, EXPR_KIND_FROM_FUNCTION);
130 
131  /*
132  * Create a JsonTablePlan that will generate row pattern that becomes
133  * source data for JSON path expressions in jt->columns. This also adds
134  * the columns' transformed JsonExpr nodes into tf->colvalexprs.
135  */
136  cxt.jt = jt;
137  cxt.tf = tf;
138  tf->plan = (Node *) transformJsonTableColumns(&cxt, jt->columns,
139  jt->passing,
140  rootPathSpec);
141 
142  /*
143  * Copy the transformed PASSING arguments into the TableFunc node, because
144  * they are evaluated separately from the JsonExpr that we just put in
145  * TableFunc.docexpr. JsonExpr.passing_values is still kept around for
146  * get_json_table().
147  */
148  je = (JsonExpr *) tf->docexpr;
149  tf->passingvalexprs = copyObject(je->passing_values);
150 
151  tf->ordinalitycol = -1; /* undefine ordinality column number */
152  tf->location = jt->location;
153 
154  pstate->p_lateral_active = false;
155 
156  /*
157  * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
158  * there are any lateral cross-references in it.
159  */
160  is_lateral = jt->lateral || contain_vars_of_level((Node *) tf, 0);
161 
162  return addRangeTableEntryForTableFunc(pstate,
163  tf, jt->alias, is_lateral, true);
164 }
int errdetail(const char *fmt,...)
Definition: elog.c:1203
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:118
static char * generateJsonTablePathName(JsonTableParseContext *cxt)
static JsonTablePlan * transformJsonTableColumns(JsonTableParseContext *cxt, List *columns, List *passingArgs, JsonTablePathSpec *pathspec)
static void CheckDuplicateColumnOrPathNames(JsonTableParseContext *cxt, List *columns)
@ EXPR_KIND_FROM_FUNCTION
Definition: parse_node.h:45
ParseNamespaceItem * addRangeTableEntryForTableFunc(ParseState *pstate, TableFunc *tf, Alias *alias, bool lateral, bool inFromCl)
@ TFT_JSON_TABLE
Definition: primnodes.h:100
@ JSON_BEHAVIOR_ERROR
Definition: primnodes.h:1766
@ JSON_BEHAVIOR_EMPTY
Definition: primnodes.h:1767
@ JSON_BEHAVIOR_EMPTY_ARRAY
Definition: primnodes.h:1771
@ JSON_TABLE_OP
Definition: primnodes.h:1805
ParseLoc location
Definition: primnodes.h:1793
JsonBehaviorType btype
Definition: primnodes.h:1790
List * passing_values
Definition: primnodes.h:1836
JsonExprOp op
Definition: parsenodes.h:1788
List * passing
Definition: parsenodes.h:1793
JsonBehavior * on_empty
Definition: parsenodes.h:1795
ParseLoc location
Definition: parsenodes.h:1799
Node * pathspec
Definition: parsenodes.h:1792
JsonBehavior * on_error
Definition: parsenodes.h:1796
JsonValueExpr * context_item
Definition: parsenodes.h:1791
JsonBehavior * on_error
Definition: parsenodes.h:1828
List * columns
Definition: parsenodes.h:1827
JsonTablePathSpec * pathspec
Definition: parsenodes.h:1825
Alias * alias
Definition: parsenodes.h:1829
bool lateral
Definition: parsenodes.h:1830
List * passing
Definition: parsenodes.h:1826
JsonValueExpr * context_item
Definition: parsenodes.h:1824
ParseLoc location
Definition: parsenodes.h:1831
bool p_lateral_active
Definition: parse_node.h:221
ParseLoc location
Definition: primnodes.h:145
Node * docexpr
Definition: primnodes.h:119
TableFuncType functype
Definition: primnodes.h:113
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:443

References addRangeTableEntryForTableFunc(), JsonTable::alias, Assert, JsonBehavior::btype, castNode, CheckDuplicateColumnOrPathNames(), JsonTable::columns, contain_vars_of_level(), JsonFuncExpr::context_item, JsonTable::context_item, copyObject, TableFunc::docexpr, ereport, errcode(), errdetail(), errmsg(), ERROR, EXPR_KIND_FROM_FUNCTION, TableFunc::functype, generateJsonTablePathName(), IsA, JSON_BEHAVIOR_EMPTY, JSON_BEHAVIOR_EMPTY_ARRAY, JSON_BEHAVIOR_ERROR, JSON_TABLE_OP, JsonTableParseContext::jt, JsonTable::lateral, list_make1, JsonFuncExpr::location, JsonTable::location, TableFunc::location, JsonBehavior::location, makeNode, JsonTablePathSpec::name, JsonFuncExpr::on_empty, JsonFuncExpr::on_error, JsonTable::on_error, JsonFuncExpr::op, ParseState::p_lateral_active, parser_errposition(), JsonFuncExpr::passing, JsonTable::passing, JsonExpr::passing_values, JsonTableParseContext::pathNameId, JsonTableParseContext::pathNames, JsonFuncExpr::pathspec, JsonTable::pathspec, JsonTablePathSpec::string, JsonTableParseContext::tf, TFT_JSON_TABLE, transformExpr(), and transformJsonTableColumns().

Referenced by transformFromClauseItem().

◆ transformLimitClause()

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

Definition at line 1879 of file parse_clause.c.

1882 {
1883  Node *qual;
1884 
1885  if (clause == NULL)
1886  return NULL;
1887 
1888  qual = transformExpr(pstate, clause, exprKind);
1889 
1890  qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
1891 
1892  /* LIMIT can't refer to any variables of the current query */
1893  checkExprIsVarFree(pstate, qual, constructName);
1894 
1895  /*
1896  * Don't allow NULLs in FETCH FIRST .. WITH TIES. This test is ugly and
1897  * extremely simplistic, in that you can pass a NULL anyway by hiding it
1898  * inside an expression -- but this protects ruleutils against emitting an
1899  * unadorned NULL that's not accepted back by the grammar.
1900  */
1901  if (exprKind == EXPR_KIND_LIMIT && limitOption == LIMIT_OPTION_WITH_TIES &&
1902  IsA(clause, A_Const) && castNode(A_Const, clause)->isnull)
1903  ereport(ERROR,
1904  (errcode(ERRCODE_INVALID_ROW_COUNT_IN_LIMIT_CLAUSE),
1905  errmsg("row count cannot be null in FETCH FIRST ... WITH TIES clause")));
1906 
1907  return qual;
1908 }
@ LIMIT_OPTION_WITH_TIES
Definition: nodes.h:432
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
@ EXPR_KIND_LIMIT
Definition: parse_node.h:62

References castNode, checkExprIsVarFree(), coerce_to_specific_type(), ereport, errcode(), errmsg(), ERROR, EXPR_KIND_LIMIT, IsA, LIMIT_OPTION_WITH_TIES, and transformExpr().

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

◆ transformOnConflictArbiter()

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

Definition at line 3295 of file parse_clause.c.

3299 {
3300  InferClause *infer = onConflictClause->infer;
3301 
3302  *arbiterExpr = NIL;
3303  *arbiterWhere = NULL;
3304  *constraint = InvalidOid;
3305 
3306  if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3307  ereport(ERROR,
3308  (errcode(ERRCODE_SYNTAX_ERROR),
3309  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3310  errhint("For example, ON CONFLICT (column_name)."),
3311  parser_errposition(pstate,
3312  exprLocation((Node *) onConflictClause))));
3313 
3314  /*
3315  * To simplify certain aspects of its design, speculative insertion into
3316  * system catalogs is disallowed
3317  */
3318  if (IsCatalogRelation(pstate->p_target_relation))
3319  ereport(ERROR,
3320  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3321  errmsg("ON CONFLICT is not supported with system catalog tables"),
3322  parser_errposition(pstate,
3323  exprLocation((Node *) onConflictClause))));
3324 
3325  /* Same applies to table used by logical decoding as catalog table */
3327  ereport(ERROR,
3328  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3329  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3331  parser_errposition(pstate,
3332  exprLocation((Node *) onConflictClause))));
3333 
3334  /* ON CONFLICT DO NOTHING does not require an inference clause */
3335  if (infer)
3336  {
3337  if (infer->indexElems)
3338  *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3339  pstate->p_target_relation);
3340 
3341  /*
3342  * Handling inference WHERE clause (for partial unique index
3343  * inference)
3344  */
3345  if (infer->whereClause)
3346  *arbiterWhere = transformExpr(pstate, infer->whereClause,
3348 
3349  /*
3350  * If the arbiter is specified by constraint name, get the constraint
3351  * OID and mark the constrained columns as requiring SELECT privilege,
3352  * in the same way as would have happened if the arbiter had been
3353  * specified by explicit reference to the constraint's index columns.
3354  */
3355  if (infer->conname)
3356  {
3357  Oid relid = RelationGetRelid(pstate->p_target_relation);
3358  RTEPermissionInfo *perminfo = pstate->p_target_nsitem->p_perminfo;
3359  Bitmapset *conattnos;
3360 
3361  conattnos = get_relation_constraint_attnos(relid, infer->conname,
3362  false, constraint);
3363 
3364  /* Make sure the rel as a whole is marked for SELECT access */
3365  perminfo->requiredPerms |= ACL_SELECT;
3366  /* Mark the constrained columns as requiring SELECT access */
3367  perminfo->selectedCols = bms_add_members(perminfo->selectedCols,
3368  conattnos);
3369  }
3370  }
3371 
3372  /*
3373  * It's convenient to form a list of expressions based on the
3374  * representation used by CREATE INDEX, since the same restrictions are
3375  * appropriate (e.g. on subqueries). However, from here on, a dedicated
3376  * primnode representation is used for inference elements, and so
3377  * assign_query_collations() can be trusted to do the right thing with the
3378  * post parse analysis query tree inference clause representation.
3379  */
3380 }
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:917
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:103
@ ONCONFLICT_UPDATE
Definition: nodes.h:420
static List * resolve_unique_index_expr(ParseState *pstate, InferClause *infer, Relation heapRel)
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:73
#define ACL_SELECT
Definition: parsenodes.h:77
Bitmapset * get_relation_constraint_attnos(Oid relid, const char *conname, bool missing_ok, Oid *constraintOid)
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationIsUsedAsCatalogTable(relation)
Definition: rel.h:386
#define RelationGetRelationName(relation)
Definition: rel.h:539
char * conname
Definition: parsenodes.h:1611
List * indexElems
Definition: parsenodes.h:1609
Node * whereClause
Definition: parsenodes.h:1610
InferClause * infer
Definition: parsenodes.h:1625
OnConflictAction action
Definition: parsenodes.h:1624
Bitmapset * selectedCols
Definition: parsenodes.h:1293

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

Referenced by transformOnConflictClause().

◆ transformSortClause()

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

Definition at line 2730 of file parse_clause.c.

2735 {
2736  List *sortlist = NIL;
2737  ListCell *olitem;
2738 
2739  foreach(olitem, orderlist)
2740  {
2741  SortBy *sortby = (SortBy *) lfirst(olitem);
2742  TargetEntry *tle;
2743 
2744  if (useSQL99)
2745  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2746  targetlist, exprKind);
2747  else
2748  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2749  targetlist, exprKind);
2750 
2751  sortlist = addTargetToSortList(pstate, tle,
2752  sortlist, *targetlist, sortby);
2753  }
2754 
2755  return sortlist;
2756 }
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)

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

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

◆ transformWhereClause()

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

Definition at line 1852 of file parse_clause.c.

1854 {
1855  Node *qual;
1856 
1857  if (clause == NULL)
1858  return NULL;
1859 
1860  qual = transformExpr(pstate, clause, exprKind);
1861 
1862  qual = coerce_to_boolean(pstate, qual, constructName);
1863 
1864  return qual;
1865 }
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

References coerce_to_boolean(), and transformExpr().

Referenced by AlterPolicy(), CreatePolicy(), CreateTriggerFiringOn(), ParseFuncOrColumn(), test_rls_hooks_permissive(), test_rls_hooks_restrictive(), transformDeleteStmt(), transformIndexStmt(), transformJoinOnClause(), transformJsonAggConstructor(), transformMergeStmt(), transformOnConflictClause(), transformPLAssignStmt(), TransformPubWhereClauses(), transformRuleStmt(), transformSelectStmt(), and transformUpdateStmt().

◆ transformWindowDefinitions()

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

Definition at line 2763 of file parse_clause.c.

2766 {
2767  List *result = NIL;
2768  Index winref = 0;
2769  ListCell *lc;
2770 
2771  foreach(lc, windowdefs)
2772  {
2773  WindowDef *windef = (WindowDef *) lfirst(lc);
2774  WindowClause *refwc = NULL;
2775  List *partitionClause;
2776  List *orderClause;
2777  Oid rangeopfamily = InvalidOid;
2778  Oid rangeopcintype = InvalidOid;
2779  WindowClause *wc;
2780 
2781  winref++;
2782 
2783  /*
2784  * Check for duplicate window names.
2785  */
2786  if (windef->name &&
2787  findWindowClause(result, windef->name) != NULL)
2788  ereport(ERROR,
2789  (errcode(ERRCODE_WINDOWING_ERROR),
2790  errmsg("window \"%s\" is already defined", windef->name),
2791  parser_errposition(pstate, windef->location)));
2792 
2793  /*
2794  * If it references a previous window, look that up.
2795  */
2796  if (windef->refname)
2797  {
2798  refwc = findWindowClause(result, windef->refname);
2799  if (refwc == NULL)
2800  ereport(ERROR,
2801  (errcode(ERRCODE_UNDEFINED_OBJECT),
2802  errmsg("window \"%s\" does not exist",
2803  windef->refname),
2804  parser_errposition(pstate, windef->location)));
2805  }
2806 
2807  /*
2808  * Transform PARTITION and ORDER specs, if any. These are treated
2809  * almost exactly like top-level GROUP BY and ORDER BY clauses,
2810  * including the special handling of nondefault operator semantics.
2811  */
2812  orderClause = transformSortClause(pstate,
2813  windef->orderClause,
2814  targetlist,
2816  true /* force SQL99 rules */ );
2817  partitionClause = transformGroupClause(pstate,
2818  windef->partitionClause,
2819  NULL,
2820  targetlist,
2821  orderClause,
2823  true /* force SQL99 rules */ );
2824 
2825  /*
2826  * And prepare the new WindowClause.
2827  */
2828  wc = makeNode(WindowClause);
2829  wc->name = windef->name;
2830  wc->refname = windef->refname;
2831 
2832  /*
2833  * Per spec, a windowdef that references a previous one copies the
2834  * previous partition clause (and mustn't specify its own). It can
2835  * specify its own ordering clause, but only if the previous one had
2836  * none. It always specifies its own frame clause, and the previous
2837  * one must not have a frame clause. Yeah, it's bizarre that each of
2838  * these cases works differently, but SQL:2008 says so; see 7.11
2839  * <window clause> syntax rule 10 and general rule 1. The frame
2840  * clause rule is especially bizarre because it makes "OVER foo"
2841  * different from "OVER (foo)", and requires the latter to throw an
2842  * error if foo has a nondefault frame clause. Well, ours not to
2843  * reason why, but we do go out of our way to throw a useful error
2844  * message for such cases.
2845  */
2846  if (refwc)
2847  {
2848  if (partitionClause)
2849  ereport(ERROR,
2850  (errcode(ERRCODE_WINDOWING_ERROR),
2851  errmsg("cannot override PARTITION BY clause of window \"%s\"",
2852  windef->refname),
2853  parser_errposition(pstate, windef->location)));
2855  }
2856  else
2857  wc->partitionClause = partitionClause;
2858  if (refwc)
2859  {
2860  if (orderClause && refwc->orderClause)
2861  ereport(ERROR,
2862  (errcode(ERRCODE_WINDOWING_ERROR),
2863  errmsg("cannot override ORDER BY clause of window \"%s\"",
2864  windef->refname),
2865  parser_errposition(pstate, windef->location)));
2866  if (orderClause)
2867  {
2868  wc->orderClause = orderClause;
2869  wc->copiedOrder = false;
2870  }
2871  else
2872  {
2873  wc->orderClause = copyObject(refwc->orderClause);
2874  wc->copiedOrder = true;
2875  }
2876  }
2877  else
2878  {
2879  wc->orderClause = orderClause;
2880  wc->copiedOrder = false;
2881  }
2882  if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2883  {
2884  /*
2885  * Use this message if this is a WINDOW clause, or if it's an OVER
2886  * clause that includes ORDER BY or framing clauses. (We already
2887  * rejected PARTITION BY above, so no need to check that.)
2888  */
2889  if (windef->name ||
2890  orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2891  ereport(ERROR,
2892  (errcode(ERRCODE_WINDOWING_ERROR),
2893  errmsg("cannot copy window \"%s\" because it has a frame clause",
2894  windef->refname),
2895  parser_errposition(pstate, windef->location)));
2896  /* Else this clause is just OVER (foo), so say this: */
2897  ereport(ERROR,
2898  (errcode(ERRCODE_WINDOWING_ERROR),
2899  errmsg("cannot copy window \"%s\" because it has a frame clause",
2900  windef->refname),
2901  errhint("Omit the parentheses in this OVER clause."),
2902  parser_errposition(pstate, windef->location)));
2903  }
2904  wc->frameOptions = windef->frameOptions;
2905 
2906  /*
2907  * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
2908  * column; check that and get its sort opfamily info.
2909  */
2910  if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
2913  {
2914  SortGroupClause *sortcl;
2915  Node *sortkey;
2916  int16 rangestrategy;
2917 
2918  if (list_length(wc->orderClause) != 1)
2919  ereport(ERROR,
2920  (errcode(ERRCODE_WINDOWING_ERROR),
2921  errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
2922  parser_errposition(pstate, windef->location)));
2923  sortcl = linitial_node(SortGroupClause, wc->orderClause);
2924  sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
2925  /* Find the sort operator in pg_amop */
2926  if (!get_ordering_op_properties(sortcl->sortop,
2927  &rangeopfamily,
2928  &rangeopcintype,
2929  &rangestrategy))
2930  elog(ERROR, "operator %u is not a valid ordering operator",
2931  sortcl->sortop);
2932  /* Record properties of sort ordering */
2933  wc->inRangeColl = exprCollation(sortkey);
2934  wc->inRangeAsc = !sortcl->reverse_sort;
2935  wc->inRangeNullsFirst = sortcl->nulls_first;
2936  }
2937 
2938  /* Per spec, GROUPS mode requires an ORDER BY clause */
2939  if (wc->frameOptions & FRAMEOPTION_GROUPS)
2940  {
2941  if (wc->orderClause == NIL)
2942  ereport(ERROR,
2943  (errcode(ERRCODE_WINDOWING_ERROR),
2944  errmsg("GROUPS mode requires an ORDER BY clause"),
2945  parser_errposition(pstate, windef->location)));
2946  }
2947 
2948  /* Process frame offset expressions */
2949  wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
2950  rangeopfamily, rangeopcintype,
2951  &wc->startInRangeFunc,
2952  windef->startOffset);
2953  wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
2954  rangeopfamily, rangeopcintype,
2955  &wc->endInRangeFunc,
2956  windef->endOffset);
2957  wc->winref = winref;
2958 
2959  result = lappend(result, wc);
2960  }
2961 
2962  return result;
2963 }
int16_t int16
Definition: c.h:480
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:207
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:816
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
List * transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
static Node * transformFrameOffset(ParseState *pstate, int frameOptions, Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc, Node *clause)
static WindowClause * findWindowClause(List *wclist, const char *name)
@ EXPR_KIND_WINDOW_PARTITION
Definition: parse_node.h:49
@ EXPR_KIND_WINDOW_ORDER
Definition: parse_node.h:50
#define FRAMEOPTION_END_OFFSET
Definition: parsenodes.h:604
#define FRAMEOPTION_START_OFFSET
Definition: parsenodes.h:602
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:584
#define FRAMEOPTION_GROUPS
Definition: parsenodes.h:586
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:610
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial_node(type, l)
Definition: pg_list.h:181
Node * startOffset
Definition: parsenodes.h:1547
List * partitionClause
Definition: parsenodes.h:1543
Node * endOffset
Definition: parsenodes.h:1548
List * orderClause
Definition: parsenodes.h:1545
List * orderClause
Definition: parsenodes.h:569
ParseLoc location
Definition: parsenodes.h:573
List * partitionClause
Definition: parsenodes.h:568
Node * startOffset
Definition: parsenodes.h:571
char * refname
Definition: parsenodes.h:567
Node * endOffset
Definition: parsenodes.h:572
int frameOptions
Definition: parsenodes.h:570
char * name
Definition: parsenodes.h:566
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:379

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

Referenced by transformPLAssignStmt(), and transformSelectStmt().