PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
parse_clause.h File Reference
Include dependency graph for parse_clause.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

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

Function Documentation

◆ addTargetToSortList()

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

Definition at line 3393 of file parse_clause.c.

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

References Assert(), assignSortGroupRef(), cancel_parser_errposition_callback(), COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, compatible_oper_opid(), elog, SortGroupClause::eqop, ereport, errcode(), errhint(), errmsg(), ERROR, TargetEntry::expr, exprLocation(), exprType(), get_equality_op_for_ordering_op(), get_sort_group_operators(), InvalidOid, lappend(), llast, SortBy::location, makeNode, NIL, SortBy::node, SortGroupClause::nulls_first, OidIsValid, op_hashjoinable(), SortGroupClause::reverse_sort, setup_parser_errposition_callback(), SORTBY_ASC, SORTBY_DEFAULT, SORTBY_DESC, SortBy::sortby_dir, SortBy::sortby_nulls, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, SORTBY_USING, SortGroupClause::sortop, strVal, targetIsInSortList(), SortGroupClause::tleSortGroupRef, and SortBy::useOp.

Referenced by transformAggregateCall(), and transformSortClause().

◆ assignSortGroupRef()

Index assignSortGroupRef ( TargetEntry tle,
List tlist 
)

Definition at line 3594 of file parse_clause.c.

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

References lfirst, and TargetEntry::ressortgroupref.

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

◆ setTargetTable()

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

Definition at line 178 of file parse_clause.c.

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

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

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

◆ targetIsInSortList()

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

Definition at line 3635 of file parse_clause.c.

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

References get_commutator(), InvalidOid, lfirst, TargetEntry::ressortgroupref, SortGroupClause::sortop, and SortGroupClause::tleSortGroupRef.

Referenced by addTargetToGroupList(), addTargetToSortList(), check_output_expressions(), examine_simple_variable(), targetIsInAllPartitionLists(), transformDistinctOnClause(), and transformGroupClauseExpr().

◆ transformDistinctClause()

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

Definition at line 2985 of file parse_clause.c.

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

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

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

◆ transformDistinctOnClause()

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

Definition at line 3069 of file parse_clause.c.

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

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

Referenced by transformPLAssignStmt(), and transformSelectStmt().

◆ transformFromClause()

void transformFromClause ( ParseState pstate,
List frmList 
)

Definition at line 112 of file parse_clause.c.

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

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

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

◆ transformGroupClause()

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

Definition at line 2632 of file parse_clause.c.

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

References Assert(), bms_add_member(), exprLocation(), flatten_grouping_sets(), GROUPING_SET_CUBE, GROUPING_SET_EMPTY, GROUPING_SET_ROLLUP, GROUPING_SET_SETS, GROUPING_SET_SIMPLE, IsA, lappend(), lfirst, list_make1, list_make1_int, makeGroupingSet(), NIL, transformGroupClauseExpr(), and transformGroupingSet().

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

◆ transformJsonTable()

ParseNamespaceItem * transformJsonTable ( ParseState pstate,
JsonTable jt 
)

Definition at line 74 of file parse_jsontable.c.

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

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

Referenced by transformFromClauseItem().

◆ transformLimitClause()

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

Definition at line 1881 of file parse_clause.c.

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

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

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

◆ transformOnConflictArbiter()

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

Definition at line 3297 of file parse_clause.c.

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

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

Referenced by transformOnConflictClause().

◆ transformSortClause()

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

Definition at line 2732 of file parse_clause.c.

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

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

◆ transformWhereClause()

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

Definition at line 1854 of file parse_clause.c.

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

References coerce_to_boolean(), and transformExpr().

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

◆ transformWindowDefinitions()

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

Definition at line 2765 of file parse_clause.c.

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

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

Referenced by transformPLAssignStmt(), and transformSelectStmt().