From 777db43ebfb2f89dd2bdd55c1452475508a64474 Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Mon, 9 Jun 2025 14:00:12 +0100 Subject: [PATCH 1/5] wip --- packages/db/src/query/evaluators.ts | 27 ++++++++++ packages/db/src/query/pipeline-compiler.ts | 6 +-- packages/db/src/query/query-builder.ts | 60 ++++++++++++++-------- packages/db/src/query/schema.ts | 15 ++++-- 4 files changed, 78 insertions(+), 30 deletions(-) diff --git a/packages/db/src/query/evaluators.ts b/packages/db/src/query/evaluators.ts index 6a0ba8bcc6..73268be375 100644 --- a/packages/db/src/query/evaluators.ts +++ b/packages/db/src/query/evaluators.ts @@ -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 */ diff --git a/packages/db/src/query/pipeline-compiler.ts b/packages/db/src/query/pipeline-compiler.ts index 1d5ea48b03..105d9ca172 100644 --- a/packages/db/src/query/pipeline-compiler.ts +++ b/packages/db/src/query/pipeline-compiler.ts @@ -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" @@ -95,7 +95,7 @@ export function compileQueryPipeline>( if (query.where) { pipeline = pipeline.pipe( filter(([_key, row]) => { - const result = evaluateConditionOnNamespacedRow( + const result = evaluateWhereOnNamespacedRow( row, query.where!, mainTableAlias @@ -117,7 +117,7 @@ export function compileQueryPipeline>( 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 diff --git a/packages/db/src/query/query-builder.ts b/packages/db/src/query/query-builder.ts index 9cc2c277a3..20e993a3c6 100644 --- a/packages/db/src/query/query-builder.ts +++ b/packages/db/src/query/query-builder.ts @@ -10,6 +10,7 @@ import type { OrderBy, Query, Select, + WhereCallback, WithQuery, } from "./schema.js" import type { @@ -296,17 +297,23 @@ export class BaseQueryBuilder> { */ where(condition: Condition): QueryBuilder + /** + * Add a where clause with a callback function. + */ + where(callback: WhereCallback): QueryBuilder + /** * 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 { @@ -317,22 +324,23 @@ export class BaseQueryBuilder> { 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 @@ -354,17 +362,24 @@ export class BaseQueryBuilder> { */ having(condition: Condition): QueryBuilder + /** + * Add a having clause with a callback function. + * For filtering results after they have been grouped. + */ + having(callback: WhereCallback): QueryBuilder + /** * 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 { @@ -374,22 +389,23 @@ export class BaseQueryBuilder> { 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 diff --git a/packages/db/src/query/schema.ts b/packages/db/src/query/schema.ts index 96c90d2d5f..4f7f046cf1 100644 --- a/packages/db/src/query/schema.ts +++ b/packages/db/src/query/schema.ts @@ -199,14 +199,19 @@ export type From = InputReference<{ schema: TContext[`baseSchema`] }> -export type Where = Condition +export type WhereCallback = ( + context: TContext["schema"] +) => boolean + +export type Where = Array | WhereCallback> + +// Having is the same implementation as a where clause, its just run after the group by +export type Having = Where export type GroupBy = | PropertyReference | Array> -export type Having = Condition - export type Limit = number export type Offset = number @@ -220,9 +225,9 @@ export interface BaseQuery { as?: As from: From join?: Array> - where?: Condition + where?: Where groupBy?: GroupBy - having?: Condition + having?: Having orderBy?: OrderBy limit?: Limit offset?: Offset From 217b09d0e2f7a574b62a6a9e059b9b06082260dd Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Mon, 9 Jun 2025 14:43:41 +0100 Subject: [PATCH 2/5] working old tests --- packages/db/src/query/evaluators.ts | 4 +- packages/db/src/query/query-builder.ts | 4 +- packages/db/src/query/schema.ts | 6 +- packages/db/tests/query/compiler.test.ts | 4 +- packages/db/tests/query/conditions.test.ts | 38 ++--- .../tests/query/function-integration.test.ts | 26 ++-- packages/db/tests/query/group-by.test.ts | 4 +- packages/db/tests/query/having.test.ts | 30 ++-- packages/db/tests/query/in-operator.test.ts | 42 ++--- packages/db/tests/query/like-operator.test.ts | 18 +-- .../db/tests/query/nested-conditions.test.ts | 146 ++++++++++-------- .../query/query-builder/group-by.test.ts | 2 +- .../tests/query/query-builder/having.test.ts | 16 +- .../db/tests/query/query-builder/join.test.ts | 18 +-- .../tests/query/query-builder/where.test.ts | 24 ++- packages/db/tests/query/query-types.test.ts | 24 +-- packages/db/tests/query/table-alias.test.ts | 24 +-- packages/db/tests/query/with.test.ts | 12 +- 18 files changed, 228 insertions(+), 214 deletions(-) diff --git a/packages/db/src/query/evaluators.ts b/packages/db/src/query/evaluators.ts index 73268be375..73d514920b 100644 --- a/packages/db/src/query/evaluators.ts +++ b/packages/db/src/query/evaluators.ts @@ -22,8 +22,8 @@ export function evaluateWhereOnNamespacedRow( ): 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 where.every((item) => { + if (typeof item === `function`) { return (item as WhereCallback)(namespacedRow) } else { return evaluateConditionOnNamespacedRow( diff --git a/packages/db/src/query/query-builder.ts b/packages/db/src/query/query-builder.ts index 20e993a3c6..ad7e5db4d3 100644 --- a/packages/db/src/query/query-builder.ts +++ b/packages/db/src/query/query-builder.ts @@ -325,7 +325,7 @@ export class BaseQueryBuilder> { let condition: any // Determine if this is a callback, complete condition, or individual parts - if (typeof leftOrConditionOrCallback === 'function') { + if (typeof leftOrConditionOrCallback === `function`) { // It's a callback function condition = leftOrConditionOrCallback } else if (operator !== undefined && right !== undefined) { @@ -390,7 +390,7 @@ export class BaseQueryBuilder> { let condition: any // Determine if this is a callback, complete condition, or individual parts - if (typeof leftOrConditionOrCallback === 'function') { + if (typeof leftOrConditionOrCallback === `function`) { // It's a callback function condition = leftOrConditionOrCallback } else if (operator !== undefined && right !== undefined) { diff --git a/packages/db/src/query/schema.ts b/packages/db/src/query/schema.ts index 4f7f046cf1..902408313e 100644 --- a/packages/db/src/query/schema.ts +++ b/packages/db/src/query/schema.ts @@ -200,10 +200,12 @@ export type From = InputReference<{ }> export type WhereCallback = ( - context: TContext["schema"] + context: TContext[`schema`] ) => boolean -export type Where = Array | WhereCallback> +export type Where = Array< + Condition | WhereCallback +> // Having is the same implementation as a where clause, its just run after the group by export type Having = Where diff --git a/packages/db/tests/query/compiler.test.ts b/packages/db/tests/query/compiler.test.ts index 0d98d21cf2..cdcdef4d5c 100644 --- a/packages/db/tests/query/compiler.test.ts +++ b/packages/db/tests/query/compiler.test.ts @@ -151,7 +151,7 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@name`, `@age`], from: `users`, - where: [`@age`, `>`, 20], + where: [[`@age`, `>`, 20]], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -198,7 +198,7 @@ describe(`Query`, () => { const query: Query = { 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]) }) diff --git a/packages/db/tests/query/conditions.test.ts b/packages/db/tests/query/conditions.test.ts index e3cd42340c..ef041521f4 100644 --- a/packages/db/tests/query/conditions.test.ts +++ b/packages/db/tests/query/conditions.test.ts @@ -86,7 +86,7 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@name`], from: `products`, - where: [`@category`, `=`, `Electronics`], + where: [[`@category`, `=`, `Electronics`]], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -131,7 +131,7 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@name`, `@category`], from: `products`, - where: [`@category`, `!=`, `Electronics`], + where: [[`@category`, `!=`, `Electronics`]], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -176,7 +176,7 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@name`, `@price`], from: `products`, - where: [`@price`, `>`, 500], + where: [[`@price`, `>`, 500]], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -221,7 +221,7 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@name`, `@discount`], from: `products`, - where: [`@discount`, `is not`, null], + where: [[`@discount`, `is not`, null]], } // In our test data, only the Smartphone has a non-null discount @@ -270,7 +270,7 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@name`, `@price`, `@category`], from: `products`, - where: [`@price`, `<`, 500], + where: [[`@price`, `<`, 500]], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -315,7 +315,7 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@name`, `@price`, `@category`], from: `products`, - where: [`@category`, `=`, `Electronics`, `and`, `@price`, `<`, 500], + where: [[`@category`, `=`, `Electronics`, `and`, `@price`, `<`, 500]], } // Verify our test data - only Headphones should match both conditions @@ -366,7 +366,7 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@name`, `@price`, `@category`], from: `products`, - where: [`@category`, `=`, `Electronics`, `or`, `@price`, `<`, 100], + where: [[`@category`, `=`, `Electronics`, `or`, `@price`, `<`, 100]], } // Verify our test data - should match Electronics OR price < 100 @@ -424,17 +424,19 @@ describe(`Query`, () => { from: `products`, where: [ [ - `@category`, - `=`, - `Electronics`, - `and`, - `@price`, - `>`, - 200, - ] as FlatCompositeCondition, - `or` as LogicalOperator, - [`@category`, `=`, `Books`], // Simple condition for the right side - ] as NestedCompositeCondition, + [ + `@category`, + `=`, + `Electronics`, + `and`, + `@price`, + `>`, + 200, + ] as FlatCompositeCondition, + `or` as LogicalOperator, + [`@category`, `=`, `Books`], // Simple condition for the right side + ] as NestedCompositeCondition, + ], } // Verify our test data manually to confirm what should match diff --git a/packages/db/tests/query/function-integration.test.ts b/packages/db/tests/query/function-integration.test.ts index 2c56095fab..85c47755f4 100644 --- a/packages/db/tests/query/function-integration.test.ts +++ b/packages/db/tests/query/function-integration.test.ts @@ -220,7 +220,7 @@ describe(`Query Function Integration`, () => { }, ], from: `users`, - where: [`@active`, `=`, false], + where: [[`@active`, `=`, false]], } const results = runQuery(query) @@ -295,7 +295,7 @@ describe(`Query Function Integration`, () => { }, ], from: `users`, - where: [`@active`, `=`, true], + where: [[`@active`, `=`, true]], } const results = runQuery(query) @@ -321,7 +321,7 @@ describe(`Query Function Integration`, () => { const query: Query = { select: [`@id`, `@name`], from: `users`, - where: [{ UPPER: `@name` }, `=`, `BOB`], + where: [[{ UPPER: `@name` }, `=`, `BOB`]], } const results = runQuery(query) @@ -335,7 +335,7 @@ describe(`Query Function Integration`, () => { const query: Query = { select: [`@id`, `@name`], from: `users`, - where: [{ LENGTH: `@name` }, `>`, 5], + where: [[{ LENGTH: `@name` }, `>`, 5]], } const results = runQuery(query) @@ -349,7 +349,7 @@ describe(`Query Function Integration`, () => { const query: Query = { select: [`@id`, `@name`], from: `users`, - where: [{ JSON_EXTRACT: [`@preferences`, `theme`] }, `=`, `dark`], + where: [[{ JSON_EXTRACT: [`@preferences`, `theme`] }, `=`, `dark`]], } const results = runQuery(query) @@ -363,13 +363,15 @@ describe(`Query Function Integration`, () => { select: [`@id`, `@name`, `@email`], from: `users`, where: [ - { LENGTH: `@name` }, - `<`, - 6, - `and`, - { JSON_EXTRACT_PATH: [`@preferences`, `notifications`] }, - `=`, - true, + [ + { LENGTH: `@name` }, + `<`, + 6, + `and`, + { JSON_EXTRACT_PATH: [`@preferences`, `notifications`] }, + `=`, + true, + ], ], } diff --git a/packages/db/tests/query/group-by.test.ts b/packages/db/tests/query/group-by.test.ts index 62d32d85d1..3954b84c9a 100644 --- a/packages/db/tests/query/group-by.test.ts +++ b/packages/db/tests/query/group-by.test.ts @@ -277,7 +277,7 @@ describe(`D2QL GROUP BY`, () => { ], from: `orders`, groupBy: [`@customer_id`, `@status`], - having: [{ col: `total_amount` }, `>`, 200], + having: [[{ col: `total_amount` }, `>`, 200]], } const messagesRet = runQuery(query) @@ -415,7 +415,7 @@ describe(`D2QL GROUP BY`, () => { { order_count: { COUNT: `@order_id` } as any }, ], from: `orders`, - where: [`@status`, `=`, `completed`], + where: [[`@status`, `=`, `completed`]], groupBy: [`@customer_id`], } diff --git a/packages/db/tests/query/having.test.ts b/packages/db/tests/query/having.test.ts index a75bcce5f6..ae95024274 100644 --- a/packages/db/tests/query/having.test.ts +++ b/packages/db/tests/query/having.test.ts @@ -104,7 +104,7 @@ describe(`Query - HAVING Clause`, () => { const query: Query = { select: [`@id`, `@name`, `@price`, `@category`], from: `products`, - having: [`@price`, `>`, 300] as Condition, + having: [[`@price`, `>`, 300] as Condition], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -147,8 +147,8 @@ describe(`Query - HAVING Clause`, () => { const query: Query = { select: [`@id`, `@name`, `@price`, `@category`, `@inStock`], from: `products`, - where: [`@inStock`, `=`, true] as Condition, - having: [`@price`, `>`, 200] as Condition, + where: [[`@inStock`, `=`, true] as Condition], + having: [[`@price`, `>`, 200] as Condition], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -192,12 +192,14 @@ describe(`Query - HAVING Clause`, () => { select: [`@id`, `@name`, `@price`, `@category`, `@rating`], from: `products`, having: [ - [`@price`, `>`, 100], - `and`, - [`@price`, `<`, 600], - `and`, - [`@rating`, `>=`, 4.0], - ] as unknown as Condition, + [ + [`@price`, `>`, 100], + `and`, + [`@price`, `<`, 600], + `and`, + [`@rating`, `>=`, 4.0], + ] as unknown as Condition, + ], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -248,10 +250,12 @@ describe(`Query - HAVING Clause`, () => { select: [`@id`, `@name`, `@price`, `@category`, `@inStock`], from: `products`, having: [ - [[`@category`, `=`, `Electronics`], `and`, [`@price`, `<`, 600]], - `or`, - [[`@category`, `=`, `Furniture`], `and`, [`@inStock`, `=`, true]], - ] as unknown as Condition, + [ + [[`@category`, `=`, `Electronics`], `and`, [`@price`, `<`, 600]], + `or`, + [[`@category`, `=`, `Furniture`], `and`, [`@inStock`, `=`, true]], + ] as unknown as Condition, + ], } const graph = new D2({ initialFrontier: v([0, 0]) }) diff --git a/packages/db/tests/query/in-operator.test.ts b/packages/db/tests/query/in-operator.test.ts index 9dbed5b9b5..36b0203487 100644 --- a/packages/db/tests/query/in-operator.test.ts +++ b/packages/db/tests/query/in-operator.test.ts @@ -82,7 +82,7 @@ describe(`Query - IN Operator`, () => { const query: Query = { select: [`@id`, `@name`, `@category`], from: `items`, - where: [`@category`, `in`, [`Electronics`, `Books`]] as Condition, + where: [[`@category`, `in`, [`Electronics`, `Books`]] as Condition], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -119,7 +119,7 @@ describe(`Query - IN Operator`, () => { const query: Query = { select: [`@id`, `@name`], from: `items`, - where: [`@category`, `in`, [`electronics`, `books`]] as Condition, // lowercase categories + where: [[`@category`, `in`, [`electronics`, `books`]] as Condition], // lowercase categories } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -156,7 +156,7 @@ describe(`Query - IN Operator`, () => { const query: Query = { select: [`@id`, `@name`, `@category`], from: `items`, - where: [`@category`, `not in`, [`Electronics`, `Books`]] as Condition, + where: [[`@category`, `not in`, [`Electronics`, `Books`]] as Condition], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -194,7 +194,7 @@ describe(`Query - IN Operator`, () => { const query: Query = { select: [`@id`, `@name`], from: `items`, - where: [`@id`, `in`, [`1`, `2`, `3`]] as Condition, // String IDs instead of numbers + where: [[`@id`, `in`, [`1`, `2`, `3`]] as Condition], // String IDs instead of numbers } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -238,8 +238,10 @@ describe(`Query - IN Operator`, () => { select: [`@id`, `@name`, `@tags`], from: `items`, where: [ - [`@tags`, `in`, [[`electronics`], [`audio`]]] as unknown as Condition, - ] as unknown as Condition, + [ + [`@tags`, `in`, [[`electronics`], [`audio`]]] as unknown as Condition, + ] as unknown as Condition, + ], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -274,7 +276,7 @@ describe(`Query - IN Operator`, () => { const query: Query = { select: [`@id`, `@name`, `@isActive`], from: `items`, - where: [`@isActive`, `in`, [null, false]] as Condition, + where: [[`@isActive`, `in`, [null, false]] as Condition], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -318,13 +320,15 @@ describe(`Query - IN Operator`, () => { select: [`@id`, `@name`, `@metadata`], from: `items`, where: [ - `@metadata`, - `in`, [ - { value: { brand: `TechBrand`, model: `X15` } }, - { value: { brand: `OtherBrand`, model: `Y20` } }, - ], - ] as Condition, + `@metadata`, + `in`, + [ + { value: { brand: `TechBrand`, model: `X15` } }, + { value: { brand: `OtherBrand`, model: `Y20` } }, + ], + ] as Condition, + ], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -359,7 +363,7 @@ describe(`Query - IN Operator`, () => { const query: Query = { select: [`@id`, `@name`], from: `items`, - where: [`@category`, `in`, []] as Condition, // Empty array + where: [[`@category`, `in`, []] as Condition], // Empty array } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -396,10 +400,12 @@ describe(`Query - IN Operator`, () => { select: [`@id`, `@name`, `@category`, `@price`], from: `items`, where: [ - [`@category`, `in`, [`Electronics`, `Books`]], - `and`, - [`@price`, `>`, 100], - ] as unknown as Condition, + [ + [`@category`, `in`, [`Electronics`, `Books`]], + `and`, + [`@price`, `>`, 100], + ] as unknown as Condition, + ], } const graph = new D2({ initialFrontier: v([0, 0]) }) diff --git a/packages/db/tests/query/like-operator.test.ts b/packages/db/tests/query/like-operator.test.ts index abde3b1498..978a7b50e9 100644 --- a/packages/db/tests/query/like-operator.test.ts +++ b/packages/db/tests/query/like-operator.test.ts @@ -101,7 +101,7 @@ describe(`Query - LIKE Operator`, () => { const query: Query = { select: [`@id`, `@name`], from: `items`, - where: [`@name`, `like`, `Laptop%`] as Condition, + where: [[`@name`, `like`, `Laptop%`] as Condition], } const results = runQuery(query) @@ -115,7 +115,7 @@ describe(`Query - LIKE Operator`, () => { const query: Query = { select: [`@id`, `@name`, `@description`], from: `items`, - where: [`@description`, `like`, `%laptop%`] as Condition, + where: [[`@description`, `like`, `%laptop%`] as Condition], } const results = runQuery(query) @@ -146,7 +146,7 @@ describe(`Query - LIKE Operator`, () => { const query: Query = { select: [`@id`, `@SKU`], from: `items`, - where: [`@SKU`, `like`, `TECH-___-2023`] as Condition, + where: [[`@SKU`, `like`, `TECH-___-2023`] as Condition], } // Create a separate graph for this test with our specific SKU test items @@ -185,7 +185,7 @@ describe(`Query - LIKE Operator`, () => { const query: Query = { select: [`@id`, `@SKU`], from: `items`, - where: [`@SKU`, `like`, `TECH-__%-____`] as Condition, + where: [[`@SKU`, `like`, `TECH-__%-____`] as Condition], } const results = runQuery(query) @@ -198,7 +198,7 @@ describe(`Query - LIKE Operator`, () => { const query: Query = { select: [`@id`, `@name`], from: `items`, - where: [`@name`, `like`, `Office Desk 60\\%`] as Condition, + where: [[`@name`, `like`, `Office Desk 60\\%`] as Condition], } const results = runQuery(query) @@ -211,7 +211,7 @@ describe(`Query - LIKE Operator`, () => { const query: Query = { select: [`@id`, `@name`, `@category`], from: `items`, - where: [`@category`, `not like`, `Elec%`] as Condition, + where: [[`@category`, `not like`, `Elec%`] as Condition], } const results = runQuery(query) @@ -224,7 +224,7 @@ describe(`Query - LIKE Operator`, () => { const query: Query = { select: [`@id`, `@name`, `@description`], from: `items`, - where: [`@description`, `like`, `%[0-9]%`] as Condition, // Using regex special char + where: [[`@description`, `like`, `%[0-9]%`] as Condition], // Using regex special char } const results = runQuery(query) @@ -238,7 +238,7 @@ describe(`Query - LIKE Operator`, () => { const query: Query = { select: [`@id`, `@name`, `@description`], from: `items`, - where: [`@description`, `like`, `%2-%`] as Condition, // Looking for "2-" in description + where: [[`@description`, `like`, `%2-%`] as Condition], // Looking for "2-" in description } const results = runQuery(query) @@ -252,7 +252,7 @@ describe(`Query - LIKE Operator`, () => { const query: Query = { select: [`@id`, `@name`], from: `items`, - where: [`@name`, `like`, `laptop%`] as Condition, // lowercase, but data has uppercase + where: [[`@name`, `like`, `laptop%`] as Condition], // lowercase, but data has uppercase } const results = runQuery(query) diff --git a/packages/db/tests/query/nested-conditions.test.ts b/packages/db/tests/query/nested-conditions.test.ts index 3ce022bded..043e47661d 100644 --- a/packages/db/tests/query/nested-conditions.test.ts +++ b/packages/db/tests/query/nested-conditions.test.ts @@ -112,10 +112,12 @@ describe(`Query`, () => { select: [`@id`, `@name`, `@category`], from: `products`, where: [ - [`@category`, `=`, `Books`], - `or`, - [`@category`, `=`, `Furniture`], - ] as NestedCompositeCondition, + [ + [`@category`, `=`, `Books`], + `or`, + [`@category`, `=`, `Furniture`], + ] as NestedCompositeCondition, + ], } // Run the query and check results @@ -140,10 +142,12 @@ describe(`Query`, () => { select: [`@id`, `@name`, `@category`, `@inStock`], from: `products`, where: [ - [`@category`, `=`, `Electronics`], - `and`, - [`@inStock`, `=`, true], - ] as NestedCompositeCondition, + [ + [`@category`, `=`, `Electronics`], + `and`, + [`@inStock`, `=`, true], + ] as NestedCompositeCondition, + ], } // Run the query and check results @@ -165,18 +169,20 @@ describe(`Query`, () => { select: [`@id`, `@name`, `@rating`, `@price`], from: `products`, where: [ - `@category`, - `=`, - `Electronics`, - `and`, - `@rating`, - `>`, - 4, - `and`, - `@price`, - `<`, - 1000, - ] as FlatCompositeCondition, + [ + `@category`, + `=`, + `Electronics`, + `and`, + `@rating`, + `>`, + 4, + `and`, + `@price`, + `<`, + 1000, + ] as FlatCompositeCondition, + ], } // Run the query and check results @@ -199,25 +205,27 @@ describe(`Query`, () => { from: `products`, where: [ [ - `@category`, - `=`, - `Electronics`, - `and`, - `@price`, - `>`, - 500, - ] as FlatCompositeCondition, - `or`, - [ - `@category`, - `=`, - `Furniture`, - `and`, - `@inStock`, - `=`, - true, - ] as FlatCompositeCondition, - ] as NestedCompositeCondition, + [ + `@category`, + `=`, + `Electronics`, + `and`, + `@price`, + `>`, + 500, + ] as FlatCompositeCondition, + `or`, + [ + `@category`, + `=`, + `Furniture`, + `and`, + `@inStock`, + `=`, + true, + ] as FlatCompositeCondition, + ] as NestedCompositeCondition, + ], } // Run the query and check results @@ -246,35 +254,37 @@ describe(`Query`, () => { from: `products`, where: [ [ - `@category`, - `=`, - `Electronics`, - `and`, - `@price`, - `>`, - 1000, - ] as FlatCompositeCondition, - `or`, - [ - `@category`, - `=`, - `Books`, - `and`, - `@rating`, - `>`, - 4.5, - ] as FlatCompositeCondition, - `or`, - [ - `@category`, - `=`, - `Furniture`, - `and`, - `@price`, - `<`, - 200, - ] as FlatCompositeCondition, - ] as NestedCompositeCondition, + [ + `@category`, + `=`, + `Electronics`, + `and`, + `@price`, + `>`, + 1000, + ] as FlatCompositeCondition, + `or`, + [ + `@category`, + `=`, + `Books`, + `and`, + `@rating`, + `>`, + 4.5, + ] as FlatCompositeCondition, + `or`, + [ + `@category`, + `=`, + `Furniture`, + `and`, + `@price`, + `<`, + 200, + ] as FlatCompositeCondition, + ] as NestedCompositeCondition, + ], } // Run the query and check results diff --git a/packages/db/tests/query/query-builder/group-by.test.ts b/packages/db/tests/query/query-builder/group-by.test.ts index e4bf7762d3..2cbd52b1e1 100644 --- a/packages/db/tests/query/query-builder/group-by.test.ts +++ b/packages/db/tests/query/query-builder/group-by.test.ts @@ -86,7 +86,7 @@ describe(`QueryBuilder.groupBy`, () => { const builtQuery = query._query expect(builtQuery.groupBy).toBe(`@d.name`) - expect(builtQuery.having).toEqual([{ SUM: `@e.salary` }, `>`, 100000]) + expect(builtQuery.having).toEqual([[{ SUM: `@e.salary` }, `>`, 100000]]) }) it(`can be combined with other query methods`, () => { diff --git a/packages/db/tests/query/query-builder/having.test.ts b/packages/db/tests/query/query-builder/having.test.ts index 210c01dc3b..b2188427da 100644 --- a/packages/db/tests/query/query-builder/having.test.ts +++ b/packages/db/tests/query/query-builder/having.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest" import { queryBuilder } from "../../../src/query/query-builder.js" +import type { SimpleCondition } from "../../../src/query/schema.js" import type { Input, Schema } from "../../../src/query/types.js" // Test schema @@ -31,7 +32,7 @@ describe(`QueryBuilder.having`, () => { .having(`@salary`, `>`, 50000) const builtQuery = query._query - expect(builtQuery.having).toEqual([`@salary`, `>`, 50000]) + expect(builtQuery.having).toEqual([[`@salary`, `>`, 50000]]) }) it(`supports various comparison operators`, () => { @@ -55,7 +56,7 @@ describe(`QueryBuilder.having`, () => { const builtQuery = query._query expect(builtQuery.having).toBeDefined() - const having = builtQuery.having! + const having = builtQuery.having![0]! as SimpleCondition expect(having[1]).toBe(op) } }) @@ -72,7 +73,7 @@ describe(`QueryBuilder.having`, () => { .having(`@e.salary`, `>`, `@d.budget`) const builtQuery = query._query - expect(builtQuery.having).toEqual([`@e.salary`, `>`, `@d.budget`]) + expect(builtQuery.having).toEqual([[`@e.salary`, `>`, `@d.budget`]]) }) it(`allows comparing literals to property references`, () => { @@ -81,10 +82,10 @@ describe(`QueryBuilder.having`, () => { .having(50000, `<`, `@salary`) const builtQuery = query._query - expect(builtQuery.having).toEqual([50000, `<`, `@salary`]) + expect(builtQuery.having).toEqual([[50000, `<`, `@salary`]]) }) - it(`combines multiple having calls with AND`, () => { + it(`combines multiple having calls`, () => { const query = queryBuilder() .from(`employees`) .having(`@salary`, `>`, 50000) @@ -93,7 +94,6 @@ describe(`QueryBuilder.having`, () => { const builtQuery = query._query expect(builtQuery.having).toEqual([ [`@salary`, `>`, 50000], - `and`, [`@active`, `=`, true], ]) }) @@ -104,7 +104,7 @@ describe(`QueryBuilder.having`, () => { const query = queryBuilder().from(`employees`).having(condition) const builtQuery = query._query - expect(builtQuery.having).toEqual(condition) + expect(builtQuery.having).toEqual([condition]) }) it(`works in a practical example with groupBy`, () => { @@ -122,7 +122,7 @@ describe(`QueryBuilder.having`, () => { const builtQuery = query._query expect(builtQuery.groupBy).toBe(`@d.name`) - expect(builtQuery.having).toEqual([{ SUM: `@e.salary` }, `>`, 100000]) + expect(builtQuery.having).toEqual([[{ SUM: `@e.salary` }, `>`, 100000]]) }) it(`allows combining with other query methods`, () => { diff --git a/packages/db/tests/query/query-builder/join.test.ts b/packages/db/tests/query/query-builder/join.test.ts index 9aa92ef283..9e7369e30a 100644 --- a/packages/db/tests/query/query-builder/join.test.ts +++ b/packages/db/tests/query/query-builder/join.test.ts @@ -91,22 +91,6 @@ describe(`QueryBuilder.join`, () => { expect(join[1]!.as).toBe(`d2`) }) - it(`allows join with a where condition`, () => { - const query = queryBuilder() - .from(`employees`, `e`) - .join({ - type: `inner`, - from: `departments`, - as: `d`, - on: [`@e.department_id`, `=`, `@d.id`], - where: [`@d.budget`, `>`, 1000000], - }) - - const builtQuery = query._query - expect(builtQuery.join).toBeDefined() - expect(builtQuery.join![0]!.where).toEqual([`@d.budget`, `>`, 1000000]) - }) - it(`allows accessing joined table in select`, () => { const query = queryBuilder() .from(`employees`, `e`) @@ -139,7 +123,7 @@ describe(`QueryBuilder.join`, () => { .where(`@d.budget`, `>`, 1000000) const builtQuery = query._query - expect(builtQuery.where).toEqual([`@d.budget`, `>`, 1000000]) + expect(builtQuery.where).toEqual([[`@d.budget`, `>`, 1000000]]) }) it(`creates a complex query with multiple joins, select and where`, () => { diff --git a/packages/db/tests/query/query-builder/where.test.ts b/packages/db/tests/query/query-builder/where.test.ts index 5735a22cb9..a2e4bc87c7 100644 --- a/packages/db/tests/query/query-builder/where.test.ts +++ b/packages/db/tests/query/query-builder/where.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest" import { queryBuilder } from "../../../src/query/query-builder.js" +import type { SimpleCondition } from "../../../src/query/schema.js" import type { Input, Schema } from "../../../src/query/types.js" // Test schema @@ -30,7 +31,7 @@ describe(`QueryBuilder.where`, () => { .where(`@id`, `=`, 1) const builtQuery = query._query - expect(builtQuery.where).toEqual([`@id`, `=`, 1]) + expect(builtQuery.where).toEqual([[`@id`, `=`, 1]]) }) it(`supports various comparison operators`, () => { @@ -55,7 +56,7 @@ describe(`QueryBuilder.where`, () => { const builtQuery = query._query expect(builtQuery.where).toBeDefined() // Type assertion since we know where is defined based on our query - const where = builtQuery.where! + const where = builtQuery.where![0]! as SimpleCondition expect(where[1]).toBe(op) } }) @@ -67,9 +68,7 @@ describe(`QueryBuilder.where`, () => { const builtQuery = query._query expect(builtQuery.where).toEqual([ - `@e.department_id`, - `=`, - `@department.id`, + [`@e.department_id`, `=`, `@department.id`], ]) }) @@ -79,7 +78,7 @@ describe(`QueryBuilder.where`, () => { .where(10000, `<`, `@salary`) const builtQuery = query._query - expect(builtQuery.where).toEqual([10000, `<`, `@salary`]) + expect(builtQuery.where).toEqual([[10000, `<`, `@salary`]]) }) it(`supports boolean literals`, () => { @@ -88,10 +87,10 @@ describe(`QueryBuilder.where`, () => { .where(`@active`, `=`, true) const builtQuery = query._query - expect(builtQuery.where).toEqual([`@active`, `=`, true]) + expect(builtQuery.where).toEqual([[`@active`, `=`, true]]) }) - it(`combines multiple where calls with AND`, () => { + it(`combines multiple where calls`, () => { const query = queryBuilder() .from(`employees`) .where(`@id`, `>`, 10) @@ -100,7 +99,6 @@ describe(`QueryBuilder.where`, () => { const builtQuery = query._query expect(builtQuery.where).toEqual([ [`@id`, `>`, 10], - `and`, [`@salary`, `>=`, 50000], ]) }) @@ -114,8 +112,8 @@ describe(`QueryBuilder.where`, () => { const builtQuery = query._query expect(builtQuery.where).toEqual([ - [[`@id`, `>`, 10], `and`, [`@salary`, `>=`, 50000]], - `and`, + [`@id`, `>`, 10], + [`@salary`, `>=`, 50000], [`@active`, `=`, true], ]) }) @@ -126,7 +124,7 @@ describe(`QueryBuilder.where`, () => { const query = queryBuilder().from(`employees`).where(condition) const builtQuery = query._query - expect(builtQuery.where).toEqual(condition) + expect(builtQuery.where).toEqual([condition]) }) it(`allows combining with other methods`, () => { @@ -136,7 +134,7 @@ describe(`QueryBuilder.where`, () => { .select(`@id`, `@name`, `@salary`) const builtQuery = query._query - expect(builtQuery.where).toEqual([`@salary`, `>`, 50000]) + expect(builtQuery.where).toEqual([[`@salary`, `>`, 50000]]) expect(builtQuery.select).toEqual([`@id`, `@name`, `@salary`]) }) }) diff --git a/packages/db/tests/query/query-types.test.ts b/packages/db/tests/query/query-types.test.ts index c8aac6038c..f93bac5a94 100644 --- a/packages/db/tests/query/query-types.test.ts +++ b/packages/db/tests/query/query-types.test.ts @@ -55,7 +55,7 @@ const aliasedQuery = { const simpleWhereQuery = { select: [`@id`, `@name`], from: `users`, - where: [`@age`, `>`, 18] as SimpleCondition, + where: [[`@age`, `>`, 18] as SimpleCondition], } satisfies Query // Valid query with flat composite WHERE condition @@ -63,14 +63,16 @@ const compositeWhereQuery = { select: [`@id`, `@name`], from: `users`, where: [ - `@age`, - `>`, - 18, - `and` as LogicalOperator, - `@active`, - `=`, - true, - ] as FlatCompositeCondition, + [ + `@age`, + `>`, + 18, + `and` as LogicalOperator, + `@active`, + `=`, + true, + ] as FlatCompositeCondition, + ], } satisfies Query // Full query with all optional properties @@ -78,9 +80,9 @@ const fullQuery = { select: [`@id`, `@name`, { age_years: `@age` }], as: `user_data`, from: `users`, - where: [`@active`, `=`, true] as SimpleCondition, + where: [[`@active`, `=`, true] as SimpleCondition], groupBy: [`@department`], - having: [`@count`, `>`, 5] as SimpleCondition, + having: [[`@count`, `>`, 5] as SimpleCondition], orderBy: { "@name": `asc` }, limit: 10, offset: 20, diff --git a/packages/db/tests/query/table-alias.test.ts b/packages/db/tests/query/table-alias.test.ts index cf5fd7cfba..5c81aa4185 100644 --- a/packages/db/tests/query/table-alias.test.ts +++ b/packages/db/tests/query/table-alias.test.ts @@ -127,7 +127,7 @@ describe(`Query - Table Aliasing`, () => { select: [`@p.id`, `@p.name`, `@p.price`], from: `products`, as: `p`, - where: [`@p.category`, `=`, `Electronics`] as Condition, + where: [[`@p.category`, `=`, `Electronics`] as Condition], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -171,7 +171,7 @@ describe(`Query - Table Aliasing`, () => { select: [`@p.id`, `@p.name`, `@p.price`], from: `products`, as: `p`, - having: [`@p.price`, `>`, 500] as Condition, + having: [[`@p.price`, `>`, 500] as Condition], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -222,10 +222,12 @@ describe(`Query - Table Aliasing`, () => { from: `products`, as: `p`, where: [ - [`@p.price`, `>`, 100], // Aliased condition - `and`, - [`@inStock`, `=`, true], // Non-aliased condition - ] as unknown as Condition, + [ + [`@p.price`, `>`, 100], // Aliased condition + `and`, + [`@inStock`, `=`, true], // Non-aliased condition + ] as unknown as Condition, + ], } const graph = new D2({ initialFrontier: v([0, 0]) }) @@ -280,10 +282,12 @@ describe(`Query - Table Aliasing`, () => { from: `products`, as: `p`, where: [ - [[`@p.category`, `=`, `Electronics`], `and`, [`@p.price`, `<`, 1000]], - `or`, - [[`@p.category`, `=`, `Books`], `and`, [`@p.rating`, `>=`, 4.5]], - ] as unknown as Condition, + [ + [[`@p.category`, `=`, `Electronics`], `and`, [`@p.price`, `<`, 1000]], + `or`, + [[`@p.category`, `=`, `Books`], `and`, [`@p.rating`, `>=`, 4.5]], + ] as unknown as Condition, + ], } const graph = new D2({ initialFrontier: v([0, 0]) }) diff --git a/packages/db/tests/query/with.test.ts b/packages/db/tests/query/with.test.ts index e35f9f08a2..0f2e9d8b73 100644 --- a/packages/db/tests/query/with.test.ts +++ b/packages/db/tests/query/with.test.ts @@ -58,7 +58,7 @@ describe(`Query`, () => { { select: [`@id`, `@name`, `@age`], from: `users`, - where: [`@age`, `>`, 20], + where: [[`@age`, `>`, 20]], as: `adult_users`, }, ], @@ -117,13 +117,13 @@ describe(`Query`, () => { { select: [`@id`, `@name`, `@age`], from: `users`, - where: [`@active`, `=`, true], + where: [[`@active`, `=`, true]], as: `active_users`, }, { select: [`@id`, `@name`, `@age`], from: `active_users`, - where: [`@age`, `>`, 20], + where: [[`@age`, `>`, 20]], as: `active_adult_users`, }, ], @@ -197,13 +197,13 @@ describe(`Query`, () => { { select: [`@id`, `@name`], from: `users`, - where: [`@age`, `>`, 20], + where: [[`@age`, `>`, 20]], as: `filtered_users`, }, { select: [`@id`, `@name`], from: `users`, - where: [`@active`, `=`, true], + where: [[`@active`, `=`, true]], as: `filtered_users`, // Duplicate name }, ], @@ -227,7 +227,7 @@ describe(`Query`, () => { { select: [`@id`, `@name`], from: `users`, - where: [`@age`, `>`, 20], + where: [[`@age`, `>`, 20]], as: `adult_users`, }, ], From 86423fa24199ba47739c29f12413d955242e3e33 Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Mon, 9 Jun 2025 16:22:30 +0100 Subject: [PATCH 3/5] tests --- packages/db/tests/query/conditions.test.ts | 154 ++++++++++++++++++ .../tests/query/query-builder/having.test.ts | 44 +++++ .../tests/query/query-builder/where.test.ts | 40 +++++ 3 files changed, 238 insertions(+) diff --git a/packages/db/tests/query/conditions.test.ts b/packages/db/tests/query/conditions.test.ts index ef041521f4..8f2534f7d8 100644 --- a/packages/db/tests/query/conditions.test.ts +++ b/packages/db/tests/query/conditions.test.ts @@ -494,5 +494,159 @@ describe(`Query`, () => { expect(matches).toBe(true) }) }) + + test(`callback function in where clause`, () => { + const callback = (context: any) => { + const product = context.products + return product.price > 500 && product.inStock + } + + const query: Query = { + select: [`@id`, `@name`, `@price`, `@inStock`], + from: `products`, + where: [callback], + } + + const graph = new D2({ initialFrontier: v([0, 0]) }) + const input = graph.newInput<[number, Product]>() + const pipeline = compileQueryPipeline(query, { [query.from]: input }) + + const messages: Array> = [] + pipeline.pipe( + output((message) => { + messages.push(message) + }) + ) + + graph.finalize() + + input.sendData( + v([1, 0]), + new MultiSet( + sampleProducts.map((product) => [[product.id, product], 1]) + ) + ) + input.sendFrontier(new Antichain([v([1, 0])])) + + graph.run() + + // Check the filtered results + const dataMessages = messages.filter((m) => m.type === MessageType.DATA) + const results = dataMessages[0]!.data.collection + .getInner() + .map(([data]) => data) + + // Should only include expensive products that are in stock + // From our sample data: Laptop (1200, true) and Smartphone (800, true) + expect(results).toHaveLength(2) + + // Verify the callback logic + results.forEach(([_key, result]) => { + expect(result.price).toBeGreaterThan(500) + expect(result.inStock).toBe(true) + }) + }) + + test(`mixed conditions and callbacks`, () => { + const callback = (context: any) => { + return context.products.tags.includes(`tech`) + } + + const query: Query = { + select: [`@id`, `@name`, `@category`, `@tags`, `@inStock`], + from: `products`, + where: [[`@inStock`, `=`, true], callback], + } + + const graph = new D2({ initialFrontier: v([0, 0]) }) + const input = graph.newInput<[number, Product]>() + const pipeline = compileQueryPipeline(query, { [query.from]: input }) + + const messages: Array> = [] + pipeline.pipe( + output((message) => { + messages.push(message) + }) + ) + + graph.finalize() + + input.sendData( + v([1, 0]), + new MultiSet( + sampleProducts.map((product) => [[product.id, product], 1]) + ) + ) + input.sendFrontier(new Antichain([v([1, 0])])) + + graph.run() + + // Check the filtered results + const dataMessages = messages.filter((m) => m.type === MessageType.DATA) + const results = dataMessages[0]!.data.collection + .getInner() + .map(([data]) => data) + + // Should include products that are in stock AND have "tech" tag + // From our sample data: Laptop (1) and Smartphone (2) - Headphones is not in stock + expect(results).toHaveLength(2) + + // Verify both conditions are met + results.forEach(([_key, result]) => { + expect(result.inStock).toBe(true) + expect(result.tags).toContain(`tech`) + }) + }) + + test(`multiple callback functions`, () => { + const callback1 = (context: any) => + context.products.category === `Electronics` + const callback2 = (context: any) => context.products.price < 1000 + + const query: Query = { + select: [`@id`, `@name`, `@price`, `@category`], + from: `products`, + where: [callback1, callback2], + } + + const graph = new D2({ initialFrontier: v([0, 0]) }) + const input = graph.newInput<[number, Product]>() + const pipeline = compileQueryPipeline(query, { [query.from]: input }) + + const messages: Array> = [] + pipeline.pipe( + output((message) => { + messages.push(message) + }) + ) + + graph.finalize() + + input.sendData( + v([1, 0]), + new MultiSet( + sampleProducts.map((product) => [[product.id, product], 1]) + ) + ) + input.sendFrontier(new Antichain([v([1, 0])])) + + graph.run() + + // Check the filtered results + const dataMessages = messages.filter((m) => m.type === MessageType.DATA) + const results = dataMessages[0]!.data.collection + .getInner() + .map(([data]) => data) + + // Should include Electronics products under $1000 + // From our sample data: Smartphone (800) and Headphones (150) + expect(results).toHaveLength(2) + + // Verify both callbacks are satisfied (AND logic) + results.forEach(([_key, result]) => { + expect(result.category).toBe(`Electronics`) + expect(result.price).toBeLessThan(1000) + }) + }) }) }) diff --git a/packages/db/tests/query/query-builder/having.test.ts b/packages/db/tests/query/query-builder/having.test.ts index b2188427da..b9c7a4df7f 100644 --- a/packages/db/tests/query/query-builder/having.test.ts +++ b/packages/db/tests/query/query-builder/having.test.ts @@ -107,6 +107,50 @@ describe(`QueryBuilder.having`, () => { expect(builtQuery.having).toEqual([condition]) }) + it(`supports callback functions`, () => { + const callback = ({ employees }: any) => { + // For HAVING clauses, we might be working with aggregated data + return employees.salary > 60000 + } + + const query = queryBuilder().from(`employees`).having(callback) + + const builtQuery = query._query + expect(builtQuery.having).toEqual([callback]) + expect(typeof builtQuery.having![0]).toBe(`function`) + }) + + it(`combines callback with traditional conditions`, () => { + const query = queryBuilder() + .from(`employees`) + .having(`@salary`, `>`, 50000) + .having(({ employees }) => employees.salary > 100000) + .having(`@active`, `=`, true) + + const builtQuery = query._query + expect(builtQuery.having).toHaveLength(3) + expect(builtQuery.having![0]).toEqual([`@salary`, `>`, 50000]) + expect(typeof builtQuery.having![1]).toBe(`function`) + expect(builtQuery.having![2]).toEqual([`@active`, `=`, true]) + }) + + it(`supports multiple callback functions`, () => { + const callback1 = ({ employees }: any) => employees.salary > 60000 + const callback2 = ({ employees }: any) => employees.count > 5 + + const query = queryBuilder() + .from(`employees`) + .having(callback1) + .having(callback2) + + const builtQuery = query._query + expect(builtQuery.having).toHaveLength(2) + expect(typeof builtQuery.having![0]).toBe(`function`) + expect(typeof builtQuery.having![1]).toBe(`function`) + expect(builtQuery.having![0]).toBe(callback1) + expect(builtQuery.having![1]).toBe(callback2) + }) + it(`works in a practical example with groupBy`, () => { const query = queryBuilder() .from(`employees`, `e`) diff --git a/packages/db/tests/query/query-builder/where.test.ts b/packages/db/tests/query/query-builder/where.test.ts index a2e4bc87c7..4048b26cbe 100644 --- a/packages/db/tests/query/query-builder/where.test.ts +++ b/packages/db/tests/query/query-builder/where.test.ts @@ -127,6 +127,46 @@ describe(`QueryBuilder.where`, () => { expect(builtQuery.where).toEqual([condition]) }) + it(`supports callback functions`, () => { + const query = queryBuilder() + .from(`employees`) + .where(({ employees }) => employees.salary > 50000) + + const builtQuery = query._query + expect(typeof builtQuery.where![0]).toBe(`function`) + }) + + it(`combines callback with traditional conditions`, () => { + const query = queryBuilder() + .from(`employees`) + .where(`@active`, `=`, true) + .where(({ employees }) => employees.salary > 50000) + .where(`@department_id`, `!=`, null) + + const builtQuery = query._query + expect(builtQuery.where).toHaveLength(3) + expect(builtQuery.where![0]).toEqual([`@active`, `=`, true]) + expect(typeof builtQuery.where![1]).toBe(`function`) + expect(builtQuery.where![2]).toEqual([`@department_id`, `!=`, null]) + }) + + it(`supports multiple callback functions`, () => { + const callback1 = ({ employees }: any) => employees.salary > 50000 + const callback2 = ({ employees }: any) => employees.name.startsWith(`J`) + + const query = queryBuilder() + .from(`employees`) + .where(callback1) + .where(callback2) + + const builtQuery = query._query + expect(builtQuery.where).toHaveLength(2) + expect(typeof builtQuery.where![0]).toBe(`function`) + expect(typeof builtQuery.where![1]).toBe(`function`) + expect(builtQuery.where![0]).toBe(callback1) + expect(builtQuery.where![1]).toBe(callback2) + }) + it(`allows combining with other methods`, () => { const query = queryBuilder() .from(`employees`) From dd4efce9ba9ad15010b83c20adff6a4ad2949c52 Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Mon, 9 Jun 2025 16:36:27 +0100 Subject: [PATCH 4/5] fixed types --- packages/db/src/query/schema.ts | 2 +- packages/db/tests/query/query-collection.test.ts | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/db/src/query/schema.ts b/packages/db/src/query/schema.ts index 902408313e..4b0a04c7e6 100644 --- a/packages/db/src/query/schema.ts +++ b/packages/db/src/query/schema.ts @@ -200,7 +200,7 @@ export type From = InputReference<{ }> export type WhereCallback = ( - context: TContext[`schema`] + context: TContext extends { schema: infer S } ? S : any ) => boolean export type Where = Array< diff --git a/packages/db/tests/query/query-collection.test.ts b/packages/db/tests/query/query-collection.test.ts index 485c5338e7..45b4aaa2b0 100644 --- a/packages/db/tests/query/query-collection.test.ts +++ b/packages/db/tests/query/query-collection.test.ts @@ -183,7 +183,7 @@ describe(`Query Collections`, () => { expect(result.state.get(`KEY::${result.id}/4`)).toBeUndefined() }) - it(`should be able to query a collection without a select`, async () => { + it(`should be able to query a collection without a select using a callback for the where clause`, async () => { const emitter = mitt() // Create collection with mutation capability @@ -216,7 +216,9 @@ describe(`Query Collections`, () => { })) ) - const query = queryBuilder().from({ collection }).where(`@age`, `>`, 30) + const query = queryBuilder() + .from({ person: collection }) + .where(({ person }) => person.age > 30) const compiledQuery = compileQuery(query) From 978f8af082316c07fb3f556821820904bd7ee178 Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Mon, 9 Jun 2025 16:38:57 +0100 Subject: [PATCH 5/5] changeset --- .changeset/floppy-berries-enjoy.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/floppy-berries-enjoy.md diff --git a/.changeset/floppy-berries-enjoy.md b/.changeset/floppy-berries-enjoy.md new file mode 100644 index 0000000000..da0598b507 --- /dev/null +++ b/.changeset/floppy-berries-enjoy.md @@ -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