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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/orange-laws-watch.md
Original file line number Diff line number Diff line change
@@ -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
3 changes: 0 additions & 3 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,6 @@ const Todos = () => {
.where('@completed', '=', false)
.orderBy({'@created_at': 'asc'})
.select('@id', '@text')
.keyBy('@id')
)

return <List items={ todos } />
Expand All @@ -302,7 +301,6 @@ const Todos = () => {
})
.where('@lists.active', '=', true)
.select(`@todos.id`, `@todos.title`, `@lists.name`)
.keyBy('@id')
)

return <List items={ todos } />
Expand Down Expand Up @@ -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.
Expand Down
3 changes: 0 additions & 3 deletions docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,6 @@ const Todos = () => {
.where('@completed', '=', false)
.orderBy({'@created_at': 'asc'})
.select('@id', '@text')
.keyBy('@id')
)

return <List items={ todos } />
Expand All @@ -306,7 +305,6 @@ const Todos = () => {
})
.where('@lists.active', '=', true)
.select(`@todos.id`, `@todos.title`, `@lists.name`)
.keyBy('@id')
)

return <List items={ todos } />
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 0 additions & 2 deletions examples/react/todo/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -265,15 +265,13 @@ export default function App() {
const { data: todos } = useLiveQuery((q) =>
q
.from({ todoCollection: todoCollection as Collection<UpdateTodo> })
.keyBy(`@id`)
.orderBy(`@created_at`)
.select(`@id`, `@created_at`, `@text`, `@completed`)
)

const { data: configData } = useLiveQuery((q) =>
q
.from({ configCollection: configCollection as Collection<UpdateConfig> })
.keyBy(`@id`)
.select(`@id`, `@key`, `@value`)
)

Expand Down
27 changes: 20 additions & 7 deletions packages/db/src/query/compiled-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,18 +112,23 @@ export class CompiledQuery<TResults extends object = Record<string, unknown>> {
return this.resultCollection
}

private sendChangesToInput(inputKey: string, changes: Array<ChangeMessage>) {
private sendChangesToInput(
inputKey: string,
changes: Array<ChangeMessage>,
getId: (item: ChangeMessage[`value`]) => any
) {
const input = this.inputs[inputKey]!
const multiSetArray: MultiSetArray<unknown> = []
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))
Expand Down Expand Up @@ -157,7 +162,11 @@ export class CompiledQuery<TResults extends object = Record<string, unknown>> {

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()
Expand All @@ -168,7 +177,11 @@ export class CompiledQuery<TResults extends object = Record<string, unknown>> {
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()
Expand Down
43 changes: 22 additions & 21 deletions packages/db/src/query/evaluators.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { evaluateOperandOnNestedRow } from "./extractors.js"
import { evaluateOperandOnNamespacedRow } from "./extractors.js"
import { compareValues, convertLikeToRegex, isValueInArray } from "./utils.js"
import type {
Comparator,
Expand All @@ -7,21 +7,22 @@ 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<string, unknown>,
export function evaluateConditionOnNamespacedRow(
namespacedRow: NamespacedRow,
condition: Condition,
mainTableAlias?: string,
joinedTableAlias?: string
): boolean {
// 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,
Expand All @@ -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],
Expand All @@ -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],
Expand All @@ -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
Expand All @@ -96,8 +97,8 @@ export function evaluateConditionOnNestedRow(
if (operator === `and`) {
result =
result &&
evaluateConditionOnNestedRow(
nestedRow,
evaluateConditionOnNamespacedRow(
namespacedRow,
nextCondition,
mainTableAlias,
joinedTableAlias
Expand All @@ -106,8 +107,8 @@ export function evaluateConditionOnNestedRow(
// logicalOp === `or`
result =
result ||
evaluateConditionOnNestedRow(
nestedRow,
evaluateConditionOnNamespacedRow(
namespacedRow,
nextCondition,
mainTableAlias,
joinedTableAlias
Expand All @@ -125,23 +126,23 @@ export function evaluateConditionOnNestedRow(
/**
* Evaluates a simple condition against a nested row structure
*/
export function evaluateSimpleConditionOnNestedRow(
nestedRow: Record<string, unknown>,
export function evaluateSimpleConditionOnNamespacedRow(
namespacedRow: Record<string, unknown>,
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
Expand Down
45 changes: 24 additions & 21 deletions packages/db/src/query/extractors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>,
export function extractValueFromNamespacedRow(
namespacedRow: Record<string, unknown>,
columnRef: string,
mainTableAlias?: string,
joinedTableAlias?: string
Expand All @@ -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<string, unknown>
| null
| undefined
Expand All @@ -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<string, unknown>
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
>
Expand All @@ -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` &&
Expand All @@ -69,17 +72,17 @@ export function extractValueFromNestedRow(
/**
* Evaluates an operand against a nested row structure
*/
export function evaluateOperandOnNestedRow(
nestedRow: Record<string, unknown>,
export function evaluateOperandOnNamespacedRow(
namespacedRow: Record<string, unknown>,
operand: ConditionOperand,
mainTableAlias?: string,
joinedTableAlias?: string
): unknown {
// Handle column references
if (typeof operand === `string` && operand.startsWith(`@`)) {
const columnRef = operand.substring(1)
return extractValueFromNestedRow(
nestedRow,
return extractValueFromNamespacedRow(
namespacedRow,
columnRef,
mainTableAlias,
joinedTableAlias
Expand All @@ -92,17 +95,17 @@ 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
)

// 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
Expand All @@ -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
Expand Down
Loading