forked from TanStack/db
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpowersync.test.ts
More file actions
497 lines (420 loc) · 13.6 KB
/
powersync.test.ts
File metadata and controls
497 lines (420 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
import { randomUUID } from "node:crypto"
import { tmpdir } from "node:os"
import {
CrudEntry,
PowerSyncDatabase,
Schema,
Table,
column,
} from "@powersync/node"
import {
createCollection,
createTransaction,
eq,
liveQueryCollectionOptions,
} from "@tanstack/db"
import { describe, expect, it, onTestFinished, vi } from "vitest"
import { powerSyncCollectionOptions } from "../src"
import { PowerSyncTransactor } from "../src/PowerSyncTransactor"
import type { AbstractPowerSyncDatabase } from "@powersync/node"
const APP_SCHEMA = new Schema({
users: new Table({
name: column.text,
active: column.integer, // Will be mapped to Boolean
}),
documents: new Table({
name: column.text,
author: column.text,
created_at: column.text, // Will be mapped to Date
}),
})
describe(`PowerSync Integration`, () => {
async function createDatabase() {
const db = new PowerSyncDatabase({
database: {
dbFilename: `test-${randomUUID()}.sqlite`,
dbLocation: tmpdir(),
implementation: { type: `node:sqlite` },
},
schema: APP_SCHEMA,
})
onTestFinished(async () => {
await db.disconnectAndClear()
await db.close()
})
// Initial clear in case a test might have failed
await db.disconnectAndClear()
return db
}
function createDocumentsCollection(db: PowerSyncDatabase) {
const collection = createCollection(
powerSyncCollectionOptions({
database: db,
// We get typing and a default validator from this
table: APP_SCHEMA.props.documents,
})
)
onTestFinished(() => collection.cleanup())
return collection
}
async function createTestData(db: AbstractPowerSyncDatabase) {
await db.execute(`
INSERT into documents (id, name)
VALUES
(uuid(), 'one'),
(uuid(), 'two'),
(uuid(), 'three')
`)
}
describe(`sync`, () => {
it(`should initialize and fetch initial data`, async () => {
const db = await createDatabase()
await createTestData(db)
const collection = createDocumentsCollection(db)
await collection.stateWhenReady()
// Verify the collection state contains our items
expect(collection.size).toBe(3)
expect(collection.toArray.map((entry) => entry.name)).deep.equals([
`one`,
`two`,
`three`,
])
})
it(`should update when data syncs`, async () => {
const db = await createDatabase()
await createTestData(db)
const collection = createDocumentsCollection(db)
await collection.stateWhenReady()
// Verify the collection state contains our items
expect(collection.size).toBe(3)
// Make an update, simulates a sync from another client
await db.execute(`
INSERT into documents (id, name)
VALUES
(uuid(), 'four')
`)
// The collection should update
await vi.waitFor(
() => {
expect(collection.size).toBe(4)
expect(collection.toArray.map((entry) => entry.name)).deep.equals([
`one`,
`two`,
`three`,
`four`,
])
},
{ timeout: 1000 }
)
await db.execute(`
DELETE from documents
WHERE name = 'two'
`)
// The collection should update
await vi.waitFor(
() => {
expect(collection.size).toBe(3)
expect(collection.toArray.map((entry) => entry.name)).deep.equals([
`one`,
`three`,
`four`,
])
},
{ timeout: 1000 }
)
await db.execute(`
UPDATE documents
SET name = 'updated'
WHERE name = 'one'
`)
// The collection should update
await vi.waitFor(
() => {
expect(collection.size).toBe(3)
expect(collection.toArray.map((entry) => entry.name)).deep.equals([
`updated`,
`three`,
`four`,
])
},
{ timeout: 1000 }
)
})
it(`should propagate collection mutations to PowerSync`, async () => {
const db = await createDatabase()
await createTestData(db)
const collection = createDocumentsCollection(db)
await collection.stateWhenReady()
// Verify the collection state contains our items
expect(collection.size).toBe(3)
const id = randomUUID()
const tx = collection.insert({
id,
name: `new`,
author: `somebody`,
})
// The insert should optimistically update the collection
const newDoc = collection.get(id)
expect(newDoc).toBeDefined()
expect(newDoc!.name).toBe(`new`)
expect(newDoc!.author).toBe(`somebody`)
await tx.isPersisted.promise
// The item should now be present in PowerSync
// We should also have patched it back in to Tanstack DB (removing the optimistic state)
// Now do an update
await collection.update(id, (d) => (d.name = `updatedNew`)).isPersisted
.promise
const updatedDoc = collection.get(id)
expect(updatedDoc).toBeDefined()
expect(updatedDoc!.name).toBe(`updatedNew`)
// Only the updated field should be updated
expect(updatedDoc!.author).toBe(`somebody`)
await collection.delete(id).isPersisted.promise
// There should be a crud entries for this
const _crudEntries = await db.getAll(`
SELECT * FROM ps_crud ORDER BY id`)
const crudEntries = _crudEntries.map((r) => CrudEntry.fromRow(r))
expect(crudEntries.length).toBe(6)
// We can only group transactions for similar operations
expect(crudEntries.map((e) => e.op)).toEqual([
`PUT`,
`PUT`,
`PUT`,
`PUT`,
`PATCH`,
`DELETE`,
])
})
it(`should handle transactions`, async () => {
const db = await createDatabase()
await createTestData(db)
const collection = createDocumentsCollection(db)
await collection.stateWhenReady()
expect(collection.size).toBe(3)
const addTx = createTransaction({
autoCommit: false,
mutationFn: async ({ transaction }) => {
await new PowerSyncTransactor({ database: db }).applyTransaction(
transaction
)
},
})
addTx.mutate(() => {
for (let i = 0; i < 5; i++) {
collection.insert({ id: randomUUID(), name: `tx-${i}` })
}
})
await addTx.commit()
await addTx.isPersisted.promise
expect(collection.size).toBe(8)
// fetch the ps_crud items
// There should be a crud entries for this
const _crudEntries = await db.getAll(`
SELECT * FROM ps_crud ORDER BY id`)
const crudEntries = _crudEntries.map((r) => CrudEntry.fromRow(r))
const lastTransactionId =
crudEntries[crudEntries.length - 1]?.transactionId
/**
* The last items, created in the same transaction, should be in the same
* PowerSync transaction.
*/
expect(
crudEntries
.reverse()
.slice(0, 5)
.every((crudEntry) => crudEntry.transactionId == lastTransactionId)
).true
})
it(`should handle transactions with multiple collections`, async () => {
const db = await createDatabase()
await createTestData(db)
const documentsCollection = createDocumentsCollection(db)
const usersCollection = createCollection(
powerSyncCollectionOptions({
database: db,
table: APP_SCHEMA.props.users,
})
)
onTestFinished(() => usersCollection.cleanup())
await documentsCollection.stateWhenReady()
await usersCollection.stateWhenReady()
expect(documentsCollection.size).toBe(3)
expect(usersCollection.size).toBe(0)
const addTx = createTransaction({
autoCommit: false,
mutationFn: async ({ transaction }) => {
await new PowerSyncTransactor({ database: db }).applyTransaction(
transaction
)
},
})
addTx.mutate(() => {
for (let i = 0; i < 5; i++) {
documentsCollection.insert({ id: randomUUID(), name: `tx-${i}` })
usersCollection.insert({ id: randomUUID(), name: `user` })
}
})
await addTx.commit()
await addTx.isPersisted.promise
expect(documentsCollection.size).toBe(8)
expect(usersCollection.size).toBe(5)
// fetch the ps_crud items
// There should be a crud entries for this
const _crudEntries = await db.getAll(`
SELECT * FROM ps_crud ORDER BY id`)
const crudEntries = _crudEntries.map((r) => CrudEntry.fromRow(r))
const lastTransactionId =
crudEntries[crudEntries.length - 1]?.transactionId
/**
* The last items, created in the same transaction, should be in the same
* PowerSync transaction.
*/
expect(
crudEntries
.reverse()
.slice(0, 10)
.every((crudEntry) => crudEntry.transactionId == lastTransactionId)
).true
})
})
describe(`General use`, () => {
it(`should rollback transactions on error`, async () => {
const db = await createDatabase()
const options = powerSyncCollectionOptions({
database: db,
table: APP_SCHEMA.props.documents,
})
// This will cause the transactor to fail when writing to SQLite
vi.spyOn(options.utils, `getMeta`).mockImplementation(() => ({
tableName: `fakeTable`,
trackedTableName: `error`,
serializeValue: () => ({}) as any,
}))
// Create two collections for the same table
const collection = createCollection(options)
onTestFinished(() => collection.cleanup())
const addTx = createTransaction({
autoCommit: false,
mutationFn: async ({ transaction }) => {
await new PowerSyncTransactor({ database: db }).applyTransaction(
transaction
)
},
})
expect(collection.size).eq(0)
await collection.stateWhenReady()
const id = randomUUID()
addTx.mutate(() => {
collection.insert({
id,
name: `aname`,
})
})
// This should be present in the optimistic state, but should be reverted when attempting to persist
expect(collection.size).eq(1)
try {
await addTx.commit()
await addTx.isPersisted.promise
expect.fail(`Should have thrown an error`)
} catch (error) {
expect(error).toBeDefined()
// The collection should be in a clean state
expect(collection.size).toBe(0)
}
})
it(`should work with live queries`, async () => {
const db = await createDatabase()
// Create two collections for the same table
const collection = createDocumentsCollection(db)
await collection.stateWhenReady()
const liveDocuments = createCollection(
liveQueryCollectionOptions({
query: (q) =>
q
.from({ document: collection })
.where(({ document }) => eq(document.name, `book`))
.select(({ document }) => ({
id: document.id,
name: document.name,
})),
})
)
expect(liveDocuments.size).eq(0)
const bookNames = new Set<string>()
liveDocuments.subscribeChanges((changes) => {
changes
.map((change) => change.value.name)
.forEach((change) => bookNames.add(change))
})
await collection.insert({
id: randomUUID(),
name: `notabook`,
}).isPersisted.promise
await collection.insert({
id: randomUUID(),
name: `book`,
}).isPersisted.promise
expect(collection.size).eq(2)
await vi.waitFor(
() => {
expect(Array.from(bookNames)).deep.equals([`book`])
},
{ timeout: 1000 }
)
})
})
describe(`Multiple Clients`, () => {
it(`should sync updates between multiple clients`, async () => {
const db = await createDatabase()
// Create two collections for the same table
const collectionA = createDocumentsCollection(db)
await collectionA.stateWhenReady()
const collectionB = createDocumentsCollection(db)
await collectionB.stateWhenReady()
await createTestData(db)
// Both collections should have the data present after insertion
await vi.waitFor(
() => {
expect(collectionA.size).eq(3)
expect(collectionB.size).eq(3)
},
{ timeout: 1000 }
)
})
})
describe(`Lifecycle`, () => {
it(`should cleanup resources`, async () => {
const db = await createDatabase()
const collectionOptions = powerSyncCollectionOptions({
database: db,
table: APP_SCHEMA.props.documents,
})
const meta = collectionOptions.utils.getMeta()
const tableExists = async (): Promise<boolean> => {
const result = await db.writeLock(async (tx) => {
return tx.get<{ count: number }>(
`
SELECT COUNT(*) as count
FROM sqlite_temp_master
WHERE type='table' AND name = ?
`,
[meta.trackedTableName]
)
})
return result.count > 0
}
const collection = createCollection(collectionOptions)
await collection.stateWhenReady()
expect(await tableExists()).true
await collection.cleanup()
// It seems that even though `cleanup` is async, the sync disposer cannot be async
// We wait for the table to be deleted
await vi.waitFor(
async () => {
expect(await tableExists()).false
},
{ timeout: 1000 }
)
})
})
})