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
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.
diff --git a/examples/react/todo/src/App.tsx b/examples/react/todo/src/App.tsx
index 03a321e0ae..9b8fb4be16 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`)
)
diff --git a/packages/db/src/query/compiled-query.ts b/packages/db/src/query/compiled-query.ts
index f08a313b2b..691986b8c5 100644
--- a/packages/db/src/query/compiled-query.ts
+++ b/packages/db/src/query/compiled-query.ts
@@ -112,18 +112,23 @@ 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) {
+ const key = getId(change.value)
if (change.type === `insert`) {
- multiSetArray.push([change.value, 1])
+ multiSetArray.push([[key, change.value], 1])
} else if (change.type === `update`) {
- multiSetArray.push([change.previousValue, -1])
- multiSetArray.push([change.value, 1])
+ multiSetArray.push([[key, change.previousValue], -1])
+ multiSetArray.push([[key, change.value], 1])
} else {
// change.type === `delete`
- multiSetArray.push([change.value, -1])
+ multiSetArray.push([[key, change.value], -1])
}
}
input.sendData(this.version, new MultiSet(multiSetArray))
@@ -157,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()
@@ -168,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/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..1a84b638f4 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
)
@@ -48,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`) {
@@ -73,15 +80,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 +95,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..4f7ef0b2f3 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,89 @@ 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] | undefined,
+ [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 +226,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..0ae74e10a1 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
) {
@@ -25,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)) {
@@ -79,17 +80,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 +103,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 +184,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
+ 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/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/schema.ts b/packages/db/src/query/schema.ts
index 6cde3a8803..96c90d2d5f 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",
@@ -217,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