Open History to see the last commit
1import { mkdtempSync, rmSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterEach, expect, it } from 'vitest'
5import { createCollection } from '@tanstack/db'
6import {
7 createTauriSQLitePersistence as createIndexPersistence,
8 persistedCollectionOptions,
9} from '../src'
10import { createTauriSQLitePersistence as createTauriPersistence } from '../src/tauri'
11import { createTauriSQLiteTestDatabase } from './helpers/tauri-sql-test-db'
12import type { TauriSQLiteDatabaseLike } from '../src/tauri'
13
14type Todo = {
15 id: string
16 title: string
17 score: number
18}
19
20const activeCleanupFns: Array<() => void | Promise<void>> = []
21
22afterEach(async () => {
23 while (activeCleanupFns.length > 0) {
24 const cleanupFn = activeCleanupFns.pop()
25 await Promise.resolve(cleanupFn?.())
26 }
27})
28
29function createTempSqlitePath(): string {
30 const tempDirectory = mkdtempSync(
31 join(tmpdir(), `db-tauri-persistence-test-`),
32 )
33 const dbPath = join(tempDirectory, `state.sqlite`)
34 activeCleanupFns.push(() => {
35 rmSync(tempDirectory, { recursive: true, force: true })
36 })
37 return dbPath
38}
39
40function rethrowDatabaseErrorsAsStrings(
41 database: TauriSQLiteDatabaseLike,
42): TauriSQLiteDatabaseLike {
43 return {
44 ...database,
45 execute: async (...args) => {
46 try {
47 return await database.execute(...args)
48 } catch (error) {
49 throw error instanceof Error ? error.message : String(error)
50 }
51 },
52 }
53}
54
55function registerDatabaseCleanup(
56 database: TauriSQLiteDatabaseLike,
57): () => Promise<void> {
58 let closed = false
59 const close = async () => {
60 if (closed) {
61 return
62 }
63 await database.close()
64 closed = true
65 }
66 activeCleanupFns.push(close)
67 return close
68}
69
70/**
71 * Migration law (#1711): adding an already-present migration column is an
72 * idempotent no-op even when the Tauri bridge rejects with a string. Seed a
73 * real legacy SQLite table, drive migration through the Tauri driver and core
74 * adapter, then close and reopen once both migration columns exist. PRAGMA,
75 * exact legacy bytes, and public rows are the checkpoints. The unrelated-error
76 * control proves the classifier does not turn arbitrary string failures into
77 * success. This Better SQLite fixture reproduces Tauri's error boundary but is
78 * not a native Tauri runtime receipt.
79 */
80it(`migrates and reopens a legacy database when Tauri reports duplicate columns as strings`, async () => {
81 const dbPath = createTempSqlitePath()
82 const collectionId = `todos-string-migration`
83
84 const seedDatabase = createTauriSQLiteTestDatabase({ filename: dbPath })
85 const closeSeedDatabase = registerDatabaseCleanup(seedDatabase)
86 await seedDatabase.execute(
87 `CREATE TABLE applied_tx (
88 collection_id TEXT NOT NULL,
89 term INTEGER NOT NULL,
90 seq INTEGER NOT NULL,
91 tx_id TEXT NOT NULL,
92 row_version INTEGER NOT NULL,
93 replay_json TEXT,
94 applied_at INTEGER NOT NULL,
95 PRIMARY KEY (collection_id, term, seq)
96 )`,
97 )
98 await seedDatabase.execute(
99 `INSERT INTO applied_tx (
100 collection_id,
101 term,
102 seq,
103 tx_id,
104 row_version,
105 replay_json,
106 applied_at
107 ) VALUES ($1, $2, $3, $4, $5, $6, $7)`,
108 [
109 collectionId,
110 1,
111 1,
112 `legacy-tx`,
113 1,
114 `{"mutations":[]}`,
115 Math.floor(Date.now() / 1000),
116 ],
117 )
118 await closeSeedDatabase()
119
120 const migrationDatabase = rethrowDatabaseErrorsAsStrings(
121 createTauriSQLiteTestDatabase({ filename: dbPath }),
122 )
123 const closeMigrationDatabase = registerDatabaseCleanup(migrationDatabase)
124 const migrationPersistence = createTauriPersistence({
125 database: migrationDatabase,
126 })
127
128 await migrationPersistence.adapter.applyCommittedTx(collectionId, {
129 txId: `post-migration-tx`,
130 term: 1,
131 seq: 2,
132 rowVersion: 2,
133 mutations: [
134 {
135 type: `insert`,
136 key: `1`,
137 value: {
138 id: `1`,
139 title: `Survives migration`,
140 score: 1,
141 },
142 },
143 ],
144 })
145
146 const migratedColumns = await migrationDatabase.select<
147 Array<{ name: string }>
148 >(`PRAGMA table_info(applied_tx)`)
149 expect(migratedColumns.map((column) => column.name)).toEqual(
150 expect.arrayContaining([`replay_json`, `replay_requires_full_reload`]),
151 )
152 expect(
153 await migrationDatabase.select<
154 Array<{ tx_id: string; replay_json: string | null }>
155 >(
156 `SELECT tx_id, replay_json
157 FROM applied_tx
158 WHERE tx_id = 'legacy-tx'`,
159 ),
160 ).toEqual([{ tx_id: `legacy-tx`, replay_json: `{"mutations":[]}` }])
161 await closeMigrationDatabase()
162
163 const reopenedDatabase = rethrowDatabaseErrorsAsStrings(
164 createTauriSQLiteTestDatabase({ filename: dbPath }),
165 )
166 registerDatabaseCleanup(reopenedDatabase)
167 const reopenedPersistence = createTauriPersistence({
168 database: reopenedDatabase,
169 })
170
171 await expect(
172 reopenedPersistence.adapter.loadSubset(collectionId, {}),
173 ).resolves.toEqual([
174 {
175 key: `1`,
176 value: {
177 id: `1`,
178 title: `Survives migration`,
179 score: 1,
180 },
181 },
182 ])
183 expect(
184 await reopenedDatabase.select<
185 Array<{ tx_id: string; replay_json: string | null }>
186 >(
187 `SELECT tx_id, replay_json
188 FROM applied_tx
189 WHERE tx_id = 'legacy-tx'`,
190 ),
191 ).toEqual([{ tx_id: `legacy-tx`, replay_json: `{"mutations":[]}` }])
192})
193
194it(`propagates unrelated string failures from a Tauri migration`, async () => {
195 const dbPath = createTempSqlitePath()
196 const database = createTauriSQLiteTestDatabase({ filename: dbPath })
197 registerDatabaseCleanup(database)
198 const failingDatabase: TauriSQLiteDatabaseLike = {
199 ...database,
200 execute: async (sql, bindValues) => {
201 if (sql.includes(`ALTER TABLE applied_tx ADD COLUMN replay_json`)) {
202 throw `database is locked`
203 }
204 return database.execute(sql, bindValues)
205 },
206 }
207 const persistence = createTauriPersistence({ database: failingDatabase })
208
209 await expect(
210 persistence.adapter.loadSubset(`todos-unrelated-migration-error`, {}),
211 ).rejects.toBe(`database is locked`)
212})
213
214it(`persists data across app restart (close and reopen)`, async () => {
215 const dbPath = createTempSqlitePath()
216 const collectionId = `todos-restart`
217
218 const firstDatabase = createTauriSQLiteTestDatabase({ filename: dbPath })
219 const firstPersistence = createTauriPersistence({
220 database: firstDatabase,
221 })
222 const firstAdapter = firstPersistence.adapter
223
224 await firstAdapter.applyCommittedTx(collectionId, {
225 txId: `tx-restart-1`,
226 term: 1,
227 seq: 1,
228 rowVersion: 1,
229 mutations: [
230 {
231 type: `insert`,
232 key: `1`,
233 value: {
234 id: `1`,
235 title: `Survives restart`,
236 score: 10,
237 },
238 },
239 ],
240 })
241 await Promise.resolve(firstDatabase.close())
242
243 const secondDatabase = createTauriSQLiteTestDatabase({ filename: dbPath })
244 activeCleanupFns.push(async () => {
245 await Promise.resolve(secondDatabase.close())
246 })
247 const secondPersistence = createTauriPersistence({
248 database: secondDatabase,
249 })
250 const secondAdapter = secondPersistence.adapter
251
252 const rows = await secondAdapter.loadSubset(collectionId, {})
253 expect(rows).toEqual([
254 {
255 key: `1`,
256 value: {
257 id: `1`,
258 title: `Survives restart`,
259 score: 10,
260 },
261 },
262 ])
263})
264
265it(`shares the same runtime behavior through index and tauri entrypoints`, async () => {
266 const dbPath = createTempSqlitePath()
267 const collectionId = `todos-entrypoints`
268 const database = createTauriSQLiteTestDatabase({ filename: dbPath })
269 activeCleanupFns.push(async () => {
270 await Promise.resolve(database.close())
271 })
272
273 const indexPersistence = createIndexPersistence({ database })
274 const tauriPersistence = createTauriPersistence({ database })
275
276 await indexPersistence.adapter.applyCommittedTx(collectionId, {
277 txId: `tx-entrypoint-1`,
278 term: 1,
279 seq: 1,
280 rowVersion: 1,
281 mutations: [
282 {
283 type: `insert`,
284 key: `1`,
285 value: {
286 id: `1`,
287 title: `Entry point parity`,
288 score: 1,
289 },
290 },
291 ],
292 })
293
294 const rows = await tauriPersistence.adapter.loadSubset(collectionId, {})
295 expect(rows[0]?.value.title).toBe(`Entry point parity`)
296})
297
298it(`resumes persisted sync after cleanup and restart`, async () => {
299 const dbPath = createTempSqlitePath()
300 const collectionId = `todos-lifecycle`
301 const database = createTauriSQLiteTestDatabase({ filename: dbPath })
302 activeCleanupFns.push(async () => {
303 await Promise.resolve(database.close())
304 })
305
306 const persistence = createTauriPersistence({
307 database,
308 })
309 const collection = createCollection(
310 persistedCollectionOptions<Todo, string>({
311 id: collectionId,
312 getKey: (todo) => todo.id,
313 persistence,
314 syncMode: `eager`,
315 }),
316 )
317 activeCleanupFns.push(() => collection.cleanup())
318
319 await collection.stateWhenReady()
320 const initialInsert = collection.insert({
321 id: `1`,
322 title: `Before cleanup`,
323 score: 1,
324 })
325 await initialInsert.isPersisted.promise
326 expect(collection.get(`1`)?.title).toBe(`Before cleanup`)
327
328 await collection.cleanup()
329 collection.startSyncImmediate()
330 await collection.stateWhenReady()
331
332 const resumedInsert = collection.insert({
333 id: `2`,
334 title: `After restart`,
335 score: 2,
336 })
337 await resumedInsert.isPersisted.promise
338 expect(collection.get(`2`)?.title).toBe(`After restart`)
339
340 const persistedRows = await persistence.adapter.loadSubset(collectionId, {})
341 expect(persistedRows).toEqual(
342 expect.arrayContaining([
343 expect.objectContaining({
344 key: `1`,
345 }),
346 expect.objectContaining({
347 key: `2`,
348 }),
349 ]),
350 )
351})