diff --git a/.changeset/lemon-deer-tell.md b/.changeset/lemon-deer-tell.md new file mode 100644 index 0000000000..39540dc83b --- /dev/null +++ b/.changeset/lemon-deer-tell.md @@ -0,0 +1,5 @@ +--- +"@tanstack/db": patch +--- + +the select operator is not optional on a query, it will default to returning the whole row for a basic query, and a namespaced object when there are joins diff --git a/packages/db/src/query/pipeline-compiler.ts b/packages/db/src/query/pipeline-compiler.ts index 0c802a6d91..1d5ea48b03 100644 --- a/packages/db/src/query/pipeline-compiler.ts +++ b/packages/db/src/query/pipeline-compiler.ts @@ -6,7 +6,11 @@ import { processOrderBy } from "./order-by.js" import { processSelect } from "./select.js" import type { Query } from "./schema.js" import type { IStreamBuilder } from "@electric-sql/d2ts" -import type { KeyedStream, NamespacedAndKeyedStream } from "../types.js" +import type { + InputRow, + KeyedStream, + NamespacedAndKeyedStream, +} from "../types.js" /** * Compiles a query into a D2 pipeline @@ -136,7 +140,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 - + : !query.join && !query.groupBy + ? pipeline.pipe( + map(([key, row]) => [key, row[mainTableAlias]] as InputRow) + ) + : pipeline return resultPipeline as T } diff --git a/packages/db/src/query/query-builder.ts b/packages/db/src/query/query-builder.ts index 6cf035b008..9cc2c277a3 100644 --- a/packages/db/src/query/query-builder.ts +++ b/packages/db/src/query/query-builder.ts @@ -438,6 +438,7 @@ export class BaseQueryBuilder> { Input > } + hasJoin: true } > > @@ -474,6 +475,7 @@ export class BaseQueryBuilder> { schema: TContext[`schema`] & { [K in T]: RemoveIndexSignature } + hasJoin: true } > > @@ -513,6 +515,7 @@ export class BaseQueryBuilder> { schema: TContext[`schema`] & { [K in TAs]: RemoveIndexSignature } + hasJoin: true } > > @@ -864,10 +867,12 @@ export function queryBuilder() { export type ResultsFromContext> = Flatten< TContext[`result`] extends object - ? TContext[`result`] - : TContext[`result`] extends undefined - ? TContext[`schema`] - : object + ? TContext[`result`] // If there is a select we will have a result type + : TContext[`hasJoin`] extends true + ? TContext[`schema`] // If there is a join, the query returns the namespaced schema + : TContext[`default`] extends keyof TContext[`schema`] + ? TContext[`schema`][TContext[`default`]] // If there is no join we return the flat default schema + : never // Should never happen > export type ResultFromQueryBuilder = Flatten< diff --git a/packages/db/src/query/types.ts b/packages/db/src/query/types.ts index 9c85a41850..3acff88d09 100644 --- a/packages/db/src/query/types.ts +++ b/packages/db/src/query/types.ts @@ -20,6 +20,7 @@ export type Context< schema: TSchema default?: keyof TSchema result?: Record + hasJoin?: boolean } // Helper types diff --git a/packages/db/tests/query/query-collection.test.ts b/packages/db/tests/query/query-collection.test.ts index 500c0bcdb1..485c5338e7 100644 --- a/packages/db/tests/query/query-collection.test.ts +++ b/packages/db/tests/query/query-collection.test.ts @@ -152,7 +152,7 @@ describe(`Query Collections`, () => { { type: `update`, changes: { - id: 4, + id: `4`, name: `Kyle Doe 2`, }, }, @@ -162,8 +162,133 @@ describe(`Query Collections`, () => { expect(result.state.size).toBe(2) expect(result.state.get(`KEY::${result.id}/4`)).toEqual({ - _key: 4, - id: 4, + _key: `4`, + id: `4`, + name: `Kyle Doe 2`, + }) + + // Delete the person + emitter.emit(`sync`, [ + { + type: `delete`, + changes: { + id: `4`, + }, + }, + ]) + + await waitForChanges() + + expect(result.state.size).toBe(1) + expect(result.state.get(`KEY::${result.id}/4`)).toBeUndefined() + }) + + it(`should be able to query a collection without a select`, async () => { + const emitter = mitt() + + // Create collection with mutation capability + const collection = new Collection({ + id: `optimistic-changes-test`, + getId: (item) => item.id, + sync: { + sync: ({ begin, write, commit }) => { + // Listen for sync events + emitter.on(`sync`, (changes) => { + begin() + ;(changes as Array).forEach((change) => { + write({ + type: change.type, + value: change.changes as Person, + }) + }) + commit() + }) + }, + }, + }) + + // Sync from initial state + emitter.emit( + `sync`, + initialPersons.map((person) => ({ + type: `insert`, + changes: person, + })) + ) + + const query = queryBuilder().from({ collection }).where(`@age`, `>`, 30) + + const compiledQuery = compileQuery(query) + + compiledQuery.start() + + const result = compiledQuery.results + + expect(result.state.size).toBe(1) + expect(result.state.get(`KEY::${result.id}/3`)).toEqual({ + _key: `3`, + age: 35, + email: `john.smith@example.com`, + id: `3`, + isActive: false, + name: `John Smith`, + }) + + // Insert a new person + emitter.emit(`sync`, [ + { + key: `4`, + type: `insert`, + changes: { + id: `4`, + name: `Kyle Doe`, + age: 40, + email: `kyle.doe@example.com`, + isActive: true, + }, + }, + ]) + + await waitForChanges() + + expect(result.state.size).toBe(2) + expect(result.state.get(`KEY::${result.id}/3`)).toEqual({ + _key: `3`, + age: 35, + email: `john.smith@example.com`, + id: `3`, + isActive: false, + name: `John Smith`, + }) + expect(result.state.get(`KEY::${result.id}/4`)).toEqual({ + _key: `4`, + age: 40, + email: `kyle.doe@example.com`, + id: `4`, + isActive: true, + name: `Kyle Doe`, + }) + + // Update the person + emitter.emit(`sync`, [ + { + type: `update`, + changes: { + id: `4`, + name: `Kyle Doe 2`, + }, + }, + ]) + + await waitForChanges() + + expect(result.state.size).toBe(2) + expect(result.state.get(`KEY::${result.id}/4`)).toEqual({ + _key: `4`, + age: 40, + email: `kyle.doe@example.com`, + id: `4`, + isActive: true, name: `Kyle Doe 2`, }) @@ -344,6 +469,216 @@ describe(`Query Collections`, () => { expect(result.state.get(`KEY::${result.id}/[3,1]`)).toBeUndefined() }) + it(`should join collections and return combined results with no select`, async () => { + const emitter = mitt() + + // Create person collection + const personCollection = new Collection({ + id: `person-collection-test`, + getId: (item) => item.id, + sync: { + sync: ({ begin, write, commit }) => { + emitter.on(`sync-person`, (changes) => { + begin() + ;(changes as Array).forEach((change) => { + write({ + type: change.type, + value: change.changes as Person, + }) + }) + commit() + }) + }, + }, + }) + + // Create issue collection + const issueCollection = new Collection({ + id: `issue-collection-test`, + getId: (item) => item.id, + sync: { + sync: ({ begin, write, commit }) => { + emitter.on(`sync-issue`, (changes) => { + begin() + ;(changes as Array).forEach((change) => { + write({ + type: change.type, + value: change.changes as Issue, + }) + }) + commit() + }) + }, + }, + }) + + // Sync initial person data + emitter.emit( + `sync-person`, + initialPersons.map((person) => ({ + type: `insert`, + changes: person, + })) + ) + + // Sync initial issue data + emitter.emit( + `sync-issue`, + initialIssues.map((issue) => ({ + type: `insert`, + changes: issue, + })) + ) + + // Create a query with a join between persons and issues + const query = queryBuilder() + .from({ issues: issueCollection }) + .join({ + type: `inner`, + from: { persons: personCollection }, + on: [`@persons.id`, `=`, `@issues.userId`], + }) + + const compiledQuery = compileQuery(query) + compiledQuery.start() + + const result = compiledQuery.results + + await waitForChanges() + + // Verify that we have the expected joined results + expect(result.state.size).toBe(3) + + expect(result.state.get(`KEY::${result.id}/[1,1]`)).toEqual({ + _key: `[1,1]`, + issues: { + description: `Issue 1 description`, + id: `1`, + title: `Issue 1`, + userId: `1`, + }, + persons: { + age: 30, + email: `john.doe@example.com`, + id: `1`, + isActive: true, + name: `John Doe`, + }, + }) + + expect(result.state.get(`KEY::${result.id}/[2,2]`)).toEqual({ + _key: `[2,2]`, + issues: { + description: `Issue 2 description`, + id: `2`, + title: `Issue 2`, + userId: `2`, + }, + persons: { + age: 25, + email: `jane.doe@example.com`, + id: `2`, + isActive: true, + name: `Jane Doe`, + }, + }) + + expect(result.state.get(`KEY::${result.id}/[3,1]`)).toEqual({ + _key: `[3,1]`, + issues: { + description: `Issue 3 description`, + id: `3`, + title: `Issue 3`, + userId: `1`, + }, + persons: { + age: 30, + email: `john.doe@example.com`, + id: `1`, + isActive: true, + name: `John Doe`, + }, + }) + + // Add a new issue for user 1 + emitter.emit(`sync-issue`, [ + { + key: `4`, + type: `insert`, + changes: { + id: `4`, + title: `Issue 4`, + description: `Issue 4 description`, + userId: `2`, + }, + }, + ]) + + await waitForChanges() + + expect(result.state.size).toBe(4) + expect(result.state.get(`KEY::${result.id}/[4,2]`)).toEqual({ + _key: `[4,2]`, + issues: { + description: `Issue 4 description`, + id: `4`, + title: `Issue 4`, + userId: `2`, + }, + persons: { + age: 25, + email: `jane.doe@example.com`, + id: `2`, + isActive: true, + name: `Jane Doe`, + }, + }) + + // Update an issue we're already joined with + emitter.emit(`sync-issue`, [ + { + type: `update`, + changes: { + id: 2, + title: `Updated Issue 2`, + }, + }, + ]) + + await waitForChanges() + + // The updated title should be reflected in the joined results + expect(result.state.get(`KEY::${result.id}/[2,2]`)).toEqual({ + _key: `[2,2]`, + issues: { + description: `Issue 2 description`, + id: 2, + title: `Updated Issue 2`, + userId: `2`, + }, + persons: { + age: 25, + email: `jane.doe@example.com`, + id: `2`, + isActive: true, + name: `Jane Doe`, + }, + }) + + // Delete an issue + emitter.emit(`sync-issue`, [ + { + changes: { id: `3` }, + type: `delete`, + }, + ]) + + await waitForChanges() + + // After deletion, user 3 should no longer have a joined result + expect(result.state.get(`KEY::${result.id}/[3,1]`)).toBeUndefined() + }) + it(`should order results by specified fields`, async () => { const emitter = mitt()