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

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

3801{
3802 Index maxRef;
3803 ListCell *l;
3804
3805 if (tle->ressortgroupref) /* already has one? */
3806 return tle->ressortgroupref;
3807
3808 /* easiest way to pick an unused refnumber: max used + 1 */
3809 maxRef = 0;
3810 foreach(l, tlist)
3811 {
3812 Index ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
3813
3814 if (ref > maxRef)
3815 maxRef = ref;
3816 }
3817 tle->ressortgroupref = maxRef + 1;
3818 return tle->ressortgroupref;
3819}
unsigned int Index
Definition c.h:700
#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:313
ParseNamespaceItem * p_target_nsitem
Definition parse_node.h:225
Relation p_target_relation
Definition parse_node.h:224
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 3841 of file parse_clause.c.

3842{
3843 Index ref = tle->ressortgroupref;
3844 ListCell *l;
3845
3846 /* no need to scan list if tle has no marker */
3847 if (ref == 0)
3848 return false;
3849
3850 foreach(l, sortList)
3851 {
3853
3854 if (scl->tleSortGroupRef == ref &&
3855 (sortop == InvalidOid ||
3856 sortop == scl->sortop ||
3857 sortop == get_commutator(scl->sortop)))
3858 return true;
3859 }
3860 return false;
3861}
Oid get_commutator(Oid opno)
Definition lsyscache.c:1729

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

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

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

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

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

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,...) 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:1793
@ JSON_BEHAVIOR_EMPTY
Definition primnodes.h:1794
@ JSON_BEHAVIOR_EMPTY_ARRAY
Definition primnodes.h:1798
@ JSON_TABLE_OP
Definition primnodes.h:1832
ParseLoc location
Definition primnodes.h:1820
JsonBehaviorType btype
Definition primnodes.h:1817
JsonBehavior * on_error
List * columns
JsonTablePathSpec * pathspec
Alias * alias
List * passing
JsonValueExpr * context_item
ParseLoc location
bool p_lateral_active
Definition parse_node.h:220
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 2017 of file parse_clause.c.

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

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

2935{
2936 List *sortlist = NIL;
2938
2939 foreach(olitem, orderlist)
2940 {
2943
2944 if (useSQL99)
2945 tle = findTargetlistEntrySQL99(pstate, sortby->node,
2946 targetlist, exprKind);
2947 else
2948 tle = findTargetlistEntrySQL92(pstate, sortby->node,
2949 targetlist, exprKind);
2950
2952 sortlist, *targetlist, sortby);
2953 }
2954
2955 return sortlist;
2956}
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 1990 of file parse_clause.c.

1992{
1993 Node *qual;
1994
1995 if (clause == NULL)
1996 return NULL;
1997
1998 qual = transformExpr(pstate, clause, exprKind);
1999
2000 qual = coerce_to_boolean(pstate, qual, constructName);
2001
2002 return qual;
2003}
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 2963 of file parse_clause.c.

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