Skip to content
Merged
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/floppy-berries-enjoy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tanstack/db": patch
---

live query where clauses can now be a callback function that receives each row as a context object allowing full javascript access to the row data for filtering
27 changes: 27 additions & 0 deletions packages/db/src/query/evaluators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,36 @@ import type {
ConditionOperand,
LogicalOperator,
SimpleCondition,
Where,
WhereCallback,
} from "./schema.js"
import type { NamespacedRow } from "../types.js"

/**
* Evaluates a Where clause (which is always an array of conditions and/or callbacks) against a nested row structure
*/
export function evaluateWhereOnNamespacedRow(
namespacedRow: NamespacedRow,
where: Where,
mainTableAlias?: string,
joinedTableAlias?: string
): boolean {
// Where is always an array of conditions and/or callbacks
// Evaluate all items and combine with AND logic
return where.every((item) => {
if (typeof item === `function`) {
return (item as WhereCallback)(namespacedRow)
} else {
return evaluateConditionOnNamespacedRow(
namespacedRow,
item as Condition,
mainTableAlias,
joinedTableAlias
)
}
})
}

/**
* Evaluates a condition against a nested row structure
*/
Expand Down
6 changes: 3 additions & 3 deletions packages/db/src/query/pipeline-compiler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { filter, map } from "@electric-sql/d2ts"
import { evaluateConditionOnNamespacedRow } from "./evaluators.js"
import { evaluateWhereOnNamespacedRow } from "./evaluators.js"
import { processJoinClause } from "./joins.js"
import { processGroupBy } from "./group-by.js"
import { processOrderBy } from "./order-by.js"
Expand Down Expand Up @@ -95,7 +95,7 @@ export function compileQueryPipeline<T extends IStreamBuilder<unknown>>(
if (query.where) {
pipeline = pipeline.pipe(
filter(([_key, row]) => {
const result = evaluateConditionOnNamespacedRow(
const result = evaluateWhereOnNamespacedRow(
row,
query.where!,
mainTableAlias
Expand All @@ -117,7 +117,7 @@ export function compileQueryPipeline<T extends IStreamBuilder<unknown>>(
filter(([_key, row]) => {
// For HAVING, we're working with the flattened row that contains both
// the group by keys and the aggregate results directly
const result = evaluateConditionOnNamespacedRow(
const result = evaluateWhereOnNamespacedRow(
row,
query.having!,
mainTableAlias
Expand Down
60 changes: 38 additions & 22 deletions packages/db/src/query/query-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
OrderBy,
Query,
Select,
WhereCallback,
WithQuery,
} from "./schema.js"
import type {
Expand Down Expand Up @@ -296,17 +297,23 @@ export class BaseQueryBuilder<TContext extends Context<Schema>> {
*/
where(condition: Condition<TContext>): QueryBuilder<TContext>

/**
* Add a where clause with a callback function.
*/
where(callback: WhereCallback<TContext>): QueryBuilder<TContext>

/**
* Add a where clause to filter the results.
* Can be called multiple times to add AND conditions.
* Also supports callback functions that receive the row context.
*
* @param leftOrCondition The left operand or complete condition
* @param leftOrConditionOrCallback The left operand, complete condition, or callback function
* @param operator Optional comparison operator
* @param right Optional right operand
* @returns A new QueryBuilder with the where clause added
*/
where(
leftOrCondition: any,
leftOrConditionOrCallback: any,
operator?: any,
right?: any
): QueryBuilder<TContext> {
Expand All @@ -317,22 +324,23 @@ export class BaseQueryBuilder<TContext extends Context<Schema>> {

let condition: any

// Determine if this is a complete condition or individual parts
if (operator !== undefined && right !== undefined) {
// Determine if this is a callback, complete condition, or individual parts
if (typeof leftOrConditionOrCallback === `function`) {
// It's a callback function
condition = leftOrConditionOrCallback
} else if (operator !== undefined && right !== undefined) {
// Create a condition from parts
condition = [leftOrCondition, operator, right]
condition = [leftOrConditionOrCallback, operator, right]
} else {
// Use the provided condition directly
condition = leftOrCondition
condition = leftOrConditionOrCallback
}

// Where is always an array, so initialize or append
if (!newBuilder.query.where) {
newBuilder.query.where = condition
newBuilder.query.where = [condition]
} else {
// Create a composite condition with AND
// Use any to bypass type checking issues
const andArray: any = [newBuilder.query.where, `and`, condition]
newBuilder.query.where = andArray
newBuilder.query.where = [...newBuilder.query.where, condition]
}

return newBuilder as unknown as QueryBuilder<TContext>
Expand All @@ -354,17 +362,24 @@ export class BaseQueryBuilder<TContext extends Context<Schema>> {
*/
having(condition: Condition<TContext>): QueryBuilder<TContext>

/**
* Add a having clause with a callback function.
* For filtering results after they have been grouped.
*/
having(callback: WhereCallback<TContext>): QueryBuilder<TContext>

/**
* Add a having clause to filter the grouped results.
* Can be called multiple times to add AND conditions.
* Also supports callback functions that receive the row context.
*
* @param leftOrCondition The left operand or complete condition
* @param leftOrConditionOrCallback The left operand, complete condition, or callback function
* @param operator Optional comparison operator
* @param right Optional right operand
* @returns A new QueryBuilder with the having clause added
*/
having(
leftOrCondition: any,
leftOrConditionOrCallback: any,
operator?: any,
right?: any
): QueryBuilder<TContext> {
Expand All @@ -374,22 +389,23 @@ export class BaseQueryBuilder<TContext extends Context<Schema>> {

let condition: any

// Determine if this is a complete condition or individual parts
if (operator !== undefined && right !== undefined) {
// Determine if this is a callback, complete condition, or individual parts
if (typeof leftOrConditionOrCallback === `function`) {
// It's a callback function
condition = leftOrConditionOrCallback
} else if (operator !== undefined && right !== undefined) {
// Create a condition from parts
condition = [leftOrCondition, operator, right]
condition = [leftOrConditionOrCallback, operator, right]
} else {
// Use the provided condition directly
condition = leftOrCondition
condition = leftOrConditionOrCallback
}

// Having is always an array, so initialize or append
if (!newBuilder.query.having) {
newBuilder.query.having = condition
newBuilder.query.having = [condition]
} else {
// Create a composite condition with AND
// Use any to bypass type checking issues
const andArray: any = [newBuilder.query.having, `and`, condition]
newBuilder.query.having = andArray
newBuilder.query.having = [...newBuilder.query.having, condition]
}

return newBuilder as QueryBuilder<TContext>
Expand Down
17 changes: 12 additions & 5 deletions packages/db/src/query/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,14 +199,21 @@ export type From<TContext extends Context = Context> = InputReference<{
schema: TContext[`baseSchema`]
}>

export type Where<TContext extends Context = Context> = Condition<TContext>
export type WhereCallback<TContext extends Context = Context> = (
context: TContext extends { schema: infer S } ? S : any
) => boolean

export type Where<TContext extends Context = Context> = Array<
Condition<TContext> | WhereCallback<TContext>
>

// Having is the same implementation as a where clause, its just run after the group by
export type Having<TContext extends Context = Context> = Where<TContext>

export type GroupBy<TContext extends Context = Context> =
| PropertyReference<TContext>
| Array<PropertyReference<TContext>>

export type Having<TContext extends Context = Context> = Condition<TContext>

export type Limit<TContext extends Context = Context> = number

export type Offset<TContext extends Context = Context> = number
Expand All @@ -220,9 +227,9 @@ export interface BaseQuery<TContext extends Context = Context> {
as?: As<TContext>
from: From<TContext>
join?: Array<JoinClause<TContext>>
where?: Condition<TContext>
where?: Where<TContext>
groupBy?: GroupBy<TContext>
having?: Condition<TContext>
having?: Having<TContext>
orderBy?: OrderBy<TContext>
limit?: Limit<TContext>
offset?: Offset<TContext>
Expand Down
4 changes: 2 additions & 2 deletions packages/db/tests/query/compiler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ describe(`Query`, () => {
const query: Query<Context> = {
select: [`@id`, `@name`, `@age`],
from: `users`,
where: [`@age`, `>`, 20],
where: [[`@age`, `>`, 20]],
}

const graph = new D2({ initialFrontier: v([0, 0]) })
Expand Down Expand Up @@ -198,7 +198,7 @@ describe(`Query`, () => {
const query: Query<Context> = {
select: [`@id`, `@name`],
from: `users`,
where: [`@age`, `>`, 20, `and`, `@active`, `=`, true],
where: [[`@age`, `>`, 20, `and`, `@active`, `=`, true]],
}

const graph = new D2({ initialFrontier: v([0, 0]) })
Expand Down
Loading