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 { createExpoSQLitePersistence, persistedCollectionOptions } from '../src'
7import { createExpoSQLiteTestDatabase } from './helpers/expo-sqlite-test-db'
8
9type Todo = {
10 id: string
11 title: string
12 score: number
13}
14
15const activeCleanupFns: Array<() => void | Promise<void>> = []
16
17afterEach(async () => {
18 while (activeCleanupFns.length > 0) {
19 const cleanupFn = activeCleanupFns.pop()
20 await Promise.resolve(cleanupFn?.())
21 }
22})
23
24function createTempSqlitePath(): string {
25 const tempDirectory = mkdtempSync(join(tmpdir(), `db-expo-persistence-test-`))
26 const dbPath = join(tempDirectory, `state.sqlite`)
27 activeCleanupFns.push(() => {
28 rmSync(tempDirectory, { recursive: true, force: true })
29 })
30 return dbPath
31}
32
33it(`persists data across app restart (close and reopen)`, async () => {
34 const dbPath = createTempSqlitePath()
35 const collectionId = `todos-restart`
36
37 const firstDatabase = createExpoSQLiteTestDatabase({ filename: dbPath })
38 const firstPersistence = createExpoSQLitePersistence({
39 database: firstDatabase,
40 })
41 const firstAdapter = firstPersistence.adapter
42
43 await firstAdapter.applyCommittedTx(collectionId, {
44 txId: `tx-restart-1`,
45 term: 1,
46 seq: 1,
47 rowVersion: 1,
48 mutations: [
49 {
50 type: `insert`,
51 key: `1`,
52 value: {
53 id: `1`,
54 title: `Survives restart`,
55 score: 10,
56 },
57 },
58 ],
59 })
60 await firstDatabase.closeAsync()
61
62 const secondDatabase = createExpoSQLiteTestDatabase({ filename: dbPath })
63 activeCleanupFns.push(() => secondDatabase.closeAsync())
64 const secondPersistence = createExpoSQLitePersistence({
65 database: secondDatabase,
66 })
67 const secondAdapter = secondPersistence.adapter
68
69 const rows = await secondAdapter.loadSubset(collectionId, {})
70 expect(rows).toEqual([
71 {
72 key: `1`,
73 value: {
74 id: `1`,
75 title: `Survives restart`,
76 score: 10,
77 },
78 },
79 ])
80})
81
82it(`keeps all committed rows under rapid mutation bursts`, async () => {
83 const dbPath = createTempSqlitePath()
84 const collectionId = `todos-burst`
85 const database = createExpoSQLiteTestDatabase({ filename: dbPath })
86 activeCleanupFns.push(() => database.closeAsync())
87
88 const persistence = createExpoSQLitePersistence({
89 database,
90 })
91 const adapter = persistence.adapter
92
93 const burstSize = 50
94 for (let index = 0; index < burstSize; index++) {
95 const rowId = String(index + 1)
96 await adapter.applyCommittedTx(collectionId, {
97 txId: `tx-burst-${rowId}`,
98 term: 1,
99 seq: index + 1,
100 rowVersion: index + 1,
101 mutations: [
102 {
103 type: `insert`,
104 key: rowId,
105 value: {
106 id: rowId,
107 title: `Todo ${rowId}`,
108 score: index,
109 },
110 },
111 ],
112 })
113 }
114
115 const rows = await adapter.loadSubset(collectionId, {})
116 expect(rows).toHaveLength(burstSize)
117})
118
119it(`resumes persisted sync after simulated background/foreground transitions`, async () => {
120 const dbPath = createTempSqlitePath()
121 const collectionId = `todos-lifecycle`
122 const database = createExpoSQLiteTestDatabase({ filename: dbPath })
123 activeCleanupFns.push(() => database.closeAsync())
124
125 const persistence = createExpoSQLitePersistence({
126 database,
127 })
128 const collection = createCollection(
129 persistedCollectionOptions<Todo, string>({
130 id: collectionId,
131 getKey: (todo) => todo.id,
132 persistence,
133 syncMode: `eager`,
134 }),
135 )
136 activeCleanupFns.push(() => collection.cleanup())
137
138 await collection.stateWhenReady()
139
140 const initialInsert = collection.insert({
141 id: `1`,
142 title: `Before background`,
143 score: 1,
144 })
145 await initialInsert.isPersisted.promise
146 expect(collection.get(`1`)?.title).toBe(`Before background`)
147
148 await collection.cleanup()
149 collection.startSyncImmediate()
150 await collection.stateWhenReady()
151
152 const postResumeInsert = collection.insert({
153 id: `2`,
154 title: `Post resume write`,
155 score: 2,
156 })
157 await postResumeInsert.isPersisted.promise
158 expect(collection.get(`2`)?.title).toBe(`Post resume write`)
159
160 const persistedRows = await persistence.adapter.loadSubset(collectionId, {})
161 expect(persistedRows).toEqual(
162 expect.arrayContaining([
163 expect.objectContaining({
164 key: `1`,
165 }),
166 expect.objectContaining({
167 key: `2`,
168 }),
169 ]),
170 )
171})