|
| 1 | +import { Aggregate } from './ir.js' |
| 2 | +import { toExpression } from './builder/ref-proxy.js' |
| 3 | +import type { ExpressionLike } from './builder/functions.js' |
| 4 | +import type { NamespacedRow } from '../types.js' |
| 5 | + |
| 6 | +/** |
| 7 | + * A single row as seen by an aggregate: `[rowKey, namespacedRow]`. |
| 8 | + */ |
| 9 | +export type AggregateEntry = [string, NamespacedRow] |
| 10 | + |
| 11 | +/** |
| 12 | + * Accessors handed to a custom aggregate factory. |
| 13 | + */ |
| 14 | +export type AggregateContext = { |
| 15 | + /** |
| 16 | + * Raw value of the aggregate's first argument for this row. |
| 17 | + * No numeric coercion is applied. |
| 18 | + */ |
| 19 | + value: (entry: AggregateEntry) => unknown |
| 20 | + /** |
| 21 | + * Stable per-row key. Use it to keep rows distinct (values emitted by |
| 22 | + * `preMap` are consolidated by hash) or to order deterministically. |
| 23 | + */ |
| 24 | + key: (entry: AggregateEntry) => string |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * Implementation of a custom aggregate, mirroring db-ivm's basic aggregate contract. |
| 29 | + * |
| 30 | + * `reduce` receives the complete consolidated multiset for the group on every |
| 31 | + * change, as `[value, multiplicity]` pairs — it is a full recompute, not a delta. |
| 32 | + * Ignoring `multiplicity` under-counts duplicate values. |
| 33 | + */ |
| 34 | +export type CustomAggregateImpl<TValue = unknown, TResult = unknown> = { |
| 35 | + preMap: (entry: AggregateEntry) => TValue |
| 36 | + reduce: (values: Array<[TValue, number]>) => TValue |
| 37 | + postMap?: (result: TValue) => TResult |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Factory that builds a custom aggregate implementation for one compiled query. |
| 42 | + * |
| 43 | + * `additionalArgs` holds the evaluated values of any arguments after the first |
| 44 | + * one in the aggregate expression; they must be constant expressions. |
| 45 | + */ |
| 46 | +export type CustomAggregateFactory<TValue = any, TResult = unknown> = ( |
| 47 | + ctx: AggregateContext, |
| 48 | + additionalArgs: Array<unknown>, |
| 49 | +) => CustomAggregateImpl<TValue, TResult> |
| 50 | + |
| 51 | +// `any` for the value type: it is existential from the registry's point of view, |
| 52 | +// and `unknown` would make user implementations non-assignable (contravariance). |
| 53 | +type AnyCustomAggregateFactory = CustomAggregateFactory<any, unknown> |
| 54 | + |
| 55 | +/** Aggregate names implemented natively by the group-by compiler. */ |
| 56 | +export const BUILTIN_AGGREGATE_NAMES: ReadonlySet<string> = new Set([ |
| 57 | + `sum`, |
| 58 | + `count`, |
| 59 | + `avg`, |
| 60 | + `min`, |
| 61 | + `max`, |
| 62 | +]) |
| 63 | + |
| 64 | +const customAggregates = new Map<string, AnyCustomAggregateFactory>() |
| 65 | + |
| 66 | +const DEV = |
| 67 | + typeof process !== `undefined` && process.env.NODE_ENV !== `production` |
| 68 | + |
| 69 | +/** |
| 70 | + * Registers a custom aggregate function under `name` (case-insensitive). |
| 71 | + * |
| 72 | + * Re-registering a name — including a built-in — replaces the previous |
| 73 | + * implementation for queries compiled afterwards and warns in development. |
| 74 | + * Already-compiled live queries keep the implementation they were compiled with. |
| 75 | + */ |
| 76 | +export function registerAggregate( |
| 77 | + name: string, |
| 78 | + factory: AnyCustomAggregateFactory, |
| 79 | +): void { |
| 80 | + const normalized = name.toLowerCase() |
| 81 | + |
| 82 | + if (DEV) { |
| 83 | + if (BUILTIN_AGGREGATE_NAMES.has(normalized)) { |
| 84 | + console.warn( |
| 85 | + `[@tanstack/db] registerAggregate("${name}") overrides the built-in ` + |
| 86 | + `aggregate "${normalized}". This affects every query compiled afterwards, ` + |
| 87 | + `app-wide. Already-compiled queries keep the built-in behavior.`, |
| 88 | + ) |
| 89 | + } else if (customAggregates.has(normalized)) { |
| 90 | + console.warn( |
| 91 | + `[@tanstack/db] registerAggregate("${name}") replaces an existing custom ` + |
| 92 | + `aggregate registration. Queries compiled before this call keep the ` + |
| 93 | + `previous implementation.`, |
| 94 | + ) |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + customAggregates.set(normalized, factory) |
| 99 | +} |
| 100 | + |
| 101 | +/** |
| 102 | + * Removes a custom aggregate registration. |
| 103 | + * |
| 104 | + * If the name shadowed a built-in, the built-in becomes active again because |
| 105 | + * the compiler falls back to it when no registration exists. |
| 106 | + * |
| 107 | + * @returns whether a registration existed for the name |
| 108 | + */ |
| 109 | +export function unregisterAggregate(name: string): boolean { |
| 110 | + return customAggregates.delete(name.toLowerCase()) |
| 111 | +} |
| 112 | + |
| 113 | +/** Names of all currently registered custom aggregates. */ |
| 114 | +export function getRegisteredAggregates(): ReadonlySet<string> { |
| 115 | + return new Set(customAggregates.keys()) |
| 116 | +} |
| 117 | + |
| 118 | +/** Looks up a registered custom aggregate factory. Used by the compiler. */ |
| 119 | +export function getCustomAggregate( |
| 120 | + name: string, |
| 121 | +): AnyCustomAggregateFactory | undefined { |
| 122 | + return customAggregates.get(name.toLowerCase()) |
| 123 | +} |
| 124 | + |
| 125 | +/** |
| 126 | + * Registers a custom aggregate and returns a typed builder function for use in |
| 127 | + * `select()` callbacks. |
| 128 | + * |
| 129 | + * @param name - Aggregate name (case-insensitive) |
| 130 | + * @param factory - Builds the aggregate implementation from the row accessors |
| 131 | + * and the evaluated extra parameters |
| 132 | + * @returns a function taking the aggregated expression plus the extra parameters |
| 133 | + * |
| 134 | + * @example |
| 135 | + * ```ts |
| 136 | + * const groupConcat = createAggregate<string, [separator?: string]>( |
| 137 | + * `group_concat`, |
| 138 | + * (ctx, [separator = `,`]) => ({ |
| 139 | + * preMap: (entry) => [ctx.key(entry), String(ctx.value(entry) ?? ``)], |
| 140 | + * reduce: (values) => |
| 141 | + * values |
| 142 | + * .filter(([, multiplicity]) => multiplicity > 0) |
| 143 | + * .sort(([a], [b]) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)) |
| 144 | + * .map(([[, text]]) => text) |
| 145 | + * .join(separator), |
| 146 | + * }), |
| 147 | + * ) |
| 148 | + * |
| 149 | + * query.groupBy(({ todo }) => todo.listId).select(({ todo }) => ({ |
| 150 | + * listId: todo.listId, |
| 151 | + * names: groupConcat(todo.text, ` | `), |
| 152 | + * })) |
| 153 | + * ``` |
| 154 | + */ |
| 155 | +export function createAggregate<TResult, TParams extends Array<unknown> = []>( |
| 156 | + name: string, |
| 157 | + factory: ( |
| 158 | + ctx: AggregateContext, |
| 159 | + params: TParams, |
| 160 | + ) => CustomAggregateImpl<any, TResult>, |
| 161 | +): (arg: ExpressionLike, ...params: TParams) => Aggregate<TResult> { |
| 162 | + registerAggregate(name, (ctx, additionalArgs) => |
| 163 | + factory(ctx, additionalArgs as TParams), |
| 164 | + ) |
| 165 | + |
| 166 | + return (arg: ExpressionLike, ...params: TParams) => |
| 167 | + new Aggregate<TResult>(name, [ |
| 168 | + toExpression(arg), |
| 169 | + ...params.map((param) => toExpression(param)), |
| 170 | + ]) |
| 171 | +} |
0 commit comments