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

3609{
3610 Oid restype = exprType((Node *) tle->expr);
3611 Oid sortop;
3612 Oid eqop;
3613 bool hashable;
3614 bool reverse;
3615 int location;
3617
3618 /* if tlist item is an UNKNOWN literal, change it to TEXT */
3619 if (restype == UNKNOWNOID)
3620 {
3621 tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3622 restype, TEXTOID, -1,
3625 -1);
3626 restype = TEXTOID;
3627 }
3628
3629 /*
3630 * Rather than clutter the API of get_sort_group_operators and the other
3631 * functions we're about to use, make use of error context callback to
3632 * mark any error reports with a parse position. We point to the operator
3633 * location if present, else to the expression being sorted. (NB: use the
3634 * original untransformed expression here; the TLE entry might well point
3635 * at a duplicate expression in the regular SELECT list.)
3636 */
3637 location = sortby->location;
3638 if (location < 0)
3639 location = exprLocation(sortby->node);
3640 setup_parser_errposition_callback(&pcbstate, pstate, location);
3641
3642 /* determine the sortop, eqop, and directionality */
3643 switch (sortby->sortby_dir)
3644 {
3645 case SORTBY_DEFAULT:
3646 case SORTBY_ASC:
3648 true, true, false,
3649 &sortop, &eqop, NULL,
3650 &hashable);
3651 reverse = false;
3652 break;
3653 case SORTBY_DESC:
3655 false, true, true,
3656 NULL, &eqop, &sortop,
3657 &hashable);
3658 reverse = true;
3659 break;
3660 case SORTBY_USING:
3661 Assert(sortby->useOp != NIL);
3662 sortop = compatible_oper_opid(sortby->useOp,
3663 restype,
3664 restype,
3665 false);
3666
3667 /*
3668 * Verify it's a valid ordering operator, fetch the corresponding
3669 * equality operator, and determine whether to consider it like
3670 * ASC or DESC.
3671 */
3672 eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3673 if (!OidIsValid(eqop))
3674 ereport(ERROR,
3676 errmsg("operator %s is not a valid ordering operator",
3677 strVal(llast(sortby->useOp))),
3678 errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3679
3680 /*
3681 * Also see if the equality operator is hashable.
3682 */
3683 hashable = op_hashjoinable(eqop, restype);
3684 break;
3685 default:
3686 elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3687 sortop = InvalidOid; /* keep compiler quiet */
3688 eqop = InvalidOid;
3689 hashable = false;
3690 reverse = false;
3691 break;
3692 }
3693
3695
3696 /* avoid making duplicate sortlist entries */
3697 if (!targetIsInSortList(tle, sortop, sortlist))
3698 {
3700
3701 sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3702
3703 sortcl->eqop = eqop;
3704 sortcl->sortop = sortop;
3705 sortcl->hashable = hashable;
3706 sortcl->reverse_sort = reverse;
3707
3708 switch (sortby->sortby_nulls)
3709 {
3711 /* NULLS FIRST is default for DESC; other way for ASC */
3712 sortcl->nulls_first = reverse;
3713 break;
3714 case SORTBY_NULLS_FIRST:
3715 sortcl->nulls_first = true;
3716 break;
3717 case SORTBY_NULLS_LAST:
3718 sortcl->nulls_first = false;
3719 break;
3720 default:
3721 elog(ERROR, "unrecognized sortby_nulls: %d",
3722 sortby->sortby_nulls);
3723 break;
3724 }
3725
3727 }
3728
3729 return sortlist;
3730}
#define Assert(condition)
Definition c.h:943
#define OidIsValid(objectId)
Definition c.h:858
int errcode(int sqlerrcode)
Definition elog.c:875
int errhint(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
List * lappend(List *list, void *datum)
Definition list.c:339
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition lsyscache.c:326
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition lsyscache.c:1668
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
int exprLocation(const Node *expr)
Definition nodeFuncs.c:1403
#define makeNode(_type_)
Definition nodes.h:161
static char * errmsg
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:183
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition parse_oper.c:497
@ 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:769
@ COERCION_IMPLICIT
Definition primnodes.h:747
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 3808 of file parse_clause.c.

3809{
3810 Index maxRef;
3811 ListCell *l;
3812
3813 if (tle->ressortgroupref) /* already has one? */
3814 return tle->ressortgroupref;
3815
3816 /* easiest way to pick an unused refnumber: max used + 1 */
3817 maxRef = 0;
3818 foreach(l, tlist)
3819 {
3820 Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3821
3822 if (ref > maxRef)
3823 maxRef = ref;
3824 }
3825 tle->ressortgroupref = maxRef + 1;
3826 return tle->ressortgroupref;
3827}
unsigned int Index
Definition c.h:698
#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 182 of file parse_clause.c.

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

3850{
3851 Index ref = tle->ressortgroupref;
3852 ListCell *l;
3853
3854 /* no need to scan list if tle has no marker */
3855 if (ref == 0)
3856 return false;
3857
3858 foreach(l, sortList)
3859 {
3861
3862 if (scl->tleSortGroupRef == ref &&
3863 (sortop == InvalidOid ||
3864 sortop == scl->sortop ||
3865 sortop == get_commutator(scl->sortop)))
3866 return true;
3867 }
3868 return false;
3869}
Oid get_commutator(Oid opno)
Definition lsyscache.c:1740

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

3194{
3195 List *result = NIL;
3198
3199 /*
3200 * The distinctClause should consist of all ORDER BY items followed by all
3201 * other non-resjunk targetlist items. There must not be any resjunk
3202 * ORDER BY items --- that would imply that we are sorting by a value that
3203 * isn't necessarily unique within a DISTINCT group, so the results
3204 * wouldn't be well-defined. This construction ensures we follow the rule
3205 * that sortClause and distinctClause match; in fact the sortClause will
3206 * always be a prefix of distinctClause.
3207 *
3208 * Note a corner case: the same TLE could be in the ORDER BY list multiple
3209 * times with different sortops. We have to include it in the
3210 * distinctClause the same way to preserve the prefix property. The net
3211 * effect will be that the TLE value will be made unique according to both
3212 * sortops.
3213 */
3214 foreach(slitem, sortClause)
3215 {
3217 TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
3218
3219 if (tle->resjunk)
3220 ereport(ERROR,
3222 is_agg ?
3223 errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
3224 errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
3225 parser_errposition(pstate,
3226 exprLocation((Node *) tle->expr))));
3228 }
3229
3230 /*
3231 * Now add any remaining non-resjunk tlist items, using default sort/group
3232 * semantics for their data types.
3233 */
3234 foreach(tlitem, *targetlist)
3235 {
3237
3238 if (tle->resjunk)
3239 continue; /* ignore junk */
3241 result, *targetlist,
3242 exprLocation((Node *) tle->expr));
3243 }
3244
3245 /*
3246 * Complain if we found nothing to make DISTINCT. Returning an empty list
3247 * would cause the parsed Query to look like it didn't have DISTINCT, with
3248 * results that would probably surprise the user. Note: this case is
3249 * presently impossible for aggregates because of grammar restrictions,
3250 * but we check anyway.
3251 */
3252 if (result == NIL)
3253 ereport(ERROR,
3255 is_agg ?
3256 errmsg("an aggregate with DISTINCT must have at least one argument") :
3257 errmsg("SELECT DISTINCT must have at least one column")));
3258
3259 return result;
3260}
uint32 result
#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, parser_errposition(), and result.

Referenced by transformAggregateCall(), and transformSelectStmt().

◆ transformDistinctOnClause()

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

Definition at line 3276 of file parse_clause.c.

3278{
3279 List *result = NIL;
3281 bool skipped_sortitem;
3282 ListCell *lc;
3283 ListCell *lc2;
3284
3285 /*
3286 * Add all the DISTINCT ON expressions to the tlist (if not already
3287 * present, they are added as resjunk items). Assign sortgroupref numbers
3288 * to them, and make a list of these numbers. (NB: we rely below on the
3289 * sortgrouprefs list being one-for-one with the original distinctlist.
3290 * Also notice that we could have duplicate DISTINCT ON expressions and
3291 * hence duplicate entries in sortgrouprefs.)
3292 */
3293 foreach(lc, distinctlist)
3294 {
3295 Node *dexpr = (Node *) lfirst(lc);
3296 int sortgroupref;
3298
3299 tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
3301 sortgroupref = assignSortGroupRef(tle, *targetlist);
3302 sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
3303 }
3304
3305 /*
3306 * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
3307 * semantics from ORDER BY items that match DISTINCT ON items, and also
3308 * adopt their column sort order. We insist that the distinctClause and
3309 * sortClause match, so throw error if we find the need to add any more
3310 * distinctClause items after we've skipped an ORDER BY item that wasn't
3311 * in DISTINCT ON.
3312 */
3313 skipped_sortitem = false;
3314 foreach(lc, sortClause)
3315 {
3317
3318 if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
3319 {
3320 if (skipped_sortitem)
3321 ereport(ERROR,
3323 errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3324 parser_errposition(pstate,
3325 get_matching_location(scl->tleSortGroupRef,
3327 distinctlist))));
3328 else
3330 }
3331 else
3332 skipped_sortitem = true;
3333 }
3334
3335 /*
3336 * Now add any remaining DISTINCT ON items, using default sort/group
3337 * semantics for their data types. (Note: this is pretty questionable; if
3338 * the ORDER BY list doesn't include all the DISTINCT ON items and more
3339 * besides, you certainly aren't using DISTINCT ON in the intended way,
3340 * and you probably aren't going to get consistent results. It might be
3341 * better to throw an error or warning here. But historically we've
3342 * allowed it, so keep doing so.)
3343 */
3345 {
3346 Node *dexpr = (Node *) lfirst(lc);
3347 int sortgroupref = lfirst_int(lc2);
3348 TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
3349
3351 continue; /* already in list (with some semantics) */
3352 if (skipped_sortitem)
3353 ereport(ERROR,
3355 errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
3358 result, *targetlist,
3360 }
3361
3362 /*
3363 * An empty result list is impossible here because of grammar
3364 * restrictions.
3365 */
3366 Assert(result != NIL);
3367
3368 return result;
3369}
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:62
#define forboth(cell1, list1, cell2, list2)
Definition pg_list.h:550
#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(), result, and targetIsInSortList().

Referenced by transformSelectStmt().

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)
extern

Definition at line 116 of file parse_clause.c.

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

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

2784{
2785 List *result = NIL;
2787 List *gsets = NIL;
2788 ListCell *gl;
2789 bool hasGroupingSets = false;
2791
2792 /* Handle GROUP BY ALL */
2793 if (groupByAll)
2794 {
2795 /* There cannot have been any explicit grouplist items */
2796 Assert(grouplist == NIL);
2797
2798 /* Iterate over targets, adding acceptable ones to the result list */
2799 foreach_ptr(TargetEntry, tle, *targetlist)
2800 {
2801 /* Ignore junk TLEs */
2802 if (tle->resjunk)
2803 continue;
2804
2805 /*
2806 * TLEs containing aggregates are not okay to add to GROUP BY
2807 * (compare checkTargetlistEntrySQL92). But the SQL standard
2808 * directs us to skip them, so it's fine.
2809 */
2810 if (pstate->p_hasAggs &&
2811 contain_aggs_of_level((Node *) tle->expr, 0))
2812 continue;
2813
2814 /*
2815 * Likewise, TLEs containing window functions are not okay to add
2816 * to GROUP BY. At this writing, the SQL standard is silent on
2817 * what to do with them, but by analogy to aggregates we'll just
2818 * skip them.
2819 */
2820 if (pstate->p_hasWindowFuncs &&
2821 contain_windowfuncs((Node *) tle->expr))
2822 continue;
2823
2824 /*
2825 * Otherwise, add the TLE to the result using default sort/group
2826 * semantics. We specify the parse location as the TLE's
2827 * location, despite the comment for addTargetToGroupList
2828 * discouraging that. The only other thing we could point to is
2829 * the ALL keyword, which seems unhelpful when there are multiple
2830 * TLEs.
2831 */
2833 result, *targetlist,
2834 exprLocation((Node *) tle->expr));
2835 }
2836
2837 /* If we found any acceptable targets, we're done */
2838 if (result != NIL)
2839 return result;
2840
2841 /*
2842 * Otherwise, the SQL standard says to treat it like "GROUP BY ()".
2843 * Build a representation of that, and let the rest of this function
2844 * handle it.
2845 */
2847 }
2848
2849 /*
2850 * Recursively flatten implicit RowExprs. (Technically this is only needed
2851 * for GROUP BY, per the syntax rules for grouping sets, but we do it
2852 * anyway.)
2853 */
2855 true,
2857
2858 /*
2859 * If the list is now empty, but hasGroupingSets is true, it's because we
2860 * elided redundant empty grouping sets. Restore a single empty grouping
2861 * set to leave a canonical form: GROUP BY ()
2862 */
2863
2865 {
2867 NIL,
2869 }
2870
2871 foreach(gl, flat_grouplist)
2872 {
2873 Node *gexpr = (Node *) lfirst(gl);
2874
2875 if (IsA(gexpr, GroupingSet))
2876 {
2878
2879 switch (gset->kind)
2880 {
2881 case GROUPING_SET_EMPTY:
2882 gsets = lappend(gsets, gset);
2883 break;
2885 /* can't happen */
2886 Assert(false);
2887 break;
2888 case GROUPING_SET_SETS:
2889 case GROUPING_SET_CUBE:
2891 gsets = lappend(gsets,
2893 pstate, gset,
2894 targetlist, sortClause,
2895 exprKind, useSQL99, true));
2896 break;
2897 }
2898 }
2899 else
2900 {
2902 pstate, gexpr,
2903 targetlist, sortClause,
2904 exprKind, useSQL99, true);
2905
2906 if (ref > 0)
2907 {
2909 if (hasGroupingSets)
2910 gsets = lappend(gsets,
2914 }
2915 }
2916 }
2917
2918 /* parser should prevent this */
2919 Assert(gsets == NIL || groupingSets != NULL);
2920
2921 if (groupingSets)
2922 *groupingSets = gsets;
2923
2924 return result;
2925}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
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:244
#define foreach_ptr(type, var, lst)
Definition pg_list.h:501
#define list_make1_int(x1)
Definition pg_list.h:259
bool contain_windowfuncs(Node *node)
bool contain_aggs_of_level(Node *node, int levelsup)
bool p_hasWindowFuncs
Definition parse_node.h:247
bool p_hasAggs
Definition parse_node.h:246

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, result, 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,...) pg_attribute_printf(1
#define castNode(_type_, nodeptr)
Definition nodes.h:182
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:102
@ JSON_BEHAVIOR_ERROR
Definition primnodes.h:1806
@ JSON_BEHAVIOR_EMPTY
Definition primnodes.h:1807
@ JSON_BEHAVIOR_EMPTY_ARRAY
Definition primnodes.h:1811
@ JSON_TABLE_OP
Definition primnodes.h:1845
ParseLoc location
Definition primnodes.h:1833
JsonBehaviorType btype
Definition primnodes.h:1830
JsonBehavior * on_error
List * columns
JsonTablePathSpec * pathspec
Alias * alias
List * passing
JsonValueExpr * context_item
ParseLoc location
bool p_lateral_active
Definition parse_node.h:224
ParseLoc location
Definition primnodes.h:147
Node * docexpr
Definition primnodes.h:121
TableFuncType functype
Definition primnodes.h:115
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 2025 of file parse_clause.c.

2028{
2029 Node *qual;
2030
2031 if (clause == NULL)
2032 return NULL;
2033
2034 qual = transformExpr(pstate, clause, exprKind);
2035
2036 qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
2037
2038 /* LIMIT can't refer to any variables of the current query */
2039 checkExprIsVarFree(pstate, qual, constructName);
2040
2041 /*
2042 * Don't allow NULLs in FETCH FIRST .. WITH TIES. This test is ugly and
2043 * extremely simplistic, in that you can pass a NULL anyway by hiding it
2044 * inside an expression -- but this protects ruleutils against emitting an
2045 * unadorned NULL that's not accepted back by the grammar.
2046 */
2047 if (exprKind == EXPR_KIND_LIMIT && limitOption == LIMIT_OPTION_WITH_TIES &&
2048 IsA(clause, A_Const) && castNode(A_Const, clause)->isnull)
2049 ereport(ERROR,
2051 errmsg("row count cannot be null in FETCH FIRST ... WITH TIES clause")));
2052
2053 return qual;
2054}
@ LIMIT_OPTION_WITH_TIES
Definition nodes.h:443
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:63

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

3513{
3514 InferClause *infer = onConflictClause->infer;
3515
3516 *arbiterExpr = NIL;
3517 *arbiterWhere = NULL;
3518 *constraint = InvalidOid;
3519
3520 if ((onConflictClause->action == ONCONFLICT_UPDATE ||
3521 onConflictClause->action == ONCONFLICT_SELECT) && !infer)
3522 ereport(ERROR,
3524 errmsg("ON CONFLICT DO %s requires inference specification or constraint name",
3525 onConflictClause->action == ONCONFLICT_UPDATE ? "UPDATE" : "SELECT"),
3526 errhint("For example, ON CONFLICT (column_name)."),
3527 parser_errposition(pstate,
3528 exprLocation((Node *) onConflictClause)));
3529
3530 /*
3531 * To simplify certain aspects of its design, speculative insertion into
3532 * system catalogs is disallowed
3533 */
3535 ereport(ERROR,
3537 errmsg("ON CONFLICT is not supported with system catalog tables"),
3538 parser_errposition(pstate,
3539 exprLocation((Node *) onConflictClause))));
3540
3541 /* Same applies to table used by logical decoding as catalog table */
3543 ereport(ERROR,
3545 errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
3547 parser_errposition(pstate,
3548 exprLocation((Node *) onConflictClause))));
3549
3550 /* ON CONFLICT DO NOTHING does not require an inference clause */
3551 if (infer)
3552 {
3553 if (infer->indexElems)
3554 *arbiterExpr = resolve_unique_index_expr(pstate, infer,
3555 pstate->p_target_relation);
3556
3557 /*
3558 * Handling inference WHERE clause (for partial unique index
3559 * inference)
3560 */
3561 if (infer->whereClause)
3562 *arbiterWhere = transformExpr(pstate, infer->whereClause,
3564
3565 /*
3566 * If the arbiter is specified by constraint name, get the constraint
3567 * OID and mark the constrained columns as requiring SELECT privilege,
3568 * in the same way as would have happened if the arbiter had been
3569 * specified by explicit reference to the constraint's index columns.
3570 */
3571 if (infer->conname)
3572 {
3573 Oid relid = RelationGetRelid(pstate->p_target_relation);
3576
3578 false, constraint);
3579
3580 /* Make sure the rel as a whole is marked for SELECT access */
3581 perminfo->requiredPerms |= ACL_SELECT;
3582 /* Mark the constrained columns as requiring SELECT access */
3583 perminfo->selectedCols = bms_add_members(perminfo->selectedCols,
3584 conattnos);
3585 }
3586 }
3587
3588 /*
3589 * It's convenient to form a list of expressions based on the
3590 * representation used by CREATE INDEX, since the same restrictions are
3591 * appropriate (e.g. on subqueries). However, from here on, a dedicated
3592 * primnode representation is used for inference elements, and so
3593 * assign_query_collations() can be trusted to do the right thing with the
3594 * post parse analysis query tree inference clause representation.
3595 */
3596}
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:901
bool IsCatalogRelation(Relation relation)
Definition catalog.c:104
@ ONCONFLICT_SELECT
Definition nodes.h:431
@ 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:74
#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:516
#define RelationIsUsedAsCatalogTable(relation)
Definition rel.h:399
#define RelationGetRelationName(relation)
Definition rel.h:550
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_SELECT, 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 2938 of file parse_clause.c.

2943{
2944 List *sortlist = NIL;
2946
2947 foreach(olitem, orderlist)
2948 {
2951
2952 if (useSQL99)
2953 tle = findTargetlistEntrySQL99(pstate, sortby->node,
2954 targetlist, exprKind);
2955 else
2956 tle = findTargetlistEntrySQL92(pstate, sortby->node,
2957 targetlist, exprKind);
2958
2960 sortlist, *targetlist, sortby);
2961 }
2962
2963 return sortlist;
2964}
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 1998 of file parse_clause.c.

2000{
2001 Node *qual;
2002
2003 if (clause == NULL)
2004 return NULL;
2005
2006 qual = transformExpr(pstate, clause, exprKind);
2007
2008 qual = coerce_to_boolean(pstate, qual, constructName);
2009
2010 return qual;
2011}
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 2971 of file parse_clause.c.

2974{
2975 List *result = NIL;
2976 Index winref = 0;
2977 ListCell *lc;
2978
2979 foreach(lc, windowdefs)
2980 {
2983 List *partitionClause;
2984 List *orderClause;
2987 WindowClause *wc;
2988
2989 winref++;
2990
2991 /*
2992 * Check for duplicate window names.
2993 */
2994 if (windef->name &&
2996 ereport(ERROR,
2998 errmsg("window \"%s\" is already defined", windef->name),
2999 parser_errposition(pstate, windef->location)));
3000
3001 /*
3002 * If it references a previous window, look that up.
3003 */
3004 if (windef->refname)
3005 {
3006 refwc = findWindowClause(result, windef->refname);
3007 if (refwc == NULL)
3008 ereport(ERROR,
3010 errmsg("window \"%s\" does not exist",
3011 windef->refname),
3012 parser_errposition(pstate, windef->location)));
3013 }
3014
3015 /*
3016 * Transform PARTITION and ORDER specs, if any. These are treated
3017 * almost exactly like top-level GROUP BY and ORDER BY clauses,
3018 * including the special handling of nondefault operator semantics.
3019 */
3020 orderClause = transformSortClause(pstate,
3021 windef->orderClause,
3022 targetlist,
3024 true /* force SQL99 rules */ );
3025 partitionClause = transformGroupClause(pstate,
3026 windef->partitionClause,
3027 false /* not GROUP BY ALL */ ,
3028 NULL,
3029 targetlist,
3030 orderClause,
3032 true /* force SQL99 rules */ );
3033
3034 /*
3035 * And prepare the new WindowClause.
3036 */
3037 wc = makeNode(WindowClause);
3038 wc->name = windef->name;
3039 wc->refname = windef->refname;
3040
3041 /*
3042 * Per spec, a windowdef that references a previous one copies the
3043 * previous partition clause (and mustn't specify its own). It can
3044 * specify its own ordering clause, but only if the previous one had
3045 * none. It always specifies its own frame clause, and the previous
3046 * one must not have a frame clause. Yeah, it's bizarre that each of
3047 * these cases works differently, but SQL:2008 says so; see 7.11
3048 * <window clause> syntax rule 10 and general rule 1. The frame
3049 * clause rule is especially bizarre because it makes "OVER foo"
3050 * different from "OVER (foo)", and requires the latter to throw an
3051 * error if foo has a nondefault frame clause. Well, ours not to
3052 * reason why, but we do go out of our way to throw a useful error
3053 * message for such cases.
3054 */
3055 if (refwc)
3056 {
3057 if (partitionClause)
3058 ereport(ERROR,
3060 errmsg("cannot override PARTITION BY clause of window \"%s\"",
3061 windef->refname),
3062 parser_errposition(pstate, windef->location)));
3063 wc->partitionClause = copyObject(refwc->partitionClause);
3064 }
3065 else
3066 wc->partitionClause = partitionClause;
3067 if (refwc)
3068 {
3069 if (orderClause && refwc->orderClause)
3070 ereport(ERROR,
3072 errmsg("cannot override ORDER BY clause of window \"%s\"",
3073 windef->refname),
3074 parser_errposition(pstate, windef->location)));
3075 if (orderClause)
3076 {
3077 wc->orderClause = orderClause;
3078 wc->copiedOrder = false;
3079 }
3080 else
3081 {
3082 wc->orderClause = copyObject(refwc->orderClause);
3083 wc->copiedOrder = true;
3084 }
3085 }
3086 else
3087 {
3088 wc->orderClause = orderClause;
3089 wc->copiedOrder = false;
3090 }
3091 if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
3092 {
3093 /*
3094 * Use this message if this is a WINDOW clause, or if it's an OVER
3095 * clause that includes ORDER BY or framing clauses. (We already
3096 * rejected PARTITION BY above, so no need to check that.)
3097 */
3098 if (windef->name ||
3099 orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
3100 ereport(ERROR,
3102 errmsg("cannot copy window \"%s\" because it has a frame clause",
3103 windef->refname),
3104 parser_errposition(pstate, windef->location)));
3105 /* Else this clause is just OVER (foo), so say this: */
3106 ereport(ERROR,
3108 errmsg("cannot copy window \"%s\" because it has a frame clause",
3109 windef->refname),
3110 errhint("Omit the parentheses in this OVER clause."),
3111 parser_errposition(pstate, windef->location)));
3112 }
3113 wc->frameOptions = windef->frameOptions;
3114
3115 /*
3116 * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
3117 * column; check that and get its sort opfamily info.
3118 */
3119 if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
3122 {
3124 Node *sortkey;
3126
3127 if (list_length(wc->orderClause) != 1)
3128 ereport(ERROR,
3130 errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
3131 parser_errposition(pstate, windef->location)));
3133 sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
3134 /* Find the sort operator in pg_amop */
3138 &rangecmptype))
3139 elog(ERROR, "operator %u is not a valid ordering operator",
3140 sortcl->sortop);
3141 /* Record properties of sort ordering */
3142 wc->inRangeColl = exprCollation(sortkey);
3143 wc->inRangeAsc = !sortcl->reverse_sort;
3144 wc->inRangeNullsFirst = sortcl->nulls_first;
3145 }
3146
3147 /* Per spec, GROUPS mode requires an ORDER BY clause */
3149 {
3150 if (wc->orderClause == NIL)
3151 ereport(ERROR,
3153 errmsg("GROUPS mode requires an ORDER BY clause"),
3154 parser_errposition(pstate, windef->location)));
3155 }
3156
3157 /* Process frame offset expressions */
3160 &wc->startInRangeFunc,
3164 &wc->endInRangeFunc,
3165 windef->endOffset);
3166 wc->winref = winref;
3167
3168 result = lappend(result, wc);
3169 }
3170
3171 return result;
3172}
CompareType
Definition cmptype.h:32
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, CompareType *cmptype)
Definition lsyscache.c:261
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
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:633
#define FRAMEOPTION_START_OFFSET
Definition parsenodes.h:631
#define FRAMEOPTION_RANGE
Definition parsenodes.h:613
#define FRAMEOPTION_GROUPS
Definition parsenodes.h:615
#define FRAMEOPTION_DEFAULTS
Definition parsenodes.h:639
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, result, WindowClause::startOffset, transformFrameOffset(), transformGroupClause(), transformSortClause(), and WindowClause::winref.

Referenced by transformSelectStmt().