Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import { tmpdir } from 'node:os'
3import { PowerSyncDatabase, Schema, Table, column } from '@powersync/node'
4import { createCollection, createLiveQueryCollection, eq } from '@tanstack/db'
5import pDefer from 'p-defer'
6import { describe, expect, it, onTestFinished, vi } from 'vitest'
7import { powerSyncCollectionOptions } from '../src'
8import type { Collection } from '@tanstack/db'
9
10/**
11 * # Does PowerSync settlement carry initial-query readiness?
12 *
13 * ARCHITECTURE.md law 10 makes a settled `loadSubset` the readiness evidence
14 * for an on-demand source, and law 7 says a successful load settles only after
15 * its rows are visible. These witnesses drive a real PowerSync database under a
16 * real live query and record the rows visible at the first-ready transition.
17 */
18
19const APP_SCHEMA = new Schema({
20 products: new Table({ name: column.text, category: column.text }),
21})
22
23async function createDatabase() {
24 const db = new PowerSyncDatabase({
25 database: {
26 dbFilename: `test-readiness-${randomUUID()}.sqlite`,
27 dbLocation: tmpdir(),
28 implementation: { type: `node:sqlite` },
29 },
30 schema: APP_SCHEMA,
31 })
32 onTestFinished(async () => {
33 await new Promise((resolve) => setTimeout(resolve, 100))
34 await db.disconnectAndClear()
35 await db.close()
36 })
37 await db.disconnectAndClear()
38 await db.execute(`
39 INSERT INTO products (id, name, category)
40 VALUES ('a1', 'A', 'electronics'), ('a2', 'B', 'electronics'),
41 ('c1', 'C', 'clothing')
42 `)
43 return db
44}
45
46function rowsAtFirstReady(query: Collection<any, any, any>) {
47 const seen: { rows?: Array<unknown> } = {}
48 query.onFirstReady(() => {
49 seen.rows = query.toArray.map((row: { id: string }) => row.id).sort()
50 })
51 return seen
52}
53
54function createSource(
55 database: PowerSyncDatabase,
56 syncMode: `eager` | `on-demand` | undefined,
57 onLoadSubset?: () => Promise<void>,
58) {
59 const table = APP_SCHEMA.props.products
60 const source = createCollection(
61 syncMode === `on-demand`
62 ? powerSyncCollectionOptions({ database, table, syncMode, onLoadSubset })
63 : powerSyncCollectionOptions({ database, table }),
64 )
65 onTestFinished(() => source.cleanup())
66 return source
67}
68
69function electronics(source: ReturnType<typeof createSource>) {
70 return createLiveQueryCollection((q) =>
71 q
72 .from({ product: source })
73 .where(({ product }) => eq(product.category, `electronics`)),
74 )
75}
76
77describe(`PowerSync initial readiness follows applied subset settlement`, () => {
78 it(`an on-demand query is first ready with its subset rows visible`, async () => {
79 const db = await createDatabase()
80 const source = createSource(db, `on-demand`)
81 const query = electronics(source)
82 onTestFinished(() => query.cleanup())
83 const seen = rowsAtFirstReady(query)
84 await query.preload()
85 expect(seen.rows).toEqual([`a1`, `a2`])
86 })
87
88 it(`a held subset hook holds readiness until the hook and rows settle`, async () => {
89 const db = await createDatabase()
90 const hook = pDefer<void>()
91 const source = createSource(db, `on-demand`, () => hook.promise)
92 const query = electronics(source)
93 onTestFinished(() => query.cleanup())
94 const seen = rowsAtFirstReady(query)
95 const preload = query.preload()
96 await new Promise((resolve) => setTimeout(resolve, 50))
97 expect(query.isReady()).toBe(false)
98 hook.resolve()
99 await preload
100 expect(seen.rows).toEqual([`a1`, `a2`])
101 })
102
103 it(`a failed subset hook errors the query and never readies it`, async () => {
104 const db = await createDatabase()
105 const loggedError = vi.spyOn(console, `error`).mockImplementation(() => {})
106 onTestFinished(() => loggedError.mockRestore())
107 const source = createSource(db, `on-demand`, () =>
108 Promise.reject(new Error(`hook failed`)),
109 )
110 const query = electronics(source)
111 onTestFinished(() => query.cleanup())
112 const seen = rowsAtFirstReady(query)
113 await query.preload().catch(() => {})
114 await vi.waitFor(() => expect(query.status).toBe(`error`))
115 expect(seen.rows).toBeUndefined()
116 })
117
118 it(`a demand released during its hook installs no rows`, async () => {
119 const db = await createDatabase()
120 const hook = pDefer<void>()
121 let entered = false
122 const source = createSource(db, `on-demand`, () => {
123 entered = true
124 return hook.promise
125 })
126 const query = electronics(source)
127 void query.preload().catch(() => {})
128 await vi.waitFor(() => expect(entered).toBe(true))
129 await query.cleanup()
130 hook.resolve()
131 await new Promise((resolve) => setTimeout(resolve, 100))
132 expect(source.size).toBe(0)
133 })
134
135 it(`a source with no syncMode is eager and gates readiness`, async () => {
136 const db = await createDatabase()
137 const source = createSource(db, undefined)
138 expect(source.config.syncMode).not.toBe(`on-demand`)
139 const query = electronics(source)
140 onTestFinished(() => query.cleanup())
141 let sourceReadyAtQueryReady: boolean | undefined
142 query.onFirstReady(() => {
143 sourceReadyAtQueryReady = source.isReady()
144 })
145 const seen = rowsAtFirstReady(query)
146 await query.preload()
147 expect(sourceReadyAtQueryReady).toBe(true)
148 expect(seen.rows).toEqual([`a1`, `a2`])
149 })
150})