Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fn-select-groupby-error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/db': patch
---

fix(db): throw error when fn.select() is used with groupBy()
11 changes: 11 additions & 0 deletions packages/db/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,17 @@ export class DistinctRequiresSelectError extends QueryCompilationError {
}
}

export class FnSelectWithGroupByError extends QueryCompilationError {
constructor() {
super(
`fn.select() cannot be used with groupBy(). ` +
`groupBy requires the compiler to statically analyze aggregate functions (count, sum, max, etc.) in the SELECT clause, ` +
`which is not possible with fn.select() since it is an opaque function. ` +
`Use .select() instead of .fn.select() when combining with groupBy().`,
)
}
}

export class HavingRequiresGroupByError extends QueryCompilationError {
constructor() {
super(`HAVING clause requires GROUP BY clause`)
Expand Down
5 changes: 5 additions & 0 deletions packages/db/src/query/compiler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
CollectionInputNotFoundError,
DistinctRequiresSelectError,
DuplicateAliasInSubqueryError,
FnSelectWithGroupByError,
HavingRequiresGroupByError,
LimitOffsetRequireOrderByError,
UnsupportedFromTypeError,
Expand Down Expand Up @@ -218,6 +219,10 @@ export function compileQuery(
throw new DistinctRequiresSelectError()
}

if (query.fnSelect && query.groupBy && query.groupBy.length > 0) {
throw new FnSelectWithGroupByError()
}

// Process the SELECT clause early - always create $selected
// This eliminates duplication and allows for DISTINCT implementation
if (query.fnSelect) {
Expand Down
25 changes: 25 additions & 0 deletions packages/db/tests/query/group-by.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2167,6 +2167,31 @@ function createGroupByTests(autoIndex: `off` | `eager`): void {
expect(result?.totalAmount).toBe(700)
})
})

describe(`fn.select with groupBy throws error`, () => {
let ordersCollection: ReturnType<typeof createOrdersCollection>

beforeEach(() => {
ordersCollection = createOrdersCollection(autoIndex)
})

test(`fn.select with groupBy should throw FnSelectWithGroupByError`, () => {
expect(() =>
createLiveQueryCollection({
startSync: true,
query: (q) =>
q
.from({ orders: ordersCollection })
.groupBy(({ orders }) => orders.customer_id)
.fn.select((row) => ({
customerId: row.orders.customer_id,
totalAmount: sum(row.orders.amount),
orderCount: count(row.orders.id),
})),
}),
).toThrow(`fn.select() cannot be used with groupBy()`)
})
})
})
}

Expand Down
Loading