PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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, bool groupByAll, 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 
)
extern

Definition at line 3461 of file parse_clause.c.

3463{
3464 Oid restype = exprType((Node *) tle->expr);
3465 Oid sortop;
3466 Oid eqop;
3467 bool hashable;
3468 bool reverse;
3469 int location;
3471
3472 /* if tlist item is an UNKNOWN literal, change it to TEXT */
3473 if (restype == UNKNOWNOID)
3474 {
3475 tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3476 restype, TEXTOID, -1,
3479 -1);
3480 restype = TEXTOID;
3481 }
3482
3483 /*
3484 * Rather than clutter the API of get_sort_group_operators and the other
3485 * functions we're about to use, make use of error context callback to
3486 * mark any error reports with a parse position. We point to the operator
3487 * location if present, else to the expression being sorted. (NB: use the
3488 * original untransformed expression here; the TLE entry might well point
3489 * at a duplicate expression in the regular SELECT list.)
3490 */
3491 location = sortby->location;
3492 if (location < 0)
3493 location = exprLocation(sortby->node);
3494 setup_parser_errposition_callback(&pcbstate, pstate, location);
3495
3496 /* determine the sortop, eqop, and directionality */
3497 switch (sortby->sortby_dir)
3498 {
3499 case SORTBY_DEFAULT:
3500 case SORTBY_ASC:
3502 true, true, false,
3503 &sortop, &eqop, NULL,
3504 &hashable);
3505 reverse = false;
3506 break;
3507 case SORTBY_DESC:
3509 false, true, true,
3510 NULL, &eqop, &sortop,
3511 &hashable);
3512 reverse = true;
3513 break;
3514 case SORTBY_USING:
3515 Assert(sortby->useOp != NIL);
3516 sortop = compatible_oper_opid(sortby->useOp,
3517 restype,
3518 restype,
3519 false);
3520
3521 /*
3522 * Verify it's a valid ordering operator, fetch the corresponding
3523 * equality operator, and determine whether to consider it like
3524 * ASC or DESC.
3525 */
3526 eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3527 if (!OidIsValid(eqop))
3528 ereport(ERROR,
3530 errmsg("operator %s is not a valid ordering operator",
3531 strVal(llast(sortby->useOp))),
3532 errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3533
3534 /*
3535 * Also see if the equality operator is hashable.
3536 */
3537 hashable = op_hashjoinable(eqop, restype);
3538 break;
3539 default:
3540 elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3541 sortop = InvalidOid; /* keep compiler quiet */
3542 eqop = InvalidOid;
3543 hashable = false;
3544 reverse = false;
3545 break;
3546 }
3547
3549
3550 /* avoid making duplicate sortlist entries */
3551 if (!targetIsInSortList(tle, sortop, sortlist))
3552 {
3554
3555 sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3556
3557 sortcl->eqop = eqop;
3558 sortcl->sortop = sortop;
3559 sortcl->hashable = hashable;
3560 sortcl->reverse_sort = reverse;
3561
3562 switch (sortby->sortby_nulls)
3563 {
3565 /* NULLS FIRST is default for DESC; other way for ASC */
3566 sortcl->nulls_first = reverse;
3567 break;
3568 case SORTBY_NULLS_FIRST:
3569 sortcl->nulls_first = true;
3570 break;
3571 case SORTBY_NULLS_LAST:
3572 sortcl->nulls_first = false;
3573 break;
3574 default:
3575 elog(ERROR, "unrecognized sortby_nulls: %d",
3576 sortby->sortby_nulls);
3577 break;
3578 }
3579
3581 }
3582
3583 return sortlist;
3584}
#define Assert(condition)
Definition c.h:873
#define OidIsValid(objectId)
Definition c.h:788
int errhint(const char *fmt,...)
Definition elog.c:1330
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
List * lappend(List *list, void *datum)
Definition list.c:339
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition lsyscache.c:324
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition lsyscache.c:1587
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
int exprLocation(const Node *expr)
Definition nodeFuncs.c:1384
#define makeNode(_type_)
Definition nodes.h:161
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)
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:181
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition parse_oper.c:490
@ 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
unsigned int Oid
static int fb(int x)
@ COERCE_IMPLICIT_CAST
Definition primnodes.h:768
@ COERCION_IMPLICIT
Definition primnodes.h:746
Definition nodes.h:135
#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, ereport, errcode(), errhint(), errmsg(), ERROR, exprLocation(), exprType(), fb(), get_equality_op_for_ordering_op(), get_sort_group_operators(), InvalidOid, lappend(), llast, makeNode, NIL, OidIsValid, op_hashjoinable(), setup_parser_errposition_callback(), SORTBY_ASC, SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, SORTBY_USING, strVal, and targetIsInSortList().

Referenced by transformAggregateCall(), and transformSortClause().

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)
extern

Definition at line 3662 of file parse_clause.c.

3663{
3664 Index maxRef;
3665 ListCell *l;
3666
3667 if (tle->ressortgroupref) /* already has one? */
3668 return tle->ressortgroupref;
3669
3670 /* easiest way to pick an unused refnumber: max used + 1 */
3671 maxRef = 0;
3672 foreach(l, tlist)
3673 {
3674 Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3675
3676 if (ref > maxRef)
3677 maxRef = ref;
3678 }
3679 tle->ressortgroupref = maxRef + 1;
3680 return tle->ressortgroupref;
3681}
unsigned int Index
Definition c.h:628
#define lfirst(lc)
Definition pg_list.h:172

References fb(), and lfirst.

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

◆ setTargetTable()

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

Definition at line 178 of file parse_clause.c.

180{
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))
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 */
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:297
ParseNamespaceItem * p_target_nsitem
Definition parse_node.h:210
Relation p_target_relation
Definition parse_node.h:209
char * relname
Definition primnodes.h:83
Alias * alias
Definition primnodes.h:92
char * schemaname
Definition primnodes.h:80
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126

References addNSItemToQuery(), addRangeTableEntryForRelation(), RangeVar::alias, ereport, errcode(), errmsg(), ERROR, fb(), NoLock, ParseNamespaceItem::p_perminfo, 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 
)
extern

Definition at line 3703 of file parse_clause.c.

3704{
3705 Index ref = tle->ressortgroupref;
3706 ListCell *l;
3707
3708 /* no need to scan list if tle has no marker */
3709 if (ref == 0)
3710 return false;
3711
3712 foreach(l, sortList)
3713 {
3715
3716 if (scl->tleSortGroupRef == ref &&
3717 (sortop == InvalidOid ||
3718 sortop == scl->sortop ||
3719 sortop == get_commutator(scl->sortop)))
3720 return true;
3721 }
3722 return false;
3723}
Oid get_commutator(Oid opno)
Definition lsyscache.c:1659

References fb(), get_commutator(), InvalidOid, and lfirst.

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 
)
extern

Definition at line 3048 of file parse_clause.c.

3050{
3051 List *result = NIL;
3054
3055 /*
3056 * The distinctClause should consist of all ORDER BY items followed by all
3057 * other non-resjunk targetlist items. There must not be any resjunk
3058 * ORDER BY items --- that would imply that we are sorting by a value that
3059 * isn't necessarily unique within a DISTINCT group, so the results
3060 * wouldn't be well-defined. This construction ensures we follow the rule
3061 * that sortClause and distinctClause match; in fact the sortClause will
3062 * always be a prefix of distinctClause.
3063 *
3064 * Note a corner case: the same TLE could be in the ORDER BY list multiple
3065 * times with different sortops. We have to include it in the
3066 * distinctClause the same way to preserve the prefix property. The net
3067 * effect will be that the TLE value will be made unique according to both
3068 * sortops.
3069 */
3070 foreach(slitem, sortClause)
3071 {
3073 TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
3074
3075 if (tle->resjunk)
3076 ereport(ERROR,
3078 is_agg ?
3079 errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
3080 errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
3081 parser_errposition(pstate,
3082 exprLocation((Node *) tle->expr))));
3083 result = lappend(result, copyObject(scl));
3084 }
3085
3086 /*
3087 * Now add any remaining non-resjunk tlist items, using default sort/group
3088 * semantics for their data types.
3089 */
3090 foreach(tlitem, *targetlist)
3091 {
3093
3094 if (tle->resjunk)
3095 continue; /* ignore junk */
3096 result = addTargetToGroupList(pstate, tle,
3097 result, *targetlist,
3098 exprLocation((Node *) tle->expr));
3099 }
3100
3101 /*
3102 * Complain if we found nothing to make DISTINCT. Returning an empty list
3103 * would cause the parsed Query to look like it didn't have DISTINCT, with
3104 * results that would probably surprise the user. Note: this case is
3105 * presently impossible for aggregates because of grammar restrictions,
3106 * but we check anyway.
3107 */
3108 if (result == NIL)
3109 ereport(ERROR,
3111 is_agg ?
3112 errmsg("an aggregate with DISTINCT must have at least one argument") :
3113 errmsg("SELECT DISTINCT must have at least one column")));
3114
3115 return result;
3116}
#define copyObject(obj)
Definition nodes.h:232
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:376

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

Referenced by transformAggregateCall(), and transformSelectStmt().

◆ transformDistinctOnClause()

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

Definition at line 3132 of file parse_clause.c.

3134{
3135 List *result = NIL;
3137 bool skipped_sortitem;
3138 ListCell *lc;
3139 ListCell *lc2;
3140
3141 /*
3142 * Add all the DISTINCT ON expressions to the tlist (if not already
3143 * present, they are added as resjunk items). Assign sortgroupref numbers
3144 * to them, and make a list of these numbers. (NB: we rely below on the
3145 * sortgrouprefs list being one-for-one with the original distinctlist.
3146 * Also notice that we could have duplicate DISTINCT ON expressions and
3147 * hence duplicate entries in sortgrouprefs.)
3148 */
3149 foreach(lc, distinctlist)
3150 {
3151 Node *dexpr = (Node *) lfirst(lc);
3152 int sortgroupref;
3154
3155 tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
3157 sortgroupref = assignSortGroupRef(tle, *targetlist);
3158 sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
3159 }
3160
3161 /*
3162 * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
3163 * semantics from ORDER BY items that match DISTINCT ON items, and also
3164 * adopt their column sort order. We insist that the distinctClause and
3165 * sortClause match, so throw error if we find the need to add any more
3166 * distinctClause items after we've skipped an ORDER BY item that wasn't
3167 * in DISTINCT ON.
3168 */
3169 skipped_sortitem = false;
3170 foreach(lc, sortClause)
3171 {
3173
3174 if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
3175 {
3176 if (skipped_sortitem)
3177 ereport(ERROR,
3179 errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3180 parser_errposition(pstate,
3181 get_matching_location(scl->tleSortGroupRef,
3183 distinctlist))));
3184 else
3185 result = lappend(result, copyObject(scl));
3186 }
3187 else
3188 skipped_sortitem = true;
3189 }
3190
3191 /*
3192 * Now add any remaining DISTINCT ON items, using default sort/group
3193 * semantics for their data types. (Note: this is pretty questionable; if
3194 * the ORDER BY list doesn't include all the DISTINCT ON items and more
3195 * besides, you certainly aren't using DISTINCT ON in the intended way,
3196 * and you probably aren't going to get consistent results. It might be
3197 * better to throw an error or warning here. But historically we've
3198 * allowed it, so keep doing so.)
3199 */
3201 {
3202 Node *dexpr = (Node *) lfirst(lc);
3203 int sortgroupref = lfirst_int(lc2);
3204 TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
3205
3206 if (targetIsInSortList(tle, InvalidOid, result))
3207 continue; /* already in list (with some semantics) */
3208 if (skipped_sortitem)
3209 ereport(ERROR,
3211 errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3213 result = addTargetToGroupList(pstate, tle,
3214 result, *targetlist,
3216 }
3217
3218 /*
3219 * An empty result list is impossible here because of grammar
3220 * restrictions.
3221 */
3222 Assert(result != NIL);
3223
3224 return result;
3225}
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:354

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

Referenced by transformSelectStmt().

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)
extern

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);
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:203
List * p_joinlist
Definition parse_node.h:201

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

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

◆ transformGroupClause()

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

Definition at line 2636 of file parse_clause.c.

2640{
2641 List *result = NIL;
2643 List *gsets = NIL;
2644 ListCell *gl;
2645 bool hasGroupingSets = false;
2647
2648 /* Handle GROUP BY ALL */
2649 if (groupByAll)
2650 {
2651 /* There cannot have been any explicit grouplist items */
2652 Assert(grouplist == NIL);
2653
2654 /* Iterate over targets, adding acceptable ones to the result list */
2655 foreach_ptr(TargetEntry, tle, *targetlist)
2656 {
2657 /* Ignore junk TLEs */
2658 if (tle->resjunk)
2659 continue;
2660
2661 /*
2662 * TLEs containing aggregates are not okay to add to GROUP BY
2663 * (compare checkTargetlistEntrySQL92). But the SQL standard
2664 * directs us to skip them, so it's fine.
2665 */
2666 if (pstate->p_hasAggs &&
2667 contain_aggs_of_level((Node *) tle->expr, 0))
2668 continue;
2669
2670 /*
2671 * Likewise, TLEs containing window functions are not okay to add
2672 * to GROUP BY. At this writing, the SQL standard is silent on
2673 * what to do with them, but by analogy to aggregates we'll just
2674 * skip them.
2675 */
2676 if (pstate->p_hasWindowFuncs &&
2677 contain_windowfuncs((Node *) tle->expr))
2678 continue;
2679
2680 /*
2681 * Otherwise, add the TLE to the result using default sort/group
2682 * semantics. We specify the parse location as the TLE's
2683 * location, despite the comment for addTargetToGroupList
2684 * discouraging that. The only other thing we could point to is
2685 * the ALL keyword, which seems unhelpful when there are multiple
2686 * TLEs.
2687 */
2688 result = addTargetToGroupList(pstate, tle,
2689 result, *targetlist,
2690 exprLocation((Node *) tle->expr));
2691 }
2692
2693 /* If we found any acceptable targets, we're done */
2694 if (result != NIL)
2695 return result;
2696
2697 /*
2698 * Otherwise, the SQL standard says to treat it like "GROUP BY ()".
2699 * Build a representation of that, and let the rest of this function
2700 * handle it.
2701 */
2703 }
2704
2705 /*
2706 * Recursively flatten implicit RowExprs. (Technically this is only needed
2707 * for GROUP BY, per the syntax rules for grouping sets, but we do it
2708 * anyway.)
2709 */
2711 true,
2713
2714 /*
2715 * If the list is now empty, but hasGroupingSets is true, it's because we
2716 * elided redundant empty grouping sets. Restore a single empty grouping
2717 * set to leave a canonical form: GROUP BY ()
2718 */
2719
2721 {
2723 NIL,
2725 }
2726
2727 foreach(gl, flat_grouplist)
2728 {
2729 Node *gexpr = (Node *) lfirst(gl);
2730
2731 if (IsA(gexpr, GroupingSet))
2732 {
2734
2735 switch (gset->kind)
2736 {
2737 case GROUPING_SET_EMPTY:
2738 gsets = lappend(gsets, gset);
2739 break;
2741 /* can't happen */
2742 Assert(false);
2743 break;
2744 case GROUPING_SET_SETS:
2745 case GROUPING_SET_CUBE:
2747 gsets = lappend(gsets,
2748 transformGroupingSet(&result,
2749 pstate, gset,
2750 targetlist, sortClause,
2751 exprKind, useSQL99, true));
2752 break;
2753 }
2754 }
2755 else
2756 {
2758 pstate, gexpr,
2759 targetlist, sortClause,
2760 exprKind, useSQL99, true);
2761
2762 if (ref > 0)
2763 {
2765 if (hasGroupingSets)
2766 gsets = lappend(gsets,
2770 }
2771 }
2772 }
2773
2774 /* parser should prevent this */
2775 Assert(gsets == NIL || groupingSets != NULL);
2776
2777 if (groupingSets)
2778 *groupingSets = gsets;
2779
2780 return result;
2781}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:814
GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location)
Definition makefuncs.c:892
#define IsA(nodeptr, _type_)
Definition nodes.h:164
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)
static Node * transformGroupingSet(List **flatresult, ParseState *pstate, GroupingSet *gset, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99, bool toplevel)
@ GROUPING_SET_CUBE
@ GROUPING_SET_SIMPLE
@ GROUPING_SET_ROLLUP
@ GROUPING_SET_SETS
@ GROUPING_SET_EMPTY
#define list_make1(x1)
Definition pg_list.h:212
#define foreach_ptr(type, var, lst)
Definition pg_list.h:469
#define list_make1_int(x1)
Definition pg_list.h:227
bool contain_windowfuncs(Node *node)
bool contain_aggs_of_level(Node *node, int levelsup)
bool p_hasWindowFuncs
Definition parse_node.h:227
bool p_hasAggs
Definition parse_node.h:226

References addTargetToGroupList(), Assert, bms_add_member(), contain_aggs_of_level(), contain_windowfuncs(), exprLocation(), fb(), flatten_grouping_sets(), foreach_ptr, 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, ParseState::p_hasAggs, ParseState::p_hasWindowFuncs, transformGroupClauseExpr(), and transformGroupingSet().

Referenced by transformSelectStmt(), and transformWindowDefinitions().

◆ transformJsonTable()

ParseNamespaceItem * transformJsonTable ( ParseState pstate,
JsonTable jt 
)
extern

Definition at line 74 of file parse_jsontable.c.

75{
76 TableFunc *tf;
78 JsonExpr *je;
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 &&
92 errmsg("invalid %s behavior", "ON ERROR"),
93 errdetail("Only EMPTY [ ARRAY ] or ERROR is allowed in the top-level ON ERROR clause."),
95
96 cxt.pathNameId = 0;
97 if (rootPathSpec->name == NULL)
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);
116
117 /*
118 * Transform JsonFuncExpr representing the top JSON_TABLE context_item and
119 * pathspec into a dummy JSON_TABLE_OP JsonExpr.
120 */
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;
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,
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:1216
#define castNode(_type_, nodeptr)
Definition nodes.h:182
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition parse_expr.c:120
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:101
@ JSON_BEHAVIOR_ERROR
Definition primnodes.h:1791
@ JSON_BEHAVIOR_EMPTY
Definition primnodes.h:1792
@ JSON_BEHAVIOR_EMPTY_ARRAY
Definition primnodes.h:1796
@ JSON_TABLE_OP
Definition primnodes.h:1830
ParseLoc location
Definition primnodes.h:1818
JsonBehaviorType btype
Definition primnodes.h:1815
JsonBehavior * on_error
List * columns
JsonTablePathSpec * pathspec
Alias * alias
List * passing
JsonValueExpr * context_item
ParseLoc location
bool p_lateral_active
Definition parse_node.h:205
ParseLoc location
Definition primnodes.h:146
Node * docexpr
Definition primnodes.h:120
TableFuncType functype
Definition primnodes.h:114
bool contain_vars_of_level(Node *node, int levelsup)
Definition var.c:444

References addRangeTableEntryForTableFunc(), JsonTable::alias, Assert, JsonBehavior::btype, castNode, CheckDuplicateColumnOrPathNames(), JsonTable::columns, contain_vars_of_level(), JsonTable::context_item, copyObject, TableFunc::docexpr, ereport, errcode(), errdetail(), errmsg(), ERROR, EXPR_KIND_FROM_FUNCTION, fb(), TableFunc::functype, generateJsonTablePathName(), IsA, JSON_BEHAVIOR_EMPTY, JSON_BEHAVIOR_EMPTY_ARRAY, JSON_BEHAVIOR_ERROR, JSON_TABLE_OP, JsonTableParseContext::jt, JsonTable::lateral, list_make1, JsonTable::location, TableFunc::location, JsonBehavior::location, makeNode, JsonTable::on_error, ParseState::p_lateral_active, parser_errposition(), JsonTable::passing, JsonTableParseContext::pathNameId, JsonTableParseContext::pathNames, JsonTable::pathspec, 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 
)
extern

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,
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:442
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, fb(), IsA, LIMIT_OPTION_WITH_TIES, and transformExpr().

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

◆ transformOnConflictArbiter()

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

Definition at line 3365 of file parse_clause.c.

3369{
3370 InferClause *infer = onConflictClause->infer;
3371
3372 *arbiterExpr = NIL;
3373 *arbiterWhere = NULL;
3374 *constraint = InvalidOid;
3375
3376 if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
3377 ereport(ERROR,
3379 errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
3380 errhint("For example, ON CONFLICT (column_name)."),
3381 parser_errposition(pstate,
3382 exprLocation((Node *) onConflictClause))));
3383
3384 /*
3385 * To simplify certain aspects of its design, speculative insertion into
3386 * system catalogs is disallowed
3387 */
3389 ereport(ERROR,
3391 errmsg("ON CONFLICT is not supported with system catalog tables"),
3392 parser_errposition(pstate,
3393 exprLocation((Node *) onConflictClause))));
3394
3395 /* Same applies to table used by logical decoding as catalog table */
3397 ereport(ERROR,
3399 errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3401 parser_errposition(pstate,
3402 exprLocation((Node *) onConflictClause))));
3403
3404 /* ON CONFLICT DO NOTHING does not require an inference clause */
3405 if (infer)
3406 {
3407 if (infer->indexElems)
3408 *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3409 pstate->p_target_relation);
3410
3411 /*
3412 * Handling inference WHERE clause (for partial unique index
3413 * inference)
3414 */
3415 if (infer->whereClause)
3416 *arbiterWhere = transformExpr(pstate, infer->whereClause,
3418
3419 /*
3420 * If the arbiter is specified by constraint name, get the constraint
3421 * OID and mark the constrained columns as requiring SELECT privilege,
3422 * in the same way as would have happened if the arbiter had been
3423 * specified by explicit reference to the constraint's index columns.
3424 */
3425 if (infer->conname)
3426 {
3427 Oid relid = RelationGetRelid(pstate->p_target_relation);
3430
3432 false, constraint);
3433
3434 /* Make sure the rel as a whole is marked for SELECT access */
3435 perminfo->requiredPerms |= ACL_SELECT;
3436 /* Mark the constrained columns as requiring SELECT access */
3437 perminfo->selectedCols = bms_add_members(perminfo->selectedCols,
3438 conattnos);
3439 }
3440 }
3441
3442 /*
3443 * It's convenient to form a list of expressions based on the
3444 * representation used by CREATE INDEX, since the same restrictions are
3445 * appropriate (e.g. on subqueries). However, from here on, a dedicated
3446 * primnode representation is used for inference elements, and so
3447 * assign_query_collations() can be trusted to do the right thing with the
3448 * post parse analysis query tree inference clause representation.
3449 */
3450}
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:916
bool IsCatalogRelation(Relation relation)
Definition catalog.c:104
@ ONCONFLICT_UPDATE
Definition nodes.h:430
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:514
#define RelationIsUsedAsCatalogTable(relation)
Definition rel.h:397
#define RelationGetRelationName(relation)
Definition rel.h:548
char * conname
List * indexElems
Node * whereClause
InferClause * infer
OnConflictAction action

References ACL_SELECT, OnConflictClause::action, bms_add_members(), InferClause::conname, ereport, errcode(), errhint(), errmsg(), ERROR, EXPR_KIND_INDEX_PREDICATE, exprLocation(), fb(), 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, resolve_unique_index_expr(), transformExpr(), and InferClause::whereClause.

Referenced by transformOnConflictClause().

◆ transformSortClause()

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

Definition at line 2794 of file parse_clause.c.

2799{
2800 List *sortlist = NIL;
2802
2803 foreach(olitem, orderlist)
2804 {
2807
2808 if (useSQL99)
2809 tle = findTargetlistEntrySQL99(pstate, sortby->node,
2810 targetlist, exprKind);
2811 else
2812 tle = findTargetlistEntrySQL92(pstate, sortby->node,
2813 targetlist, exprKind);
2814
2816 sortlist, *targetlist, sortby);
2817 }
2818
2819 return sortlist;
2820}
static TargetEntry * findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, ParseExprKind exprKind)
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)

References addTargetToSortList(), fb(), findTargetlistEntrySQL92(), findTargetlistEntrySQL99(), lfirst, and NIL.

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

◆ transformWhereClause()

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

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(), fb(), and transformExpr().

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

◆ transformWindowDefinitions()

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

Definition at line 2827 of file parse_clause.c.

2830{
2831 List *result = NIL;
2832 Index winref = 0;
2833 ListCell *lc;
2834
2835 foreach(lc, windowdefs)
2836 {
2839 List *partitionClause;
2840 List *orderClause;
2843 WindowClause *wc;
2844
2845 winref++;
2846
2847 /*
2848 * Check for duplicate window names.
2849 */
2850 if (windef->name &&
2851 findWindowClause(result, windef->name) != NULL)
2852 ereport(ERROR,
2854 errmsg("window \"%s\" is already defined", windef->name),
2855 parser_errposition(pstate, windef->location)));
2856
2857 /*
2858 * If it references a previous window, look that up.
2859 */
2860 if (windef->refname)
2861 {
2862 refwc = findWindowClause(result, windef->refname);
2863 if (refwc == NULL)
2864 ereport(ERROR,
2866 errmsg("window \"%s\" does not exist",
2867 windef->refname),
2868 parser_errposition(pstate, windef->location)));
2869 }
2870
2871 /*
2872 * Transform PARTITION and ORDER specs, if any. These are treated
2873 * almost exactly like top-level GROUP BY and ORDER BY clauses,
2874 * including the special handling of nondefault operator semantics.
2875 */
2876 orderClause = transformSortClause(pstate,
2877 windef->orderClause,
2878 targetlist,
2880 true /* force SQL99 rules */ );
2881 partitionClause = transformGroupClause(pstate,
2882 windef->partitionClause,
2883 false /* not GROUP BY ALL */ ,
2884 NULL,
2885 targetlist,
2886 orderClause,
2888 true /* force SQL99 rules */ );
2889
2890 /*
2891 * And prepare the new WindowClause.
2892 */
2893 wc = makeNode(WindowClause);
2894 wc->name = windef->name;
2895 wc->refname = windef->refname;
2896
2897 /*
2898 * Per spec, a windowdef that references a previous one copies the
2899 * previous partition clause (and mustn't specify its own). It can
2900 * specify its own ordering clause, but only if the previous one had
2901 * none. It always specifies its own frame clause, and the previous
2902 * one must not have a frame clause. Yeah, it's bizarre that each of
2903 * these cases works differently, but SQL:2008 says so; see 7.11
2904 * <window clause> syntax rule 10 and general rule 1. The frame
2905 * clause rule is especially bizarre because it makes "OVER foo"
2906 * different from "OVER (foo)", and requires the latter to throw an
2907 * error if foo has a nondefault frame clause. Well, ours not to
2908 * reason why, but we do go out of our way to throw a useful error
2909 * message for such cases.
2910 */
2911 if (refwc)
2912 {
2913 if (partitionClause)
2914 ereport(ERROR,
2916 errmsg("cannot override PARTITION BY clause of window \"%s\"",
2917 windef->refname),
2918 parser_errposition(pstate, windef->location)));
2919 wc->partitionClause = copyObject(refwc->partitionClause);
2920 }
2921 else
2922 wc->partitionClause = partitionClause;
2923 if (refwc)
2924 {
2925 if (orderClause && refwc->orderClause)
2926 ereport(ERROR,
2928 errmsg("cannot override ORDER BY clause of window \"%s\"",
2929 windef->refname),
2930 parser_errposition(pstate, windef->location)));
2931 if (orderClause)
2932 {
2933 wc->orderClause = orderClause;
2934 wc->copiedOrder = false;
2935 }
2936 else
2937 {
2938 wc->orderClause = copyObject(refwc->orderClause);
2939 wc->copiedOrder = true;
2940 }
2941 }
2942 else
2943 {
2944 wc->orderClause = orderClause;
2945 wc->copiedOrder = false;
2946 }
2947 if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
2948 {
2949 /*
2950 * Use this message if this is a WINDOW clause, or if it's an OVER
2951 * clause that includes ORDER BY or framing clauses. (We already
2952 * rejected PARTITION BY above, so no need to check that.)
2953 */
2954 if (windef->name ||
2955 orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
2956 ereport(ERROR,
2958 errmsg("cannot copy window \"%s\" because it has a frame clause",
2959 windef->refname),
2960 parser_errposition(pstate, windef->location)));
2961 /* Else this clause is just OVER (foo), so say this: */
2962 ereport(ERROR,
2964 errmsg("cannot copy window \"%s\" because it has a frame clause",
2965 windef->refname),
2966 errhint("Omit the parentheses in this OVER clause."),
2967 parser_errposition(pstate, windef->location)));
2968 }
2969 wc->frameOptions = windef->frameOptions;
2970
2971 /*
2972 * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
2973 * column; check that and get its sort opfamily info.
2974 */
2975 if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
2978 {
2980 Node *sortkey;
2982
2983 if (list_length(wc->orderClause) != 1)
2984 ereport(ERROR,
2986 errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
2987 parser_errposition(pstate, windef->location)));
2989 sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
2990 /* Find the sort operator in pg_amop */
2994 &rangecmptype))
2995 elog(ERROR, "operator %u is not a valid ordering operator",
2996 sortcl->sortop);
2997 /* Record properties of sort ordering */
2998 wc->inRangeColl = exprCollation(sortkey);
2999 wc->inRangeAsc = !sortcl->reverse_sort;
3000 wc->inRangeNullsFirst = sortcl->nulls_first;
3001 }
3002
3003 /* Per spec, GROUPS mode requires an ORDER BY clause */
3005 {
3006 if (wc->orderClause == NIL)
3007 ereport(ERROR,
3009 errmsg("GROUPS mode requires an ORDER BY clause"),
3010 parser_errposition(pstate, windef->location)));
3011 }
3012
3013 /* Process frame offset expressions */
3016 &wc->startInRangeFunc,
3020 &wc->endInRangeFunc,
3021 windef->endOffset);
3022 wc->winref = winref;
3023
3024 result = lappend(result, wc);
3025 }
3026
3027 return result;
3028}
CompareType
Definition cmptype.h:32
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, CompareType *cmptype)
Definition lsyscache.c:259
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:821
List * transformGroupClause(ParseState *pstate, List *grouplist, bool groupByAll, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, 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:630
#define FRAMEOPTION_START_OFFSET
Definition parsenodes.h:628
#define FRAMEOPTION_RANGE
Definition parsenodes.h:610
#define FRAMEOPTION_GROUPS
Definition parsenodes.h:612
#define FRAMEOPTION_DEFAULTS
Definition parsenodes.h:636
static int list_length(const List *l)
Definition pg_list.h:152
#define linitial_node(type, l)
Definition pg_list.h:181
Node * startOffset
List * partitionClause
Node * endOffset
List * orderClause
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition tlist.c:388

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

Referenced by transformSelectStmt().