From e4eebaf2d9a08bfd11cef62c89e285d2686da34b Mon Sep 17 00:00:00 2001 From: David Christensen Date: Sun, 29 Nov 2026 16:30:37 +0000 Subject: [PATCH v2 1/2] Restructure transformGroupClause() into explicit layers The GROUP BY transformation code had grown hard to follow, particularly after grouping sets were added: transformGroupClauseExpr() mixed targetlist lookup, local duplicate elimination, flat-list membership checks and ORDER BY operator inheritance, all threaded through long pass-through argument lists, and its header comment claimed it always returned the item's ressortgroupref when it could in fact return 0. Split the work into separate steps, each with one job: * resolveGroupingExpr() finds or creates the targetlist entry for a grouping expression. This is the only step where SQL92 and SQL99 rules differ. * addGroupingTarget() ensures a targetlist entry is represented in the flat groupClause, copying operator info from a matching ORDER BY item if there is one and otherwise falling back to addTargetToGroupList() for default semantics. It always returns a nonzero sortgroupref. * transformGroupingItem() combines the two and handles local duplicate elimination when the caller says it is safe; its comment now states that it returns 0 for a dropped duplicate. The fixed per-clause arguments are collected into a GroupClauseState struct. No behavior change is intended. Discussion: https://postgr.es/m/3278800.1783989856@sss.pgh.pa.us --- src/backend/parser/parse_clause.c | 339 ++++++++++++++---------------- src/tools/pgindent/typedefs.list | 1 + 2 files changed, 154 insertions(+), 186 deletions(-) diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c index 7a5179b905..bba1f9bc3e 100644 --- a/src/backend/parser/parse_clause.c +++ b/src/backend/parser/parse_clause.c @@ -2346,161 +2346,154 @@ flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets) } /* - * Transform a single expression within a GROUP BY clause or grouping set. + * Working state for transforming a GROUP BY or PARTITION BY clause. * - * The expression is added to the targetlist if not already present, and to the - * flatresult list (which will become the groupClause) if not already present - * there. The sortClause is consulted for operator and sort order hints. - * - * Returns the ressortgroupref of the expression. - * - * flatresult reference to flat list of SortGroupClause nodes - * seen_local bitmapset of sortgrouprefs already seen at the local level - * pstate ParseState - * gexpr node to transform - * targetlist reference to TargetEntry list - * sortClause ORDER BY clause (SortGroupClause nodes) - * exprKind expression kind - * useSQL99 SQL99 rather than SQL92 syntax - * toplevel false if within any grouping set + * The fields other than flatresult are fixed for the whole clause; they are + * kept here so that the recursive routines below don't each need a long list + * of pass-through arguments. */ -static Index -transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local, - ParseState *pstate, Node *gexpr, - List **targetlist, List *sortClause, - ParseExprKind exprKind, bool useSQL99, bool toplevel) +typedef struct GroupClauseState { - TargetEntry *tle; - bool found = false; + ParseState *pstate; + List **targetlist; /* reference to TargetEntry list */ + List *sortClause; /* ORDER BY clause (SortGroupClause nodes) */ + ParseExprKind exprKind; /* expression kind */ + bool useSQL99; /* SQL99 rather than SQL92 syntax */ + List *flatresult; /* flat list of SortGroupClause nodes being + * built; becomes the groupClause */ +} GroupClauseState; - if (useSQL99) - tle = findTargetlistEntrySQL99(pstate, gexpr, - targetlist, exprKind); +/* + * Find or create the targetlist entry for one grouping expression. + * + * This is the only step in which the SQL92 and SQL99 interpretations of a + * grouping item differ (SQL92 additionally allows output-column names and + * numbers). If the expression is not already in the targetlist, it is added + * as a resjunk entry. + */ +static TargetEntry * +resolveGroupingExpr(GroupClauseState *gcs, Node *gexpr) +{ + if (gcs->useSQL99) + return findTargetlistEntrySQL99(gcs->pstate, gexpr, + gcs->targetlist, gcs->exprKind); else - tle = findTargetlistEntrySQL92(pstate, gexpr, - targetlist, exprKind); + return findTargetlistEntrySQL92(gcs->pstate, gexpr, + gcs->targetlist, gcs->exprKind); +} +/* + * Ensure that a targetlist entry is represented in the flat groupClause. + * + * If the entry is already in the flat list, nothing is added. Otherwise a + * SortGroupClause is appended. If the entry also appears in ORDER BY, the + * operator info is copied from the (first) matching ORDER BY item. This means + * that if you write something like "GROUP BY foo ORDER BY foo USING <<<", the + * GROUP BY operation silently takes on the equality semantics implied by the + * ORDER BY. There are two reasons to do this: it improves the odds that we + * can implement both GROUP BY and ORDER BY with a single sort step, and it + * allows the user to choose the equality semantics used by GROUP BY, should + * she be working with a datatype that has more than one equality operator. + * If there is no matching ORDER BY item, we fall back to addTargetToGroupList, + * which applies the datatype's default sort/group operators. + * + * If we're in a grouping set (toplevel is false), we force the requested + * ordering to be NULLS LAST, because if we have any hope of using a sorted agg + * for the job, we're going to be tacking on generated NULL values after the + * corresponding groups. If the user demands nulls first, another sort step + * is going to be inevitable, but that's the planner's problem. + * + * This deliberately does not eliminate duplicates within a grouping list; + * that is the caller's business, since whether a duplicate can be dropped + * depends on where it appears. + * + * Returns the ressortgroupref of the entry, which is always nonzero. + */ +static Index +addGroupingTarget(GroupClauseState *gcs, TargetEntry *tle, + bool toplevel, int location) +{ if (tle->ressortgroupref > 0) { - ListCell *sl; - - /* - * Eliminate duplicates (GROUP BY x, x) but only at local level. - * (Duplicates in grouping sets can affect the number of returned - * rows, so can't be dropped indiscriminately.) - * - * Since we don't care about anything except the sortgroupref, we can - * use a bitmapset rather than scanning lists. - */ - if (bms_is_member(tle->ressortgroupref, seen_local)) - return 0; - - /* - * If we're already in the flat clause list, we don't need to consider - * adding ourselves again. - */ - found = targetIsInSortList(tle, InvalidOid, *flatresult); - if (found) + /* If we're already in the flat clause list, nothing to do */ + if (targetIsInSortList(tle, InvalidOid, gcs->flatresult)) return tle->ressortgroupref; - /* - * If the GROUP BY tlist entry also appears in ORDER BY, copy operator - * info from the (first) matching ORDER BY item. This means that if - * you write something like "GROUP BY foo ORDER BY foo USING <<<", the - * GROUP BY operation silently takes on the equality semantics implied - * by the ORDER BY. There are two reasons to do this: it improves the - * odds that we can implement both GROUP BY and ORDER BY with a single - * sort step, and it allows the user to choose the equality semantics - * used by GROUP BY, should she be working with a datatype that has - * more than one equality operator. - * - * If we're in a grouping set, though, we force our requested ordering - * to be NULLS LAST, because if we have any hope of using a sorted agg - * for the job, we're going to be tacking on generated NULL values - * after the corresponding groups. If the user demands nulls first, - * another sort step is going to be inevitable, but that's the - * planner's problem. - */ - - foreach(sl, sortClause) + foreach_node(SortGroupClause, sc, gcs->sortClause) { - SortGroupClause *sc = (SortGroupClause *) lfirst(sl); - if (sc->tleSortGroupRef == tle->ressortgroupref) { SortGroupClause *grpc = copyObject(sc); if (!toplevel) grpc->nulls_first = false; - *flatresult = lappend(*flatresult, grpc); - found = true; - break; + gcs->flatresult = lappend(gcs->flatresult, grpc); + return tle->ressortgroupref; } } } - /* - * If no match in ORDER BY, just add it to the result using default - * sort/group semantics. - */ - if (!found) - *flatresult = addTargetToGroupList(pstate, tle, - *flatresult, *targetlist, - exprLocation(gexpr)); - - /* - * _something_ must have assigned us a sortgroupref by now... - */ + /* No match in ORDER BY, so use default sort/group semantics */ + gcs->flatresult = addTargetToGroupList(gcs->pstate, tle, + gcs->flatresult, *gcs->targetlist, + location); + /* addTargetToGroupList must have assigned a sortgroupref */ + Assert(tle->ressortgroupref > 0); return tle->ressortgroupref; } /* - * Transform a list of expressions within a GROUP BY clause or grouping set. + * Transform a single (non-grouping-set) item of a GROUP BY clause or grouping + * set: resolve it to a targetlist entry and add that to the flat groupClause. + * + * If seen_local is not NULL, the item belongs to a list within which + * duplicates (GROUP BY x, x) can be eliminated, and *seen_local tracks the + * sortgrouprefs already seen in that list. Duplicates within grouping sets + * can affect the number of returned rows, so callers pass NULL when it is not + * safe to drop them. + * + * Returns the ressortgroupref of the item, or 0 if it was a duplicate that + * should be dropped from the enclosing list. + */ +static Index +transformGroupingItem(GroupClauseState *gcs, Node *gexpr, + Bitmapset **seen_local, bool toplevel) +{ + TargetEntry *tle = resolveGroupingExpr(gcs, gexpr); + Index ref = addGroupingTarget(gcs, tle, toplevel, + exprLocation(gexpr)); + + if (seen_local) + { + if (bms_is_member(ref, *seen_local)) + return 0; + *seen_local = bms_add_member(*seen_local, ref); + } + + return ref; +} + +/* + * Transform a list of expressions within a grouping set. * * The list of expressions belongs to a single clause within which duplicates * can be safely eliminated. * * Returns an integer list of ressortgroupref values. - * - * flatresult reference to flat list of SortGroupClause nodes - * pstate ParseState - * list nodes to transform - * targetlist reference to TargetEntry list - * sortClause ORDER BY clause (SortGroupClause nodes) - * exprKind expression kind - * useSQL99 SQL99 rather than SQL92 syntax - * toplevel false if within any grouping set */ static List * -transformGroupClauseList(List **flatresult, - ParseState *pstate, List *list, - List **targetlist, List *sortClause, - ParseExprKind exprKind, bool useSQL99, bool toplevel) +transformGroupClauseList(GroupClauseState *gcs, List *list) { Bitmapset *seen_local = NULL; List *result = NIL; - ListCell *gl; - foreach(gl, list) + foreach_ptr(Node, gexpr, list) { - Node *gexpr = (Node *) lfirst(gl); - - Index ref = transformGroupClauseExpr(flatresult, - seen_local, - pstate, - gexpr, - targetlist, - sortClause, - exprKind, - useSQL99, - toplevel); + Index ref = transformGroupingItem(gcs, gexpr, &seen_local, false); if (ref > 0) - { - seen_local = bms_add_member(seen_local, ref); result = lappend_int(result, ref); - } } return result; @@ -2515,37 +2508,19 @@ transformGroupClauseList(List **flatresult, * * Returns the transformed node, which now contains SIMPLE nodes with lists * of ressortgrouprefs rather than expressions. - * - * flatresult reference to flat list of SortGroupClause nodes - * pstate ParseState - * gset grouping set to transform - * targetlist reference to TargetEntry list - * sortClause ORDER BY clause (SortGroupClause nodes) - * exprKind expression kind - * useSQL99 SQL99 rather than SQL92 syntax - * toplevel false if within any grouping set */ static Node * -transformGroupingSet(List **flatresult, - ParseState *pstate, GroupingSet *gset, - List **targetlist, List *sortClause, - ParseExprKind exprKind, bool useSQL99, bool toplevel) +transformGroupingSet(GroupClauseState *gcs, GroupingSet *gset, bool toplevel) { - ListCell *gl; List *content = NIL; Assert(toplevel || gset->kind != GROUPING_SET_SETS); - foreach(gl, gset->content) + foreach_ptr(Node, n, gset->content) { - Node *n = lfirst(gl); - if (IsA(n, List)) { - List *l = transformGroupClauseList(flatresult, - pstate, (List *) n, - targetlist, sortClause, - exprKind, useSQL99, false); + List *l = transformGroupClauseList(gcs, (List *) n); content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE, l, @@ -2553,24 +2528,13 @@ transformGroupingSet(List **flatresult, } else if (IsA(n, GroupingSet)) { - GroupingSet *gset2 = (GroupingSet *) lfirst(gl); - - content = lappend(content, transformGroupingSet(flatresult, - pstate, gset2, - targetlist, sortClause, - exprKind, useSQL99, false)); + content = lappend(content, + transformGroupingSet(gcs, (GroupingSet *) n, + false)); } else { - Index ref = transformGroupClauseExpr(flatresult, - NULL, - pstate, - n, - targetlist, - sortClause, - exprKind, - useSQL99, - false); + Index ref = transformGroupingItem(gcs, n, NULL, false); content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE, list_make1_int(ref), @@ -2585,7 +2549,7 @@ transformGroupingSet(List **flatresult, ereport(ERROR, (errcode(ERRCODE_TOO_MANY_COLUMNS), errmsg("CUBE is limited to 12 elements"), - parser_errposition(pstate, gset->location))); + parser_errposition(gcs->pstate, gset->location))); } return (Node *) makeGroupingSet(gset->kind, content, gset->location); @@ -2602,16 +2566,24 @@ transformGroupingSet(List **flatresult, * This is also used for window PARTITION BY clauses (which act almost the * same, but are always interpreted per SQL99 rules). * - * Grouping sets make this a lot more complex than it was. Our goal here is - * twofold: we make a flat list of SortGroupClause nodes referencing each - * distinct expression used for grouping, with those expressions added to the - * targetlist if needed. At the same time, we build the groupingSets tree, - * which stores only ressortgrouprefs as integer lists inside GroupingSet nodes - * (possibly nested, but limited in depth: a GROUPING_SET_SETS node can contain - * nested SIMPLE, CUBE or ROLLUP nodes, but not more sets - we flatten that - * out; while CUBE and ROLLUP can contain only SIMPLE nodes). - * - * We skip much of the hard work if there are no grouping sets. + * Our goal here is twofold: we make a flat list of SortGroupClause nodes + * referencing each distinct expression used for grouping, with those + * expressions added to the targetlist if needed. At the same time, if there + * are grouping sets, we build the groupingSets tree, which stores only + * ressortgrouprefs as integer lists inside GroupingSet nodes (possibly nested, + * but limited in depth: a GROUPING_SET_SETS node can contain nested SIMPLE, + * CUBE or ROLLUP nodes, but not more sets - we flatten that out; while CUBE + * and ROLLUP can contain only SIMPLE nodes). + * + * The work is layered as follows: + * + * 1. flatten_grouping_sets() normalizes the syntactic structure. + * 2. Each grouping item is resolved to a targetlist entry by + * resolveGroupingExpr(); only this step depends on SQL92 vs SQL99 rules. + * 3. Each resolved entry is added to the flat groupClause by + * addGroupingTarget(), which is where ORDER BY semantics are inherited. + * 4. transformGroupingItem() and its callers handle duplicate elimination + * and build the groupingSets tree from the resulting sortgrouprefs. * * One subtlety is that the groupClause list can end up empty while the * groupingSets list is not; this happens if there are only empty grouping @@ -2634,13 +2606,19 @@ transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99) { - List *result = NIL; + GroupClauseState gcs; List *flat_grouplist; List *gsets = NIL; - ListCell *gl; bool hasGroupingSets = false; Bitmapset *seen_local = NULL; + gcs.pstate = pstate; + gcs.targetlist = targetlist; + gcs.sortClause = sortClause; + gcs.exprKind = exprKind; + gcs.useSQL99 = useSQL99; + gcs.flatresult = NIL; + /* * Recursively flatten implicit RowExprs. (Technically this is only needed * for GROUP BY, per the syntax rules for grouping sets, but we do it @@ -2655,7 +2633,6 @@ transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, * elided redundant empty grouping sets. Restore a single empty grouping * set to leave a canonical form: GROUP BY () */ - if (flat_grouplist == NIL && hasGroupingSets) { flat_grouplist = list_make1(makeGroupingSet(GROUPING_SET_EMPTY, @@ -2663,10 +2640,8 @@ transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, exprLocation((Node *) grouplist))); } - foreach(gl, flat_grouplist) + foreach_ptr(Node, gexpr, flat_grouplist) { - Node *gexpr = (Node *) lfirst(gl); - if (IsA(gexpr, GroupingSet)) { GroupingSet *gset = (GroupingSet *) gexpr; @@ -2684,29 +2659,21 @@ transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, case GROUPING_SET_CUBE: case GROUPING_SET_ROLLUP: gsets = lappend(gsets, - transformGroupingSet(&result, - pstate, gset, - targetlist, sortClause, - exprKind, useSQL99, true)); + transformGroupingSet(&gcs, gset, true)); break; } } else { - Index ref = transformGroupClauseExpr(&result, seen_local, - pstate, gexpr, - targetlist, sortClause, - exprKind, useSQL99, true); - - if (ref > 0) - { - seen_local = bms_add_member(seen_local, ref); - if (hasGroupingSets) - gsets = lappend(gsets, - makeGroupingSet(GROUPING_SET_SIMPLE, - list_make1_int(ref), - exprLocation(gexpr))); - } + /* Plain top-level item; local duplicates can be dropped */ + Index ref = transformGroupingItem(&gcs, gexpr, + &seen_local, true); + + if (ref > 0 && hasGroupingSets) + gsets = lappend(gsets, + makeGroupingSet(GROUPING_SET_SIMPLE, + list_make1_int(ref), + exprLocation(gexpr))); } } @@ -2716,7 +2683,7 @@ transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, if (groupingSets) *groupingSets = gsets; - return result; + return gcs.flatresult; } /* diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index f10eb46926..4c11a50bc8 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1158,6 +1158,7 @@ Group GroupByColInfo GroupByOrdering GroupClause +GroupClauseState GroupPath GroupPathExtraData GroupResultPath -- 2.56.0