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 3394 of file parse_clause.c.

3396 {
3397  Oid restype = exprType((Node *) tle->expr);
3398  Oid sortop;
3399  Oid eqop;
3400  bool hashable;
3401  bool reverse;
3402  int location;
3403  ParseCallbackState pcbstate;
3404 
3405  /* if tlist item is an UNKNOWN literal, change it to TEXT */
3406  if (restype == UNKNOWNOID)
3407  {
3408  tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3409  restype, TEXTOID, -1,
3412  -1);
3413  restype = TEXTOID;
3414  }
3415 
3416  /*
3417  * Rather than clutter the API of get_sort_group_operators and the other
3418  * functions we're about to use, make use of error context callback to
3419  * mark any error reports with a parse position. We point to the operator
3420  * location if present, else to the expression being sorted. (NB: use the
3421  * original untransformed expression here; the TLE entry might well point
3422  * at a duplicate expression in the regular SELECT list.)
3423  */
3424  location = sortby->location;
3425  if (location < 0)
3426  location = exprLocation(sortby->node);
3427  setup_parser_errposition_callback(&pcbstate, pstate, location);
3428 
3429  /* determine the sortop, eqop, and directionality */
3430  switch (sortby->sortby_dir)
3431  {
3432  case SORTBY_DEFAULT:
3433  case SORTBY_ASC:
3434  get_sort_group_operators(restype,
3435  true, true, false,
3436  &sortop, &eqop, NULL,
3437  &hashable);
3438  reverse = false;
3439  break;
3440  case SORTBY_DESC:
3441  get_sort_group_operators(restype,
3442  false, true, true,
3443  NULL, &eqop, &sortop,
3444  &hashable);
3445  reverse = true;
3446  break;
3447  case SORTBY_USING:
3448  Assert(sortby->useOp != NIL);
3449  sortop = compatible_oper_opid(sortby->useOp,
3450  restype,
3451  restype,
3452  false);
3453 
3454  /*
3455  * Verify it's a valid ordering operator, fetch the corresponding
3456  * equality operator, and determine whether to consider it like
3457  * ASC or DESC.
3458  */
3459  eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3460  if (!OidIsValid(eqop))
3461  ereport(ERROR,
3462  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3463  errmsg("operator %s is not a valid ordering operator",
3464  strVal(llast(sortby->useOp))),
3465  errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3466 
3467  /*
3468  * Also see if the equality operator is hashable.
3469  */
3470  hashable = op_hashjoinable(eqop, restype);
3471  break;
3472  default:
3473  elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3474  sortop = InvalidOid; /* keep compiler quiet */
3475  eqop = InvalidOid;
3476  hashable = false;
3477  reverse = false;
3478  break;
3479  }
3480 
3482 
3483  /* avoid making duplicate sortlist entries */
3484  if (!targetIsInSortList(tle, sortop, sortlist))
3485  {
3487 
3488  sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3489 
3490  sortcl->eqop = eqop;
3491  sortcl->sortop = sortop;
3492  sortcl->hashable = hashable;
3493 
3494  switch (sortby->sortby_nulls)
3495  {
3496  case SORTBY_NULLS_DEFAULT:
3497  /* NULLS FIRST is default for DESC; other way for ASC */
3498  sortcl->nulls_first = reverse;
3499  break;
3500  case SORTBY_NULLS_FIRST:
3501  sortcl->nulls_first = true;
3502  break;
3503  case SORTBY_NULLS_LAST:
3504  sortcl->nulls_first = false;
3505  break;
3506  default:
3507  elog(ERROR, "unrecognized sortby_nulls: %d",
3508  sortby->sortby_nulls);
3509  break;
3510  }
3511 
3512  sortlist = lappend(sortlist, sortcl);
3513  }
3514 
3515  return sortlist;
3516 }
#define Assert(condition)
Definition: c.h:858
#define OidIsValid(objectId)
Definition: c.h:775
int errhint(const char *fmt,...)
Definition: elog.c:1319
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
#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:1386
#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:706
@ COERCION_IMPLICIT
Definition: primnodes.h:684
Definition: nodes.h:129
SortByNulls sortby_nulls
Definition: parsenodes.h:548
Node * node
Definition: parsenodes.h:546
List * useOp
Definition: parsenodes.h:549
SortByDir sortby_dir
Definition: parsenodes.h:547
ParseLoc location
Definition: parsenodes.h:550
Index tleSortGroupRef
Definition: parsenodes.h:1442
Expr * expr
Definition: primnodes.h:2162
#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(), 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:614
#define lfirst(lc)
Definition: pg_list.h:172
Index ressortgroupref
Definition: primnodes.h:2168

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 180 of file parse_clause.c.

182 {
183  ParseNamespaceItem *nsitem;
184 
185  /*
186  * ENRs hide tables of the same name, so we need to check for them first.
187  * In contrast, CTEs don't hide tables (for this purpose).
188  */
189  if (relation->schemaname == NULL &&
190  scanNameSpaceForENR(pstate, relation->relname))
191  ereport(ERROR,
192  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
193  errmsg("relation \"%s\" cannot be the target of a modifying statement",
194  relation->relname)));
195 
196  /* Close old target; this could only happen for multi-action rules */
197  if (pstate->p_target_relation != NULL)
199 
200  /*
201  * Open target rel and grab suitable lock (which we will hold till end of
202  * transaction).
203  *
204  * free_parsestate() will eventually do the corresponding table_close(),
205  * but *not* release the lock.
206  */
207  pstate->p_target_relation = parserOpenTable(pstate, relation,
209 
210  /*
211  * Now build an RTE and a ParseNamespaceItem.
212  */
213  nsitem = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
215  relation->alias, inh, false);
216 
217  /* remember the RTE/nsitem as being the query target */
218  pstate->p_target_nsitem = nsitem;
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  nsitem->p_perminfo->requiredPerms = requiredPerms;
230 
231  /*
232  * If UPDATE/DELETE, add table to joinlist and namespace.
233  */
234  if (alsoSource)
235  addNSItemToQuery(pstate, nsitem, true, true, true);
236 
237  return nsitem->p_rtindex;
238 }
#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:289
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:208
Relation p_target_relation
Definition: parse_node.h:207
AclMode requiredPerms
Definition: parsenodes.h:1295
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 2986 of file parse_clause.c.

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

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

115 {
116  ListCell *fl;
117 
118  /*
119  * The grammar will have produced a list of RangeVars, RangeSubselects,
120  * RangeFunctions, and/or JoinExprs. Transform each one (possibly adding
121  * entries to the rtable), check for duplicate refnames, and then add it
122  * to the joinlist and namespace.
123  *
124  * Note we must process the items left-to-right for proper handling of
125  * LATERAL references.
126  */
127  foreach(fl, frmList)
128  {
129  Node *n = lfirst(fl);
130  ParseNamespaceItem *nsitem;
131  List *namespace;
132 
133  n = transformFromClauseItem(pstate, n,
134  &nsitem,
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 }
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:201
List * p_joinlist
Definition: parse_node.h:199

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 2632 of file parse_clause.c.

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

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

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 1881 of file parse_clause.c.

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

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

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 2732 of file parse_clause.c.

2737 {
2738  List *sortlist = NIL;
2739  ListCell *olitem;
2740 
2741  foreach(olitem, orderlist)
2742  {
2743  SortBy *sortby = (SortBy *) lfirst(olitem);
2744  TargetEntry *tle;
2745 
2746  if (useSQL99)
2747  tle = findTargetlistEntrySQL99(pstate, sortby->node,
2748  targetlist, exprKind);
2749  else
2750  tle = findTargetlistEntrySQL92(pstate, sortby->node,
2751  targetlist, exprKind);
2752 
2753  sortlist = addTargetToSortList(pstate, tle,
2754  sortlist, *targetlist, sortby);
2755  }
2756 
2757  return sortlist;
2758 }
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 1854 of file parse_clause.c.

1856 {
1857  Node *qual;
1858 
1859  if (clause == NULL)
1860  return NULL;
1861 
1862  qual = transformExpr(pstate, clause, exprKind);
1863 
1864  qual = coerce_to_boolean(pstate, qual, constructName);
1865 
1866  return qual;
1867 }
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 2765 of file parse_clause.c.

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

References BTLessStrategyNumber, 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::sortop, WindowDef::startOffset, WindowClause::startOffset, transformFrameOffset(), transformGroupClause(), transformSortClause(), and WindowClause::winref.

Referenced by transformPLAssignStmt(), and transformSelectStmt().