From fee9bbc55e084a216d2259a07ab9f9d982f167e7 Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Sun, 8 Jun 2025 15:38:06 +0100 Subject: [PATCH 1/8] key all streams, and drop keyBy --- packages/db/src/query/compiled-query.ts | 8 +- packages/db/src/query/evaluators.ts | 43 +- packages/db/src/query/extractors.ts | 45 +- packages/db/src/query/group-by.ts | 42 +- packages/db/src/query/joins.ts | 160 +- packages/db/src/query/key-by.ts | 61 - packages/db/src/query/order-by.ts | 158 +- packages/db/src/query/pipeline-compiler.ts | 64 +- packages/db/src/query/schema.ts | 9 - packages/db/src/query/select.ts | 72 +- packages/db/src/types.ts | 30 + packages/db/tests/query/compiler.test.ts | 54 +- packages/db/tests/query/conditions.test.ts | 68 +- .../tests/query/function-integration.test.ts | 147 +- packages/db/tests/query/group-by.test.ts | 284 ++-- packages/db/tests/query/having.test.ts | 24 +- packages/db/tests/query/in-operator.test.ts | 81 +- packages/db/tests/query/join.test.ts | 95 +- packages/db/tests/query/key-by.test.ts | 419 ------ packages/db/tests/query/like-operator.test.ts | 15 +- .../db/tests/query/nested-conditions.test.ts | 6 +- packages/db/tests/query/order-by.test.ts | 1319 ++++------------- .../db/tests/query/query-collection.test.ts | 29 +- packages/db/tests/query/table-alias.test.ts | 30 +- .../db/tests/query/wildcard-select.test.ts | 12 +- packages/db/tests/query/with.test.ts | 42 +- 26 files changed, 1043 insertions(+), 2274 deletions(-) delete mode 100644 packages/db/src/query/key-by.ts delete mode 100644 packages/db/tests/query/key-by.test.ts diff --git a/packages/db/src/query/compiled-query.ts b/packages/db/src/query/compiled-query.ts index 219978062a..efff668f4f 100644 --- a/packages/db/src/query/compiled-query.ts +++ b/packages/db/src/query/compiled-query.ts @@ -115,13 +115,13 @@ export class CompiledQuery> { const multiSetArray: MultiSetArray = [] for (const change of changes) { if (change.type === `insert`) { - multiSetArray.push([change.value, 1]) + multiSetArray.push([[change.key, change.value], 1]) } else if (change.type === `update`) { - multiSetArray.push([change.previousValue, -1]) - multiSetArray.push([change.value, 1]) + multiSetArray.push([[change.key, change.previousValue], -1]) + multiSetArray.push([[change.key, change.value], 1]) } else { // change.type === `delete` - multiSetArray.push([change.value, -1]) + multiSetArray.push([[change.key, change.value], -1]) } } input.sendData(this.version, new MultiSet(multiSetArray)) diff --git a/packages/db/src/query/evaluators.ts b/packages/db/src/query/evaluators.ts index 72211bc384..6a0ba8bcc6 100644 --- a/packages/db/src/query/evaluators.ts +++ b/packages/db/src/query/evaluators.ts @@ -1,4 +1,4 @@ -import { evaluateOperandOnNestedRow } from "./extractors.js" +import { evaluateOperandOnNamespacedRow } from "./extractors.js" import { compareValues, convertLikeToRegex, isValueInArray } from "./utils.js" import type { Comparator, @@ -7,12 +7,13 @@ import type { LogicalOperator, SimpleCondition, } from "./schema.js" +import type { NamespacedRow } from "../types.js" /** * Evaluates a condition against a nested row structure */ -export function evaluateConditionOnNestedRow( - nestedRow: Record, +export function evaluateConditionOnNamespacedRow( + namespacedRow: NamespacedRow, condition: Condition, mainTableAlias?: string, joinedTableAlias?: string @@ -20,8 +21,8 @@ export function evaluateConditionOnNestedRow( // Handle simple conditions with exactly 3 elements if (condition.length === 3 && !Array.isArray(condition[0])) { const [left, comparator, right] = condition as SimpleCondition - return evaluateSimpleConditionOnNestedRow( - nestedRow, + return evaluateSimpleConditionOnNamespacedRow( + namespacedRow, left, comparator, right, @@ -38,8 +39,8 @@ export function evaluateConditionOnNestedRow( ![`and`, `or`].includes(condition[1] as string) ) { // Start with the first condition (first 3 elements) - let result = evaluateSimpleConditionOnNestedRow( - nestedRow, + let result = evaluateSimpleConditionOnNamespacedRow( + namespacedRow, condition[0], condition[1] as Comparator, condition[2], @@ -53,8 +54,8 @@ export function evaluateConditionOnNestedRow( // Make sure we have a complete condition to evaluate if (i + 3 <= condition.length) { - const nextResult = evaluateSimpleConditionOnNestedRow( - nestedRow, + const nextResult = evaluateSimpleConditionOnNamespacedRow( + namespacedRow, condition[i + 1], condition[i + 2] as Comparator, condition[i + 3], @@ -78,8 +79,8 @@ export function evaluateConditionOnNestedRow( // Handle nested composite conditions where the first element is an array if (condition.length > 0 && Array.isArray(condition[0])) { // Start with the first condition - let result = evaluateConditionOnNestedRow( - nestedRow, + let result = evaluateConditionOnNamespacedRow( + namespacedRow, condition[0] as Condition, mainTableAlias, joinedTableAlias @@ -96,8 +97,8 @@ export function evaluateConditionOnNestedRow( if (operator === `and`) { result = result && - evaluateConditionOnNestedRow( - nestedRow, + evaluateConditionOnNamespacedRow( + namespacedRow, nextCondition, mainTableAlias, joinedTableAlias @@ -106,8 +107,8 @@ export function evaluateConditionOnNestedRow( // logicalOp === `or` result = result || - evaluateConditionOnNestedRow( - nestedRow, + evaluateConditionOnNamespacedRow( + namespacedRow, nextCondition, mainTableAlias, joinedTableAlias @@ -125,23 +126,23 @@ export function evaluateConditionOnNestedRow( /** * Evaluates a simple condition against a nested row structure */ -export function evaluateSimpleConditionOnNestedRow( - nestedRow: Record, +export function evaluateSimpleConditionOnNamespacedRow( + namespacedRow: Record, left: ConditionOperand, comparator: Comparator, right: ConditionOperand, mainTableAlias?: string, joinedTableAlias?: string ): boolean { - const leftValue = evaluateOperandOnNestedRow( - nestedRow, + const leftValue = evaluateOperandOnNamespacedRow( + namespacedRow, left, mainTableAlias, joinedTableAlias ) - const rightValue = evaluateOperandOnNestedRow( - nestedRow, + const rightValue = evaluateOperandOnNamespacedRow( + namespacedRow, right, mainTableAlias, joinedTableAlias diff --git a/packages/db/src/query/extractors.ts b/packages/db/src/query/extractors.ts index 71d179530e..728d768792 100644 --- a/packages/db/src/query/extractors.ts +++ b/packages/db/src/query/extractors.ts @@ -3,14 +3,14 @@ import type { AllowedFunctionName, ConditionOperand } from "./schema.js" /** * Extracts a value from a nested row structure - * @param nestedRow The nested row structure + * @param namespacedRow The nested row structure * @param columnRef The column reference (may include table.column format) * @param mainTableAlias The main table alias to check first for columns without table reference * @param joinedTableAlias The joined table alias to check second for columns without table reference * @returns The extracted value or undefined if not found */ -export function extractValueFromNestedRow( - nestedRow: Record, +export function extractValueFromNamespacedRow( + namespacedRow: Record, columnRef: string, mainTableAlias?: string, joinedTableAlias?: string @@ -20,7 +20,7 @@ export function extractValueFromNestedRow( const [tableAlias, colName] = columnRef.split(`.`) as [string, string] // Get the table data - const tableData = nestedRow[tableAlias] as + const tableData = namespacedRow[tableAlias] as | Record | null | undefined @@ -34,16 +34,19 @@ export function extractValueFromNestedRow( return value } else { // If no table is specified, first try to find in the main table if provided - if (mainTableAlias && nestedRow[mainTableAlias]) { - const mainTableData = nestedRow[mainTableAlias] as Record + if (mainTableAlias && namespacedRow[mainTableAlias]) { + const mainTableData = namespacedRow[mainTableAlias] as Record< + string, + unknown + > if (typeof mainTableData === `object` && columnRef in mainTableData) { return mainTableData[columnRef] } } // Then try the joined table if provided - if (joinedTableAlias && nestedRow[joinedTableAlias]) { - const joinedTableData = nestedRow[joinedTableAlias] as Record< + if (joinedTableAlias && namespacedRow[joinedTableAlias]) { + const joinedTableData = namespacedRow[joinedTableAlias] as Record< string, unknown > @@ -53,7 +56,7 @@ export function extractValueFromNestedRow( } // If not found in main or joined table, try to find the column in any table - for (const [_tableAlias, tableData] of Object.entries(nestedRow)) { + for (const [_tableAlias, tableData] of Object.entries(namespacedRow)) { if ( tableData && typeof tableData === `object` && @@ -69,8 +72,8 @@ export function extractValueFromNestedRow( /** * Evaluates an operand against a nested row structure */ -export function evaluateOperandOnNestedRow( - nestedRow: Record, +export function evaluateOperandOnNamespacedRow( + namespacedRow: Record, operand: ConditionOperand, mainTableAlias?: string, joinedTableAlias?: string @@ -78,8 +81,8 @@ export function evaluateOperandOnNestedRow( // Handle column references if (typeof operand === `string` && operand.startsWith(`@`)) { const columnRef = operand.substring(1) - return extractValueFromNestedRow( - nestedRow, + return extractValueFromNamespacedRow( + namespacedRow, columnRef, mainTableAlias, joinedTableAlias @@ -92,8 +95,8 @@ export function evaluateOperandOnNestedRow( if (typeof colRef === `string`) { // First try to extract from nested row structure - const nestedValue = extractValueFromNestedRow( - nestedRow, + const nestedValue = extractValueFromNamespacedRow( + namespacedRow, colRef, mainTableAlias, joinedTableAlias @@ -101,8 +104,8 @@ export function evaluateOperandOnNestedRow( // If not found in nested structure, check if it's a direct property of the row // This is important for HAVING clauses that reference aggregated values - if (nestedValue === undefined && colRef in nestedRow) { - return nestedRow[colRef] + if (nestedValue === undefined && colRef in namespacedRow) { + return namespacedRow[colRef] } return nestedValue @@ -121,15 +124,15 @@ export function evaluateOperandOnNestedRow( // If the arguments are a reference or another expression, evaluate them first const evaluatedArgs = Array.isArray(args) ? args.map((arg) => - evaluateOperandOnNestedRow( - nestedRow, + evaluateOperandOnNamespacedRow( + namespacedRow, arg as ConditionOperand, mainTableAlias, joinedTableAlias ) ) - : evaluateOperandOnNestedRow( - nestedRow, + : evaluateOperandOnNamespacedRow( + namespacedRow, args as ConditionOperand, mainTableAlias, joinedTableAlias diff --git a/packages/db/src/query/group-by.ts b/packages/db/src/query/group-by.ts index 0dbfa333ab..c9ba0a9f03 100644 --- a/packages/db/src/query/group-by.ts +++ b/packages/db/src/query/group-by.ts @@ -1,11 +1,11 @@ -import { groupBy, groupByOperators, map } from "@electric-sql/d2ts" +import { groupBy, groupByOperators } from "@electric-sql/d2ts" import { - evaluateOperandOnNestedRow, - extractValueFromNestedRow, + evaluateOperandOnNamespacedRow, + extractValueFromNamespacedRow, } from "./extractors" import { isAggregateFunctionCall } from "./utils" import type { ConditionOperand, FunctionCall, Query } from "./schema" -import type { IStreamBuilder } from "@electric-sql/d2ts" +import type { NamespacedAndKeyedStream } from "../types.js" const { sum, count, avg, min, max, median, mode } = groupByOperators @@ -13,7 +13,7 @@ const { sum, count, avg, min, max, median, mode } = groupByOperators * Process the groupBy clause in a D2QL query */ export function processGroupBy( - pipeline: IStreamBuilder>, + pipeline: NamespacedAndKeyedStream, query: Query, mainTableAlias: string ) { @@ -23,7 +23,10 @@ export function processGroupBy( : [query.groupBy] // Create a key extractor function for the groupBy operator - const keyExtractor = (nestedRow: Record) => { + const keyExtractor = ([_oldKey, namespacedRow]: [ + string, + Record, + ]) => { const key: Record = {} // Extract each groupBy column value @@ -34,8 +37,8 @@ export function processGroupBy( ? columnRef.split(`.`)[1] : columnRef - key[columnName!] = extractValueFromNestedRow( - nestedRow, + key[columnName!] = extractValueFromNamespacedRow( + namespacedRow, columnRef, mainTableAlias ) @@ -73,15 +76,7 @@ export function processGroupBy( // Apply the groupBy operator if we have any aggregates if (Object.keys(aggregates).length > 0) { - pipeline = pipeline.pipe( - groupBy(keyExtractor, aggregates), - // Convert KeyValue to Record - map(([_key, value]) => { - // After groupBy, the value already contains both the key fields and aggregate results - // We need to return it as is, not wrapped in a nested structure - return value as Record - }) - ) + pipeline = pipeline.pipe(groupBy(keyExtractor, aggregates)) } return pipeline @@ -96,17 +91,20 @@ export function getAggregateFunction( mainTableAlias: string ) { // Create a value extractor function for the column to aggregate - const valueExtractor = (nestedRow: Record) => { + const valueExtractor = ([_oldKey, namespacedRow]: [ + string, + Record, + ]) => { let value: unknown if (typeof columnRef === `string` && columnRef.startsWith(`@`)) { - value = extractValueFromNestedRow( - nestedRow, + value = extractValueFromNamespacedRow( + namespacedRow, columnRef.substring(1), mainTableAlias ) } else { - value = evaluateOperandOnNestedRow( - nestedRow, + value = evaluateOperandOnNamespacedRow( + namespacedRow, columnRef as ConditionOperand, mainTableAlias ) diff --git a/packages/db/src/query/joins.ts b/packages/db/src/query/joins.ts index 4f7c6985cb..ecf62d8ce6 100644 --- a/packages/db/src/query/joins.ts +++ b/packages/db/src/query/joins.ts @@ -4,20 +4,25 @@ import { join as joinOperator, map, } from "@electric-sql/d2ts" -import { evaluateConditionOnNestedRow } from "./evaluators.js" +import { evaluateConditionOnNamespacedRow } from "./evaluators.js" import { extractJoinKey } from "./extractors.js" import type { Query } from "./index.js" import type { IStreamBuilder, JoinType } from "@electric-sql/d2ts" +import type { + KeyedStream, + NamespacedAndKeyedStream, + NamespacedRow, +} from "../types.js" /** * Creates a processing pipeline for join clauses */ export function processJoinClause( - pipeline: IStreamBuilder>, + pipeline: NamespacedAndKeyedStream, query: Query, - tables: Record>>, + tables: Record, mainTableAlias: string, - allInputs: Record>> + allInputs: Record ) { if (!query.join) return pipeline const input = allInputs[query.from] @@ -30,49 +35,56 @@ export function processJoinClause( const joinType: JoinType = joinClause.type === `cross` ? `inner` : joinClause.type + // The `in` is formatted as ['@mainKeyRef', '=', '@joinedKeyRef'] + // Destructure the main key reference and the joined key references + const [mainKeyRef, , joinedKeyRefs] = joinClause.on + // We need to prepare the main pipeline and the joined pipeline // to have the correct key format for joining const mainPipeline = pipeline.pipe( - map((nestedRow: Record) => { + map(([currentKey, namespacedRow]) => { // Extract the key from the ON condition left side for the main table - const mainRow = nestedRow[mainTableAlias] as Record + const mainRow = namespacedRow[mainTableAlias]! // Extract the join key from the main row - const keyValue = extractJoinKey( - mainRow, - joinClause.on[0], - mainTableAlias - ) + const key = extractJoinKey(mainRow, mainKeyRef, mainTableAlias) - // Return [key, nestedRow] as a KeyValue type - return [keyValue, nestedRow] as [unknown, Record] + // Return [key, namespacedRow] as a KeyValue type + return [key, [currentKey, namespacedRow]] as [ + unknown, + [string, typeof namespacedRow], + ] }) ) // Get the joined table input from the inputs map - let joinedTableInput: IStreamBuilder> + let joinedTableInput: KeyedStream if (allInputs[joinClause.from]) { // Use the provided input if available joinedTableInput = allInputs[joinClause.from]! } else { // Create a new input if not provided - joinedTableInput = input!.graph.newInput>() + joinedTableInput = + input!.graph.newInput<[string, Record]>() } tables[joinedTableAlias] = joinedTableInput // Create a pipeline for the joined table const joinedPipeline = joinedTableInput.pipe( - map((row: Record) => { + map(([currentKey, row]) => { // Wrap the row in an object with the table alias as the key - const nestedRow = { [joinedTableAlias]: row } + const namespacedRow: NamespacedRow = { [joinedTableAlias]: row } // Extract the key from the ON condition right side for the joined table - const keyValue = extractJoinKey(row, joinClause.on[2], joinedTableAlias) + const key = extractJoinKey(row, joinedKeyRefs, joinedTableAlias) - // Return [key, nestedRow] as a KeyValue type - return [keyValue, nestedRow] as [unknown, Record] + // Return [key, namespacedRow] as a KeyValue type + return [key, [currentKey, namespacedRow]] as [ + string, + [string, typeof namespacedRow], + ] }) ) @@ -123,76 +135,86 @@ export function processJoinClause( export function processJoinResults( mainTableAlias: string, joinedTableAlias: string, - joinClause: { on: any; where?: any; type: string } + joinClause: { on: any; type: string } ) { return function ( - pipeline: IStreamBuilder - ): IStreamBuilder> { + pipeline: IStreamBuilder< + [ + key: string, + [[string, NamespacedRow], [string, NamespacedRow] | undefined], + ] + > + ): NamespacedAndKeyedStream { return pipeline.pipe( // Process the join result and handle nulls in the same step - map((result: unknown) => { - const [_key, [mainNestedRow, joinedNestedRow]] = result as [ - unknown, - [ - Record | undefined, - Record | undefined, - ], - ] + map((result) => { + const [_key, [main, joined]] = result + const mainKey = main[0] + const mainNamespacedRow = main[1] + const joinedKey = joined?.[0] + const joinedNamespacedRow = joined?.[1] // For inner joins, both sides should be non-null if (joinClause.type === `inner` || joinClause.type === `cross`) { - if (!mainNestedRow || !joinedNestedRow) { + if (!mainNamespacedRow || !joinedNamespacedRow) { return undefined // Will be filtered out } } // For left joins, the main row must be non-null - if (joinClause.type === `left` && !mainNestedRow) { + if (joinClause.type === `left` && !mainNamespacedRow) { return undefined // Will be filtered out } // For right joins, the joined row must be non-null - if (joinClause.type === `right` && !joinedNestedRow) { + if (joinClause.type === `right` && !joinedNamespacedRow) { return undefined // Will be filtered out } // Merge the nested rows - const mergedNestedRow: Record = {} + const mergedNamespacedRow: NamespacedRow = {} // Add main row data if it exists - if (mainNestedRow) { - Object.entries(mainNestedRow).forEach(([tableAlias, tableData]) => { - mergedNestedRow[tableAlias] = tableData - }) + if (mainNamespacedRow) { + Object.entries(mainNamespacedRow).forEach( + ([tableAlias, tableData]) => { + mergedNamespacedRow[tableAlias] = tableData + } + ) } // If we have a joined row, add it to the merged result - if (joinedNestedRow) { - Object.entries(joinedNestedRow).forEach(([tableAlias, tableData]) => { - mergedNestedRow[tableAlias] = tableData - }) + if (joinedNamespacedRow) { + Object.entries(joinedNamespacedRow).forEach( + ([tableAlias, tableData]) => { + mergedNamespacedRow[tableAlias] = tableData + } + ) } else if (joinClause.type === `left` || joinClause.type === `full`) { - // For left or full joins, add the joined table with null data if missing - mergedNestedRow[joinedTableAlias] = null + // For left or full joins, add the joined table with undefined data if missing + // mergedNamespacedRow[joinedTableAlias] = undefined } - // For right or full joins, add the main table with null data if missing + // For right or full joins, add the main table with undefined data if missing if ( - !mainNestedRow && + !mainNamespacedRow && (joinClause.type === `right` || joinClause.type === `full`) ) { - mergedNestedRow[mainTableAlias] = null + // mergedNamespacedRow[mainTableAlias] = undefined } - return mergedNestedRow + // New key + const newKey = `[${mainKey},${joinedKey}]` + + return [newKey, mergedNamespacedRow] as [ + string, + typeof mergedNamespacedRow, + ] }), // Filter out undefined results - filter( - (value: unknown): value is Record => - value !== undefined - ), + filter((value) => value !== undefined), // Process the ON condition - filter((nestedRow: Record) => { + filter(([_key, namespacedRow]: [string, NamespacedRow]) => { // If there's no ON condition, or it's a cross join, always return true if (!joinClause.on || joinClause.type === `cross`) { return true @@ -201,46 +223,34 @@ export function processJoinResults( // For LEFT JOIN, if the right side is null, we should include the row if ( joinClause.type === `left` && - nestedRow[joinedTableAlias] === null + namespacedRow[joinedTableAlias] === undefined ) { return true } // For RIGHT JOIN, if the left side is null, we should include the row - if (joinClause.type === `right` && nestedRow[mainTableAlias] === null) { + if ( + joinClause.type === `right` && + namespacedRow[mainTableAlias] === undefined + ) { return true } // For FULL JOIN, if either side is null, we should include the row if ( joinClause.type === `full` && - (nestedRow[mainTableAlias] === null || - nestedRow[joinedTableAlias] === null) + (namespacedRow[mainTableAlias] === undefined || + namespacedRow[joinedTableAlias] === undefined) ) { return true } - const result = evaluateConditionOnNestedRow( - nestedRow, + return evaluateConditionOnNamespacedRow( + namespacedRow, joinClause.on, mainTableAlias, joinedTableAlias ) - return result - }), - // Process the WHERE clause for the join if it exists - filter((nestedRow: Record) => { - if (!joinClause.where) { - return true - } - - const result = evaluateConditionOnNestedRow( - nestedRow, - joinClause.where, - mainTableAlias, - joinedTableAlias - ) - return result }) ) } diff --git a/packages/db/src/query/key-by.ts b/packages/db/src/query/key-by.ts deleted file mode 100644 index 1ac7f8be6c..0000000000 --- a/packages/db/src/query/key-by.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { keyBy } from "@electric-sql/d2ts" -import type { IStreamBuilder } from "@electric-sql/d2ts" -import type { Query } from "./schema" - -export function processKeyBy( - resultPipeline: IStreamBuilder< - Record | [string | number, Record] - >, - query: Query -) { - if (!query.keyBy) { - return resultPipeline - } - const keyByParam = query.keyBy - - resultPipeline = resultPipeline.pipe( - keyBy((row: Record) => { - if (Array.isArray(keyByParam)) { - // Multiple columns - extract values and JSON stringify - const keyValues: Record = {} - for (const keyColumn of keyByParam) { - // Remove @ prefix if present - const columnName = (keyColumn as string).startsWith(`@`) - ? (keyColumn as string).substring(1) - : (keyColumn as string) - - if (columnName in row) { - keyValues[columnName] = row[columnName] - } else { - throw new Error( - `Key column "${columnName}" not found in result set. Make sure it's included in the select clause.` - ) - } - } - return JSON.stringify(keyValues) - } else { - // Single column - // Remove @ prefix if present - const columnName = (keyByParam as string).startsWith(`@`) - ? (keyByParam as string).substring(1) - : (keyByParam as string) - - if (!(columnName in row)) { - throw new Error( - `Key column "${columnName}" not found in result set. Make sure it's included in the select clause.` - ) - } - - const keyValue = row[columnName] - // Use the value directly if it's a string or number, otherwise JSON stringify - if (typeof keyValue === `string` || typeof keyValue === `number`) { - return keyValue - } else { - return JSON.stringify(keyValue) - } - } - }) - ) - - return resultPipeline -} diff --git a/packages/db/src/query/order-by.ts b/packages/db/src/query/order-by.ts index 38d4bb9bc9..7356f17080 100644 --- a/packages/db/src/query/order-by.ts +++ b/packages/db/src/query/order-by.ts @@ -3,19 +3,18 @@ import { orderBy, orderByWithFractionalIndex, orderByWithIndex, - topK, - topKWithFractionalIndex, - topKWithIndex, } from "@electric-sql/d2ts" -import { evaluateOperandOnNestedRow } from "./extractors" +import { evaluateOperandOnNamespacedRow } from "./extractors" import { isOrderIndexFunctionCall } from "./utils" import type { ConditionOperand, Query } from "./schema" -import type { IStreamBuilder } from "@electric-sql/d2ts" +import type { + KeyedNamespacedRow, + NamespacedAndKeyedStream, + NamespacedRow, +} from "../types" export function processOrderBy( - resultPipeline: IStreamBuilder< - Record | [string | number, Record] - >, + resultPipeline: NamespacedAndKeyedStream, query: Query, mainTableAlias: string ) { @@ -79,17 +78,13 @@ export function processOrderBy( } // Create a value extractor function for the orderBy operator - const valueExtractor = (value: unknown) => { - const row = value as Record - - // Create a nested row structure for evaluateOperandOnNestedRow - const nestedRow: Record = { [mainTableAlias]: row } - + // const valueExtractor = ([key, namespacedRow]: [ + const valueExtractor = (namespacedRow: NamespacedRow) => { // For multiple orderBy columns, create a composite key if (orderByItems.length > 1) { return orderByItems.map((item) => { - const val = evaluateOperandOnNestedRow( - nestedRow, + const val = evaluateOperandOnNamespacedRow( + namespacedRow, item.operand, mainTableAlias ) @@ -106,8 +101,8 @@ export function processOrderBy( } else if (orderByItems.length === 1) { // For a single orderBy column, use the value directly const item = orderByItems[0] - const val = evaluateOperandOnNestedRow( - nestedRow, + const val = evaluateOperandOnNamespacedRow( + namespacedRow, item!.operand, mainTableAlias ) @@ -187,109 +182,62 @@ export function processOrderBy( return (a as any).toString().localeCompare((b as any).toString()) } - let topKComparator: (a: unknown, b: unknown) => number - if (!query.keyBy) { - topKComparator = (a, b) => { - const aValue = valueExtractor(a) - const bValue = valueExtractor(b) - return comparator(aValue, bValue) - } - } - // Apply the appropriate orderBy operator based on whether an ORDER_INDEX column is requested if (hasOrderIndexColumn) { if (orderIndexType === `numeric`) { - if (query.keyBy) { - // Use orderByWithIndex for numeric indices - resultPipeline = resultPipeline.pipe( - orderByWithIndex(valueExtractor, { - limit: query.limit, - offset: query.offset, - comparator, - }), - map(([key, [value, index]]) => { - // Add the index to the result - const result = { - ...(value as Record), - [orderIndexAlias]: index, - } - return [key, result] - }) - ) - } else { - // Use topKWithIndex for numeric indices - resultPipeline = resultPipeline.pipe( - map((value) => [null, value]), - topKWithIndex(topKComparator!, { - limit: query.limit, - offset: query.offset, - }), - map(([_, [value, index]]) => { - // Add the index to the result - return { - ...(value as Record), - [orderIndexAlias]: index, - } - }) - ) - } - } else { - if (query.keyBy) { - // Use orderByWithFractionalIndex for fractional indices - resultPipeline = resultPipeline.pipe( - orderByWithFractionalIndex(valueExtractor, { - limit: query.limit, - offset: query.offset, - comparator, - }), - map(([key, [value, index]]) => { - // Add the index to the result - const result = { - ...(value as Record), - [orderIndexAlias]: index, - } - return [key, result] - }) - ) - } else { - // Use topKWithFractionalIndex for fractional indices - resultPipeline = resultPipeline.pipe( - map((value) => [null, value]), - topKWithFractionalIndex(topKComparator!, { - limit: query.limit, - offset: query.offset, - }), - map(([_, [value, index]]) => { - // Add the index to the result - return { - ...(value as Record), - [orderIndexAlias]: index, - } - }) - ) - } - } - } else { - if (query.keyBy) { - // Use regular orderBy if no index column is requested and but a keyBy is requested + // Use orderByWithIndex for numeric indices resultPipeline = resultPipeline.pipe( - orderBy(valueExtractor, { + orderByWithIndex(valueExtractor, { limit: query.limit, offset: query.offset, comparator, + }), + map(([key, [value, index]]) => { + // Add the index to the result + // We add this to the main table alias for now + // TODO: re are going to need to refactor the whole order by pipeline + const result = { + ...(value as Record), + [mainTableAlias]: { + ...value[mainTableAlias], + [orderIndexAlias]: index, + }, + } + return [key, result] as KeyedNamespacedRow }) ) } else { - // Use topK if no index column is requested and no keyBy is requested + // Use orderByWithFractionalIndex for fractional indices resultPipeline = resultPipeline.pipe( - map((value) => [null, value]), - topK(topKComparator!, { + orderByWithFractionalIndex(valueExtractor, { limit: query.limit, offset: query.offset, + comparator, }), - map(([_, value]) => value as Record) + map(([key, [value, index]]) => { + // Add the index to the result + // We add this to the main table alias for now + // TODO: re are going to need to refactor the whole order by pipeline + const result = { + ...(value as Record), + [mainTableAlias]: { + ...value[mainTableAlias], + [orderIndexAlias]: index, + }, + } + return [key, result] as KeyedNamespacedRow + }) ) } + } else { + // Use regular orderBy if no index column is requested and but a keyBy is requested + resultPipeline = resultPipeline.pipe( + orderBy(valueExtractor, { + limit: query.limit, + offset: query.offset, + comparator, + }) + ) } return resultPipeline diff --git a/packages/db/src/query/pipeline-compiler.ts b/packages/db/src/query/pipeline-compiler.ts index 70fe27c75f..0c802a6d91 100644 --- a/packages/db/src/query/pipeline-compiler.ts +++ b/packages/db/src/query/pipeline-compiler.ts @@ -1,12 +1,12 @@ import { filter, map } from "@electric-sql/d2ts" -import { evaluateConditionOnNestedRow } from "./evaluators.js" +import { evaluateConditionOnNamespacedRow } from "./evaluators.js" import { processJoinClause } from "./joins.js" import { processGroupBy } from "./group-by.js" import { processOrderBy } from "./order-by.js" -import { processKeyBy } from "./key-by.js" import { processSelect } from "./select.js" -import type { Condition, Query } from "./schema.js" +import type { Query } from "./schema.js" import type { IStreamBuilder } from "@electric-sql/d2ts" +import type { KeyedStream, NamespacedAndKeyedStream } from "../types.js" /** * Compiles a query into a D2 pipeline @@ -16,7 +16,7 @@ import type { IStreamBuilder } from "@electric-sql/d2ts" */ export function compileQueryPipeline>( query: Query, - inputs: Record>> + inputs: Record ): T { // Create a copy of the inputs map to avoid modifying the original const allInputs = { ...inputs } @@ -30,11 +30,6 @@ export function compileQueryPipeline>( throw new Error(`WITH query must have an "as" property`) } - // Ensure the WITH query is not keyed - if ((withQuery as Query).keyBy !== undefined) { - throw new Error(`WITH query cannot have a "keyBy" property`) - } - // Check if this CTE name already exists in the inputs if (allInputs[withQuery.as]) { throw new Error(`CTE with name "${withQuery.as}" already exists`) @@ -51,14 +46,12 @@ export function compileQueryPipeline>( ) // Add the compiled query to the inputs map using its alias - allInputs[withQuery.as] = compiledWithQuery as IStreamBuilder< - Record - > + allInputs[withQuery.as] = compiledWithQuery as KeyedStream } } // Create a map of table aliases to inputs - const tables: Record>> = {} + const tables: Record = {} // The main table is the one in the FROM clause const mainTableAlias = query.as || query.from @@ -72,10 +65,14 @@ export function compileQueryPipeline>( tables[mainTableAlias] = input // Prepare the initial pipeline with the main table wrapped in its alias - let pipeline = input.pipe( - map((row: unknown) => { + let pipeline: NamespacedAndKeyedStream = input.pipe( + map(([key, row]) => { // Initialize the record with a nested structure - return { [mainTableAlias]: row } as Record + const ret = [key, { [mainTableAlias]: row }] as [ + string, + Record, + ] + return ret }) ) @@ -93,10 +90,10 @@ export function compileQueryPipeline>( // Process the WHERE clause if it exists if (query.where) { pipeline = pipeline.pipe( - filter((nestedRow) => { - const result = evaluateConditionOnNestedRow( - nestedRow, - query.where as Condition, + filter(([_key, row]) => { + const result = evaluateConditionOnNamespacedRow( + row, + query.where!, mainTableAlias ) return result @@ -113,12 +110,12 @@ export function compileQueryPipeline>( // This works similarly to WHERE but is applied after any aggregations if (query.having) { pipeline = pipeline.pipe( - filter((row) => { + 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 = evaluateConditionOnNestedRow( - { [mainTableAlias]: row, ...row } as Record, - query.having as Condition, + const result = evaluateConditionOnNamespacedRow( + row, + query.having!, mainTableAlias ) return result @@ -126,21 +123,9 @@ export function compileQueryPipeline>( ) } - // Process the SELECT clause - this is where we flatten the structure - pipeline = processSelect(pipeline, query, mainTableAlias, allInputs) - - let resultPipeline: IStreamBuilder< - Record | [string | number, Record] - > = pipeline - - // Process keyBy parameter if it exists - if (query.keyBy) { - resultPipeline = processKeyBy(resultPipeline, query) - } - // Process orderBy parameter if it exists if (query.orderBy) { - resultPipeline = processOrderBy(resultPipeline, query, mainTableAlias) + pipeline = processOrderBy(pipeline, query, mainTableAlias) } else if (query.limit !== undefined || query.offset !== undefined) { // If there's a limit or offset without orderBy, throw an error throw new Error( @@ -148,5 +133,10 @@ export function compileQueryPipeline>( ) } + // Process the SELECT clause - this is where we flatten the structure + const resultPipeline: KeyedStream | NamespacedAndKeyedStream = query.select + ? processSelect(pipeline, query, mainTableAlias, allInputs) + : pipeline + return resultPipeline as T } diff --git a/packages/db/src/query/schema.ts b/packages/db/src/query/schema.ts index 6cde3a8803..4bbace57b3 100644 --- a/packages/db/src/query/schema.ts +++ b/packages/db/src/query/schema.ts @@ -169,7 +169,6 @@ export interface JoinClause { from: string as?: string on: Condition - where?: Condition } // The orderBy clause can be a string, an object mapping a column to "asc" or "desc", @@ -232,7 +231,6 @@ export interface BaseQuery { // The top-level query interface. export interface Query extends BaseQuery { - keyBy?: PropertyReference | Array> with?: Array> collections?: { [K: string]: Collection @@ -246,10 +244,3 @@ export interface WithQuery extends BaseQuery { as: string } - -// A keyed query is a query that has a keyBy clause, and so the result is always -// a keyed stream. -export interface KeyedQuery - extends Query { - keyBy: PropertyReference | Array> -} diff --git a/packages/db/src/query/select.ts b/packages/db/src/query/select.ts index da30abef00..f77e3dd270 100644 --- a/packages/db/src/query/select.ts +++ b/packages/db/src/query/select.ts @@ -1,29 +1,29 @@ import { map } from "@electric-sql/d2ts" import { - evaluateOperandOnNestedRow, - extractValueFromNestedRow, + evaluateOperandOnNamespacedRow, + extractValueFromNamespacedRow, } from "./extractors" -import type { IStreamBuilder } from "@electric-sql/d2ts" import type { ConditionOperand, Query } from "./schema" +import type { KeyedStream, NamespacedAndKeyedStream } from "../types" export function processSelect( - pipeline: IStreamBuilder>, + pipeline: NamespacedAndKeyedStream, query: Query, mainTableAlias: string, - inputs: Record>> -) { + inputs: Record +): KeyedStream { return pipeline.pipe( - map((nestedRow: Record) => { + map(([key, namespacedRow]) => { const result: Record = {} // Check if this is a grouped result (has no nested table structure) // If it's a grouped result, we need to handle it differently const isGroupedResult = query.groupBy && - Object.keys(nestedRow).some( - (key) => - !Object.keys(inputs).includes(key) && - typeof nestedRow[key] !== `object` + Object.keys(namespacedRow).some( + (namespaceKey) => + !Object.keys(inputs).includes(namespaceKey) && + typeof namespacedRow[namespaceKey] !== `object` ) for (const item of query.select) { @@ -32,10 +32,13 @@ export function processSelect( if ((item as string) === `@*`) { // For grouped results, just return the row as is if (isGroupedResult) { - Object.assign(result, nestedRow) + Object.assign(result, namespacedRow) } else { // Extract all columns from all tables - Object.assign(result, extractAllColumnsFromAllTables(nestedRow)) + Object.assign( + result, + extractAllColumnsFromAllTables(namespacedRow) + ) } continue } @@ -56,7 +59,7 @@ export function processSelect( // Extract all columns from the specified table Object.assign( result, - extractAllColumnsFromTable(nestedRow, tableAlias) + extractAllColumnsFromTable(namespacedRow, tableAlias) ) } continue @@ -68,12 +71,12 @@ export function processSelect( const alias = columnRef // For grouped results, check if the column is directly in the row first - if (isGroupedResult && columnRef in nestedRow) { - result[alias] = nestedRow[columnRef] + if (isGroupedResult && columnRef in namespacedRow) { + result[alias] = namespacedRow[columnRef] } else { // Extract the value from the nested structure - result[alias] = extractValueFromNestedRow( - nestedRow, + result[alias] = extractValueFromNamespacedRow( + namespacedRow, columnRef, mainTableAlias, undefined @@ -95,12 +98,12 @@ export function processSelect( const columnRef = (expr as string).substring(1) // For grouped results, check if the column is directly in the row first - if (isGroupedResult && columnRef in nestedRow) { - result[alias] = nestedRow[columnRef] + if (isGroupedResult && columnRef in namespacedRow) { + result[alias] = namespacedRow[columnRef] } else { // Extract the value from the nested structure - result[alias] = extractValueFromNestedRow( - nestedRow, + result[alias] = extractValueFromNamespacedRow( + namespacedRow, columnRef, mainTableAlias, undefined @@ -108,12 +111,14 @@ export function processSelect( } } else if (typeof expr === `object`) { // For grouped results, the aggregate results are already in the row - if (isGroupedResult && alias in nestedRow) { - result[alias] = nestedRow[alias] + if (isGroupedResult && alias in namespacedRow) { + result[alias] = namespacedRow[alias] + } else if ((expr as { ORDER_INDEX: unknown }).ORDER_INDEX) { + result[alias] = namespacedRow[mainTableAlias]![alias] } else { // This might be a function call - result[alias] = evaluateOperandOnNestedRow( - nestedRow, + result[alias] = evaluateOperandOnNamespacedRow( + namespacedRow, expr as ConditionOperand, mainTableAlias, undefined @@ -124,23 +129,26 @@ export function processSelect( } } - return result + return [key, result] as [string, typeof result] }) ) } // Helper function to extract all columns from all tables in a nested row function extractAllColumnsFromAllTables( - nestedRow: Record + namespacedRow: Record ): Record { const result: Record = {} // Process each table in the nested row - for (const [tableAlias, tableData] of Object.entries(nestedRow)) { + for (const [tableAlias, tableData] of Object.entries(namespacedRow)) { if (tableData && typeof tableData === `object`) { // Add all columns from this table to the result // If there are column name conflicts, the last table's columns will overwrite previous ones - Object.assign(result, extractAllColumnsFromTable(nestedRow, tableAlias)) + Object.assign( + result, + extractAllColumnsFromTable(namespacedRow, tableAlias) + ) } } @@ -149,13 +157,13 @@ function extractAllColumnsFromAllTables( // Helper function to extract all columns from a table in a nested row function extractAllColumnsFromTable( - nestedRow: Record, + namespacedRow: Record, tableAlias: string ): Record { const result: Record = {} // Get the table data - const tableData = nestedRow[tableAlias] as + const tableData = namespacedRow[tableAlias] as | Record | null | undefined diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts index f381b322b0..e462855498 100644 --- a/packages/db/src/types.ts +++ b/packages/db/src/types.ts @@ -1,3 +1,4 @@ +import type { IStreamBuilder } from "@electric-sql/d2ts" import type { Collection } from "./collection" import type { StandardSchemaV1 } from "@standard-schema/spec" import type { Transaction } from "./transactions" @@ -123,3 +124,32 @@ export interface CollectionConfig> { export type ChangesPayload> = Array< ChangeMessage > + +/** + * An input row from a collection + */ +export type InputRow = [unknown, Record] + +/** + * A keyed stream is a stream of rows + * This is used as the inputs from a collection to a query + */ +export type KeyedStream = IStreamBuilder + +/** + * A namespaced row is a row withing a pipeline that had each table wrapped in its alias + */ +export type NamespacedRow = Record> + +/** + * A keyed namespaced row is a row with a key and a namespaced row + * This is the main representation of a row in a query pipeline + */ +export type KeyedNamespacedRow = [unknown, NamespacedRow] + +/** + * A namespaced and keyed stream is a stream of rows + * This is used throughout a query pipeline and as the output from a query without + * a `select` clause. + */ +export type NamespacedAndKeyedStream = IStreamBuilder diff --git a/packages/db/tests/query/compiler.test.ts b/packages/db/tests/query/compiler.test.ts index 699dd8171f..0d98d21cf2 100644 --- a/packages/db/tests/query/compiler.test.ts +++ b/packages/db/tests/query/compiler.test.ts @@ -52,7 +52,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, User]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -66,7 +66,7 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleUsers.map((user) => [user, 1])) + new MultiSet(sampleUsers.map((user) => [[user.id, user], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -83,13 +83,16 @@ describe(`Query`, () => { const results = collection.getInner().map(([data]) => data) // The results should contain objects with only the selected columns - expect(results).toContainEqual({ - id: 1, - name: `Alice`, - age: 25, - email: `alice@example.com`, - active: true, - }) + expect(results).toContainEqual([ + 1, + { + id: 1, + name: `Alice`, + age: 25, + email: `alice@example.com`, + active: true, + }, + ]) }) test(`select with aliased columns`, () => { @@ -99,7 +102,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, User]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -113,7 +116,7 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleUsers.map((user) => [user, 1])) + new MultiSet(sampleUsers.map((user) => [[user.id, user], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -126,15 +129,18 @@ describe(`Query`, () => { .map(([data]) => data) // The results should contain objects with only the selected columns and aliases - expect(results).toContainEqual({ - id: 1, - user_name: `Alice`, - years_old: 25, - }) + expect(results).toContainEqual([ + 1, + { + id: 1, + user_name: `Alice`, + years_old: 25, + }, + ]) // Check that all users are included and have the correct structure expect(results).toHaveLength(4) - results.forEach((result) => { + results.forEach(([_key, result]) => { expect(Object.keys(result).sort()).toEqual( [`id`, `user_name`, `years_old`].sort() ) @@ -149,7 +155,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, User]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -163,7 +169,7 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleUsers.map((user) => [user, 1])) + new MultiSet(sampleUsers.map((user) => [[user.id, user], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -179,12 +185,12 @@ describe(`Query`, () => { expect(results).toHaveLength(3) // Alice, Charlie, Dave // Check that all results have age > 20 - results.forEach((result) => { + results.forEach(([_key, result]) => { expect(result.age).toBeGreaterThan(20) }) // Check that specific users are included - const includedIds = results.map((r) => r.id).sort() + const includedIds = results.map(([_key, r]) => r.id).sort() expect(includedIds).toEqual([1, 3, 4]) // Alice, Charlie, Dave }) @@ -196,7 +202,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, User]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -210,7 +216,7 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleUsers.map((user) => [user, 1])) + new MultiSet(sampleUsers.map((user) => [[user.id, user], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -226,7 +232,7 @@ describe(`Query`, () => { expect(results).toHaveLength(2) // Alice and Dave // Check that specific users are included - const includedIds = results.map((r) => r.id).sort() + const includedIds = results.map(([_key, r]) => r.id).sort() expect(includedIds).toEqual([1, 4]) // Alice and Dave }) }) diff --git a/packages/db/tests/query/conditions.test.ts b/packages/db/tests/query/conditions.test.ts index f0b3513a28..e3cd42340c 100644 --- a/packages/db/tests/query/conditions.test.ts +++ b/packages/db/tests/query/conditions.test.ts @@ -90,7 +90,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -104,7 +104,9 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet( + sampleProducts.map((product) => [[product.id, product], 1]) + ) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -120,7 +122,7 @@ describe(`Query`, () => { expect(results).toHaveLength(3) // Laptop, Smartphone, Headphones // Check that all results have the correct category - results.forEach((result) => { + results.forEach(([_key, result]) => { expect(result.id).toBeLessThanOrEqual(3) }) }) @@ -133,7 +135,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -147,7 +149,9 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet( + sampleProducts.map((product) => [[product.id, product], 1]) + ) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -163,7 +167,7 @@ describe(`Query`, () => { expect(results).toHaveLength(2) // Book and Desk // Check categories - results.forEach((result) => { + results.forEach(([_key, result]) => { expect(result.category).not.toBe(`Electronics`) }) }) @@ -176,7 +180,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -190,7 +194,9 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet( + sampleProducts.map((product) => [[product.id, product], 1]) + ) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -206,7 +212,7 @@ describe(`Query`, () => { expect(results).toHaveLength(2) // Laptop and Smartphone // Check prices - results.forEach((result) => { + results.forEach(([_key, result]) => { expect(result.price).toBeGreaterThan(500) }) }) @@ -225,7 +231,7 @@ describe(`Query`, () => { expect(filteredProducts).toHaveLength(1) const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -239,7 +245,9 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet( + sampleProducts.map((product) => [[product.id, product], 1]) + ) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -253,7 +261,7 @@ describe(`Query`, () => { // Should only include products with a discount expect(results).toHaveLength(1) // Only Smartphone has a discount - expect(results[0].id).toBe(2) + expect(results[0][1].id).toBe(2) }) test(`complex condition with and/or`, () => { @@ -266,7 +274,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -280,7 +288,9 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet( + sampleProducts.map((product) => [[product.id, product], 1]) + ) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -296,7 +306,7 @@ describe(`Query`, () => { expect(results).toHaveLength(3) // Headphones, Book, and Desk // Check prices - results.forEach((result) => { + results.forEach(([_key, result]) => { expect(result.price).toBeLessThan(500) }) }) @@ -316,7 +326,7 @@ describe(`Query`, () => { expect(filteredProducts[0]!.name).toBe(`Headphones`) const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -330,7 +340,9 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet( + sampleProducts.map((product) => [[product.id, product], 1]) + ) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -346,8 +358,8 @@ describe(`Query`, () => { expect(results).toHaveLength(1) // Only Headphones // Check that results match both conditions - expect(results[0].category).toBe(`Electronics`) - expect(results[0].price).toBeLessThan(500) + expect(results[0][1].category).toBe(`Electronics`) + expect(results[0][1].price).toBeLessThan(500) }) test(`composite condition with OR`, () => { @@ -365,7 +377,7 @@ describe(`Query`, () => { expect(filteredProducts).toHaveLength(4) const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -379,7 +391,9 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet( + sampleProducts.map((product) => [[product.id, product], 1]) + ) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -395,7 +409,7 @@ describe(`Query`, () => { expect(results).toHaveLength(4) // Verify that each result matches at least one of the conditions - results.forEach((result) => { + results.forEach(([_key, result]) => { expect(result.category === `Electronics` || result.price < 100).toBe( true ) @@ -434,7 +448,7 @@ describe(`Query`, () => { expect(filteredProducts).toHaveLength(3) const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -448,7 +462,9 @@ describe(`Query`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet( + sampleProducts.map((product) => [[product.id, product], 1]) + ) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -465,11 +481,11 @@ describe(`Query`, () => { expect(results).toHaveLength(3) // Verify that specific IDs are included - const resultIds = results.map((r) => r.id).sort() + const resultIds = results.map(([_key, r]) => r.id).sort() expect(resultIds).toEqual([1, 2, 4]) // Laptop, Smartphone, Book // Verify that each result matches the complex condition - results.forEach((result) => { + results.forEach(([_key, result]) => { const matches = (result.category === `Electronics` && result.price > 200) || result.category === `Books` diff --git a/packages/db/tests/query/function-integration.test.ts b/packages/db/tests/query/function-integration.test.ts index 1769c3caca..2c56095fab 100644 --- a/packages/db/tests/query/function-integration.test.ts +++ b/packages/db/tests/query/function-integration.test.ts @@ -77,7 +77,7 @@ describe(`Query Function Integration`, () => { */ function runQuery(query: Query): Array { const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, User]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -91,7 +91,7 @@ describe(`Query Function Integration`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleUsers.map((user) => [user, 1])) + new MultiSet(sampleUsers.map((user) => [[user.id, user], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -114,14 +114,20 @@ describe(`Query Function Integration`, () => { const results = runQuery(query) expect(results).toHaveLength(4) - expect(results).toContainEqual({ - id: 1, - upper_name: `ALICE`, - }) - expect(results).toContainEqual({ - id: 2, - upper_name: `BOB`, - }) + expect(results).toContainEqual([ + 1, + { + id: 1, + upper_name: `ALICE`, + }, + ]) + expect(results).toContainEqual([ + 2, + { + id: 2, + upper_name: `BOB`, + }, + ]) }) test(`LOWER function`, () => { @@ -133,10 +139,13 @@ describe(`Query Function Integration`, () => { const results = runQuery(query) expect(results).toHaveLength(4) - expect(results).toContainEqual({ - id: 1, - lower_email: `alice@example.com`, - }) + expect(results).toContainEqual([ + 1, + { + id: 1, + lower_email: `alice@example.com`, + }, + ]) }) test(`LENGTH function on string`, () => { @@ -148,16 +157,22 @@ describe(`Query Function Integration`, () => { const results = runQuery(query) expect(results).toHaveLength(4) - expect(results).toContainEqual({ - id: 1, - name: `Alice`, - name_length: 5, - }) - expect(results).toContainEqual({ - id: 3, - name: `Charlie`, - name_length: 7, - }) + expect(results).toContainEqual([ + 1, + { + id: 1, + name: `Alice`, + name_length: 5, + }, + ]) + expect(results).toContainEqual([ + 3, + { + id: 3, + name: `Charlie`, + name_length: 7, + }, + ]) }) test(`CONCAT function`, () => { @@ -172,10 +187,13 @@ describe(`Query Function Integration`, () => { const results = runQuery(query) expect(results).toHaveLength(4) - expect(results).toContainEqual({ - id: 1, - full_details: `Alice (alice@example.com)`, - }) + expect(results).toContainEqual([ + 1, + { + id: 1, + full_details: `Alice (alice@example.com)`, + }, + ]) }) }) @@ -208,7 +226,7 @@ describe(`Query Function Integration`, () => { const results = runQuery(query) expect(results).toHaveLength(1) // Only Charlie is inactive - expect(results[0].status).toBe(`CHARLIE IS INACTIVE`) + expect(results[0][1].status).toBe(`CHARLIE IS INACTIVE`) }) test(`DATE function`, () => { @@ -222,15 +240,15 @@ describe(`Query Function Integration`, () => { expect(results).toHaveLength(4) // Verify that each result has a joined field with a Date object - results.forEach((result) => { + results.forEach(([_, result]) => { expect(result.joined).toBeInstanceOf(Date) }) // Check specific dates - expect(results[0].id).toBe(1) // Alice - expect(results[0].joined.getFullYear()).toBe(2023) - expect(results[0].joined.getMonth()).toBe(0) // January (0-indexed) - expect(results[0].joined.getUTCDate()).toBe(15) + expect(results[0][0]).toBe(1) // Alice + expect(results[0][1].joined.getFullYear()).toBe(2023) + expect(results[0][1].joined.getMonth()).toBe(0) // January (0-indexed) + expect(results[0][1].joined.getUTCDate()).toBe(15) }) }) @@ -248,16 +266,22 @@ describe(`Query Function Integration`, () => { const results = runQuery(query) expect(results).toHaveLength(4) - expect(results).toContainEqual({ - id: 1, - name: `Alice`, - theme: `dark`, - }) - expect(results).toContainEqual({ - id: 2, - name: `Bob`, - theme: `light`, - }) + expect(results).toContainEqual([ + 1, + { + id: 1, + name: `Alice`, + theme: `dark`, + }, + ]) + expect(results).toContainEqual([ + 2, + { + id: 2, + name: `Bob`, + theme: `light`, + }, + ]) }) test(`JSON_EXTRACT_PATH function (alias)`, () => { @@ -278,13 +302,16 @@ describe(`Query Function Integration`, () => { expect(results).toHaveLength(3) // Alice, Bob, Dave // Bob has notifications disabled - expect(results).toContainEqual({ - id: 2, - notifications_enabled: false, - }) + expect(results).toContainEqual([ + 2, + { + id: 2, + notifications_enabled: false, + }, + ]) // Alice and Dave have notifications enabled expect( - results.filter((r) => r.notifications_enabled === true).length + results.filter(([_, r]) => r.notifications_enabled === true).length ).toBe(2) }) }) @@ -300,8 +327,8 @@ describe(`Query Function Integration`, () => { const results = runQuery(query) expect(results).toHaveLength(1) - expect(results[0].id).toBe(2) - expect(results[0].name).toBe(`Bob`) + expect(results[0][0]).toBe(2) + expect(results[0][1].name).toBe(`Bob`) }) test(`Filter with LENGTH function`, () => { @@ -314,8 +341,8 @@ describe(`Query Function Integration`, () => { const results = runQuery(query) expect(results).toHaveLength(1) - expect(results[0].id).toBe(3) - expect(results[0].name).toBe(`Charlie`) + expect(results[0][0]).toBe(3) + expect(results[0][1].name).toBe(`Charlie`) }) test(`Filter with JSON_EXTRACT function`, () => { @@ -328,7 +355,7 @@ describe(`Query Function Integration`, () => { const results = runQuery(query) expect(results).toHaveLength(2) // Alice and Dave - expect(results.map((r) => r.id).sort()).toEqual([1, 4]) + expect(results.map(([id]) => id).sort()).toEqual([1, 4]) }) test(`Complex filter with multiple functions`, () => { @@ -351,18 +378,18 @@ describe(`Query Function Integration`, () => { // It turns out both Alice and Dave match our criteria expect(results).toHaveLength(2) // Sort results by ID for consistent testing - const sortedResults = [...results].sort((a, b) => a.id - b.id) + const sortedResults = [...results].sort((a, b) => a[1].id - b[1].id) // Check that Alice is included - expect(sortedResults[0].id).toBe(1) - expect(sortedResults[0].name).toBe(`Alice`) + expect(sortedResults[0][0]).toBe(1) + expect(sortedResults[0][1].name).toBe(`Alice`) // Check that Dave is included - expect(sortedResults[1].id).toBe(4) - expect(sortedResults[1].name).toBe(`Dave`) + expect(sortedResults[1][0]).toBe(4) + expect(sortedResults[1][1].name).toBe(`Dave`) // Verify that both users have name length < 6 and notifications enabled - results.forEach((result) => { + results.forEach(([_, result]) => { expect(result.name.length).toBeLessThan(6) // We could also verify the JSON data directly if needed }) diff --git a/packages/db/tests/query/group-by.test.ts b/packages/db/tests/query/group-by.test.ts index 10fccc541c..62d32d85d1 100644 --- a/packages/db/tests/query/group-by.test.ts +++ b/packages/db/tests/query/group-by.test.ts @@ -22,12 +22,15 @@ type Context = { } type Result = [ - { - customer_id: number - status: string - total_amount: number - order_count: number - }, + [ + string, + { + customer_id: number + status: string + total_amount: number + order_count: number + }, + ], number, ] @@ -101,7 +104,7 @@ describe(`D2QL GROUP BY`, () => { // Send the sample data to the input for (const order of orders) { - ordersInput.sendData(v([1]), new MultiSet([[order, 1]])) + ordersInput.sendData(v([1]), new MultiSet([[[order.order_id, order], 1]])) } // Close the input by sending a frontier update @@ -140,27 +143,36 @@ describe(`D2QL GROUP BY`, () => { const expected = [ [ - { - customer_id: 1, - total_amount: 300, - order_count: 2, - }, + [ + `{"customer_id":1}`, + { + customer_id: 1, + total_amount: 300, + order_count: 2, + }, + ], 1, ], [ - { - customer_id: 2, - total_amount: 450, - order_count: 2, - }, + [ + `{"customer_id":2}`, + { + customer_id: 2, + total_amount: 450, + order_count: 2, + }, + ], 1, ], [ - { - customer_id: 3, - total_amount: 250, - order_count: 1, - }, + [ + `{"customer_id":3}`, + { + customer_id: 3, + total_amount: 250, + order_count: 1, + }, + ], 1, ], ] @@ -190,46 +202,58 @@ describe(`D2QL GROUP BY`, () => { const expected: Array = [ [ - { - customer_id: 1, - status: `completed`, - total_amount: 300, - order_count: 2, - }, + [ + `{"customer_id":1,"status":"completed"}`, + { + customer_id: 1, + status: `completed`, + total_amount: 300, + order_count: 2, + }, + ], 1, ], [ - { - customer_id: 2, - status: `completed`, - total_amount: 300, - order_count: 1, - }, + [ + `{"customer_id":2,"status":"completed"}`, + { + customer_id: 2, + status: `completed`, + total_amount: 300, + order_count: 1, + }, + ], 1, ], [ - { - customer_id: 2, - status: `pending`, - total_amount: 150, - order_count: 1, - }, + [ + `{"customer_id":2,"status":"pending"}`, + { + customer_id: 2, + status: `pending`, + total_amount: 150, + order_count: 1, + }, + ], 1, ], [ - { - customer_id: 3, - status: `pending`, - total_amount: 250, - order_count: 1, - }, + [ + `{"customer_id":3,"status":"pending"}`, + { + customer_id: 3, + status: `pending`, + total_amount: 250, + order_count: 1, + }, + ], 1, ], ] result - .sort((a, b) => a[0].customer_id - b[0].customer_id) - .sort((a, b) => a[0].status.localeCompare(b[0].status)) + .sort((a, b) => a[0][1].customer_id - b[0][1].customer_id) + .sort((a, b) => a[0][1].status.localeCompare(b[0][1].status)) expect(result).toEqual(expected) }) @@ -266,37 +290,46 @@ describe(`D2QL GROUP BY`, () => { const expected: Array = [ [ - { - customer_id: 1, - status: `completed`, - total_amount: 300, - order_count: 2, - }, + [ + `{"customer_id":1,"status":"completed"}`, + { + customer_id: 1, + status: `completed`, + total_amount: 300, + order_count: 2, + }, + ], 1, ], [ - { - customer_id: 2, - status: `completed`, - total_amount: 300, - order_count: 1, - }, + [ + `{"customer_id":2,"status":"completed"}`, + { + customer_id: 2, + status: `completed`, + total_amount: 300, + order_count: 1, + }, + ], 1, ], [ - { - customer_id: 3, - status: `pending`, - total_amount: 250, - order_count: 1, - }, + [ + `{"customer_id":3,"status":"pending"}`, + { + customer_id: 3, + status: `pending`, + total_amount: 250, + order_count: 1, + }, + ], 1, ], ] result - .sort((a, b) => a[0].customer_id - b[0].customer_id) - .sort((a, b) => a[0].status.localeCompare(b[0].status)) + .sort((a, b) => a[0][1].customer_id - b[0][1].customer_id) + .sort((a, b) => a[0][1].status.localeCompare(b[0][1].status)) expect(result).toEqual(expected) }) @@ -325,42 +358,51 @@ describe(`D2QL GROUP BY`, () => { const expected = [ [ - { - customer_id: 1, - total_amount: 300, - avg_amount: 150, - min_amount: 100, - max_amount: 200, - order_count: 2, - }, + [ + `{"customer_id":1}`, + { + customer_id: 1, + total_amount: 300, + avg_amount: 150, + min_amount: 100, + max_amount: 200, + order_count: 2, + }, + ], 1, ], [ - { - customer_id: 2, - total_amount: 450, - avg_amount: 225, - min_amount: 150, - max_amount: 300, - order_count: 2, - }, + [ + `{"customer_id":2}`, + { + customer_id: 2, + total_amount: 450, + avg_amount: 225, + min_amount: 150, + max_amount: 300, + order_count: 2, + }, + ], 1, ], [ - { - customer_id: 3, - total_amount: 250, - avg_amount: 250, - min_amount: 250, - max_amount: 250, - order_count: 1, - }, + [ + `{"customer_id":3}`, + { + customer_id: 3, + total_amount: 250, + avg_amount: 250, + min_amount: 250, + max_amount: 250, + order_count: 1, + }, + ], 1, ], ] // Sort by customer_id for consistent comparison - result.sort((a, b) => a[0].customer_id - b[0].customer_id) + result.sort((a, b) => a[0][1].customer_id - b[0][1].customer_id) expect(result).toEqual(expected) }) @@ -387,25 +429,31 @@ describe(`D2QL GROUP BY`, () => { const expected = [ [ - { - customer_id: 1, - total_amount: 300, - order_count: 2, - }, + [ + `{"customer_id":1}`, + { + customer_id: 1, + total_amount: 300, + order_count: 2, + }, + ], 1, ], [ - { - customer_id: 2, - total_amount: 300, - order_count: 1, - }, + [ + `{"customer_id":2}`, + { + customer_id: 2, + total_amount: 300, + order_count: 1, + }, + ], 1, ], ] // Sort by customer_id for consistent comparison - result.sort((a, b) => a[0].customer_id - b[0].customer_id) + result.sort((a, b) => a[0][1].customer_id - b[0][1].customer_id) expect(result).toEqual(expected) }) @@ -431,25 +479,31 @@ describe(`D2QL GROUP BY`, () => { const expected = [ [ - { - status: `completed`, - total_amount: 600, - order_count: 3, - }, + [ + `{"status":"completed"}`, + { + status: `completed`, + total_amount: 600, + order_count: 3, + }, + ], 1, ], [ - { - status: `pending`, - total_amount: 400, - order_count: 2, - }, + [ + `{"status":"pending"}`, + { + status: `pending`, + total_amount: 400, + order_count: 2, + }, + ], 1, ], ] // Sort by status for consistent comparison - result.sort((a, b) => a[0].status.localeCompare(b[0].status)) + result.sort((a, b) => a[0][1].status.localeCompare(b[0][1].status)) expect(result).toEqual(expected) }) diff --git a/packages/db/tests/query/having.test.ts b/packages/db/tests/query/having.test.ts index 55d78933a8..a75bcce5f6 100644 --- a/packages/db/tests/query/having.test.ts +++ b/packages/db/tests/query/having.test.ts @@ -108,7 +108,7 @@ describe(`Query - HAVING Clause`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -122,7 +122,7 @@ describe(`Query - HAVING Clause`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet(sampleProducts.map((product) => [[product.id, product], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -132,7 +132,7 @@ describe(`Query - HAVING Clause`, () => { const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = dataMessages[0]!.data.collection .getInner() - .map(([data]) => data) + .map(([data]) => data[1]) expect(results).toHaveLength(4) expect(results.every((p) => p.price > 300)).toBe(true) @@ -152,7 +152,7 @@ describe(`Query - HAVING Clause`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -166,7 +166,7 @@ describe(`Query - HAVING Clause`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet(sampleProducts.map((product) => [[product.id, product], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -176,7 +176,7 @@ describe(`Query - HAVING Clause`, () => { const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = dataMessages[0]!.data.collection .getInner() - .map(([data]) => data) + .map(([data]) => data[1]) expect(results).toHaveLength(3) expect(results.every((p) => p.inStock === true)).toBe(true) @@ -201,7 +201,7 @@ describe(`Query - HAVING Clause`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -215,7 +215,7 @@ describe(`Query - HAVING Clause`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet(sampleProducts.map((product) => [[product.id, product], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -225,7 +225,7 @@ describe(`Query - HAVING Clause`, () => { const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = dataMessages[0]!.data.collection .getInner() - .map(([data]) => data) + .map(([data]) => data[1]) expect(results).toHaveLength(2) @@ -255,7 +255,7 @@ describe(`Query - HAVING Clause`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -269,7 +269,7 @@ describe(`Query - HAVING Clause`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet(sampleProducts.map((product) => [[product.id, product], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -279,7 +279,7 @@ describe(`Query - HAVING Clause`, () => { const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = dataMessages[0]!.data.collection .getInner() - .map(([data]) => data) + .map(([data]) => data[1]) // Expected: inexpensive electronics or in-stock furniture expect(results).toHaveLength(3) diff --git a/packages/db/tests/query/in-operator.test.ts b/packages/db/tests/query/in-operator.test.ts index a18d763a95..9dbed5b9b5 100644 --- a/packages/db/tests/query/in-operator.test.ts +++ b/packages/db/tests/query/in-operator.test.ts @@ -86,7 +86,7 @@ describe(`Query - IN Operator`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, TestItem]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -98,14 +98,17 @@ describe(`Query - IN Operator`, () => { graph.finalize() - input.sendData(v([1, 0]), new MultiSet(testData.map((item) => [item, 1]))) + input.sendData( + v([1, 0]), + new MultiSet(testData.map((item) => [[item.id, item], 1])) + ) input.sendFrontier(new Antichain([v([1, 0])])) graph.run() const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = - dataMessages[0]?.data.collection.getInner().map(([data]) => data) || [] + dataMessages[0]?.data.collection.getInner().map(([data]) => data[1]) || [] // Should return items in Electronics or Books categories (1, 2, 4, 5) expect(results).toHaveLength(4) @@ -120,7 +123,7 @@ describe(`Query - IN Operator`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, TestItem]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -132,14 +135,17 @@ describe(`Query - IN Operator`, () => { graph.finalize() - input.sendData(v([1, 0]), new MultiSet(testData.map((item) => [item, 1]))) + input.sendData( + v([1, 0]), + new MultiSet(testData.map((item) => [[item.id, item], 1])) + ) input.sendFrontier(new Antichain([v([1, 0])])) graph.run() const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = - dataMessages[0]?.data.collection.getInner().map(([data]) => data) || [] + dataMessages[0]?.data.collection.getInner().map(([data]) => data[1]) || [] // Should NOT match 'Electronics' or 'Books' with lowercase 'electronics' and 'books' // (case-sensitive matching) @@ -154,7 +160,7 @@ describe(`Query - IN Operator`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, TestItem]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -166,14 +172,17 @@ describe(`Query - IN Operator`, () => { graph.finalize() - input.sendData(v([1, 0]), new MultiSet(testData.map((item) => [item, 1]))) + input.sendData( + v([1, 0]), + new MultiSet(testData.map((item) => [[item.id, item], 1])) + ) input.sendFrontier(new Antichain([v([1, 0])])) graph.run() const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = - dataMessages[0]?.data.collection.getInner().map(([data]) => data) || [] + dataMessages[0]?.data.collection.getInner().map(([data]) => data[1]) || [] // Should return items NOT in Electronics or Books categories (just Furniture - id 3) expect(results).toHaveLength(1) @@ -189,7 +198,7 @@ describe(`Query - IN Operator`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, TestItem]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -201,14 +210,17 @@ describe(`Query - IN Operator`, () => { graph.finalize() - input.sendData(v([1, 0]), new MultiSet(testData.map((item) => [item, 1]))) + input.sendData( + v([1, 0]), + new MultiSet(testData.map((item) => [[item.id, item], 1])) + ) input.sendFrontier(new Antichain([v([1, 0])])) graph.run() const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = - dataMessages[0]?.data.collection.getInner().map(([data]) => data) || [] + dataMessages[0]?.data.collection.getInner().map(([data]) => data[1]) || [] // Should return items with IDs 1, 2, and 3, despite string vs number difference expect(results).toHaveLength(3) @@ -231,7 +243,7 @@ describe(`Query - IN Operator`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, TestItem]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -243,14 +255,17 @@ describe(`Query - IN Operator`, () => { graph.finalize() - input.sendData(v([1, 0]), new MultiSet(testData.map((item) => [item, 1]))) + input.sendData( + v([1, 0]), + new MultiSet(testData.map((item) => [[item.id, item], 1])) + ) input.sendFrontier(new Antichain([v([1, 0])])) graph.run() const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = - dataMessages[0]?.data.collection.getInner().map(([data]) => data) || [] + dataMessages[0]?.data.collection.getInner().map(([data]) => data[1]) || [] // TODO: Finish this test! }) @@ -263,7 +278,7 @@ describe(`Query - IN Operator`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, TestItem]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -275,14 +290,17 @@ describe(`Query - IN Operator`, () => { graph.finalize() - input.sendData(v([1, 0]), new MultiSet(testData.map((item) => [item, 1]))) + input.sendData( + v([1, 0]), + new MultiSet(testData.map((item) => [[item.id, item], 1])) + ) input.sendFrontier(new Antichain([v([1, 0])])) graph.run() const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = - dataMessages[0]?.data.collection.getInner().map(([data]) => data) || [] + dataMessages[0]?.data.collection.getInner().map(([data]) => data[1]) || [] // Should return items with isActive that is null/undefined or false (items 3 and 5) expect(results).toHaveLength(2) @@ -310,7 +328,7 @@ describe(`Query - IN Operator`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, TestItem]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -322,14 +340,17 @@ describe(`Query - IN Operator`, () => { graph.finalize() - input.sendData(v([1, 0]), new MultiSet(testData.map((item) => [item, 1]))) + input.sendData( + v([1, 0]), + new MultiSet(testData.map((item) => [[item.id, item], 1])) + ) input.sendFrontier(new Antichain([v([1, 0])])) graph.run() const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = - dataMessages[0]?.data.collection.getInner().map(([data]) => data) || [] + dataMessages[0]?.data.collection.getInner().map(([data]) => data[1]) || [] // TODO: Finish this test! }) @@ -342,7 +363,7 @@ describe(`Query - IN Operator`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, TestItem]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -354,14 +375,17 @@ describe(`Query - IN Operator`, () => { graph.finalize() - input.sendData(v([1, 0]), new MultiSet(testData.map((item) => [item, 1]))) + input.sendData( + v([1, 0]), + new MultiSet(testData.map((item) => [[item.id, item], 1])) + ) input.sendFrontier(new Antichain([v([1, 0])])) graph.run() const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = - dataMessages[0]?.data.collection.getInner().map(([data]) => data) || [] + dataMessages[0]?.data.collection.getInner().map(([data]) => data[1]) || [] // Nothing should be in an empty array expect(results).toHaveLength(0) @@ -379,7 +403,7 @@ describe(`Query - IN Operator`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, TestItem]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -391,14 +415,17 @@ describe(`Query - IN Operator`, () => { graph.finalize() - input.sendData(v([1, 0]), new MultiSet(testData.map((item) => [item, 1]))) + input.sendData( + v([1, 0]), + new MultiSet(testData.map((item) => [[item.id, item], 1])) + ) input.sendFrontier(new Antichain([v([1, 0])])) graph.run() const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = - dataMessages[0]?.data.collection.getInner().map(([data]) => data) || [] + dataMessages[0]?.data.collection.getInner().map(([data]) => data[1]) || [] // Should return items that are in category Electronics or Books AND have price > 100 // This matches items 1, 2, and 5: diff --git a/packages/db/tests/query/join.test.ts b/packages/db/tests/query/join.test.ts index 651aee528f..285707945d 100644 --- a/packages/db/tests/query/join.test.ts +++ b/packages/db/tests/query/join.test.ts @@ -156,8 +156,8 @@ describe(`Query - JOIN Clauses`, () => { const graph = new D2({ initialFrontier: 0 }) // Create inputs for each table - const mainInput = graph.newInput() - const inputs: Record> = { + const mainInput = graph.newInput<[number, T]>() + const inputs: Record> = { [query.from]: mainInput, } @@ -165,7 +165,7 @@ describe(`Query - JOIN Clauses`, () => { if (query.join) { for (const joinClause of query.join) { const tableName = joinClause.from - inputs[tableName] = graph.newInput() + inputs[tableName] = graph.newInput<[number, any]>() } } @@ -177,7 +177,9 @@ describe(`Query - JOIN Clauses`, () => { pipeline.pipe( output((message) => { if (message.type === MessageType.DATA) { - const data = message.data.collection.getInner().map(([item]) => item) + const data = message.data.collection + .getInner() + .map(([item]: [any, any]) => item[1]) results.push(...data) } }) @@ -187,7 +189,7 @@ describe(`Query - JOIN Clauses`, () => { graph.finalize() // Send data to the main input - mainInput.sendData(0, new MultiSet(mainData.map((d) => [d, 1]))) + mainInput.sendData(0, new MultiSet(mainData.map((d) => [[d.id, d], 1]))) mainInput.sendFrontier(1) // Send data to the joined inputs @@ -198,7 +200,7 @@ describe(`Query - JOIN Clauses`, () => { const input = inputs[tableName] if (input && data.length > 0) { - input.sendData(0, new MultiSet(data.map((d) => [d, 1]))) + input.sendData(0, new MultiSet(data.map((d) => [[d.id, d], 1]))) input.sendFrontier(1) } } @@ -431,85 +433,4 @@ describe(`Query - JOIN Clauses`, () => { expect(results[0].price).toBeDefined() expect(results[0].quantity).toBeDefined() }) - - it(`should support filtering with WHERE on joined data`, () => { - const query: Query = { - select: [ - { - order_id: `@orders.id`, - user_name: `@users.name`, - product_name: `@products.name`, - category: `@products.category`, - }, - ], - from: `orders`, - join: [ - { - type: `inner`, - from: `users`, - on: [`@orders.userId`, `=`, `@users.id`], - }, - { - type: `inner`, - from: `products`, - on: [`@orders.productId`, `=`, `@products.id`], - }, - ], - // Filter to only include electronics orders - where: [`@products.category`, `=`, `Electronics`], - } - - const results = runQueryWithJoins(orders, query, { - users, - products, - }) - - // Only 3 orders are for electronic products - expect(results).toHaveLength(3) - - // All results should be for electronics - for (const result of results) { - expect(result.category).toBe(`Electronics`) - } - }) - - it(`should support filtering with a WHERE clause on the join`, () => { - const query: Query = { - select: [ - { - order_id: `@orders.id`, - user_name: `@users.name`, - product_name: `@products.name`, - }, - ], - from: `orders`, - join: [ - { - type: `inner`, - from: `users`, - on: [`@orders.userId`, `=`, `@users.id`], - // Only join with admin users - where: [`@users.role`, `=`, `admin`], - }, - { - type: `inner`, - from: `products`, - on: [`@orders.productId`, `=`, `@products.id`], - }, - ], - } - - const results = runQueryWithJoins(orders, query, { - users, - products, - }) - - // Only 2 orders were placed by admin users (Alice) - expect(results).toHaveLength(2) - - // All results should be for the admin user - for (const result of results) { - expect(result.user_name).toBe(`Alice Johnson`) - } - }) }) diff --git a/packages/db/tests/query/key-by.test.ts b/packages/db/tests/query/key-by.test.ts deleted file mode 100644 index ecfde72f90..0000000000 --- a/packages/db/tests/query/key-by.test.ts +++ /dev/null @@ -1,419 +0,0 @@ -import { describe, expect, test } from "vitest" -import { - Antichain, - D2, - MessageType, - MultiSet, - output, - v, -} from "@electric-sql/d2ts" -import { compileQueryPipeline } from "../../src/query/pipeline-compiler.js" -import type { Query } from "../../src/query/schema.js" -import type { Keyed, Message } from "@electric-sql/d2ts" - -// Sample user type for tests -type User = { - id: number - name: string - age: number - email: string - active: boolean - metadata: { - createdAt: string - tags: Array - } -} - -type Context = { - baseSchema: { - users: User - } - schema: { - users: User - } -} - -// Sample data for tests -const sampleUsers: Array = [ - { - id: 1, - name: `Alice`, - age: 25, - email: `alice@example.com`, - active: true, - metadata: { - createdAt: `2023-01-01`, - tags: [`admin`, `user`], - }, - }, - { - id: 2, - name: `Bob`, - age: 19, - email: `bob@example.com`, - active: true, - metadata: { - createdAt: `2023-02-15`, - tags: [`user`], - }, - }, - { - id: 3, - name: `Charlie`, - age: 30, - email: `charlie@example.com`, - active: false, - metadata: { - createdAt: `2023-03-20`, - tags: [`user`, `tester`], - }, - }, - { - id: 4, - name: `Dave`, - age: 22, - email: `dave@example.com`, - active: true, - metadata: { - createdAt: `2023-04-10`, - tags: [`user`], - }, - }, -] - -describe(`Query keyBy`, () => { - test(`keyBy with a single string column`, () => { - const query: Query = { - select: [`@id`, `@name`, `@age`, `@email`], - from: `users`, - keyBy: `@id`, - } - - const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() - 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(sampleUsers.map((user) => [user, 1])) - ) - input.sendFrontier(new Antichain([v([1, 0])])) - - graph.run() - - // Check that we have the correct number of messages - const dataMessages = messages.filter((m) => m.type === MessageType.DATA) - expect(dataMessages).toHaveLength(1) - - // Get the keyed data from the message - const keyedData = dataMessages[0]!.data.collection.getInner() - expect(keyedData).toHaveLength(4) - - // Check that the data is keyed by id - keyedData.forEach(([keyedItem]) => { - const [key, value] = keyedItem as Keyed> - - // The key should be a number (the id) - expect(typeof key).toBe(`number`) - - // The value should have the id, name, age, and email properties - expect(value).toHaveProperty(`id`, key) - expect(value).toHaveProperty(`name`) - expect(value).toHaveProperty(`age`) - expect(value).toHaveProperty(`email`) - - // Verify that the key matches the id in the value - expect(key).toBe(value.id) - }) - }) - - test(`keyBy with a single numeric column`, () => { - const query: Query = { - select: [`@id`, `@name`, `@age`, `@email`], - from: `users`, - keyBy: `@age`, - } - - const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() - 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(sampleUsers.map((user) => [user, 1])) - ) - input.sendFrontier(new Antichain([v([1, 0])])) - - graph.run() - - // Get the keyed data from the message - const dataMessages = messages.filter((m) => m.type === MessageType.DATA) - const keyedData = dataMessages[0]!.data.collection.getInner() - - // Check that the data is keyed by age - keyedData.forEach(([keyedItem]) => { - const [key, value] = keyedItem as Keyed> - - // The key should be a number (the age) - expect(typeof key).toBe(`number`) - - // Verify that the key matches the age in the value - expect(key).toBe(value.age) - }) - }) - - test(`keyBy with a complex object column (JSON serialized)`, () => { - const query: Query = { - select: [`@id`, `@name`, `@metadata`], - from: `users`, - keyBy: `@metadata`, - } - - const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() - 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(sampleUsers.map((user) => [user, 1])) - ) - input.sendFrontier(new Antichain([v([1, 0])])) - - graph.run() - - // Get the keyed data from the message - const dataMessages = messages.filter((m) => m.type === MessageType.DATA) - const keyedData = dataMessages[0]!.data.collection.getInner() - - // Check that the data is keyed by metadata (serialized) - keyedData.forEach(([keyedItem]) => { - const [key, value] = keyedItem as Keyed> - - // The key should be a string (serialized metadata) - expect(typeof key).toBe(`string`) - - // We should be able to parse it back to an object - const parsedKey = JSON.parse(key) - expect(parsedKey).toHaveProperty(`createdAt`) - expect(parsedKey).toHaveProperty(`tags`) - - // The parsed key should match the metadata in the value - expect(parsedKey).toEqual(value.metadata) - }) - }) - - test(`keyBy with multiple columns`, () => { - const query: Query = { - select: [`@id`, `@name`, `@age`, `@active`], - from: `users`, - keyBy: [`@name`, `@age`], - } - - const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() - 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(sampleUsers.map((user) => [user, 1])) - ) - input.sendFrontier(new Antichain([v([1, 0])])) - - graph.run() - - // Get the keyed data from the message - const dataMessages = messages.filter((m) => m.type === MessageType.DATA) - const keyedData = dataMessages[0]!.data.collection.getInner() - - // Check that the data is keyed by name and age - keyedData.forEach(([keyedItem]) => { - const [key, value] = keyedItem as Keyed> - - // The key should be a string (serialized object with name and age) - expect(typeof key).toBe(`string`) - - // We should be able to parse it back to an object - const parsedKey = JSON.parse(key) - expect(parsedKey).toHaveProperty(`name`) - expect(parsedKey).toHaveProperty(`age`) - - // The parsed key should match the name and age in the value - expect(parsedKey.name).toBe(value.name) - expect(parsedKey.age).toBe(value.age) - }) - }) - - test(`keyBy with wildcard select`, () => { - const query: Query = { - select: [`@*`], - from: `users`, - keyBy: `@id`, - } - - const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() - 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(sampleUsers.map((user) => [user, 1])) - ) - input.sendFrontier(new Antichain([v([1, 0])])) - - graph.run() - - // Get the keyed data from the message - const dataMessages = messages.filter((m) => m.type === MessageType.DATA) - const keyedData = dataMessages[0]!.data.collection.getInner() - - // Check that the data is keyed by id - keyedData.forEach(([keyedItem]) => { - const [key, value] = keyedItem as Keyed> - - // The key should be a number (the id) - expect(typeof key).toBe(`number`) - - // The value should have all properties - expect(value).toHaveProperty(`id`, key) - expect(value).toHaveProperty(`name`) - expect(value).toHaveProperty(`age`) - expect(value).toHaveProperty(`email`) - expect(value).toHaveProperty(`active`) - expect(value).toHaveProperty(`metadata`) - }) - }) - - test(`keyBy with column not in select throws error`, () => { - const query: Query = { - select: [`@id`, `@name`], - from: `users`, - keyBy: `@age`, // age is not in select - } - - const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() - - // This should throw an error - expect(() => { - const pipeline = compileQueryPipeline(query, { [query.from]: input }) - - pipeline.pipe(output(() => {})) - - graph.finalize() - - input.sendData( - v([1, 0]), - new MultiSet(sampleUsers.map((user) => [user, 1])) - ) - input.sendFrontier(new Antichain([v([1, 0])])) - - graph.run() - }).toThrow(/Key column "age" not found in result set/) - }) - - test(`keyBy with filtered data`, () => { - const query: Query = { - select: [`@id`, `@name`, `@age`, `@active`], - from: `users`, - where: [`@age`, `>`, 20], - keyBy: `@id`, - } - - const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() - 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(sampleUsers.map((user) => [user, 1])) - ) - input.sendFrontier(new Antichain([v([1, 0])])) - - graph.run() - - // Get the keyed data from the message - const dataMessages = messages.filter((m) => m.type === MessageType.DATA) - const keyedData = dataMessages[0]!.data.collection.getInner() - - // Should only have users with age > 20 - expect(keyedData).toHaveLength(3) // Alice, Charlie, Dave - - // Check that the data is keyed by id and filtered correctly - keyedData.forEach(([keyedItem]) => { - const [key, value] = keyedItem as Keyed> - - // The key should be a number (the id) - expect(typeof key).toBe(`number`) - - // The value should have age > 20 - expect(Number(value.age)).toBeGreaterThan(20) - - // Verify that the key matches the id in the value - expect(key).toBe(value.id) - }) - - // Check that specific users are included - const includedIds = keyedData - .map(([keyedItem]) => { - const [key] = keyedItem as Keyed> - return key - }) - .sort() - - expect(includedIds).toEqual([1, 3, 4]) // Alice, Charlie, Dave - }) -}) diff --git a/packages/db/tests/query/like-operator.test.ts b/packages/db/tests/query/like-operator.test.ts index 36ad545ca7..abde3b1498 100644 --- a/packages/db/tests/query/like-operator.test.ts +++ b/packages/db/tests/query/like-operator.test.ts @@ -71,7 +71,7 @@ describe(`Query - LIKE Operator`, () => { function runQuery(query: Query): Array { const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, TestItem]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -83,14 +83,17 @@ describe(`Query - LIKE Operator`, () => { graph.finalize() - input.sendData(v([1, 0]), new MultiSet(testData.map((item) => [item, 1]))) + input.sendData( + v([1, 0]), + new MultiSet(testData.map((item) => [[item.id, item], 1])) + ) input.sendFrontier(new Antichain([v([1, 0])])) graph.run() const dataMessages = messages.filter((m) => m.type === MessageType.DATA) return ( - dataMessages[0]?.data.collection.getInner().map(([data]) => data) || [] + dataMessages[0]?.data.collection.getInner().map(([data]) => data[1]) || [] ) } @@ -148,7 +151,7 @@ describe(`Query - LIKE Operator`, () => { // Create a separate graph for this test with our specific SKU test items const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, TestItem]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -163,7 +166,7 @@ describe(`Query - LIKE Operator`, () => { // Use the special SKU test items input.sendData( v([1, 0]), - new MultiSet(skuTestItems.map((item) => [item, 1])) + new MultiSet(skuTestItems.map((item) => [[item.id, item], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -171,7 +174,7 @@ describe(`Query - LIKE Operator`, () => { const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = - dataMessages[0]?.data.collection.getInner().map(([data]) => data) || [] + dataMessages[0]?.data.collection.getInner().map(([data]) => data[1]) || [] // Both 'TECH-ABC-2023' and 'TECH-XYZ-2023' should match 'TECH-___-2023' expect(results).toHaveLength(2) diff --git a/packages/db/tests/query/nested-conditions.test.ts b/packages/db/tests/query/nested-conditions.test.ts index 3caa73461d..3ce022bded 100644 --- a/packages/db/tests/query/nested-conditions.test.ts +++ b/packages/db/tests/query/nested-conditions.test.ts @@ -306,7 +306,7 @@ describe(`Query`, () => { // Helper function to run queries and collect results function runQuery(query: Query): Array { const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -320,7 +320,7 @@ function runQuery(query: Query): Array { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet(sampleProducts.map((product) => [[product.id, product], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -332,5 +332,5 @@ function runQuery(query: Query): Array { return [] } - return dataMessages[0]!.data.collection.getInner().map(([data]) => data) + return dataMessages[0]!.data.collection.getInner().map(([data]) => data[1]) } diff --git a/packages/db/tests/query/order-by.test.ts b/packages/db/tests/query/order-by.test.ts index 979c2d1fa9..05c532dbe9 100644 --- a/packages/db/tests/query/order-by.test.ts +++ b/packages/db/tests/query/order-by.test.ts @@ -38,11 +38,16 @@ describe(`Query`, () => { // Compiling the query should throw an error expect(() => { const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - name: string - age: number - }>() + const input = graph.newInput< + [ + number, + { + id: number + name: string + age: number + }, + ] + >() compileQueryPipeline(query, { users: input }) }).toThrow( `LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results` @@ -59,11 +64,16 @@ describe(`Query`, () => { // Compiling the query should throw an error expect(() => { const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - name: string - age: number - }>() + const input = graph.newInput< + [ + number, + { + id: number + name: string + age: number + }, + ] + >() compileQueryPipeline(query, { users: input }) }).toThrow( `LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results` @@ -79,10 +89,15 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -99,11 +114,11 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `z` }], 1], + [[3, { id: 3, value: `b` }], 1], + [[4, { id: 4, value: `y` }], 1], + [[5, { id: 5, value: `c` }], 1], ]) ) input.sendFrontier(1) @@ -115,624 +130,34 @@ describe(`Query`, () => { const result = latestMessage.collection.getInner() expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) - ).toEqual([ - [{ id: 1, value: `a` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 5, value: `c` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 2, value: `z` }, 1], - ]) - }) - - test(`initial results with limit`, () => { - const query: Query = { - select: [`@id`, `@value`], - from: `input`, - orderBy: `@value`, - limit: 3, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], - ]) - ) - input.sendFrontier(1) - - graph.run() - - expect(latestMessage).not.toBeNull() - - const result = latestMessage.collection.getInner() - - expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) - ).toEqual([ - [{ id: 1, value: `a` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 5, value: `c` }, 1], - ]) - }) - - test(`initial results with limit and offset`, () => { - const query: Query = { - select: [`@id`, `@value`], - from: `input`, - orderBy: `@value`, - limit: 2, - offset: 2, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], - ]) - ) - input.sendFrontier(1) - - graph.run() - - expect(latestMessage).not.toBeNull() - - const result = latestMessage.collection.getInner() - - expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) - ).toEqual([ - [{ id: 5, value: `c` }, 1], - [{ id: 4, value: `y` }, 1], - ]) - }) - - test(`incremental update - adding new rows`, () => { - const query: Query = { - select: [`@id`, `@value`], - from: `input`, - orderBy: `@value`, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - // Initial data - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `c` }, 1], - [{ id: 2, value: `d` }, 1], - [{ id: 3, value: `e` }, 1], - ]) - ) - input.sendFrontier(1) - graph.run() - - // Initial result should be all three items in alphabetical order - let result = latestMessage.collection.getInner() - expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) - ).toEqual([ - [{ id: 1, value: `c` }, 1], - [{ id: 2, value: `d` }, 1], - [{ id: 3, value: `e` }, 1], - ]) - - // Add new rows that should appear in the result - input.sendData( - 1, - new MultiSet([ - [{ id: 4, value: `a` }, 1], - [{ id: 5, value: `b` }, 1], - ]) - ) - input.sendFrontier(2) - graph.run() - - // Result should now include the new rows in the correct order - result = latestMessage.collection.getInner() - - const expectedResult = [ - [{ id: 4, value: `a` }, 1], - [{ id: 5, value: `b` }, 1], - ] - - expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) - ).toEqual(expectedResult) - }) - - test(`incremental update - removing rows`, () => { - const query: Query = { - select: [`@id`, `@value`], - from: `input`, - orderBy: `@value`, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - // Initial data - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `b` }, 1], - [{ id: 3, value: `c` }, 1], - [{ id: 4, value: `d` }, 1], - ]) - ) - input.sendFrontier(1) - graph.run() - - // Initial result should be all four items - let result = latestMessage.collection.getInner() - expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) - ).toEqual([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `b` }, 1], - [{ id: 3, value: `c` }, 1], - [{ id: 4, value: `d` }, 1], - ]) - - // Remove 'b' from the result set - input.sendData(1, new MultiSet([[{ id: 2, value: `b` }, -1]])) - input.sendFrontier(2) - graph.run() - - // Result should show 'b' being removed - result = latestMessage.collection.getInner() - - const expectedResult = [[{ id: 2, value: `b` }, -1]] - - expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) - ).toEqual(expectedResult) - }) - }) - describe(`with no index and keyBy`, () => { - test(`initial results`, () => { - const query: Query = { - select: [`@id`, `@value`], - from: `input`, - keyBy: `@id`, - orderBy: `@value`, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], - ]) - ) - input.sendFrontier(1) - - graph.run() - - expect(latestMessage).not.toBeNull() - - const result = latestMessage.collection.getInner() - - expect( - sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) - ).toEqual([ - [[1, { id: 1, value: `a` }], 1], - [[3, { id: 3, value: `b` }], 1], - [[5, { id: 5, value: `c` }], 1], - [[4, { id: 4, value: `y` }], 1], - [[2, { id: 2, value: `z` }], 1], - ]) - }) - - test(`initial results with limit`, () => { - const query: Query = { - select: [`@id`, `@value`], - from: `input`, - keyBy: `@id`, - orderBy: `@value`, - limit: 3, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], - ]) - ) - input.sendFrontier(1) - - graph.run() - - expect(latestMessage).not.toBeNull() - - const result = latestMessage.collection.getInner() - - expect( - sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) - ).toEqual([ - [[1, { id: 1, value: `a` }], 1], - [[3, { id: 3, value: `b` }], 1], - [[5, { id: 5, value: `c` }], 1], - ]) - }) - - test(`initial results with limit and offset`, () => { - const query: Query = { - select: [`@id`, `@value`], - from: `input`, - keyBy: `@id`, - orderBy: `@value`, - limit: 2, - offset: 2, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], - ]) - ) - input.sendFrontier(1) - - graph.run() - - expect(latestMessage).not.toBeNull() - - const result = latestMessage.collection.getInner() - - expect( - sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) - ).toEqual([ - [[5, { id: 5, value: `c` }], 1], - [[4, { id: 4, value: `y` }], 1], - ]) - }) - - test(`incremental update - adding new rows`, () => { - const query: Query = { - select: [`@id`, `@value`], - from: `input`, - keyBy: `@id`, - orderBy: `@value`, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - // Initial data - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `c` }, 1], - [{ id: 2, value: `d` }, 1], - [{ id: 3, value: `e` }, 1], - ]) - ) - input.sendFrontier(1) - graph.run() - - // Initial result should be all three items in alphabetical order - let result = latestMessage.collection.getInner() - expect( - sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) - ).toEqual([ - [[1, { id: 1, value: `c` }], 1], - [[2, { id: 2, value: `d` }], 1], - [[3, { id: 3, value: `e` }], 1], - ]) - - // Add new rows that should appear in the result - input.sendData( - 1, - new MultiSet([ - [{ id: 4, value: `a` }, 1], - [{ id: 5, value: `b` }, 1], - ]) - ) - input.sendFrontier(2) - graph.run() - - // Result should now include the new rows in the correct order - result = latestMessage.collection.getInner() - const expectedResult = [ - [[4, { id: 4, value: `a` }], 1], - [[5, { id: 5, value: `b` }], 1], - ] - - expect( - sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) - ).toEqual(expectedResult) - }) - - test(`incremental update - removing rows`, () => { - const query: Query = { - select: [`@id`, `@value`], - from: `input`, - keyBy: `@id`, - orderBy: `@value`, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - // Initial data - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `b` }, 1], - [{ id: 3, value: `c` }, 1], - [{ id: 4, value: `d` }, 1], - ]) - ) - input.sendFrontier(1) - graph.run() - - // Initial result should be all four items - let result = latestMessage.collection.getInner() - expect( - sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) - ).toEqual([ - [[1, { id: 1, value: `a` }], 1], - [[2, { id: 2, value: `b` }], 1], - [[3, { id: 3, value: `c` }], 1], - [[4, { id: 4, value: `d` }], 1], - ]) - - // Remove 'b' from the result set - input.sendData(1, new MultiSet([[{ id: 2, value: `b` }, -1]])) - input.sendFrontier(2) - graph.run() - - // Result should show 'b' being removed - result = latestMessage.collection.getInner() - const expectedResult = [[[2, { id: 2, value: `b` }], -1]] - - expect( - sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) - ).toEqual(expectedResult) - }) - }) - describe(`with numeric index`, () => { - test(`initial results`, () => { - const query: Query = { - select: [`@id`, `@value`, { index: { ORDER_INDEX: `numeric` } }], - from: `input`, - orderBy: `@value`, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], - ]) - ) - input.sendFrontier(1) - - graph.run() - - expect(latestMessage).not.toBeNull() - - const result = latestMessage.collection.getInner() - - expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) + sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) ).toEqual([ - [{ id: 1, value: `a`, index: 0 }, 1], - [{ id: 3, value: `b`, index: 1 }, 1], - [{ id: 5, value: `c`, index: 2 }, 1], - [{ id: 4, value: `y`, index: 3 }, 1], - [{ id: 2, value: `z`, index: 4 }, 1], + [[1, { id: 1, value: `a` }], 1], + [[3, { id: 3, value: `b` }], 1], + [[5, { id: 5, value: `c` }], 1], + [[4, { id: 4, value: `y` }], 1], + [[2, { id: 2, value: `z` }], 1], ]) }) test(`initial results with limit`, () => { const query: Query = { - select: [`@id`, `@value`, { index: { ORDER_INDEX: `numeric` } }], + select: [`@id`, `@value`], from: `input`, orderBy: `@value`, limit: 3, } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -749,11 +174,11 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `z` }], 1], + [[3, { id: 3, value: `b` }], 1], + [[4, { id: 4, value: `y` }], 1], + [[5, { id: 5, value: `c` }], 1], ]) ) input.sendFrontier(1) @@ -765,17 +190,17 @@ describe(`Query`, () => { const result = latestMessage.collection.getInner() expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) + sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) ).toEqual([ - [{ id: 1, value: `a`, index: 0 }, 1], - [{ id: 3, value: `b`, index: 1 }, 1], - [{ id: 5, value: `c`, index: 2 }, 1], + [[1, { id: 1, value: `a` }], 1], + [[3, { id: 3, value: `b` }], 1], + [[5, { id: 5, value: `c` }], 1], ]) }) test(`initial results with limit and offset`, () => { const query: Query = { - select: [`@id`, `@value`, { index: { ORDER_INDEX: `numeric` } }], + select: [`@id`, `@value`], from: `input`, orderBy: `@value`, limit: 2, @@ -783,10 +208,15 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -803,11 +233,11 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `z` }], 1], + [[3, { id: 3, value: `b` }], 1], + [[4, { id: 4, value: `y` }], 1], + [[5, { id: 5, value: `c` }], 1], ]) ) input.sendFrontier(1) @@ -819,25 +249,30 @@ describe(`Query`, () => { const result = latestMessage.collection.getInner() expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) + sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) ).toEqual([ - [{ id: 5, value: `c`, index: 2 }, 1], - [{ id: 4, value: `y`, index: 3 }, 1], + [[5, { id: 5, value: `c` }], 1], + [[4, { id: 4, value: `y` }], 1], ]) }) test(`incremental update - adding new rows`, () => { const query: Query = { - select: [`@id`, `@value`, { index: { ORDER_INDEX: `numeric` } }], + select: [`@id`, `@value`], from: `input`, orderBy: `@value`, } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -855,9 +290,9 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `c` }, 1], - [{ id: 2, value: `d` }, 1], - [{ id: 3, value: `e` }, 1], + [[1, { id: 1, value: `c` }], 1], + [[2, { id: 2, value: `d` }], 1], + [[3, { id: 3, value: `e` }], 1], ]) ) input.sendFrontier(1) @@ -866,19 +301,19 @@ describe(`Query`, () => { // Initial result should be all three items in alphabetical order let result = latestMessage.collection.getInner() expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) + sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) ).toEqual([ - [{ id: 1, value: `c`, index: 0 }, 1], - [{ id: 2, value: `d`, index: 1 }, 1], - [{ id: 3, value: `e`, index: 2 }, 1], + [[1, { id: 1, value: `c` }], 1], + [[2, { id: 2, value: `d` }], 1], + [[3, { id: 3, value: `e` }], 1], ]) // Add new rows that should appear in the result input.sendData( 1, new MultiSet([ - [{ id: 4, value: `a` }, 1], - [{ id: 5, value: `b` }, 1], + [[4, { id: 4, value: `a` }], 1], + [[5, { id: 5, value: `b` }], 1], ]) ) input.sendFrontier(2) @@ -888,33 +323,32 @@ describe(`Query`, () => { result = latestMessage.collection.getInner() const expectedResult = [ - [{ id: 4, value: `a`, index: 0 }, 1], - [{ id: 5, value: `b`, index: 1 }, 1], - [{ id: 1, value: `c`, index: 0 }, -1], - [{ id: 1, value: `c`, index: 2 }, 1], - [{ id: 2, value: `d`, index: 1 }, -1], - [{ id: 2, value: `d`, index: 3 }, 1], - [{ id: 3, value: `e`, index: 2 }, -1], - [{ id: 3, value: `e`, index: 4 }, 1], + [[4, { id: 4, value: `a` }], 1], + [[5, { id: 5, value: `b` }], 1], ] expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) + sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) ).toEqual(expectedResult) }) test(`incremental update - removing rows`, () => { const query: Query = { - select: [`@id`, `@value`, { index: { ORDER_INDEX: `numeric` } }], + select: [`@id`, `@value`], from: `input`, orderBy: `@value`, } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -932,10 +366,10 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `b` }, 1], - [{ id: 3, value: `c` }, 1], - [{ id: 4, value: `d` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `b` }], 1], + [[3, { id: 3, value: `c` }], 1], + [[4, { id: 4, value: `d` }], 1], ]) ) input.sendFrontier(1) @@ -944,49 +378,47 @@ describe(`Query`, () => { // Initial result should be all four items let result = latestMessage.collection.getInner() expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) + sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) ).toEqual([ - [{ id: 1, value: `a`, index: 0 }, 1], - [{ id: 2, value: `b`, index: 1 }, 1], - [{ id: 3, value: `c`, index: 2 }, 1], - [{ id: 4, value: `d`, index: 3 }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `b` }], 1], + [[3, { id: 3, value: `c` }], 1], + [[4, { id: 4, value: `d` }], 1], ]) // Remove 'b' from the result set - input.sendData(1, new MultiSet([[{ id: 2, value: `b` }, -1]])) + input.sendData(1, new MultiSet([[[2, { id: 2, value: `b` }], -1]])) input.sendFrontier(2) graph.run() - // Result should show 'b' being removed and indices adjusted + // Result should show 'b' being removed result = latestMessage.collection.getInner() - const expectedResult = [ - [{ id: 2, value: `b`, index: 1 }, -1], - [{ id: 3, value: `c`, index: 2 }, -1], - [{ id: 3, value: `c`, index: 1 }, 1], - [{ id: 4, value: `d`, index: 3 }, -1], - [{ id: 4, value: `d`, index: 2 }, 1], - ] + const expectedResult = [[[2, { id: 2, value: `b` }], -1]] expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) + sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) ).toEqual(expectedResult) }) }) - describe(`with keyBy and numeric index`, () => { + describe(`with numeric index`, () => { test(`initial results`, () => { const query: Query = { select: [`@id`, `@value`, { index: { ORDER_INDEX: `numeric` } }], from: `input`, - keyBy: `@id`, orderBy: `@value`, } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -1003,11 +435,11 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `z` }], 1], + [[3, { id: 3, value: `b` }], 1], + [[4, { id: 4, value: `y` }], 1], + [[5, { id: 5, value: `c` }], 1], ]) ) input.sendFrontier(1) @@ -1033,16 +465,20 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@value`, { index: { ORDER_INDEX: `numeric` } }], from: `input`, - keyBy: `@id`, orderBy: `@value`, limit: 3, } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -1059,11 +495,11 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `z` }], 1], + [[3, { id: 3, value: `b` }], 1], + [[4, { id: 4, value: `y` }], 1], + [[5, { id: 5, value: `c` }], 1], ]) ) input.sendFrontier(1) @@ -1087,17 +523,21 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@value`, { index: { ORDER_INDEX: `numeric` } }], from: `input`, - keyBy: `@id`, orderBy: `@value`, limit: 2, offset: 2, } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -1114,11 +554,11 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `z` }], 1], + [[3, { id: 3, value: `b` }], 1], + [[4, { id: 4, value: `y` }], 1], + [[5, { id: 5, value: `c` }], 1], ]) ) input.sendFrontier(1) @@ -1141,15 +581,19 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@value`, { index: { ORDER_INDEX: `numeric` } }], from: `input`, - keyBy: `@id`, orderBy: `@value`, } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -1167,9 +611,9 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `c` }, 1], - [{ id: 2, value: `d` }, 1], - [{ id: 3, value: `e` }, 1], + [[1, { id: 1, value: `c` }], 1], + [[2, { id: 2, value: `d` }], 1], + [[3, { id: 3, value: `e` }], 1], ]) ) input.sendFrontier(1) @@ -1189,8 +633,8 @@ describe(`Query`, () => { input.sendData( 1, new MultiSet([ - [{ id: 4, value: `a` }, 1], - [{ id: 5, value: `b` }, 1], + [[4, { id: 4, value: `a` }], 1], + [[5, { id: 5, value: `b` }], 1], ]) ) input.sendFrontier(2) @@ -1198,6 +642,7 @@ describe(`Query`, () => { // Result should now include the new rows in the correct order result = latestMessage.collection.getInner() + const expectedResult = [ [[4, { id: 4, value: `a`, index: 0 }], 1], [[5, { id: 5, value: `b`, index: 1 }], 1], @@ -1218,15 +663,19 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@value`, { index: { ORDER_INDEX: `numeric` } }], from: `input`, - keyBy: `@id`, orderBy: `@value`, } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -1244,10 +693,10 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `b` }, 1], - [{ id: 3, value: `c` }, 1], - [{ id: 4, value: `d` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `b` }], 1], + [[3, { id: 3, value: `c` }], 1], + [[4, { id: 4, value: `d` }], 1], ]) ) input.sendFrontier(1) @@ -1265,12 +714,13 @@ describe(`Query`, () => { ]) // Remove 'b' from the result set - input.sendData(1, new MultiSet([[{ id: 2, value: `b` }, -1]])) + input.sendData(1, new MultiSet([[[2, { id: 2, value: `b` }], -1]])) input.sendFrontier(2) graph.run() // Result should show 'b' being removed and indices adjusted result = latestMessage.collection.getInner() + const expectedResult = [ [[2, { id: 2, value: `b`, index: 1 }], -1], [[3, { id: 3, value: `c`, index: 2 }], -1], @@ -1293,10 +743,15 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -1313,11 +768,11 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `z` }], 1], + [[3, { id: 3, value: `b` }], 1], + [[4, { id: 4, value: `y` }], 1], + [[5, { id: 5, value: `c` }], 1], ]) ) input.sendFrontier(1) @@ -1329,13 +784,13 @@ describe(`Query`, () => { const result = latestMessage.collection.getInner() expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) + sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) ).toEqual([ - [{ id: 1, value: `a`, index: `a0` }, 1], - [{ id: 3, value: `b`, index: `a1` }, 1], - [{ id: 5, value: `c`, index: `a2` }, 1], - [{ id: 4, value: `y`, index: `a3` }, 1], - [{ id: 2, value: `z`, index: `a4` }, 1], + [[1, { id: 1, value: `a`, index: `a0` }], 1], + [[3, { id: 3, value: `b`, index: `a1` }], 1], + [[5, { id: 5, value: `c`, index: `a2` }], 1], + [[4, { id: 4, value: `y`, index: `a3` }], 1], + [[2, { id: 2, value: `z`, index: `a4` }], 1], ]) }) @@ -1348,10 +803,15 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -1368,11 +828,11 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `z` }], 1], + [[3, { id: 3, value: `b` }], 1], + [[4, { id: 4, value: `y` }], 1], + [[5, { id: 5, value: `c` }], 1], ]) ) input.sendFrontier(1) @@ -1384,11 +844,11 @@ describe(`Query`, () => { const result = latestMessage.collection.getInner() expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) + sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) ).toEqual([ - [{ id: 1, value: `a`, index: `a0` }, 1], - [{ id: 3, value: `b`, index: `a1` }, 1], - [{ id: 5, value: `c`, index: `a2` }, 1], + [[1, { id: 1, value: `a`, index: `a0` }], 1], + [[3, { id: 3, value: `b`, index: `a1` }], 1], + [[5, { id: 5, value: `c`, index: `a2` }], 1], ]) }) @@ -1402,10 +862,15 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -1422,11 +887,11 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `z` }], 1], + [[3, { id: 3, value: `b` }], 1], + [[4, { id: 4, value: `y` }], 1], + [[5, { id: 5, value: `c` }], 1], ]) ) input.sendFrontier(1) @@ -1438,10 +903,10 @@ describe(`Query`, () => { const result = latestMessage.collection.getInner() expect( - sortResults(result, (a, b) => a.value.localeCompare(b.value)) + sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) ).toEqual([ - [{ id: 5, value: `c`, index: `a0` }, 1], - [{ id: 4, value: `y`, index: `a1` }, 1], + [[5, { id: 5, value: `c`, index: `a0` }], 1], + [[4, { id: 4, value: `y`, index: `a1` }], 1], ]) }) @@ -1449,15 +914,19 @@ describe(`Query`, () => { const query: Query = { select: [`@id`, `@value`, { index: { ORDER_INDEX: `fractional` } }], from: `input`, - keyBy: `@id`, orderBy: `@value`, } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -1475,9 +944,9 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `c` }, 1], - [{ id: 2, value: `d` }, 1], - [{ id: 3, value: `e` }, 1], + [[1, { id: 1, value: `c` }], 1], + [[2, { id: 2, value: `d` }], 1], + [[3, { id: 3, value: `e` }], 1], ]) ) input.sendFrontier(1) @@ -1497,8 +966,8 @@ describe(`Query`, () => { input.sendData( 1, new MultiSet([ - [{ id: 4, value: `a` }, 1], - [{ id: 5, value: `b` }, 1], + [[4, { id: 4, value: `a` }], 1], + [[5, { id: 5, value: `b` }], 1], ]) ) input.sendFrontier(2) @@ -1524,10 +993,15 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() + const input = graph.newInput< + [ + number, + { + id: number + value: string + }, + ] + >() let latestMessage: any = null const pipeline = compileQueryPipeline(query, { input }) @@ -1545,10 +1019,10 @@ describe(`Query`, () => { input.sendData( 0, new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `b` }, 1], - [{ id: 3, value: `c` }, 1], - [{ id: 4, value: `d` }, 1], + [[1, { id: 1, value: `a` }], 1], + [[2, { id: 2, value: `b` }], 1], + [[3, { id: 3, value: `c` }], 1], + [[4, { id: 4, value: `d` }], 1], ]) ) input.sendFrontier(1) @@ -1564,254 +1038,19 @@ describe(`Query`, () => { expect(initialRows.length).toBe(4) // Remove 'b' from the result set - input.sendData(1, new MultiSet([[{ id: 2, value: `b` }, -1]])) + input.sendData(1, new MultiSet([[[2, { id: 2, value: `b` }], -1]])) input.sendFrontier(2) graph.run() // Result should show 'b' being removed result = latestMessage.collection.getInner() - const expectedResult = [[{ id: 2, value: `b`, index: `a1` }, -1]] + const expectedResult = [[[2, { id: 2, value: `b`, index: `a1` }], -1]] expect( sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) ).toEqual(expectedResult) }) }) - describe(`with keyBy and fractional index`, () => { - test(`initial results`, () => { - const query: Query = { - select: [`@id`, `@value`, { index: { ORDER_INDEX: `fractional` } }], - from: `input`, - keyBy: `@id`, - orderBy: `@value`, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], - ]) - ) - input.sendFrontier(1) - - graph.run() - - expect(latestMessage).not.toBeNull() - - const result = latestMessage.collection.getInner() - - expect( - sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) - ).toEqual([ - [[1, { id: 1, value: `a`, index: `a0` }], 1], - [[3, { id: 3, value: `b`, index: `a1` }], 1], - [[5, { id: 5, value: `c`, index: `a2` }], 1], - [[4, { id: 4, value: `y`, index: `a3` }], 1], - [[2, { id: 2, value: `z`, index: `a4` }], 1], - ]) - }) - - test(`initial results with limit`, () => { - const query: Query = { - select: [`@id`, `@value`, { index: { ORDER_INDEX: `fractional` } }], - from: `input`, - keyBy: `@id`, - orderBy: `@value`, - limit: 3, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], - ]) - ) - input.sendFrontier(1) - - graph.run() - - expect(latestMessage).not.toBeNull() - - const result = latestMessage.collection.getInner() - - expect( - sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) - ).toEqual([ - [[1, { id: 1, value: `a`, index: `a0` }], 1], - [[3, { id: 3, value: `b`, index: `a1` }], 1], - [[5, { id: 5, value: `c`, index: `a2` }], 1], - ]) - }) - - test(`initial results with limit and offset`, () => { - const query: Query = { - select: [`@id`, `@value`, { index: { ORDER_INDEX: `fractional` } }], - from: `input`, - keyBy: `@id`, - orderBy: `@value`, - limit: 2, - offset: 2, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `z` }, 1], - [{ id: 3, value: `b` }, 1], - [{ id: 4, value: `y` }, 1], - [{ id: 5, value: `c` }, 1], - ]) - ) - input.sendFrontier(1) - - graph.run() - - expect(latestMessage).not.toBeNull() - - const result = latestMessage.collection.getInner() - - expect( - sortResults(result, (a, b) => a[1].value.localeCompare(b[1].value)) - ).toEqual([ - [[5, { id: 5, value: `c`, index: `a0` }], 1], - [[4, { id: 4, value: `y`, index: `a1` }], 1], - ]) - }) - - test(`incremental update - adding new rows`, () => { - // Skip this test for now due to fractional indexing conflicts - // The issue is with the fractional-indexing library when trying to insert - // values between existing indices - }) - - test(`incremental update - removing rows`, () => { - const query: Query = { - select: [`@id`, `@value`, { index: { ORDER_INDEX: `fractional` } }], - from: `input`, - keyBy: `@id`, - orderBy: `@value`, - } - - const graph = new D2({ initialFrontier: 0 }) - const input = graph.newInput<{ - id: number - value: string - }>() - let latestMessage: any = null - - const pipeline = compileQueryPipeline(query, { input }) - pipeline.pipe( - output((message) => { - if (message.type === MessageType.DATA) { - latestMessage = message.data - } - }) - ) - - graph.finalize() - - // Initial data - input.sendData( - 0, - new MultiSet([ - [{ id: 1, value: `a` }, 1], - [{ id: 2, value: `b` }, 1], - [{ id: 3, value: `c` }, 1], - [{ id: 4, value: `d` }, 1], - ]) - ) - input.sendFrontier(1) - graph.run() - - // Initial result should be all four items - let result = latestMessage.collection.getInner() as Array<[any, number]> - - // Verify initial state - const initialRows = result.filter( - ([_, multiplicity]) => multiplicity === 1 - ) - expect(initialRows.length).toBe(4) - - // Remove 'b' from the result set - input.sendData(1, new MultiSet([[{ id: 2, value: `b` }, -1]])) - input.sendFrontier(2) - graph.run() - - // Result should show 'b' being removed - result = latestMessage.collection.getInner() - - // Verify that a row was removed - const removedRows = result.filter( - ([_, multiplicity]) => multiplicity === -1 - ) - expect(removedRows.length).toBe(1) - expect(removedRows[0]![0][0]).toBe(2) - expect(removedRows[0]![0][1].value).toBe(`b`) - }) - }) }) }) diff --git a/packages/db/tests/query/query-collection.test.ts b/packages/db/tests/query/query-collection.test.ts index dcfc9c0123..196bd31f6b 100644 --- a/packages/db/tests/query/query-collection.test.ts +++ b/packages/db/tests/query/query-collection.test.ts @@ -104,7 +104,6 @@ describe(`Query Collections`, () => { const query = queryBuilder() .from({ collection }) .where(`@age`, `>`, 30) - .keyBy(`@id`) .select(`@id`, `@name`) const compiledQuery = compileQuery(query) @@ -251,7 +250,6 @@ describe(`Query Collections`, () => { on: [`@persons.id`, `=`, `@issues.userId`], }) .select(`@issues.id`, `@issues.title`, `@persons.name`) - .keyBy(`@id`) const compiledQuery = compileQuery(query) compiledQuery.start() @@ -263,19 +261,19 @@ describe(`Query Collections`, () => { // Verify that we have the expected joined results expect(result.state.size).toBe(3) - expect(result.state.get(`1`)).toEqual({ + expect(result.state.get(`[1,1]`)).toEqual({ id: `1`, name: `John Doe`, title: `Issue 1`, }) - expect(result.state.get(`2`)).toEqual({ + expect(result.state.get(`[2,2]`)).toEqual({ id: `2`, name: `Jane Doe`, title: `Issue 2`, }) - expect(result.state.get(`3`)).toEqual({ + expect(result.state.get(`[3,1]`)).toEqual({ id: `3`, name: `John Doe`, title: `Issue 3`, @@ -298,7 +296,7 @@ describe(`Query Collections`, () => { await waitForChanges() expect(result.state.size).toBe(4) - expect(result.state.get(`4`)).toEqual({ + expect(result.state.get(`[4,2]`)).toEqual({ id: `4`, name: `Jane Doe`, title: `Issue 4`, @@ -318,7 +316,7 @@ describe(`Query Collections`, () => { await waitForChanges() // The updated title should be reflected in the joined results - expect(result.state.get(`2`)).toEqual({ + expect(result.state.get(`[2,2]`)).toEqual({ id: `2`, name: `Jane Doe`, title: `Updated Issue 2`, @@ -374,7 +372,6 @@ describe(`Query Collections`, () => { // Test ascending order by age const ascendingQuery = queryBuilder() .from({ collection }) - .keyBy(`@id`) .orderBy(`@age`) .select(`@id`, `@name`, `@age`) @@ -396,7 +393,6 @@ describe(`Query Collections`, () => { // Test descending order by age const descendingQuery = queryBuilder() .from({ collection }) - .keyBy(`@id`) .orderBy({ "@age": `desc` }) .select(`@id`, `@name`, `@age`) @@ -418,7 +414,6 @@ describe(`Query Collections`, () => { // Test multiple order by fields const multiOrderQuery = queryBuilder() .from({ collection }) - .keyBy(`@id`) .orderBy([`@isActive`, { "@age": `asc` }]) .select(`@id`, `@name`, `@age`, `@isActive`) @@ -480,7 +475,6 @@ describe(`Query Collections`, () => { // Create a query that orders by age in ascending order const query = queryBuilder() .from({ collection }) - .keyBy(`@id`) .orderBy(`@age`) .select(`@id`, `@name`, `@age`) @@ -638,7 +632,6 @@ describe(`Query Collections`, () => { on: [`@persons.id`, `=`, `@issues.userId`], }) .select(`@issues.id`, `@issues.title`, `@persons.name`) - .keyBy(`@id`) const compiledQuery = compileQuery(query) compiledQuery.start() @@ -684,17 +677,25 @@ describe(`Query Collections`, () => { // Verify optimistic state is immediately reflected expect(result.state.size).toBe(4) - expect(result.state.get(`temp-key`)).toEqual({ + + // `[temp-key,1]` is the optimistic state for the new issue, its a composite key + // from the join in the query + expect(result.state.get(`[temp-key,1]`)).toEqual({ id: `temp-key`, name: `John Doe`, title: `New Issue`, }) + // `[4,1]` would be the synced state for the new issue, but it's not in the + // optimistic state because the transaction synced back yet + expect(result.state.get(`[4,1]`)).toBeUndefined() + // Wait for the transaction to be committed await tx.isPersisted.promise expect(result.state.size).toBe(4) - expect(result.state.get(`4`)).toBeDefined() + expect(result.state.get(`[temp-key,1]`)).toBeUndefined() + expect(result.state.get(`[4,1]`)).toBeDefined() }) }) diff --git a/packages/db/tests/query/table-alias.test.ts b/packages/db/tests/query/table-alias.test.ts index b62d0a4e14..cf5fd7cfba 100644 --- a/packages/db/tests/query/table-alias.test.ts +++ b/packages/db/tests/query/table-alias.test.ts @@ -86,7 +86,7 @@ describe(`Query - Table Aliasing`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -100,7 +100,7 @@ describe(`Query - Table Aliasing`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet(sampleProducts.map((product) => [[product.id, product], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -110,7 +110,7 @@ describe(`Query - Table Aliasing`, () => { const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = dataMessages[0]!.data.collection .getInner() - .map(([data]) => data) + .map(([data]) => data[1]) expect(results).toHaveLength(4) @@ -131,7 +131,7 @@ describe(`Query - Table Aliasing`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -145,7 +145,7 @@ describe(`Query - Table Aliasing`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet(sampleProducts.map((product) => [[product.id, product], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -155,7 +155,7 @@ describe(`Query - Table Aliasing`, () => { const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = dataMessages[0]!.data.collection .getInner() - .map(([data]) => data) + .map(([data]) => data[1]) expect(results).toHaveLength(2) @@ -175,7 +175,7 @@ describe(`Query - Table Aliasing`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -189,7 +189,7 @@ describe(`Query - Table Aliasing`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet(sampleProducts.map((product) => [[product.id, product], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -199,7 +199,7 @@ describe(`Query - Table Aliasing`, () => { const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = dataMessages[0]!.data.collection .getInner() - .map(([data]) => data) + .map(([data]) => data[1]) expect(results).toHaveLength(2) @@ -229,7 +229,7 @@ describe(`Query - Table Aliasing`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -243,7 +243,7 @@ describe(`Query - Table Aliasing`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet(sampleProducts.map((product) => [[product.id, product], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -253,7 +253,7 @@ describe(`Query - Table Aliasing`, () => { const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = dataMessages[0]!.data.collection .getInner() - .map(([data]) => data) + .map(([data]) => data[1]) // The condition @p.price > 100 AND @inStock = true should match: // - Laptop (price: 1200, inStock: true) @@ -287,7 +287,7 @@ describe(`Query - Table Aliasing`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, Product]>() const pipeline = compileQueryPipeline(query, { [query.from]: input }) const messages: Array> = [] @@ -301,7 +301,7 @@ describe(`Query - Table Aliasing`, () => { input.sendData( v([1, 0]), - new MultiSet(sampleProducts.map((product) => [product, 1])) + new MultiSet(sampleProducts.map((product) => [[product.id, product], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -311,7 +311,7 @@ describe(`Query - Table Aliasing`, () => { const dataMessages = messages.filter((m) => m.type === MessageType.DATA) const results = dataMessages[0]!.data.collection .getInner() - .map(([data]) => data) + .map(([data]) => data[1]) // Should return Smartphone (Electronics < 1000) and Book (Books with rating >= 4.5) expect(results).toHaveLength(2) diff --git a/packages/db/tests/query/wildcard-select.test.ts b/packages/db/tests/query/wildcard-select.test.ts index 60ce1c0f76..a02b53840f 100644 --- a/packages/db/tests/query/wildcard-select.test.ts +++ b/packages/db/tests/query/wildcard-select.test.ts @@ -67,8 +67,8 @@ describe(`Query Wildcard Select`, () => { beforeEach(() => { // Create a new graph for each test graph = new D2({ initialFrontier: v([0]) }) - usersInput = graph.newInput() - ordersInput = graph.newInput() + usersInput = graph.newInput<[number, User]>() + ordersInput = graph.newInput<[number, Order]>() messages = [] }) @@ -84,7 +84,7 @@ describe(`Query Wildcard Select`, () => { for (const message of dataMessages) { const items = message.data.collection .getInner() - .map(([item]: [any, number]) => item) + .map(([item]: [any, number]) => item[1]) allItems.push(...items) } return allItems @@ -109,7 +109,7 @@ describe(`Query Wildcard Select`, () => { // Send the sample data to the input for (const user of sampleUsers) { - usersInput.sendData(v([1]), new MultiSet([[user, 1]])) + usersInput.sendData(v([1]), new MultiSet([[[user.id, user], 1]])) } // Close the input by sending a frontier update @@ -141,12 +141,12 @@ describe(`Query Wildcard Select`, () => { // Send the sample data to the inputs for (const user of sampleUsers) { - usersInput.sendData(v([1]), new MultiSet([[user, 1]])) + usersInput.sendData(v([1]), new MultiSet([[[user.id, user], 1]])) } usersInput.sendFrontier(v([2])) for (const order of sampleOrders) { - ordersInput.sendData(v([1]), new MultiSet([[order, 1]])) + ordersInput.sendData(v([1]), new MultiSet([[[order.id, order], 1]])) } ordersInput.sendFrontier(v([2])) diff --git a/packages/db/tests/query/with.test.ts b/packages/db/tests/query/with.test.ts index 13cfcd7809..e35f9f08a2 100644 --- a/packages/db/tests/query/with.test.ts +++ b/packages/db/tests/query/with.test.ts @@ -67,7 +67,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, User]>() const pipeline = compileQueryPipeline(query, { users: input }) const messages: Array> = [] @@ -82,7 +82,7 @@ describe(`Query`, () => { // Send data to the input input.sendData( v([1, 0]), - new MultiSet(sampleUsers.map((user) => [user, 1])) + new MultiSet(sampleUsers.map((user) => [[user.id, user], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -92,7 +92,7 @@ describe(`Query`, () => { // Check the results const results = messages .filter((m) => m.type === MessageType.DATA) - .flatMap((m) => m.data.collection.getInner().map(([data]) => data)) + .flatMap((m) => m.data.collection.getInner().map(([data]) => data[1])) // Should only include users over 20 expect(results).toHaveLength(3) @@ -132,7 +132,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, User]>() const pipeline = compileQueryPipeline(query, { users: input }) const messages: Array> = [] @@ -147,7 +147,7 @@ describe(`Query`, () => { // Send data to the input input.sendData( v([1, 0]), - new MultiSet(sampleUsers.map((user) => [user, 1])) + new MultiSet(sampleUsers.map((user) => [[user.id, user], 1])) ) input.sendFrontier(new Antichain([v([1, 0])])) @@ -157,7 +157,7 @@ describe(`Query`, () => { // Check the results const results = messages .filter((m) => m.type === MessageType.DATA) - .flatMap((m) => m.data.collection.getInner().map(([data]) => data)) + .flatMap((m) => m.data.collection.getInner().map(([data]) => data[1])) // Should only include active users over 20 expect(results).toHaveLength(2) @@ -182,7 +182,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, User]>() // Should throw an error because the CTE is missing the 'as' property expect(() => { @@ -190,30 +190,6 @@ describe(`Query`, () => { }).toThrow(`WITH query must have an "as" property`) }) - test(`error handling - CTE with keyBy property`, () => { - // Define an invalid query with a CTE that has a keyBy property - const invalidQuery = { - with: [ - { - select: [`@id`, `@name`], - from: `users`, - as: `adult_users`, - keyBy: `@id`, // WithQuery cannot have keyBy - }, - ], - select: [`@id`, `@name`], - from: `adult_users`, - } - - const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() - - // Should throw an error because the CTE has a keyBy property - expect(() => { - compileQueryPipeline(invalidQuery as any, { users: input }) - }).toThrow(`WITH query cannot have a "keyBy" property`) - }) - test(`error handling - duplicate CTE names`, () => { // Define an invalid query with duplicate CTE names const invalidQuery = { @@ -236,7 +212,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, User]>() // Should throw an error because of duplicate CTE names expect(() => { @@ -260,7 +236,7 @@ describe(`Query`, () => { } const graph = new D2({ initialFrontier: v([0, 0]) }) - const input = graph.newInput() + const input = graph.newInput<[number, User]>() // Should throw an error because the referenced CTE doesn't exist expect(() => { From 5ace477e9d04693ac570936ebca4e292f94e3124 Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Sun, 8 Jun 2025 15:47:11 +0100 Subject: [PATCH 2/8] Fix lint --- packages/db/src/query/joins.ts | 9 ++++++--- packages/db/src/query/schema.ts | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/db/src/query/joins.ts b/packages/db/src/query/joins.ts index ecf62d8ce6..4f7ef0b2f3 100644 --- a/packages/db/src/query/joins.ts +++ b/packages/db/src/query/joins.ts @@ -141,7 +141,10 @@ export function processJoinResults( pipeline: IStreamBuilder< [ key: string, - [[string, NamespacedRow], [string, NamespacedRow] | undefined], + [ + [string, NamespacedRow] | undefined, + [string, NamespacedRow] | undefined, + ], ] > ): NamespacedAndKeyedStream { @@ -149,8 +152,8 @@ export function processJoinResults( // Process the join result and handle nulls in the same step map((result) => { const [_key, [main, joined]] = result - const mainKey = main[0] - const mainNamespacedRow = main[1] + const mainKey = main?.[0] + const mainNamespacedRow = main?.[1] const joinedKey = joined?.[0] const joinedNamespacedRow = joined?.[1] diff --git a/packages/db/src/query/schema.ts b/packages/db/src/query/schema.ts index 4bbace57b3..96c90d2d5f 100644 --- a/packages/db/src/query/schema.ts +++ b/packages/db/src/query/schema.ts @@ -216,7 +216,7 @@ export interface BaseQuery { // to expressions. Plain strings starting with "@" denote column references. // Plain string "@*" denotes all columns from all tables. // Plain string "@table.*" denotes all columns from a specific table. - select: Array> + select?: Array> as?: As from: From join?: Array> From 79b7f0dc6ee777780d9d8c72e73201ea98425a3f Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Sun, 8 Jun 2025 15:59:35 +0100 Subject: [PATCH 3/8] remove keyby from docs --- docs/index.md | 3 --- docs/overview.md | 3 --- 2 files changed, 6 deletions(-) diff --git a/docs/index.md b/docs/index.md index 7c9dfd0ecb..baa1f2142b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -279,7 +279,6 @@ const Todos = () => { .where('@completed', '=', false) .orderBy({'@created_at': 'asc'}) .select('@id', '@text') - .keyBy('@id') ) return @@ -302,7 +301,6 @@ const Todos = () => { }) .where('@lists.active', '=', true) .select(`@todos.id`, `@todos.title`, `@lists.name`) - .keyBy('@id') ) return @@ -534,7 +532,6 @@ const Todos = () => { }) .where('@l.active', '=', true) .select('@t.id', '@t.text', '@t.status', '@l.name') - .keyBy('@id') ) // Handle local writes by sending them to your API. diff --git a/docs/overview.md b/docs/overview.md index 0157a6bfa9..1a9ebe2298 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -283,7 +283,6 @@ const Todos = () => { .where('@completed', '=', false) .orderBy({'@created_at': 'asc'}) .select('@id', '@text') - .keyBy('@id') ) return @@ -306,7 +305,6 @@ const Todos = () => { }) .where('@lists.active', '=', true) .select(`@todos.id`, `@todos.title`, `@lists.name`) - .keyBy('@id') ) return @@ -538,7 +536,6 @@ const Todos = () => { }) .where('@l.active', '=', true) .select('@t.id', '@t.text', '@t.status', '@l.name') - .keyBy('@id') ) // Handle local writes by sending them to your API. From a576bd52cb68d4254381934a2f801b11ac0cd8bf Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Sun, 8 Jun 2025 16:16:32 +0100 Subject: [PATCH 4/8] Remove keyBy and fix test, including react and vue tests --- packages/db/src/query/group-by.ts | 4 + packages/db/src/query/order-by.ts | 6 +- packages/db/src/query/query-builder.ts | 19 --- packages/db/src/query/select.ts | 4 + .../tests/query/query-builder/key-by.test.ts | 111 ------------------ .../db/tests/query/query-collection.test.ts | 2 +- packages/react-db/tests/useLiveQuery.test.tsx | 34 +++--- packages/vue-db/tests/useLiveQuery.test.ts | 40 +++---- 8 files changed, 47 insertions(+), 173 deletions(-) delete mode 100644 packages/db/tests/query/query-builder/key-by.test.ts diff --git a/packages/db/src/query/group-by.ts b/packages/db/src/query/group-by.ts index c9ba0a9f03..1a84b638f4 100644 --- a/packages/db/src/query/group-by.ts +++ b/packages/db/src/query/group-by.ts @@ -51,6 +51,10 @@ export function processGroupBy( // Create aggregate functions for any aggregated columns in the SELECT clause const aggregates: Record = {} + if (!query.select) { + throw new Error(`SELECT clause is required for GROUP BY`) + } + // Scan the SELECT clause for aggregate functions for (const item of query.select) { if (typeof item === `object`) { diff --git a/packages/db/src/query/order-by.ts b/packages/db/src/query/order-by.ts index 7356f17080..0ae74e10a1 100644 --- a/packages/db/src/query/order-by.ts +++ b/packages/db/src/query/order-by.ts @@ -24,7 +24,9 @@ export function processOrderBy( let orderIndexAlias = `` // Scan the SELECT clause for ORDER_INDEX functions - for (const item of query.select) { + // TODO: Select is going to be optional in future - we will automatically add an + // attribute for the index column + for (const item of query.select!) { if (typeof item === `object`) { for (const [alias, expr] of Object.entries(item)) { if (typeof expr === `object` && isOrderIndexFunctionCall(expr)) { @@ -230,7 +232,7 @@ export function processOrderBy( ) } } else { - // Use regular orderBy if no index column is requested and but a keyBy is requested + // Use regular orderBy if no index column is requested resultPipeline = resultPipeline.pipe( orderBy(valueExtractor, { limit: query.limit, diff --git a/packages/db/src/query/query-builder.ts b/packages/db/src/query/query-builder.ts index 9042af3fe9..6cf035b008 100644 --- a/packages/db/src/query/query-builder.ts +++ b/packages/db/src/query/query-builder.ts @@ -754,25 +754,6 @@ export class BaseQueryBuilder> { return newBuilder as QueryBuilder } - /** - * Specify which column(s) to use as keys in the output keyed stream. - * - * @param keyBy The column(s) to use as keys - * @returns A new QueryBuilder with the keyBy clause set - */ - keyBy( - keyBy: PropertyReference | Array> - ): QueryBuilder { - // Create a new builder with a copy of the current query - const newBuilder = new BaseQueryBuilder() - Object.assign(newBuilder.query, this.query) - - // Set the keyBy clause - newBuilder.query.keyBy = keyBy - - return newBuilder as QueryBuilder - } - /** * Add a groupBy clause to group the results by one or more columns. * diff --git a/packages/db/src/query/select.ts b/packages/db/src/query/select.ts index f77e3dd270..38fc01fe5d 100644 --- a/packages/db/src/query/select.ts +++ b/packages/db/src/query/select.ts @@ -26,6 +26,10 @@ export function processSelect( typeof namespacedRow[namespaceKey] !== `object` ) + if (!query.select) { + throw new Error(`Cannot process missing SELECT clause`) + } + for (const item of query.select) { if (typeof item === `string`) { // Handle wildcard select - all columns from all tables diff --git a/packages/db/tests/query/query-builder/key-by.test.ts b/packages/db/tests/query/query-builder/key-by.test.ts deleted file mode 100644 index 92fe4d148f..0000000000 --- a/packages/db/tests/query/query-builder/key-by.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { describe, expect, it } from "vitest" -import { queryBuilder } from "../../../src/query/query-builder.js" -import type { Input, Schema } from "../../../src/query/types.js" - -// Test schema -interface Employee extends Input { - id: number - name: string - department_id: number - salary: number -} - -interface Department extends Input { - id: number - name: string - budget: number - location: string -} - -// Make sure TestSchema extends Schema -interface TestSchema extends Schema { - employees: Employee - departments: Department -} - -describe(`QueryBuilder.keyBy`, () => { - it(`sets a single property reference as keyBy`, () => { - const query = queryBuilder() - .from(`employees`) - .select(`@id`, `@name`) - .keyBy(`@id`) - - const builtQuery = query._query - expect(builtQuery.keyBy).toBe(`@id`) - }) - - it(`sets an array of property references as keyBy`, () => { - const query = queryBuilder() - .from(`employees`) - .select(`@id`, `@name`, `@department_id`) - .keyBy([`@id`, `@department_id`]) - - const builtQuery = query._query - expect(builtQuery.keyBy).toEqual([`@id`, `@department_id`]) - }) - - it(`overrides previous keyBy values`, () => { - const query = queryBuilder() - .from(`employees`) - .select(`@id`, `@name`, `@department_id`) - .keyBy(`@id`) - .keyBy(`@department_id`) // This should override - - const builtQuery = query._query - expect(builtQuery.keyBy).toBe(`@department_id`) - }) - - it(`works with joined tables`, () => { - const query = queryBuilder() - .from(`employees`, `e`) - .join({ - type: `inner`, - from: `departments`, - as: `d`, - on: [`@e.department_id`, `=`, `@d.id`], - }) - .select(`@e.id`, `@e.name`, `@d.name`) - .keyBy(`@d.id`) - - const builtQuery = query._query - expect(builtQuery.keyBy).toBe(`@d.id`) - }) - - it(`can be combined with other query methods`, () => { - const query = queryBuilder() - .from(`employees`, `e`) - .join({ - type: `inner`, - from: `departments`, - as: `d`, - on: [`@e.department_id`, `=`, `@d.id`], - }) - .where(`@e.salary`, `>`, 50000) - .select(`@e.id`, `@e.name`, `@d.name`) - .orderBy(`@e.salary`) - .limit(10) - .offset(5) - .keyBy(`@e.id`) - - const builtQuery = query._query - - // Check keyBy - expect(builtQuery.keyBy).toBe(`@e.id`) - - // Also verify all other parts of the query are present - expect(builtQuery.from).toBe(`employees`) - expect(builtQuery.as).toBe(`e`) - expect(builtQuery.join).toBeDefined() - expect(builtQuery.where).toBeDefined() - expect(builtQuery.select).toHaveLength(4) - expect(builtQuery.select).toEqual([ - `@e.id`, - `@e.name`, - `@d.name`, - { _orderByIndex: { ORDER_INDEX: `numeric` } }, // Added by the orderBy method - ]) - expect(builtQuery.orderBy).toBe(`@e.salary`) - expect(builtQuery.limit).toBe(10) - expect(builtQuery.offset).toBe(5) - }) -}) diff --git a/packages/db/tests/query/query-collection.test.ts b/packages/db/tests/query/query-collection.test.ts index 196bd31f6b..956fa6e759 100644 --- a/packages/db/tests/query/query-collection.test.ts +++ b/packages/db/tests/query/query-collection.test.ts @@ -333,7 +333,7 @@ describe(`Query Collections`, () => { await waitForChanges() // After deletion, user 3 should no longer have a joined result - expect(result.state.get(`3`)).toBeUndefined() + expect(result.state.get(`[3,1]`)).toBeUndefined() }) it(`should order results by specified fields`, async () => { diff --git a/packages/react-db/tests/useLiveQuery.test.tsx b/packages/react-db/tests/useLiveQuery.test.tsx index 582e49d7ac..9ef3b32476 100644 --- a/packages/react-db/tests/useLiveQuery.test.tsx +++ b/packages/react-db/tests/useLiveQuery.test.tsx @@ -117,7 +117,6 @@ describe(`Query Collections`, () => { q .from({ collection }) .where(`@age`, `>`, 30) - .keyBy(`@id`) .select(`@id`, `@name`) .orderBy({ "@id": `asc` }) ) @@ -309,7 +308,6 @@ describe(`Query Collections`, () => { on: [`@persons.id`, `=`, `@issues.userId`], }) .select(`@issues.id`, `@issues.title`, `@persons.name`) - .keyBy(`@id`) ) }) @@ -318,19 +316,19 @@ describe(`Query Collections`, () => { // Verify that we have the expected joined results expect(result.current.state.size).toBe(3) - expect(result.current.state.get(`1`)).toEqual({ + expect(result.current.state.get(`[1,1]`)).toEqual({ id: `1`, name: `John Doe`, title: `Issue 1`, }) - expect(result.current.state.get(`2`)).toEqual({ + expect(result.current.state.get(`[2,2]`)).toEqual({ id: `2`, name: `Jane Doe`, title: `Issue 2`, }) - expect(result.current.state.get(`3`)).toEqual({ + expect(result.current.state.get(`[3,1]`)).toEqual({ id: `3`, name: `John Doe`, title: `Issue 3`, @@ -355,7 +353,7 @@ describe(`Query Collections`, () => { await waitForChanges() expect(result.current.state.size).toBe(4) - expect(result.current.state.get(`4`)).toEqual({ + expect(result.current.state.get(`[4,2]`)).toEqual({ id: `4`, name: `Jane Doe`, title: `Issue 4`, @@ -377,7 +375,7 @@ describe(`Query Collections`, () => { await waitForChanges() // The updated title should be reflected in the joined results - expect(result.current.state.get(`2`)).toEqual({ + expect(result.current.state.get(`[2,2]`)).toEqual({ id: `2`, name: `Jane Doe`, title: `Updated Issue 2`, @@ -396,7 +394,7 @@ describe(`Query Collections`, () => { await waitForChanges() // After deletion, user 3 should no longer have a joined result - expect(result.current.state.get(`3`)).toBeUndefined() + expect(result.current.state.get(`[3,1]`)).toBeUndefined() }) it(`should recompile query when parameters change and change results`, async () => { @@ -442,7 +440,6 @@ describe(`Query Collections`, () => { q .from({ collection }) .where(`@age`, `>`, minAge) - .keyBy(`@id`) .select(`@id`, `@name`, `@age`), [minAge] ) @@ -562,7 +559,6 @@ describe(`Query Collections`, () => { q .from({ collection }) .where(`@age`, `>`, minAge) - .keyBy(`@id`) .select(`@id`, `@name`), [minAge] ) @@ -639,7 +635,6 @@ describe(`Query Collections`, () => { q .from({ collection }) .where(`@age`, `>`, 30) - .keyBy(`@id`) .select(`@id`, `@name`, `@team`) .orderBy({ "@id": `asc` }) ) @@ -651,14 +646,15 @@ describe(`Query Collections`, () => { q .from({ queryResult: result.current.collection }) .groupBy(`@team`) - .keyBy(`@team`) .select(`@team`, { count: { COUNT: `@id` } }) ) }) // Verify initial grouped results expect(groupedResult.current.state.size).toBe(1) - expect(groupedResult.current.state.get(`team1`)).toEqual({ + + // the `{"team":"team1"}` key is generated by the groupBy operator + expect(groupedResult.current.state.get(`{"team":"team1"}`)).toEqual({ team: `team1`, count: 1, }) @@ -697,11 +693,11 @@ describe(`Query Collections`, () => { // Verify the grouped results include the new team members expect(groupedResult.current.state.size).toBe(2) - expect(groupedResult.current.state.get(`team1`)).toEqual({ + expect(groupedResult.current.state.get(`{"team":"team1"}`)).toEqual({ team: `team1`, count: 2, }) - expect(groupedResult.current.state.get(`team2`)).toEqual({ + expect(groupedResult.current.state.get(`{"team":"team2"}`)).toEqual({ team: `team2`, count: 1, }) @@ -793,7 +789,6 @@ describe(`Query Collections`, () => { on: [`@persons.id`, `=`, `@issues.userId`], }) .select(`@issues.id`, `@issues.title`, `@persons.name`) - .keyBy(`@id`) ) // Track each render state @@ -855,11 +850,12 @@ describe(`Query Collections`, () => { // Verify optimistic state is immediately reflected expect(result.current.state.size).toBe(4) - expect(result.current.state.get(`temp-key`)).toEqual({ + expect(result.current.state.get(`[temp-key,1]`)).toEqual({ id: `temp-key`, name: `John Doe`, title: `New Issue`, }) + expect(result.current.state.get(`[4,1]`)).toBeUndefined() // Wait for the transaction to be committed await tx.isPersisted.promise @@ -874,8 +870,8 @@ describe(`Query Collections`, () => { // Verify the temporary key is replaced by the permanent one expect(result.current.state.size).toBe(4) - expect(result.current.state.get(`temp-key`)).toBeUndefined() - expect(result.current.state.get(`4`)).toEqual({ + expect(result.current.state.get(`[temp-key,1]`)).toBeUndefined() + expect(result.current.state.get(`[4,1]`)).toEqual({ id: `4`, name: `John Doe`, title: `New Issue`, diff --git a/packages/vue-db/tests/useLiveQuery.test.ts b/packages/vue-db/tests/useLiveQuery.test.ts index e41db5cd88..f8b2e3deab 100644 --- a/packages/vue-db/tests/useLiveQuery.test.ts +++ b/packages/vue-db/tests/useLiveQuery.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest" import mitt from "mitt" import { Collection, createTransaction } from "@tanstack/db" -import { computed, onUnmounted, ref, watch, watchEffect } from "vue" +import { ref, watch, watchEffect } from "vue" import { useLiveQuery } from "../src/useLiveQuery" import type { Ref } from "vue" import type { @@ -114,7 +114,6 @@ describe(`Query Collections`, () => { q .from({ collection }) .where(`@age`, `>`, 30) - .keyBy(`@id`) .select(`@id`, `@name`) .orderBy({ "@id": `asc` }) ) @@ -294,7 +293,6 @@ describe(`Query Collections`, () => { on: [`@persons.id`, `=`, `@issues.userId`], }) .select(`@issues.id`, `@issues.title`, `@persons.name`) - .keyBy(`@id`) ) await waitForChanges() @@ -302,19 +300,19 @@ describe(`Query Collections`, () => { // Verify that we have the expected joined results expect(state.value.size).toBe(3) - expect(state.value.get(`1`)).toEqual({ + expect(state.value.get(`[1,1]`)).toEqual({ id: `1`, name: `John Doe`, title: `Issue 1`, }) - expect(state.value.get(`2`)).toEqual({ + expect(state.value.get(`[2,2]`)).toEqual({ id: `2`, name: `Jane Doe`, title: `Issue 2`, }) - expect(state.value.get(`3`)).toEqual({ + expect(state.value.get(`[3,1]`)).toEqual({ id: `3`, name: `John Doe`, title: `Issue 3`, @@ -337,7 +335,7 @@ describe(`Query Collections`, () => { await waitForChanges() expect(state.value.size).toBe(4) - expect(state.value.get(`4`)).toEqual({ + expect(state.value.get(`[4,2]`)).toEqual({ id: `4`, name: `Jane Doe`, title: `Issue 4`, @@ -357,7 +355,7 @@ describe(`Query Collections`, () => { await waitForChanges() // The updated title should be reflected in the joined results - expect(state.value.get(`2`)).toEqual({ + expect(state.value.get(`[2,2]`)).toEqual({ id: `2`, name: `Jane Doe`, title: `Updated Issue 2`, @@ -374,7 +372,7 @@ describe(`Query Collections`, () => { await waitForChanges() // After deletion, user 3 should no longer have a joined result - expect(state.value.get(`3`)).toBeUndefined() + expect(state.value.get(`[3,1]`)).toBeUndefined() }) it(`should recompile query when parameters change and change results`, async () => { @@ -417,7 +415,6 @@ describe(`Query Collections`, () => { return q .from({ collection }) .where(`@age`, `>`, minAge.value) - .keyBy(`@id`) .select(`@id`, `@name`, `@age`) }) @@ -527,7 +524,6 @@ describe(`Query Collections`, () => { q .from({ collection }) .where(`@age`, `>`, minAge.value) - .keyBy(`@id`) .select(`@id`, `@name`), [minAge] ) @@ -596,7 +592,6 @@ describe(`Query Collections`, () => { q .from({ collection }) .where(`@age`, `>`, 30) - .keyBy(`@id`) .select(`@id`, `@name`, `@team`) .orderBy({ "@id": `asc` }) ) @@ -606,13 +601,13 @@ describe(`Query Collections`, () => { q .from({ queryResult: result.collection.value }) .groupBy(`@team`) - .keyBy(`@team`) .select(`@team`, { count: { COUNT: `@id` } }) ) // Verify initial grouped results expect(groupedResult.state.value.size).toBe(1) - expect(groupedResult.state.value.get(`team1`)).toEqual({ + // the `{"team":"team1"}` key is generated by the groupBy operator + expect(groupedResult.state.value.get(`{"team":"team1"}`)).toEqual({ team: `team1`, count: 1, }) @@ -649,11 +644,11 @@ describe(`Query Collections`, () => { // Verify the grouped results include the new team members expect(groupedResult.state.value.size).toBe(2) - expect(groupedResult.state.value.get(`team1`)).toEqual({ + expect(groupedResult.state.value.get(`{"team":"team1"}`)).toEqual({ team: `team1`, count: 2, }) - expect(groupedResult.state.value.get(`team2`)).toEqual({ + expect(groupedResult.state.value.get(`{"team":"team2"}`)).toEqual({ team: `team2`, count: 1, }) @@ -741,7 +736,6 @@ describe(`Query Collections`, () => { on: [`@persons.id`, `=`, `@issues.userId`], }) .select(`@issues.id`, `@issues.title`, `@persons.name`) - .keyBy(`@id`) ) // Track each render state @@ -796,11 +790,12 @@ describe(`Query Collections`, () => { // Verify optimistic state is immediately reflected expect(state.value.size).toBe(4) - expect(state.value.get(`temp-key`)).toEqual({ + expect(state.value.get(`[temp-key,1]`)).toEqual({ id: `temp-key`, name: `John Doe`, title: `New Issue`, }) + expect(state.value.get(`[4,1]`)).toBeUndefined() // Wait for the transaction to be committed await tx.isPersisted.promise @@ -808,15 +803,18 @@ describe(`Query Collections`, () => { // Check if we had any render where the temp key was removed but the permanent key wasn't added yet const hadFlicker = renderStates.some( - (state) => !state.hasTempKey && !state.hasPermKey && state.stateSize === 3 + (renderState) => + !renderState.hasTempKey && + !renderState.hasPermKey && + renderState.stateSize === 3 ) expect(hadFlicker).toBe(false) // Verify the temporary key is replaced by the permanent one expect(state.value.size).toBe(4) - expect(state.value.get(`temp-key`)).toBeUndefined() - expect(state.value.get(`4`)).toEqual({ + expect(state.value.get(`[temp-key,1]`)).toBeUndefined() + expect(state.value.get(`[4,1]`)).toEqual({ id: `4`, name: `John Doe`, title: `New Issue`, From 885a4a49653d9e6b5c247a04c86e50713c110a0b Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Sun, 8 Jun 2025 16:17:36 +0100 Subject: [PATCH 5/8] remove keyBy from example app --- examples/react/todo/src/App.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/examples/react/todo/src/App.tsx b/examples/react/todo/src/App.tsx index fee2ae2763..2fe168bdf7 100644 --- a/examples/react/todo/src/App.tsx +++ b/examples/react/todo/src/App.tsx @@ -265,7 +265,6 @@ export default function App() { const { data: todos } = useLiveQuery((q) => q .from({ todoCollection: todoCollection as Collection }) - .keyBy(`@id`) .orderBy(`@created_at`) .select(`@id`, `@created_at`, `@text`, `@completed`) ) @@ -273,7 +272,6 @@ export default function App() { const { data: configData } = useLiveQuery((q) => q .from({ configCollection: configCollection as Collection }) - .keyBy(`@id`) .select(`@id`, `@key`, `@value`) ) From 7a02d68e871b38aecf2c4a1f0056ebc8a88ac6d4 Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Sun, 8 Jun 2025 16:54:07 +0100 Subject: [PATCH 6/8] Fix a couple of missed things in test changes --- packages/react-db/tests/useLiveQuery.test.tsx | 21 ++++++----------- packages/vue-db/tests/useLiveQuery.test.ts | 23 +++++-------------- 2 files changed, 13 insertions(+), 31 deletions(-) diff --git a/packages/react-db/tests/useLiveQuery.test.tsx b/packages/react-db/tests/useLiveQuery.test.tsx index eaccc7e9de..53353d6764 100644 --- a/packages/react-db/tests/useLiveQuery.test.tsx +++ b/packages/react-db/tests/useLiveQuery.test.tsx @@ -1,8 +1,7 @@ -import { cursorTo } from "node:readline" import { describe, expect, it, vi } from "vitest" import mitt from "mitt" import { act, renderHook } from "@testing-library/react" -import { Collection, collectionsStore, createTransaction } from "@tanstack/db" +import { Collection, createTransaction } from "@tanstack/db" import { useEffect } from "react" import { useLiveQuery } from "../src/useLiveQuery" import type { @@ -262,7 +261,6 @@ describe(`Query Collections`, () => { begin() ;(changes as Array).forEach((change) => { write({ - key: change.key, type: change.type, value: change.changes as Person, }) @@ -283,7 +281,6 @@ describe(`Query Collections`, () => { begin() ;(changes as Array).forEach((change) => { write({ - key: change.key, type: change.type, value: change.changes as Issue, }) @@ -785,7 +782,6 @@ describe(`Query Collections`, () => { begin() changes.forEach((change) => { write({ - key: change.key, type: change.type, value: change.changes as Person, }) @@ -897,15 +893,12 @@ describe(`Query Collections`, () => { // Perform optimistic insert of a new issue act(() => { tx.mutate(() => - issueCollection.insert( - { - id: `temp-key`, - title: `New Issue`, - description: `New Issue Description`, - userId: `1`, - }, - { key: `temp-key` } - ) + issueCollection.insert({ + id: `temp-key`, + title: `New Issue`, + description: `New Issue Description`, + userId: `1`, + }) ) }) diff --git a/packages/vue-db/tests/useLiveQuery.test.ts b/packages/vue-db/tests/useLiveQuery.test.ts index e425543f78..49ff077ea5 100644 --- a/packages/vue-db/tests/useLiveQuery.test.ts +++ b/packages/vue-db/tests/useLiveQuery.test.ts @@ -90,7 +90,6 @@ describe(`Query Collections`, () => { begin() ;(changes as Array).forEach((change) => { write({ - key: change.key, type: change.type, value: change.changes as Person, }) @@ -249,7 +248,6 @@ describe(`Query Collections`, () => { begin() ;(changes as Array).forEach((change) => { write({ - key: change.key, type: change.type, value: change.changes as Person, }) @@ -270,7 +268,6 @@ describe(`Query Collections`, () => { begin() ;(changes as Array).forEach((change) => { write({ - key: change.key, type: change.type, value: change.changes as Issue, }) @@ -410,7 +407,6 @@ describe(`Query Collections`, () => { begin() ;(changes as Array).forEach((change) => { write({ - key: change.key, type: change.type, value: change.changes as Person, }) @@ -497,7 +493,6 @@ describe(`Query Collections`, () => { begin() ;(changes as Array).forEach((change) => { write({ - key: change.key, type: change.type, value: change.changes as Person, }) @@ -594,7 +589,6 @@ describe(`Query Collections`, () => { begin() ;(changes as Array).forEach((change) => { write({ - key: change.key, type: change.type, value: change.changes as Person, }) @@ -717,7 +711,6 @@ describe(`Query Collections`, () => { begin() changes.forEach((change) => { write({ - key: change.key, type: change.type, value: change.changes as Person, }) @@ -739,7 +732,6 @@ describe(`Query Collections`, () => { begin() changes.forEach((change) => { write({ - key: change.key, type: change.type, value: change.changes as Issue, }) @@ -821,15 +813,12 @@ describe(`Query Collections`, () => { // Perform optimistic insert of a new issue tx.mutate(() => - issueCollection.insert( - { - id: `temp-key`, - title: `New Issue`, - description: `New Issue Description`, - userId: `1`, - }, - { key: `temp-key` } - ) + issueCollection.insert({ + id: `temp-key`, + title: `New Issue`, + description: `New Issue Description`, + userId: `1`, + }) ) // Verify optimistic state is immediately reflected From 6ffc9c1ad617eadbde89c7a723e7bb77f2c41e28 Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Sun, 8 Jun 2025 17:11:34 +0100 Subject: [PATCH 7/8] changeset --- .changeset/orange-laws-watch.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .changeset/orange-laws-watch.md diff --git a/.changeset/orange-laws-watch.md b/.changeset/orange-laws-watch.md new file mode 100644 index 0000000000..b7cd181083 --- /dev/null +++ b/.changeset/orange-laws-watch.md @@ -0,0 +1,7 @@ +--- +"@tanstack/react-db": patch +"@tanstack/vue-db": patch +"@tanstack/db": patch +--- + +the `keyBy` query operator has been removed, keying withing the query pipeline is now automatic From e01f741b238023b1d9285497ca8146578abaee5e Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Mon, 9 Jun 2025 09:06:48 +0100 Subject: [PATCH 8/8] use getId to get the id from a change when injecting into D2 pipeline --- packages/db/src/query/compiled-query.ts | 25 ++++++++++++------- .../db/tests/query/query-collection.test.ts | 2 +- packages/react-db/tests/useLiveQuery.test.tsx | 6 ++--- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/packages/db/src/query/compiled-query.ts b/packages/db/src/query/compiled-query.ts index b0d3bce8f0..691986b8c5 100644 --- a/packages/db/src/query/compiled-query.ts +++ b/packages/db/src/query/compiled-query.ts @@ -112,16 +112,15 @@ export class CompiledQuery> { return this.resultCollection } - private sendChangesToInput(inputKey: string, changes: Array) { + private sendChangesToInput( + inputKey: string, + changes: Array, + getId: (item: ChangeMessage[`value`]) => any + ) { const input = this.inputs[inputKey]! const multiSetArray: MultiSetArray = [] for (const change of changes) { - // We remove the KEY::{UUID} prefix from the key used as the key for the D2 - // pipeline otherwise it will accumulate on subsequent queries and we end up with - // long and complex keys - const key = change.key.startsWith(`KEY::`) - ? change.key.slice(42) - : change.key + const key = getId(change.value) if (change.type === `insert`) { multiSetArray.push([[key, change.value], 1]) } else if (change.type === `update`) { @@ -163,7 +162,11 @@ export class CompiledQuery> { batch(() => { Object.entries(this.inputCollections).forEach(([key, collection]) => { - this.sendChangesToInput(key, collection.currentStateAsChanges()) + this.sendChangesToInput( + key, + collection.currentStateAsChanges(), + collection.config.getId + ) }) this.incrementVersion() this.sendFrontierToAllInputs() @@ -174,7 +177,11 @@ export class CompiledQuery> { fn: () => { batch(() => { Object.entries(this.inputCollections).forEach(([key, collection]) => { - this.sendChangesToInput(key, collection.derivedChanges.state) + this.sendChangesToInput( + key, + collection.derivedChanges.state, + collection.config.getId + ) }) this.incrementVersion() this.sendFrontierToAllInputs() diff --git a/packages/db/tests/query/query-collection.test.ts b/packages/db/tests/query/query-collection.test.ts index 200973e803..500c0bcdb1 100644 --- a/packages/db/tests/query/query-collection.test.ts +++ b/packages/db/tests/query/query-collection.test.ts @@ -162,7 +162,7 @@ describe(`Query Collections`, () => { expect(result.state.size).toBe(2) expect(result.state.get(`KEY::${result.id}/4`)).toEqual({ - _key: `4`, + _key: 4, id: 4, name: `Kyle Doe 2`, }) diff --git a/packages/react-db/tests/useLiveQuery.test.tsx b/packages/react-db/tests/useLiveQuery.test.tsx index 53353d6764..4773471aad 100644 --- a/packages/react-db/tests/useLiveQuery.test.tsx +++ b/packages/react-db/tests/useLiveQuery.test.tsx @@ -195,7 +195,7 @@ describe(`Query Collections`, () => { { type: `update`, changes: { - id: 4, + id: `4`, name: `Kyle Doe 2`, }, }, @@ -210,7 +210,7 @@ describe(`Query Collections`, () => { ).toEqual({ _key: `4`, _orderByIndex: 1, - id: 4, + id: `4`, name: `Kyle Doe 2`, }) @@ -218,7 +218,7 @@ describe(`Query Collections`, () => { expect(result.current.data).toContainEqual({ _key: `4`, _orderByIndex: 1, - id: 4, + id: `4`, name: `Kyle Doe 2`, })