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 {
5 createCollection,
6 createTransaction,
7 eq,
8 liveQueryCollectionOptions,
9} from '@tanstack/db'
10import { describe, expect, it, onTestFinished, vi } from 'vitest'
11import { powerSyncCollectionOptions } from '../src'
12import { PowerSyncTransactor } from '../src/PowerSyncTransactor'
13import { TEST_DATABASE_IMPLEMENTATION } from './test-db-implementation'
14import type { LockContext } from '@powersync/node'
15import type { PendingMutation } from '@tanstack/db'
16
17const APP_SCHEMA = new Schema({
18 users: new Table({
19 name: column.text,
20 active: column.integer, // Will be mapped to Boolean
21 }),
22 documents: new Table(
23 {
24 name: column.text,
25 author: column.text,
26 created_at: column.text, // Will be mapped to Date
27 },
28 {
29 trackMetadata: true,
30 },
31 ),
32})
33
34const describePowerSync = TEST_DATABASE_IMPLEMENTATION
35 ? describe
36 : describe.skip
37
38type NativeCrudRow = {
39 id: string | number
40 data: string
41 tx_id: number | null
42}
43
44function expectTransactionCrud(
45 rows: Array<NativeCrudRow>,
46 expected: Array<{ id: string; type: string; name: string }>,
47) {
48 expect(rows).toHaveLength(expected.length)
49 const observations = rows.map((row) => JSON.parse(row.data) as unknown)
50 expect(observations).toEqual(
51 expected.map(({ id, type, name }) => ({
52 id,
53 type,
54 op: `PUT`,
55 data: { name },
56 })),
57 )
58 expect(rows[0]!.tx_id).toEqual(expect.any(Number))
59 expect(rows.every((row) => row.tx_id === rows[0]!.tx_id)).toBe(true)
60}
61
62function sortTransactionRows<T extends { id: string }>(rows: Array<T>) {
63 return [...rows].sort((a, b) => a.id.localeCompare(b.id))
64}
65
66describePowerSync(`PowerSync Integration`, () => {
67 async function createDatabase() {
68 const db = new PowerSyncDatabase({
69 database: {
70 dbFilename: `test-${randomUUID()}.sqlite`,
71 dbLocation: tmpdir(),
72 implementation: TEST_DATABASE_IMPLEMENTATION,
73 },
74 schema: APP_SCHEMA,
75 })
76 onTestFinished(async () => {
77 await db.disconnectAndClear()
78 await db.close()
79 })
80 // Initial clear in case a test might have failed
81 await db.disconnectAndClear()
82 return db
83 }
84
85 function createDocumentsCollection(db: PowerSyncDatabase) {
86 const collection = createCollection(
87 powerSyncCollectionOptions({
88 database: db,
89 // We get typing and a default validator from this
90 table: APP_SCHEMA.props.documents,
91 }),
92 )
93 onTestFinished(() => collection.cleanup({ dependents: true }))
94 return collection
95 }
96
97 async function createTestData(db: PowerSyncDatabase) {
98 await db.execute(`
99 INSERT into documents (id, name)
100 VALUES
101 (uuid(), 'one'),
102 (uuid(), 'two'),
103 (uuid(), 'three')
104 `)
105 }
106
107 describe(`sync`, () => {
108 it(`should initialize and fetch initial data`, async () => {
109 const db = await createDatabase()
110 await createTestData(db)
111 const collection = createDocumentsCollection(db)
112
113 await collection.stateWhenReady()
114
115 // Verify the collection state contains our items
116 expect(collection.size).toBe(3)
117 // Sort by name since keys are random UUIDs
118 expect(collection.toArray.map((entry) => entry.name).sort()).deep.equals([
119 `one`,
120 `three`,
121 `two`,
122 ])
123 })
124
125 it(`should update when data syncs`, async () => {
126 const db = await createDatabase()
127 await createTestData(db)
128
129 const collection = createDocumentsCollection(db)
130
131 await collection.stateWhenReady()
132
133 // Verify the collection state contains our items
134 expect(collection.size).toBe(3)
135
136 // Make an update, simulates a sync from another client
137 await db.execute(`
138 INSERT into documents (id, name)
139 VALUES
140 (uuid(), 'four')
141 `)
142
143 // The collection should update
144 await vi.waitFor(
145 () => {
146 expect(collection.size).toBe(4)
147 // Sort by name since keys are random UUIDs
148 expect(
149 collection.toArray.map((entry) => entry.name).sort(),
150 ).deep.equals([`four`, `one`, `three`, `two`])
151 },
152 { timeout: 1000 },
153 )
154
155 await db.execute(`
156 DELETE from documents
157 WHERE name = 'two'
158 `)
159
160 // The collection should update
161 await vi.waitFor(
162 () => {
163 expect(collection.size).toBe(3)
164 // Sort by name since keys are random UUIDs
165 expect(
166 collection.toArray.map((entry) => entry.name).sort(),
167 ).deep.equals([`four`, `one`, `three`])
168 },
169 { timeout: 1000 },
170 )
171
172 await db.execute(`
173 UPDATE documents
174 SET name = 'updated'
175 WHERE name = 'one'
176 `)
177
178 // The collection should update
179 await vi.waitFor(
180 () => {
181 expect(collection.size).toBe(3)
182 // Sort by name since keys are random UUIDs
183 expect(
184 collection.toArray.map((entry) => entry.name).sort(),
185 ).deep.equals([`four`, `three`, `updated`])
186 },
187 { timeout: 1000 },
188 )
189 })
190
191 it(`should propagate collection mutations to PowerSync`, async () => {
192 const db = await createDatabase()
193 await createTestData(db)
194
195 const collection = createDocumentsCollection(db)
196 await collection.stateWhenReady()
197
198 // Verify the collection state contains our items
199 expect(collection.size).toBe(3)
200
201 const id = randomUUID()
202 const tx = collection.insert({
203 id,
204 name: `new`,
205 author: `somebody`,
206 })
207
208 // The insert should optimistically update the collection
209 const newDoc = collection.get(id)
210 expect(newDoc).toBeDefined()
211 expect(newDoc!.name).toBe(`new`)
212 expect(newDoc!.author).toBe(`somebody`)
213
214 await tx.when(`settled`)
215 // The item should now be present in PowerSync
216 // We should also have patched it back in to Tanstack DB (removing the optimistic state)
217
218 // Now do an update
219 await collection
220 .update(id, (d) => (d.name = `updatedNew`))
221 .when(`settled`)
222
223 const updatedDoc = collection.get(id)
224 expect(updatedDoc).toBeDefined()
225 expect(updatedDoc!.name).toBe(`updatedNew`)
226 // Only the updated field should be updated
227 expect(updatedDoc!.author).toBe(`somebody`)
228
229 await collection.delete(id).when(`settled`)
230
231 // There should be a crud entries for this
232 const crudEntries = await db.getAll<{ op: string }>(`
233 SELECT data ->> 'op' AS op FROM ps_crud ORDER BY id`)
234
235 expect(crudEntries.length).toBe(6)
236 // We can only group transactions for similar operations
237 expect(crudEntries.map((e) => e.op)).toEqual([
238 `PUT`,
239 `PUT`,
240 `PUT`,
241 `PUT`,
242 `PATCH`,
243 `DELETE`,
244 ])
245 })
246
247 it(`should handle transactions`, async () => {
248 const db = await createDatabase()
249 await createTestData(db)
250
251 const collection = createDocumentsCollection(db)
252 await collection.stateWhenReady()
253
254 expect(collection.size).toBe(3)
255
256 const seed = await db.getAll<{ id: string; name: string }>(
257 `SELECT id, name FROM documents`,
258 )
259 const initialCrud = await db.getAll<NativeCrudRow>(
260 `SELECT * FROM ps_crud ORDER BY id`,
261 )
262 const expected = [
263 { id: `transaction-doc-0`, type: `documents`, name: `tx-0` },
264 { id: `transaction-doc-1`, type: `documents`, name: `tx-1` },
265 { id: `transaction-doc-2`, type: `documents`, name: `tx-2` },
266 { id: `transaction-doc-3`, type: `documents`, name: `tx-3` },
267 { id: `transaction-doc-4`, type: `documents`, name: `tx-4` },
268 ]
269 try {
270 const addTx = createTransaction({
271 autoCommit: false,
272 mutationFn: async ({ transaction }) => {
273 await new PowerSyncTransactor({ database: db }).applyTransaction(
274 transaction,
275 )
276 },
277 })
278
279 addTx.mutate(() => {
280 for (let i = 0; i < 5; i++) {
281 collection.insert({ id: `transaction-doc-${i}`, name: `tx-${i}` })
282 }
283 })
284
285 await addTx.commit()
286 await addTx.when(`settled`)
287
288 expect(collection.size).toBe(8)
289
290 // fetch the ps_crud items
291 // There should be a crud entries for this
292 const crudEntries = await db.getAll<NativeCrudRow>(`
293 SELECT * FROM ps_crud ORDER BY id`)
294 expect(crudEntries.slice(0, initialCrud.length)).toEqual(initialCrud)
295 const newCrud = crudEntries.slice(initialCrud.length)
296 expectTransactionCrud(newCrud, expected)
297 expect(() =>
298 expectTransactionCrud(newCrud.slice(1), expected),
299 ).toThrow()
300 expect(() =>
301 expectTransactionCrud(
302 [...newCrud.slice(0, -1), newCrud[0]!],
303 expected,
304 ),
305 ).toThrow()
306 const expectedRows = sortTransactionRows([
307 ...[`one`, `two`, `three`].map((name) => ({
308 id: seed.find((row) => row.name === name)!.id,
309 name,
310 author: null,
311 created_at: null,
312 })),
313 ...expected.map(({ id, name }) => ({
314 id,
315 name,
316 author: null,
317 created_at: null,
318 })),
319 ])
320 expect(
321 sortTransactionRows(
322 await db.getAll<{ id: string }>(
323 `SELECT id, name, author, created_at FROM documents`,
324 ),
325 ),
326 ).toEqual(expectedRows)
327 expect(
328 sortTransactionRows(
329 collection.toArray.map(({ id, name, author, created_at }) => ({
330 id,
331 name,
332 author,
333 created_at,
334 })),
335 ),
336 ).toEqual(expectedRows)
337
338 const lastTransactionId = crudEntries[crudEntries.length - 1]?.tx_id
339 /**
340 * The last items, created in the same transaction, should be in the same
341 * PowerSync transaction.
342 */
343 expect(
344 crudEntries
345 .reverse()
346 .slice(0, 5)
347 .every((crudEntry) => crudEntry.tx_id == lastTransactionId),
348 ).true
349 } finally {
350 await collection.cleanup()
351 }
352 })
353
354 it(`should complete transactions that delete one key and insert another (same-millisecond tie)`, async () => {
355 const db = await createDatabase()
356
357 const options = powerSyncCollectionOptions({
358 database: db,
359 table: APP_SCHEMA.props.documents,
360 })
361 const collection = createCollection(options)
362 onTestFinished(() => collection.cleanup())
363 await collection.stateWhenReady()
364
365 // Seed the row which will be deleted in the transaction
366 await collection.insert({ id: `a`, name: `row a` }).when(`settled`)
367
368 const { trackedTableName } = options.utils.getMeta()
369
370 class SameMillisecondTransactor extends PowerSyncTransactor {
371 protected override async handleDelete(
372 mutation: PendingMutation<any>,
373 context: LockContext,
374 waitForCompletion?: boolean,
375 ) {
376 const result = await super.handleDelete(
377 mutation,
378 context,
379 waitForCompletion,
380 )
381 // Simulate the same-millisecond tie: ensure the delete's diff row
382 // wins the `ORDER BY timestamp DESC` readback of the insert below.
383 await context.execute(
384 `UPDATE ${trackedTableName} SET timestamp = '9999-12-31T23:59:59.999Z'`,
385 )
386 return result
387 }
388 }
389
390 const transactor = new SameMillisecondTransactor({ database: db })
391
392 const tx = createTransaction({
393 autoCommit: false,
394 mutationFn: async ({ transaction }) => {
395 await transactor.applyTransaction(transaction)
396 },
397 })
398
399 tx.mutate(() => {
400 collection.delete(`a`)
401 collection.insert({ id: `b`, name: `row b` })
402 })
403
404 const outcome = await Promise.race([
405 tx.commit().then(() => `persisted` as const),
406 new Promise<`timed out`>((resolve) =>
407 setTimeout(() => resolve(`timed out`), 2_000),
408 ),
409 ])
410 expect(outcome).toBe(`persisted`)
411
412 const documents = await db.getAll<{ id: string }>(
413 `SELECT id FROM documents`,
414 )
415 expect(documents.map((doc) => doc.id)).toEqual([`b`])
416 })
417
418 it(`should handle transactions with multiple collections`, async () => {
419 const db = await createDatabase()
420 await createTestData(db)
421
422 const documentsCollection = createDocumentsCollection(db)
423
424 const usersCollection = createCollection(
425 powerSyncCollectionOptions({
426 database: db,
427 table: APP_SCHEMA.props.users,
428 }),
429 )
430 onTestFinished(() => usersCollection.cleanup())
431
432 await documentsCollection.stateWhenReady()
433 await usersCollection.stateWhenReady()
434
435 expect(documentsCollection.size).toBe(3)
436 expect(usersCollection.size).toBe(0)
437
438 const seed = await db.getAll<{ id: string; name: string }>(
439 `SELECT id, name FROM documents`,
440 )
441 const initialCrud = await db.getAll<NativeCrudRow>(
442 `SELECT * FROM ps_crud ORDER BY id`,
443 )
444 const expected = [
445 { id: `mixed-doc-0`, type: `documents`, name: `tx-0` },
446 { id: `mixed-user-0`, type: `users`, name: `user` },
447 { id: `mixed-doc-1`, type: `documents`, name: `tx-1` },
448 { id: `mixed-user-1`, type: `users`, name: `user` },
449 { id: `mixed-doc-2`, type: `documents`, name: `tx-2` },
450 { id: `mixed-user-2`, type: `users`, name: `user` },
451 { id: `mixed-doc-3`, type: `documents`, name: `tx-3` },
452 { id: `mixed-user-3`, type: `users`, name: `user` },
453 { id: `mixed-doc-4`, type: `documents`, name: `tx-4` },
454 { id: `mixed-user-4`, type: `users`, name: `user` },
455 ]
456 try {
457 const addTx = createTransaction({
458 autoCommit: false,
459 mutationFn: async ({ transaction }) => {
460 await new PowerSyncTransactor({ database: db }).applyTransaction(
461 transaction,
462 )
463 },
464 })
465
466 addTx.mutate(() => {
467 for (let i = 0; i < 5; i++) {
468 documentsCollection.insert({
469 id: `mixed-doc-${i}`,
470 name: `tx-${i}`,
471 })
472 usersCollection.insert({ id: `mixed-user-${i}`, name: `user` })
473 }
474 })
475
476 await addTx.commit()
477 await addTx.when(`settled`)
478
479 expect(documentsCollection.size).toBe(8)
480 expect(usersCollection.size).toBe(5)
481
482 // fetch the ps_crud items
483 // There should be a crud entries for this
484 const crudEntries = await db.getAll<NativeCrudRow>(`
485 SELECT * FROM ps_crud ORDER BY id`)
486 expect(crudEntries.slice(0, initialCrud.length)).toEqual(initialCrud)
487 const newCrud = crudEntries.slice(initialCrud.length)
488 expectTransactionCrud(newCrud, expected)
489 const corrupted = structuredClone(newCrud)
490 corrupted[0]!.data = JSON.stringify({
491 id: `wrong-row`,
492 type: `documents`,
493 op: `PUT`,
494 data: { name: `tx-0` },
495 })
496 expect(() => expectTransactionCrud(corrupted, expected)).toThrow()
497 const expectedDocuments = sortTransactionRows([
498 ...[`one`, `two`, `three`].map((name) => ({
499 id: seed.find((row) => row.name === name)!.id,
500 name,
501 author: null,
502 created_at: null,
503 })),
504 ...expected
505 .filter((row) => row.type === `documents`)
506 .map(({ id, name }) => ({
507 id,
508 name,
509 author: null,
510 created_at: null,
511 })),
512 ])
513 const expectedUsers = sortTransactionRows(
514 expected
515 .filter((row) => row.type === `users`)
516 .map(({ id, name }) => ({ id, name, active: null })),
517 )
518 expect(
519 sortTransactionRows(
520 await db.getAll<{ id: string }>(
521 `SELECT id, name, author, created_at FROM documents`,
522 ),
523 ),
524 ).toEqual(expectedDocuments)
525 expect(
526 sortTransactionRows(
527 documentsCollection.toArray.map(
528 ({ id, name, author, created_at }) => ({
529 id,
530 name,
531 author,
532 created_at,
533 }),
534 ),
535 ),
536 ).toEqual(expectedDocuments)
537 expect(
538 sortTransactionRows(
539 await db.getAll<{ id: string }>(
540 `SELECT id, name, active FROM users`,
541 ),
542 ),
543 ).toEqual(expectedUsers)
544 expect(
545 sortTransactionRows(
546 usersCollection.toArray.map(({ id, name, active }) => ({
547 id,
548 name,
549 active,
550 })),
551 ),
552 ).toEqual(expectedUsers)
553
554 const lastTransactionId = crudEntries[crudEntries.length - 1]?.tx_id
555 /**
556 * The last items, created in the same transaction, should be in the same
557 * PowerSync transaction.
558 */
559 expect(
560 crudEntries
561 .reverse()
562 .slice(0, 10)
563 .every((crudEntry) => crudEntry.tx_id == lastTransactionId),
564 ).true
565 } finally {
566 await documentsCollection.cleanup()
567 await usersCollection.cleanup()
568 }
569 })
570
571 /**
572 * Metadata provided by the collection operation should be persisted to the database if supported by the SQLite table.
573 */
574 it(`should persist collection operation metadata`, async () => {
575 const db = await createDatabase()
576
577 const collection = createDocumentsCollection(db)
578 await collection.stateWhenReady()
579
580 const metadata = {
581 text: `some text`,
582 number: 123,
583 boolean: true,
584 }
585 const id = randomUUID()
586 await collection
587 .insert(
588 {
589 id,
590 name: `new`,
591 author: `somebody`,
592 },
593 {
594 metadata,
595 },
596 )
597 .when(`settled`)
598
599 // Now do an update
600 await collection
601 .update(id, { metadata: metadata }, (d) => (d.name = `updatedNew`))
602 .when(`settled`)
603
604 await collection.delete(id, { metadata }).when(`settled`)
605
606 // There should be a crud entries for this
607 const crudBatch = await db.getCrudBatch(100)
608 expect(crudBatch).toBeDefined()
609 const crudEntries = crudBatch!.crud
610
611 // The metadata should be available in the CRUD entries for upload
612 const stringifiedMetadata = JSON.stringify(metadata)
613 expect(crudEntries.length).toBe(3)
614 expect(crudEntries[0]!.metadata).toEqual(stringifiedMetadata)
615 expect(crudEntries[1]!.metadata).toEqual(stringifiedMetadata)
616 expect(crudEntries[2]!.metadata).toEqual(stringifiedMetadata)
617
618 // Verify the item is deleted from SQLite
619 const documents = await db.getAll(`
620 SELECT * FROM documents`)
621 expect(documents.length).toBe(0)
622 })
623 })
624
625 describe(`General use`, () => {
626 it(`should rollback transactions on error`, async () => {
627 const db = await createDatabase()
628
629 const options = powerSyncCollectionOptions({
630 database: db,
631 table: APP_SCHEMA.props.documents,
632 })
633
634 // This will cause the transactor to fail when writing to SQLite
635 vi.spyOn(options.utils, `getMeta`).mockImplementation(() => ({
636 tableName: `fakeTable`,
637 trackedTableName: `error`,
638 metadataIsTracked: true,
639 serializeValue: () => ({}) as any,
640 }))
641 // Create two collections for the same table
642 const collection = createCollection(options)
643
644 onTestFinished(() => collection.cleanup())
645 const addTx = createTransaction({
646 autoCommit: false,
647 mutationFn: async ({ transaction }) => {
648 await new PowerSyncTransactor({ database: db }).applyTransaction(
649 transaction,
650 )
651 },
652 })
653
654 expect(collection.size).eq(0)
655 await collection.stateWhenReady()
656
657 const id = randomUUID()
658 addTx.mutate(() => {
659 collection.insert({
660 id,
661 name: `aname`,
662 })
663 })
664
665 // This should be present in the optimistic state, but should be reverted when attempting to persist
666 expect(collection.size).eq(1)
667
668 try {
669 await addTx.commit()
670 await addTx.when(`settled`)
671 expect.fail(`Should have thrown an error`)
672 } catch (error) {
673 expect(error).toBeDefined()
674 // The collection should be in a clean state
675 expect(collection.size).toBe(0)
676 }
677 })
678
679 it(`should work with live queries`, async () => {
680 const db = await createDatabase()
681
682 // Create two collections for the same table
683 const collection = createDocumentsCollection(db)
684
685 await collection.stateWhenReady()
686
687 const liveDocuments = createCollection(
688 liveQueryCollectionOptions({
689 query: (q) =>
690 q
691 .from({ document: collection })
692 .where(({ document }) => eq(document.name, `book`))
693 .select(({ document }) => ({
694 id: document.id,
695 name: document.name,
696 })),
697 }),
698 )
699
700 expect(liveDocuments.size).eq(0)
701
702 const bookNames = new Set<string>()
703
704 liveDocuments.subscribeChanges((changes) => {
705 changes
706 .map((change) => change.value.name)
707 .filter((name): name is string => name !== undefined)
708 .forEach((change) => bookNames.add(change))
709 })
710
711 await collection
712 .insert({
713 id: randomUUID(),
714 name: `notabook`,
715 })
716 .when(`settled`)
717 await collection
718 .insert({
719 id: randomUUID(),
720 name: `book`,
721 })
722 .when(`settled`)
723
724 expect(collection.size).eq(2)
725 await vi.waitFor(
726 () => {
727 expect(Array.from(bookNames)).deep.equals([`book`])
728 },
729 { timeout: 1000 },
730 )
731 })
732 })
733
734 describe(`Multiple Clients`, () => {
735 it(`should sync updates between multiple clients`, async () => {
736 const db = await createDatabase()
737
738 // Create two collections for the same table
739 const collectionA = createDocumentsCollection(db)
740 await collectionA.stateWhenReady()
741
742 const collectionB = createDocumentsCollection(db)
743 await collectionB.stateWhenReady()
744
745 await createTestData(db)
746
747 // Both collections should have the data present after insertion
748 await vi.waitFor(
749 () => {
750 expect(collectionA.size).eq(3)
751 expect(collectionB.size).eq(3)
752 },
753 { timeout: 1000 },
754 )
755 })
756 })
757
758 describe(`Lifecycle`, () => {
759 it(`should cleanup resources`, async () => {
760 const db = await createDatabase()
761 const collectionOptions = powerSyncCollectionOptions({
762 database: db,
763 table: APP_SCHEMA.props.documents,
764 })
765
766 const meta = collectionOptions.utils.getMeta()
767
768 const tableExists = async (): Promise<boolean> => {
769 const result = await db.writeLock(async (tx) => {
770 return tx.get<{ count: number }>(
771 `
772 SELECT COUNT(*) as count
773 FROM sqlite_temp_master
774 WHERE type='table' AND name = ?
775 `,
776 [meta.trackedTableName],
777 )
778 })
779 return result.count > 0
780 }
781
782 const collection = createCollection(collectionOptions)
783 await collection.stateWhenReady()
784 expect(await tableExists()).true
785
786 await collection.cleanup()
787
788 // It seems that even though `cleanup` is async, the sync disposer cannot be async
789 // We wait for the table to be deleted
790 await vi.waitFor(
791 async () => {
792 expect(await tableExists()).false
793 },
794 { timeout: 1000 },
795 )
796 })
797 })
798})