PostgreSQL Source Code git master
parse_clause.h File Reference
Include dependency graph for parse_clause.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void transformFromClause (ParseState *pstate, List *frmList)
 
int setTargetTable (ParseState *pstate, RangeVar *relation, bool inh, bool alsoSource, AclMode requiredPerms)
 
NodetransformWhereClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
 
NodetransformLimitClause (ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName, LimitOption limitOption)
 
ListtransformGroupClause (ParseState *pstate, List *grouplist, 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 
)

Definition at line 3456 of file parse_clause.c.

3458{
3459 Oid restype = exprType((Node *) tle->expr);
3460 Oid sortop;
3461 Oid eqop;
3462 bool hashable;
3463 bool reverse;
3464 int location;
3465 ParseCallbackState pcbstate;
3466
3467 /* if tlist item is an UNKNOWN literal, change it to TEXT */
3468 if (restype == UNKNOWNOID)
3469 {
3470 tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
3471 restype, TEXTOID, -1,
3474 -1);
3475 restype = TEXTOID;
3476 }
3477
3478 /*
3479 * Rather than clutter the API of get_sort_group_operators and the other
3480 * functions we're about to use, make use of error context callback to
3481 * mark any error reports with a parse position. We point to the operator
3482 * location if present, else to the expression being sorted. (NB: use the
3483 * original untransformed expression here; the TLE entry might well point
3484 * at a duplicate expression in the regular SELECT list.)
3485 */
3486 location = sortby->location;
3487 if (location < 0)
3488 location = exprLocation(sortby->node);
3489 setup_parser_errposition_callback(&pcbstate, pstate, location);
3490
3491 /* determine the sortop, eqop, and directionality */
3492 switch (sortby->sortby_dir)
3493 {
3494 case SORTBY_DEFAULT:
3495 case SORTBY_ASC:
3497 true, true, false,
3498 &sortop, &eqop, NULL,
3499 &hashable);
3500 reverse = false;
3501 break;
3502 case SORTBY_DESC:
3504 false, true, true,
3505 NULL, &eqop, &sortop,
3506 &hashable);
3507 reverse = true;
3508 break;
3509 case SORTBY_USING:
3510 Assert(sortby->useOp != NIL);
3511 sortop = compatible_oper_opid(sortby->useOp,
3512 restype,
3513 restype,
3514 false);
3515
3516 /*
3517 * Verify it's a valid ordering operator, fetch the corresponding
3518 * equality operator, and determine whether to consider it like
3519 * ASC or DESC.
3520 */
3521 eqop = get_equality_op_for_ordering_op(sortop, &reverse);
3522 if (!OidIsValid(eqop))
3523 ereport(ERROR,
3524 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3525 errmsg("operator %s is not a valid ordering operator",
3526 strVal(llast(sortby->useOp))),
3527 errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
3528
3529 /*
3530 * Also see if the equality operator is hashable.
3531 */
3532 hashable = op_hashjoinable(eqop, restype);
3533 break;
3534 default:
3535 elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
3536 sortop = InvalidOid; /* keep compiler quiet */
3537 eqop = InvalidOid;
3538 hashable = false;
3539 reverse = false;
3540 break;
3541 }
3542
3544
3545 /* avoid making duplicate sortlist entries */
3546 if (!targetIsInSortList(tle, sortop, sortlist))
3547 {
3549
3550 sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
3551
3552 sortcl->eqop = eqop;
3553 sortcl->sortop = sortop;
3554 sortcl->hashable = hashable;
3555 sortcl->reverse_sort = reverse;
3556
3557 switch (sortby->sortby_nulls)
3558 {
3560 /* NULLS FIRST is default for DESC; other way for ASC */
3561 sortcl->nulls_first = reverse;
3562 break;
3563 case SORTBY_NULLS_FIRST:
3564 sortcl->nulls_first = true;
3565 break;
3566 case SORTBY_NULLS_LAST:
3567 sortcl->nulls_first = false;
3568 break;
3569 default:
3570 elog(ERROR, "unrecognized sortby_nulls: %d",
3571 sortby->sortby_nulls);
3572 break;
3573 }
3574
3575 sortlist = lappend(sortlist, sortcl);
3576 }
3577
3578 return sortlist;
3579}
#define OidIsValid(objectId)
Definition: c.h:779
int errhint(const char *fmt,...)
Definition: elog.c:1330
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:150
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:331
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1604
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1384
#define makeNode(_type_)
Definition: nodes.h:161
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:158
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:156
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:140
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:181
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:490
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:54
@ SORTBY_NULLS_LAST
Definition: parsenodes.h:56
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:55
@ SORTBY_USING
Definition: parsenodes.h:49
@ SORTBY_DESC
Definition: parsenodes.h:48
@ SORTBY_ASC
Definition: parsenodes.h:47
@ SORTBY_DEFAULT
Definition: parsenodes.h:46
#define llast(l)
Definition: pg_list.h:198
#define NIL
Definition: pg_list.h:68
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:768
@ COERCION_IMPLICIT
Definition: primnodes.h:746
Definition: nodes.h:135
SortByNulls sortby_nulls
Definition: parsenodes.h:576
Node * node
Definition: parsenodes.h:574
List * useOp
Definition: parsenodes.h:577
SortByDir sortby_dir
Definition: parsenodes.h:575
ParseLoc location
Definition: parsenodes.h:578
Index tleSortGroupRef
Definition: parsenodes.h:1469
Expr * expr
Definition: primnodes.h:2239
#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 3657 of file parse_clause.c.

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

References lfirst, and TargetEntry::ressortgroupref.

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 
)

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:297
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:210
Relation p_target_relation
Definition: parse_node.h:209
AclMode requiredPerms
Definition: parsenodes.h:1322
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 3698 of file parse_clause.c.

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

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

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

References addTargetToGroupList(), copyObject, ereport, errcode(), errmsg(), ERROR, TargetEntry::expr, exprLocation(), 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 
)

Definition at line 3132 of file parse_clause.c.

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

References checkNameSpaceConflicts(), 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 
)

Definition at line 2636 of file parse_clause.c.

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

References addTargetToGroupList(), Assert(), bms_add_member(), contain_aggs_of_level(), contain_windowfuncs(), exprLocation(), 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 
)

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:1216
#define castNode(_type_, nodeptr)
Definition: nodes.h:182
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:119
static char * generateJsonTablePathName(JsonTableParseContext *cxt)
static JsonTablePlan * transformJsonTableColumns(JsonTableParseContext *cxt, List *columns, List *passingArgs, JsonTablePathSpec *pathspec)
static void CheckDuplicateColumnOrPathNames(JsonTableParseContext *cxt, List *columns)
@ EXPR_KIND_FROM_FUNCTION
Definition: parse_node.h:45
ParseNamespaceItem * addRangeTableEntryForTableFunc(ParseState *pstate, TableFunc *tf, Alias *alias, bool lateral, bool inFromCl)
@ TFT_JSON_TABLE
Definition: primnodes.h:101
@ JSON_BEHAVIOR_ERROR
Definition: primnodes.h:1791
@ JSON_BEHAVIOR_EMPTY
Definition: primnodes.h:1792
@ JSON_BEHAVIOR_EMPTY_ARRAY
Definition: primnodes.h:1796
@ JSON_TABLE_OP
Definition: primnodes.h:1830
ParseLoc location
Definition: primnodes.h:1818
JsonBehaviorType btype
Definition: primnodes.h:1815
List * passing_values
Definition: primnodes.h:1861
JsonExprOp op
Definition: parsenodes.h:1854
List * passing
Definition: parsenodes.h:1859
JsonBehavior * on_empty
Definition: parsenodes.h:1861
ParseLoc location
Definition: parsenodes.h:1865
Node * pathspec
Definition: parsenodes.h:1858
JsonBehavior * on_error
Definition: parsenodes.h:1862
JsonValueExpr * context_item
Definition: parsenodes.h:1857
JsonBehavior * on_error
Definition: parsenodes.h:1894
List * columns
Definition: parsenodes.h:1893
JsonTablePathSpec * pathspec
Definition: parsenodes.h:1891
Alias * alias
Definition: parsenodes.h:1895
bool lateral
Definition: parsenodes.h:1896
List * passing
Definition: parsenodes.h:1892
JsonValueExpr * context_item
Definition: parsenodes.h:1890
ParseLoc location
Definition: parsenodes.h:1897
bool p_lateral_active
Definition: parse_node.h:205
ParseLoc location
Definition: primnodes.h:146
Node * docexpr
Definition: primnodes.h:120
TableFuncType functype
Definition: primnodes.h:114
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:444

References addRangeTableEntryForTableFunc(), JsonTable::alias, Assert(), JsonBehavior::btype, castNode, CheckDuplicateColumnOrPathNames(), JsonTable::columns, contain_vars_of_level(), 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:442
static void checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
@ EXPR_KIND_LIMIT
Definition: parse_node.h:62

References castNode, checkExprIsVarFree(), coerce_to_specific_type(), ereport, errcode(), errmsg(), ERROR, EXPR_KIND_LIMIT, 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 
)

Definition at line 3360 of file parse_clause.c.

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

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

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

References addTargetToSortList(), findTargetlistEntrySQL92(), findTargetlistEntrySQL99(), lfirst, NIL, and SortBy::node.

Referenced by transformAggregateCall(), 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(), TransformPubWhereClauses(), transformRuleStmt(), transformSelectStmt(), and transformUpdateStmt().

◆ transformWindowDefinitions()

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

Definition at line 2827 of file parse_clause.c.

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