Skip to content

feat(db): support custom aggregate functions - #1702

Open
jakeboone02 wants to merge 2 commits into
TanStack:mainfrom
jakeboone02:custom-aggregate-fns
Open

feat(db): support custom aggregate functions#1702
jakeboone02 wants to merge 2 commits into
TanStack:mainfrom
jakeboone02:custom-aggregate-fns

Conversation

@jakeboone02

@jakeboone02 jakeboone02 commented Jul 28, 2026

Copy link
Copy Markdown

🎯 Changes

Aggregate support in packages/db/src/query/compiler/group-by.ts was a hardcoded switch over sum, count, avg, min, max; every other name threw UnsupportedAggregateFunctionError. Domain-specific aggregations (group_concat, array_agg, bitwise OR, geometric mean, …) required forking the package.

This adds a registry for user-defined aggregates built on the existing { preMap, reduce, postMap? } contract from @tanstack/db-ivm.

Public API

createAggregate registers an aggregate and returns a typed builder for select():

import { createAggregate } from '@tanstack/db'

const groupConcat = createAggregate<string, [separator?: string]>(
  'group_concat',
  (ctx, [separator = ',']) => ({
    // pair the value with its row key so rows stay distinct and orderable
    preMap: (entry) => [ctx.key(entry), String(ctx.value(entry) ?? '')],
    reduce: (values) => {
      const rows: Array<[string, string]> = []
      for (const [row, multiplicity] of values) {
        for (let i = 0; i < multiplicity; i++) rows.push(row)
      }
      rows.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
      return rows.map(([, text]) => text).join(separator)
    },
  })
)

const result = useLiveQuery((q) =>
  q
    .from({ todo: todosCollection })
    .groupBy(({ todo }) => todo.listId)
    .select(({ todo }) => ({
      listId: todo.listId,
      allNames: groupConcat(todo.text, ' | '), // inferred as string
    }))
)

A lower-level API is exported for dynamic/plugin scenarios:

registerAggregate(name, factory)     // void
unregisterAggregate(name)            // boolean — true if a registration existed
getRegisteredAggregates()            // ReadonlySet<string>

Also newly exported to support the low-level path: toExpression, the
ExpressionLike type, and the Aggregate type (the class remains reachable as
IR.Aggregate).

Design notes

  • Factories receive the row key, not just the value. preMap outputs are consolidated by hash inside db-ivm's Index, so two rows producing the same value collapse into one entry with multiplicity 2, and iteration order is map order rather than row order. Passing ctx.key(entry) lets aggregates such as group_concat keep per-row identity and sort deterministically. ctx.value is the raw value — no numeric coercion, unlike the sum/avg path.
  • reduce is a full recompute. ReduceOperator passes the complete consolidated multiset for the group on every change, so implementations need no incremental accumulator bookkeeping. Ignoring multiplicity under-counts duplicates; this is called out in the docs.
  • Registry-first lookup. getAggregateFunction checks the registry before the built-in switch. That is what allows overriding a built-in, and it also means unregisterAggregate('sum') restores the built-in for free — no special-casing.
  • Extra arguments are compile-time constants. Arguments after the first are evaluated once against an empty row and passed to the factory as the params tuple. A column reference there now throws the new NonConstantAggregateArgumentError instead of silently evaluating to undefined.
  • Overriding built-ins is allowed, with a dev-only warning. It is a global, app-wide change that only affects queries compiled afterwards, so already-compiled live queries keep their original behavior. The tradeoffs (import-order sensitivity, blast radius, staleness) are documented, and a distinct name is recommended.
  • No new built-ins. group_concat (SQL STRING_AGG function in groupBy #422) and the unused median/mode operators in db-ivm are intentionally out of scope; they are now expressible in user land.
  • Custom aggregates flow through the existing machinery unchanged: HAVING (aggregatesEqual compares name + args), nested-in-expression extraction (__agg_N), and ordering via $selected.<alias>.

Files

File Change
packages/db/src/query/aggregates.ts New: registry, types, createAggregate, dev warning
packages/db/src/query/compiler/group-by.ts Registry-first lookup, constant-arg compilation
packages/db/src/errors.ts New NonConstantAggregateArgumentError; UnsupportedAggregateFunctionError now lists registered names
packages/db/src/query/index.ts Public exports
packages/db/src/query/builder/functions.ts Export the ExpressionLike type
packages/db/tests/query/custom-aggregates.test.ts 18 runtime tests
packages/db/tests/query/custom-aggregates.test-d.ts 3 type tests
docs/guides/live-queries.md "Custom Aggregate Functions" section

Backwards compatibility

Additive only. UnsupportedAggregateFunctionError's constructor gains an optional second parameter; existing call sites and behavior are unchanged.

✅ Checklist

  • I have tested this code locally with pnpm test.

Test coverage: registration/unregistration/case-insensitivity, snapshot semantics of getRegisteredAggregates, re-registration and built-in override warnings, group_concat with and without a custom separator, multiplicity of consolidated duplicates, postMap, raw (uncoerced) values, computed inner expressions, incremental insert/update/delete plus group removal, HAVING, nested-in-expression, orderBy via $selected, built-in override precedence and restore-on-unregister, unknown-aggregate error content, and non-constant extra argument.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset (.changeset/smart-pugs-listen.md, minor for @tanstack/db).
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • New Features
    • Added support for custom aggregate functions in grouped queries, including use in selections, computed expressions, HAVING, and ordering (including $selected).
    • Introduced typed helpers to create, register, unregister, and inspect custom aggregates.
    • Custom aggregate parameters support compile-time constants; duplicate/multiplicity behavior is preserved in results.
  • Documentation
    • Added a “Custom Aggregate Functions” guide section with examples and SSR notes.
  • Bug Fixes
    • Enhanced error messages for unsupported aggregates (including available registered names) and non-constant aggregate arguments.

Add a global, case-insensitive registry for user-defined aggregates. The
group-by compiler now looks up registrations before the built-in switch, so
custom names work anywhere built-ins do — select, having, and orderBy via
$selected — and built-ins can be overridden (warned about in dev) and restored
by unregistering.

Public API:
- createAggregate(name, factory): registers and returns a typed builder, so the
  aggregate name is declared once and its result type flows into select()
- registerAggregate / unregisterAggregate / getRegisteredAggregates for
  dynamic registration
- toExpression, ExpressionLike and the Aggregate type are now exported for the
  low-level path

Factories receive the raw value extractor plus the row key, letting aggregates
such as group_concat stay deterministic despite preMap outputs being
consolidated by value hash. Arguments after the first are evaluated once at
compile time and must be constant, otherwise NonConstantAggregateArgumentError
is thrown; UnsupportedAggregateFunctionError now lists registered names.

Closes TanStack#1558
@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 6296f697-0b2c-45e5-aec6-77c6646a61a4

📥 Commits

Reviewing files that changed from the base of the PR and between b76ee99 and ff07e12.

📒 Files selected for processing (1)
  • packages/db/tests/query/custom-aggregates.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/db/tests/query/custom-aggregates.test.ts

📝 Walkthrough

Walkthrough

Custom aggregate functions are now registerable through typed and low-level APIs, compiled ahead of built-in aggregates, usable across grouped query clauses, and covered by runtime and type tests. Documentation and minor-release metadata describe the new functionality.

Changes

Custom aggregate support

Layer / File(s) Summary
Aggregate registry and typed builders
packages/db/src/query/aggregates.ts, packages/db/src/query/builder/functions.ts, packages/db/src/query/index.ts
Adds aggregate contracts, case-insensitive registration, lookup and removal APIs, typed createAggregate builders, and public exports.
Custom aggregate compilation
packages/db/src/query/compiler/group-by.ts, packages/db/src/errors.ts
Compiles registered factories before built-ins, accepts constant parameters, and reports registered names or invalid parameter expressions in errors.
Runtime and type validation
packages/db/tests/query/custom-aggregates.test.ts, packages/db/tests/query/custom-aggregates.test-d.ts
Tests registry behavior, type inference, grouped execution, incremental updates, clause integration, overrides, and error handling.
Documentation and release metadata
docs/guides/live-queries.md, .changeset/smart-pugs-listen.md
Documents custom aggregate APIs, semantics, supported query clauses, SSR registration, and the minor package release.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant QueryBuilder
  participant GroupByCompiler
  participant CustomAggregateFactory
  QueryBuilder->>GroupByCompiler: compile aggregate expression
  GroupByCompiler->>GroupByCompiler: compile constant parameters
  GroupByCompiler->>CustomAggregateFactory: invoke with value and key accessors
  CustomAggregateFactory-->>GroupByCompiler: return aggregate implementation
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main addition of custom aggregate support.
Description check ✅ Passed The description covers the required changes, checklist, and release impact sections with sufficient detail.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
packages/db/tests/query/custom-aggregates.test.ts (2)

528-565: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Deduplicate the repeated query-building block.

The same faulty query is built and run twice — once for toThrow(UnsupportedAggregateFunctionError), once inside a try/catch to check the message. Both assertions can be made from a single execution. As per coding guidelines, **/*.{ts,tsx,js} should "extract common logic into utility functions when identical or near-identical code blocks appear in multiple places."

♻️ Suggested consolidation
-      const todos = createTodosCollection()
-      expect(() =>
-        createLiveQueryCollection({
-          startSync: true,
-          query: (q) =>
-            q
-              .from({ todo: todos })
-              .groupBy(({ todo }) => todo.listId)
-              .select(({ todo }) => ({
-                listId: todo.listId,
-                value: new Aggregate(`nope`, [
-                  toExpression(todo.points),
-                ]) as any,
-              })),
-        }),
-      ).toThrow(UnsupportedAggregateFunctionError)
-
-      try {
-        createLiveQueryCollection({
-          startSync: true,
-          query: (q) =>
-            q
-              .from({ todo: todos })
-              .groupBy(({ todo }) => todo.listId)
-              .select(({ todo }) => ({
-                listId: todo.listId,
-                value: new Aggregate(`nope`, [
-                  toExpression(todo.points),
-                ]) as any,
-              })),
-        })
-      } catch (error) {
-        expect((error as Error).message).toContain(`known_agg`)
-      }
+      const todos = createTodosCollection()
+      const buildBadQuery = () =>
+        createLiveQueryCollection({
+          startSync: true,
+          query: (q) =>
+            q
+              .from({ todo: todos })
+              .groupBy(({ todo }) => todo.listId)
+              .select(({ todo }) => ({
+                listId: todo.listId,
+                value: new Aggregate(`nope`, [
+                  toExpression(todo.points),
+                ]) as any,
+              })),
+        })
+
+      let caught: unknown
+      try {
+        buildBadQuery()
+      } catch (error) {
+        caught = error
+      }
+      expect(caught).toBeInstanceOf(UnsupportedAggregateFunctionError)
+      expect((caught as Error).message).toContain(`known_agg`)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/db/tests/query/custom-aggregates.test.ts` around lines 528 - 565,
Deduplicate the repeated query construction in the test `unknown aggregate
throws and lists registered names` by executing the faulty
`createLiveQueryCollection` call once and capturing its thrown error. Assert
that the captured error is an `UnsupportedAggregateFunctionError` and that its
message contains `known_agg`, while preserving the existing query behavior.

Source: Coding guidelines


73-76: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid any in the register test helper.

args: Array<any> plus (registerAggregate as any)(...) bypasses type checking on a helper used across ~15 test cases; a mistaken call signature wouldn't be caught. As per coding guidelines, **/*.{ts,tsx} should "use unknown instead when the type is truly unknown, and provide proper type annotations for return values."

♻️ Suggested typing
-function register(name: string, ...args: Array<any>) {
+function register(
+  name: string,
+  ...args: Parameters<typeof registerAggregate> extends [string, ...infer Rest]
+    ? Rest
+    : never
+) {
   registeredInTest.add(name.toLowerCase())
-  return (registerAggregate as any)(name, ...args)
+  return registerAggregate(name, ...(args as Parameters<typeof registerAggregate>[1..]))
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/db/tests/query/custom-aggregates.test.ts` around lines 73 - 76,
Update the register test helper to remove both any usages: type variadic args as
unknown (or with the actual aggregate registration parameter types), and give
the helper an explicit return type matching registerAggregate without casting
the function to any. Preserve the existing lowercase tracking and argument
forwarding behavior.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/db/tests/query/custom-aggregates.test.ts`:
- Around line 528-565: Deduplicate the repeated query construction in the test
`unknown aggregate throws and lists registered names` by executing the faulty
`createLiveQueryCollection` call once and capturing its thrown error. Assert
that the captured error is an `UnsupportedAggregateFunctionError` and that its
message contains `known_agg`, while preserving the existing query behavior.
- Around line 73-76: Update the register test helper to remove both any usages:
type variadic args as unknown (or with the actual aggregate registration
parameter types), and give the helper an explicit return type matching
registerAggregate without casting the function to any. Preserve the existing
lowercase tracking and argument forwarding behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 25dc9243-064f-4b52-a5ee-7702c810c717

📥 Commits

Reviewing files that changed from the base of the PR and between 67c840f and b76ee99.

📒 Files selected for processing (9)
  • .changeset/smart-pugs-listen.md
  • docs/guides/live-queries.md
  • packages/db/src/errors.ts
  • packages/db/src/query/aggregates.ts
  • packages/db/src/query/builder/functions.ts
  • packages/db/src/query/compiler/group-by.ts
  • packages/db/src/query/index.ts
  • packages/db/tests/query/custom-aggregates.test-d.ts
  • packages/db/tests/query/custom-aggregates.test.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant