MCPcopy Index your code
hub / github.com/TanStack/db / getAggregateFunction

Function getAggregateFunction

packages/db/src/query/compiler/group-by.ts:517–569  ·  view source on GitHub ↗

* Helper function to get an aggregate function based on the Agg expression

(aggExpr: Aggregate)

Source from the content-addressed store, hash-verified

515 * Helper function to get an aggregate function based on the Agg expression
516 */
517function getAggregateFunction(aggExpr: Aggregate) {
518 // Pre-compile the value extractor expression
519 const compiledExpr = compileExpression(aggExpr.args[0]!)
520
521 // Create a value extractor function for the expression to aggregate
522 const valueExtractor = ([, namespacedRow]: [string, NamespacedRow]) => {
523 const value = compiledExpr(namespacedRow)
524 // Ensure we return a number for numeric aggregate functions
525 if (typeof value === `number`) {
526 return value
527 }
528 return value != null ? Number(value) : 0
529 }
530
531 // Create a value extractor function for min/max that preserves comparable types
532 const valueExtractorForMinMax = ([, namespacedRow]: [
533 string,
534 NamespacedRow,
535 ]) => {
536 const value = compiledExpr(namespacedRow)
537 // Preserve strings, numbers, Dates, and bigints for comparison
538 if (
539 typeof value === `number` ||
540 typeof value === `string` ||
541 typeof value === `bigint` ||
542 value instanceof Date
543 ) {
544 return value
545 }
546 return value != null ? Number(value) : 0
547 }
548
549 // Create a raw value extractor function for the expression to aggregate
550 const rawValueExtractor = ([, namespacedRow]: [string, NamespacedRow]) => {
551 return compiledExpr(namespacedRow)
552 }
553
554 // Return the appropriate aggregate function
555 switch (aggExpr.name.toLowerCase()) {
556 case `sum`:
557 return sum(valueExtractor)
558 case `count`:
559 return count(rawValueExtractor)
560 case `avg`:
561 return avg(valueExtractor)
562 case `min`:
563 return min(valueExtractorForMinMax)
564 case `max`:
565 return max(valueExtractorForMinMax)
566 default:
567 throw new UnsupportedAggregateFunctionError(aggExpr.name)
568 }
569}
570
571/**
572 * Transforms expressions to replace aggregate functions with references to computed values.

Callers 1

processGroupByFunction · 0.85

Calls 6

compileExpressionFunction · 0.70
sumFunction · 0.50
countFunction · 0.50
avgFunction · 0.50
minFunction · 0.50
maxFunction · 0.50

Tested by

no test coverage detected