-
Notifications
You must be signed in to change notification settings - Fork 257
feat(db): support custom aggregate functions #1702
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jakeboone02
wants to merge
4
commits into
TanStack:main
Choose a base branch
from
jakeboone02:custom-aggregate-fns
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b76ee99
feat(db): support custom aggregate functions
jakeboone02 ff07e12
test(db): address review nits in custom aggregate tests
jakeboone02 824efcb
Merge branch 'main' into custom-aggregate-fns
jakeboone02 6a4e808
Merge branch 'main' into custom-aggregate-fns
jakeboone02 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@tanstack/db': minor | ||
| --- | ||
|
|
||
| Add support for custom aggregate functions. `createAggregate(name, factory)` registers an aggregate and returns a typed helper for use in `select()`, and the lower-level `registerAggregate` / `unregisterAggregate` / `getRegisteredAggregates` APIs are available for dynamic registration. Custom aggregates work anywhere built-ins do, including `having` and `orderBy` via `$selected`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| import { Aggregate } from './ir.js' | ||
| import { toExpression } from './builder/ref-proxy.js' | ||
| import type { ExpressionLike } from './builder/functions.js' | ||
| import type { NamespacedRow } from '../types.js' | ||
|
|
||
| /** | ||
| * A single row as seen by an aggregate: `[rowKey, namespacedRow]`. | ||
| */ | ||
| export type AggregateEntry = [string, NamespacedRow] | ||
|
|
||
| /** | ||
| * Accessors handed to a custom aggregate factory. | ||
| */ | ||
| export type AggregateContext = { | ||
| /** | ||
| * Raw value of the aggregate's first argument for this row. | ||
| * No numeric coercion is applied. | ||
| */ | ||
| value: (entry: AggregateEntry) => unknown | ||
| /** | ||
| * Stable per-row key. Use it to keep rows distinct (values emitted by | ||
| * `preMap` are consolidated by hash) or to order deterministically. | ||
| */ | ||
| key: (entry: AggregateEntry) => string | ||
| } | ||
|
|
||
| /** | ||
| * Implementation of a custom aggregate, mirroring db-ivm's basic aggregate contract. | ||
| * | ||
| * `reduce` receives the complete consolidated multiset for the group on every | ||
| * change, as `[value, multiplicity]` pairs — it is a full recompute, not a delta. | ||
| * Ignoring `multiplicity` under-counts duplicate values. | ||
| */ | ||
| export type CustomAggregateImpl<TValue = unknown, TResult = unknown> = { | ||
| preMap: (entry: AggregateEntry) => TValue | ||
| reduce: (values: Array<[TValue, number]>) => TValue | ||
| postMap?: (result: TValue) => TResult | ||
| } | ||
|
|
||
| /** | ||
| * Factory that builds a custom aggregate implementation for one compiled query. | ||
| * | ||
| * `additionalArgs` holds the evaluated values of any arguments after the first | ||
| * one in the aggregate expression; they must be constant expressions. | ||
| */ | ||
| export type CustomAggregateFactory<TValue = any, TResult = unknown> = ( | ||
| ctx: AggregateContext, | ||
| additionalArgs: Array<unknown>, | ||
| ) => CustomAggregateImpl<TValue, TResult> | ||
|
|
||
| // `any` for the value type: it is existential from the registry's point of view, | ||
| // and `unknown` would make user implementations non-assignable (contravariance). | ||
| type AnyCustomAggregateFactory = CustomAggregateFactory<any, unknown> | ||
|
|
||
| /** Aggregate names implemented natively by the group-by compiler. */ | ||
| export const BUILTIN_AGGREGATE_NAMES: ReadonlySet<string> = new Set([ | ||
| `sum`, | ||
| `count`, | ||
| `avg`, | ||
| `min`, | ||
| `max`, | ||
| ]) | ||
|
|
||
| const customAggregates = new Map<string, AnyCustomAggregateFactory>() | ||
|
|
||
| const DEV = | ||
| typeof process !== `undefined` && process.env.NODE_ENV !== `production` | ||
|
|
||
| /** | ||
| * Registers a custom aggregate function under `name` (case-insensitive). | ||
| * | ||
| * Re-registering a name — including a built-in — replaces the previous | ||
| * implementation for queries compiled afterwards and warns in development. | ||
| * Already-compiled live queries keep the implementation they were compiled with. | ||
| */ | ||
| export function registerAggregate( | ||
| name: string, | ||
| factory: AnyCustomAggregateFactory, | ||
| ): void { | ||
| const normalized = name.toLowerCase() | ||
|
|
||
| if (DEV) { | ||
| if (BUILTIN_AGGREGATE_NAMES.has(normalized)) { | ||
| console.warn( | ||
| `[@tanstack/db] registerAggregate("${name}") overrides the built-in ` + | ||
| `aggregate "${normalized}". This affects every query compiled afterwards, ` + | ||
| `app-wide. Already-compiled queries keep the built-in behavior.`, | ||
| ) | ||
| } else if (customAggregates.has(normalized)) { | ||
| console.warn( | ||
| `[@tanstack/db] registerAggregate("${name}") replaces an existing custom ` + | ||
| `aggregate registration. Queries compiled before this call keep the ` + | ||
| `previous implementation.`, | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| customAggregates.set(normalized, factory) | ||
| } | ||
|
|
||
| /** | ||
| * Removes a custom aggregate registration. | ||
| * | ||
| * If the name shadowed a built-in, the built-in becomes active again because | ||
| * the compiler falls back to it when no registration exists. | ||
| * | ||
| * @returns whether a registration existed for the name | ||
| */ | ||
| export function unregisterAggregate(name: string): boolean { | ||
| return customAggregates.delete(name.toLowerCase()) | ||
| } | ||
|
|
||
| /** Names of all currently registered custom aggregates. */ | ||
| export function getRegisteredAggregates(): ReadonlySet<string> { | ||
| return new Set(customAggregates.keys()) | ||
| } | ||
|
|
||
| /** Looks up a registered custom aggregate factory. Used by the compiler. */ | ||
| export function getCustomAggregate( | ||
| name: string, | ||
| ): AnyCustomAggregateFactory | undefined { | ||
| return customAggregates.get(name.toLowerCase()) | ||
| } | ||
|
|
||
| /** | ||
| * Registers a custom aggregate and returns a typed builder function for use in | ||
| * `select()` callbacks. | ||
| * | ||
| * @param name - Aggregate name (case-insensitive) | ||
| * @param factory - Builds the aggregate implementation from the row accessors | ||
| * and the evaluated extra parameters | ||
| * @returns a function taking the aggregated expression plus the extra parameters | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * const groupConcat = createAggregate<string, [separator?: string]>( | ||
| * `group_concat`, | ||
| * (ctx, [separator = `,`]) => ({ | ||
| * preMap: (entry) => [ctx.key(entry), String(ctx.value(entry) ?? ``)], | ||
| * reduce: (values) => | ||
| * values | ||
| * .filter(([, multiplicity]) => multiplicity > 0) | ||
| * .sort(([a], [b]) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)) | ||
| * .map(([[, text]]) => text) | ||
| * .join(separator), | ||
| * }), | ||
| * ) | ||
| * | ||
| * query.groupBy(({ todo }) => todo.listId).select(({ todo }) => ({ | ||
| * listId: todo.listId, | ||
| * names: groupConcat(todo.text, ` | `), | ||
| * })) | ||
| * ``` | ||
| */ | ||
| export function createAggregate<TResult, TParams extends Array<unknown> = []>( | ||
| name: string, | ||
| factory: ( | ||
| ctx: AggregateContext, | ||
| params: TParams, | ||
| ) => CustomAggregateImpl<any, TResult>, | ||
| ): (arg: ExpressionLike, ...params: TParams) => Aggregate<TResult> { | ||
| registerAggregate(name, (ctx, additionalArgs) => | ||
| factory(ctx, additionalArgs as TParams), | ||
| ) | ||
|
|
||
| return (arg: ExpressionLike, ...params: TParams) => | ||
| new Aggregate<TResult>(name, [ | ||
| toExpression(arg), | ||
| ...params.map((param) => toExpression(param)), | ||
| ]) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: TanStack/db
Length of output: 4380
🏁 Script executed:
Repository: TanStack/db
Length of output: 50369
🏁 Script executed:
Repository: TanStack/db
Length of output: 446
Preserve the aggregate types in this TypeScript example.
Strict TypeScript rejects the untyped
arg. Use the exportedExpressionLikeandAggregatetypes:🤖 Prompt for AI Agents
Source: MCP tools