Open History to see the last commit
1import { mkdtempSync, rmSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterAll, afterEach, beforeAll } from 'vitest'
5import { BTreeIndex, createCollection } from '@tanstack/db'
6import { persistedCollectionOptions } from '../src'
7import {
8 captureSeedData,
9 generateSeedData,
10} from '../../db-collection-e2e/src/fixtures/seed-data'
11import { runPersistedCollectionConformanceSuite } from '../../db-sqlite-persistence-core/tests/contracts/persisted-collection-conformance-contract'
12import { createOpSQLiteTestDatabase } from '../tests/helpers/op-sqlite-test-db'
13import type { Collection } from '@tanstack/db'
14import type { PersistedCollectionPersistence } from '@tanstack/db-sqlite-persistence-core'
15import type {
16 Comment,
17 E2ETestConfig,
18 Post,
19 User,
20} from '../../db-collection-e2e/src/types'
21
22type PersistableRow = {
23 id: string
24}
25
26type MobilePersistedCollectionTestConfig = E2ETestConfig
27type PersistedCollectionHarness<T extends PersistableRow> = {
28 collection: Collection<T, string | number>
29 seedPersisted: (rows: Array<T>) => Promise<void>
30}
31
32type MobilePersistenceFactory = (
33 database: ReturnType<typeof createOpSQLiteTestDatabase>,
34) => PersistedCollectionPersistence
35
36function createPersistedCollection<T extends PersistableRow>(
37 database: ReturnType<typeof createOpSQLiteTestDatabase>,
38 id: string,
39 syncMode: `eager` | `on-demand`,
40 createPersistence: MobilePersistenceFactory,
41): PersistedCollectionHarness<T> {
42 const persistence = createPersistence(database)
43 let seedTxSequence = 0
44 const seedPersisted = async (rows: Array<T>): Promise<void> => {
45 if (rows.length === 0) {
46 return
47 }
48 seedTxSequence++
49 await persistence.adapter.applyCommittedTx(id, {
50 txId: `seed-${id}-${seedTxSequence}`,
51 term: 1,
52 seq: seedTxSequence,
53 rowVersion: seedTxSequence,
54 mutations: rows.map((row) => ({
55 type: `insert` as const,
56 key: row.id,
57 value: row,
58 })),
59 })
60 }
61
62 const collection = createCollection(
63 persistedCollectionOptions<T, string | number>({
64 id,
65 syncMode,
66 getKey: (item) => item.id,
67 persistence,
68 autoIndex: `eager`,
69 defaultIndexType: BTreeIndex,
70 }),
71 )
72
73 return {
74 collection,
75 seedPersisted,
76 }
77}
78
79type PersistedTransactionHandle = {
80 isPersisted: {
81 promise: Promise<unknown>
82 }
83}
84
85async function waitForPersisted(
86 transaction: PersistedTransactionHandle,
87): Promise<void> {
88 await transaction.isPersisted.promise
89}
90
91async function seedCollection<T extends PersistableRow>(
92 collection: Collection<T, string | number>,
93 rows: Array<T>,
94): Promise<void> {
95 const tx = collection.insert(rows)
96 await waitForPersisted(tx)
97}
98
99async function insertRowIntoCollections<T extends PersistableRow>(
100 collections: ReadonlyArray<Collection<T, string | number>>,
101 row: T,
102): Promise<void> {
103 for (const collection of collections) {
104 const tx = collection.insert(row)
105 await waitForPersisted(tx)
106 }
107}
108
109async function updateRowAcrossCollections<T extends PersistableRow>(
110 collections: ReadonlyArray<Collection<T, string | number>>,
111 id: string,
112 updates: Partial<T>,
113): Promise<void> {
114 for (const collection of collections) {
115 if (!collection.has(id)) {
116 continue
117 }
118 const tx = collection.update(id, (draft) => {
119 Object.assign(draft, updates)
120 })
121 await waitForPersisted(tx)
122 }
123}
124
125async function deleteRowAcrossCollections<T extends PersistableRow>(
126 collections: ReadonlyArray<Collection<T, string | number>>,
127 id: string,
128): Promise<void> {
129 for (const collection of collections) {
130 if (!collection.has(id)) {
131 continue
132 }
133 const tx = collection.delete(id)
134 await waitForPersisted(tx)
135 }
136}
137
138export function runMobilePersistedCollectionConformanceSuite(
139 suiteName: string,
140 createPersistence: MobilePersistenceFactory,
141): void {
142 let config: MobilePersistedCollectionTestConfig | undefined
143
144 beforeAll(async () => {
145 const tempDirectory = mkdtempSync(
146 join(tmpdir(), `db-rn-persisted-conformance-`),
147 )
148 const dbPath = join(tempDirectory, `state.sqlite`)
149 const suiteId = Date.now().toString(36)
150 const database = createOpSQLiteTestDatabase({
151 filename: dbPath,
152 resultShape: `statement-array`,
153 })
154 const seedData = generateSeedData()
155 const fixture = captureSeedData(seedData, {
156 registration:
157 'packages/react-native-db-sqlite-persistence/e2e/mobile-persisted-collection-conformance-suite.ts',
158 provider: 'React Native test database and supplied persistence factory',
159 })
160
161 const eagerUsers = createPersistedCollection<User>(
162 database,
163 `mobile-persisted-users-eager-${suiteId}`,
164 `eager`,
165 createPersistence,
166 )
167 const eagerPosts = createPersistedCollection<Post>(
168 database,
169 `mobile-persisted-posts-eager-${suiteId}`,
170 `eager`,
171 createPersistence,
172 )
173 const eagerComments = createPersistedCollection<Comment>(
174 database,
175 `mobile-persisted-comments-eager-${suiteId}`,
176 `eager`,
177 createPersistence,
178 )
179
180 const onDemandUsers = createPersistedCollection<User>(
181 database,
182 `mobile-persisted-users-ondemand-${suiteId}`,
183 `on-demand`,
184 createPersistence,
185 )
186 const onDemandPosts = createPersistedCollection<Post>(
187 database,
188 `mobile-persisted-posts-ondemand-${suiteId}`,
189 `on-demand`,
190 createPersistence,
191 )
192 const onDemandComments = createPersistedCollection<Comment>(
193 database,
194 `mobile-persisted-comments-ondemand-${suiteId}`,
195 `on-demand`,
196 createPersistence,
197 )
198
199 await Promise.all([
200 eagerUsers.collection.preload(),
201 eagerPosts.collection.preload(),
202 eagerComments.collection.preload(),
203 ])
204
205 await seedCollection(eagerUsers.collection, seedData.users)
206 await seedCollection(eagerPosts.collection, seedData.posts)
207 await seedCollection(eagerComments.collection, seedData.comments)
208 await onDemandUsers.seedPersisted(seedData.users)
209 await onDemandPosts.seedPersisted(seedData.posts)
210 await onDemandComments.seedPersisted(seedData.comments)
211
212 config = {
213 fixture,
214 collections: {
215 eager: {
216 users: eagerUsers.collection,
217 posts: eagerPosts.collection,
218 comments: eagerComments.collection,
219 },
220 onDemand: {
221 users: onDemandUsers.collection,
222 posts: onDemandPosts.collection,
223 comments: onDemandComments.collection,
224 },
225 },
226 mutations: {
227 insertUser: async (user) =>
228 insertRowIntoCollections(
229 [eagerUsers.collection, onDemandUsers.collection],
230 user,
231 ),
232 updateUser: async (id, updates) =>
233 updateRowAcrossCollections(
234 [eagerUsers.collection, onDemandUsers.collection],
235 id,
236 updates,
237 ),
238 deleteUser: async (id) =>
239 deleteRowAcrossCollections(
240 [eagerUsers.collection, onDemandUsers.collection],
241 id,
242 ),
243 insertPost: async (post) =>
244 insertRowIntoCollections(
245 [eagerPosts.collection, onDemandPosts.collection],
246 post,
247 ),
248 deletePost: async (id) =>
249 deleteRowAcrossCollections(
250 [eagerPosts.collection, onDemandPosts.collection],
251 id,
252 ),
253 },
254 setup: async () => {},
255 afterEach: async () => {
256 await Promise.all([
257 onDemandUsers.collection.cleanup(),
258 onDemandPosts.collection.cleanup(),
259 onDemandComments.collection.cleanup(),
260 ])
261
262 onDemandUsers.collection.startSyncImmediate()
263 onDemandPosts.collection.startSyncImmediate()
264 onDemandComments.collection.startSyncImmediate()
265 },
266 teardown: async () => {
267 await Promise.all([
268 eagerUsers.collection.cleanup(),
269 eagerPosts.collection.cleanup(),
270 eagerComments.collection.cleanup(),
271 onDemandUsers.collection.cleanup(),
272 onDemandPosts.collection.cleanup(),
273 onDemandComments.collection.cleanup(),
274 ])
275 await Promise.resolve(database.close())
276 rmSync(tempDirectory, { recursive: true, force: true })
277 },
278 }
279 })
280
281 afterEach(async () => {
282 if (config?.afterEach) {
283 await config.afterEach()
284 }
285 })
286
287 afterAll(async () => {
288 if (config) {
289 await config.teardown()
290 }
291 })
292
293 function getConfig(): Promise<MobilePersistedCollectionTestConfig> {
294 if (!config) {
295 throw new Error(`${suiteName} config is not initialized`)
296 }
297 return Promise.resolve(config)
298 }
299
300 runPersistedCollectionConformanceSuite(suiteName, getConfig)
301}