Skip to content

Group rows for GROUP BY, grouping sets and DISTINCT in one partitioning step #3168

Backlog

Description

@mathiasrw

What happens today

  • For GROUP BY, compileGroup (src/select/groupby.js) generates one block per grouping set. Each block builds a text key from the grouped values joined with a backtick (line 92), with the set number in front when there are several sets (lines 93-95), and looks it up in this.xgroups, created per run in queryfn3 (src/select/queryfn.js, lines 127-128).
  • CUBE, ROLLUP and GROUPING SETS are expanded into those blocks by decartes (src/select/rollup.js).
  • Aggregates without GROUP BY use the key '' (groupby.js, lines 86-88). With no rows queryfn3 (lines 174-190) builds the group by hand.
  • DISTINCT has its own pass over the finished rows (doDistinct or its successor from Compare the rows of set operations and DISTINCT with one key function #3167).

What to change

  1. Add internal.partition in src/select/groupby.js. find(set, values) returns the group for a grouping set and its key values, and creates it when it is new (calling init of each aggregate from Give every aggregate the same init, step and result interface #2660 and storing the first row). Groups are kept in a Map by key and listed in first-seen order.
  2. Add compare.v4.groupKey(set, values) to src/engine/compare.js. It returns exactly today's text key.
  3. compileGroup generates, per grouping set, the key values, one call to find, then the step calls of the aggregates.
  4. Aggregates without GROUP BY are one grouping set with no key values. Create its group when the run starts and remove the special case in queryfn3 lines 174-190. result of a state that saw no row gives today's values (0 for COUNT, SUM and TOTAL, undefined for the rest).
  5. DISTINCT uses the same helper with one set made of all output columns and its current key rule. It keeps its row order and the last row of each key.

Window functions in src/select/select.js stay as they are.

What stays the same

Done when

  • A new test file named after this issue covers GROUP BY with one and two keys, values that share today's text key (1 and '1', NULL and 'null'), CUBE, ROLLUP, GROUPING SETS, aggregates over no rows with and without GROUP BY, HAVING that removes every group, and DISTINCT, against results recorded on main before the change.
  • bun test/performance/bench.js --group=group-by shows no slowdown beyond the noise described in test/performance/README.md.
  • The full test suite and the CI checks (dialect test, parity check, run-state check, binding check) pass, and the pull request lists every parity difference.

Depends on

#3163 and #2660

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions