Hi Matheus,

Sorry for the delay in getting back to this, it's been a minute. Thanks
for the careful review and the testing; comparing GROUP BY ALL against
the explicit GROUP BY across all of those cases is exactly the kind of
checking this patch needs, and it was helpful to have it.

Attached is v2, rebased on current master and now split into two
patches:

  0001 Restructure transformGroupClause() into explicit layers
  0002 Add GROUP BY ALL

0001 is intended to be a pure refactor with no behavior change, and
0002 adds the feature on top of it. Responses to your points inline.

> 1: The refactoring requested on the revert thread
>
> When GROUP BY ALL was reverted, IIUC, Tom concern was not only the
> ORDER BY bug itself, but that the GROUP BY transformation code needed
> to be redesigned first [1]. He asked to figure out which operations
> need to happen for which cases (plain GROUP BY, grouping sets, GROUP
> BY ALL, SQL92 vs SQL99) and then find a "less-baroque layering".
>
> The new addTargetToGroupClause() fixes the bug, but it seems to me
> that it's the same kind of change as Chao original fix. The GROUP BY
> ALL path is still a separate early-return branch at the top of
> transformGroupClause(). So I'm wondering if this patch is in the right
> direction based on the previous feedbacks?

Fair point, and I agree. v1 fixed the bug but didn't do what Tom asked
for. So I went through the cases first, to see which operations each
one actually needs:

- Every grouping item, whatever the case, has to be resolved to a
  targetlist entry, and that entry then has to be added to the flat
  groupClause, picking up operator info from a matching ORDER BY item if
  there is one.

- SQL92 vs SQL99 only matters for the first of those steps. SQL92 adds
  output-column names and numbers, then falls through to the SQL99
  lookup. GROUP BY ALL never has either form, since it starts from the
  targetlist entries themselves.

- Duplicate elimination is the part that differs by position. Plain
  top-level items and items in a list inside a grouping set can drop
  local duplicates. Bare items directly inside a grouping set can't,
  since that can change the number of returned rows.

- Grouping sets only add the work of building the groupingSets tree
  from the resulting sortgrouprefs.

- GROUP BY ALL only differs in where the list comes from. It's the
  qualifying targetlist entries, or GROUP BY () if there aren't any.

0001 restructures the code to follow that:

- resolveGroupingExpr() finds or creates the targetlist entry for an
  item. This is now the only place that looks at SQL92 vs SQL99.

- addGroupingTarget() makes sure an entry is in the flat groupClause,
  copying the ORDER BY operator info if there's a match and otherwise
  using addTargetToGroupList() for the default operators. It always
  returns a nonzero sortgroupref.

- transformGroupingItem() combines the two and does local duplicate
  elimination when the caller says it's safe. Its comment now says it
  returns 0 for a dropped duplicate, which fixes the misleading
  "Returns the ressortgroupref" comment Tom pointed out on
  transformGroupClauseExpr().

- transformGroupClauseList(), transformGroupingSet() and
  transformGroupClause() just walk the structure and build the
  groupingSets tree.

The arguments that are fixed for the whole clause (pstate, targetlist,
sortClause, exprKind, useSQL99, and the flat result list) are now
collected in a small GroupClauseState struct, rather than passed
through every level.

With that in place, 0002 doesn't need a separate branch for GROUP BY
ALL. groupByAllTargets() builds the list of qualifying targetlist
entries (or an empty grouping set if none qualify), that list replaces
the empty grouplist, and everything after that is the normal path.
resolveGroupingExpr() returns a TargetEntry item as-is. So the ORDER BY
handling, duplicate handling and the GROUP BY () fallback all come from
the same code that explicit GROUP BY uses, rather than being something
GROUP BY ALL has to reproduce.

I left findTargetlistEntrySQL92() and findTargetlistEntrySQL99() as
they are. They're shared with ORDER BY and DISTINCT ON, so it didn't
seem right to fold them into the GROUP BY code.

> 2: Changes from the reverted version are missing
>
> Before the revert Peter updated the window function comment, since the
> SQL standard now specifies the current behavior [2]. The patch brings
> back the old wording:
> [...]
> The reverted version said "and the SQL standard directs us to skip
> them". The commit message has the same claim.
>
> The docs on queries.sgml and select.sgml also lost the "referring to
> the same query level" wording for aggregate functions.

Good catch, thanks. Both the window function comment and the commit
message now say the standard directs us to skip them, and the "referring
to the same query level" wording is back in queries.sgml and
select.sgml.

> 3: Naming of the new helper
>
> addTargetToGroupClause() and the existing addTargetToGroupList() are
> very similar names doing different things, which is a bit confusing
> when reading transformGroupClause(). Maybe a different name, or at
> least mention in the header comment how it differs from
> addTargetToGroupList()?

The helper is now addGroupingTarget(). Its header comment says it
consults ORDER BY first and only falls back to addTargetToGroupList()
for the default semantics.

> 4: Daniel comments on Chao's patch
>
> Daniel comments on the same helper in Chao's patch [3] also apply
> here: the function comment could absorb part of the big comment on the
> foreach, and since this is now a separate function we could return
> directly when a matching ORDER BY item is found instead of using the
> "found" flag.
>
> Also, the new helper's comment correctly says that it can return 0,
> but transformGroupClauseExpr() still says "Returns the ressortgroupref
> of the expression", which was one of the misleading comments Tom
> pointed out, and it can also return 0.

Done. The ORDER BY and NULLS LAST explanation moved into the
addGroupingTarget() header, it returns as soon as it finds a match, and
the "found" flag is gone. transformGroupClauseExpr() itself is gone
now; as above, the function that can return 0 (transformGroupingItem())
says so.

> 5: Tests
>
> - aggregates.sql already has an avg_rec (x numeric) type a few lines
>   below the new tests, used to test the same record_ops vs
>   record_image_ops difference. Maybe we can move the new tests after
>   it and reuse the type instead of creating gba_rec?

Done. The tests now come after the existing avg_rec tests and use that
type.

> - The record_image test doesn't fix the plan type. Chao original repro
>   used enable_hashagg = off, so I think it would be good to run it
>   with both sorted and hashed aggregation (or add an EXPLAIN) so we
>   don't lose the sorted case coverage.

The ORDER BY ... USING case now runs with enable_hashagg = off and
again with enable_sort = off, each with an EXPLAIN. Since record_image
equality isn't hashable, the second run still gets a sorted plan, and
the EXPLAIN shows that. So I also added a case with default (hashable)
equality that gets a GroupAggregate and a HashAggregate respectively,
and checks they return the same result.

> - Maybe add a deparse test for a view with ORDER BY ... USING, since
>   that's the case that GROUP BY ALL needs to reproduce exactly on
>   reload.

Added. The view deparses as GROUP BY ALL with the ORDER BY ... USING,
and selecting from it gives the two groups.

> 6: Docs
>
> It may be worth documenting that when all target list entries contain
> aggregates (or the target list is empty) GROUP BY ALL behaves like
> GROUP BY (), so one row is returned even on an empty table.

Added to both queries.sgml and select.sgml. There are also tests showing
the one-row result on an empty table for an all-aggregate and an empty
target list.

Thanks again for the review, and let me know what you think of the new
layout.


David

Attachment: v2-0002-Add-GROUP-BY-ALL.patch
Description: Binary data

Attachment: v2-0001-Restructure-transformGroupClause-into-explicit-la.patch
Description: Binary data

Reply via email to