Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

powersync.test.ts

793 lines23.6 KB

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
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)
61​
62function sortTransactionRows<T extends { id: string }>(rows: Array<T>) {
63 return [...rows].sort((a, b) => a.id.localeCompare(b.id))
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())
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.isPersisted.promise
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.update(id, (d) => (d.name = `updatedNew`)).isPersisted
220 .promise
221​
222 const updatedDoc = collection.get(id)
223 expect(updatedDoc).toBeDefined()
224 expect(updatedDoc!.name).toBe(`updatedNew`)
225 // Only the updated field should be updated
226 expect(updatedDoc!.author).toBe(`somebody`)
227​
228 await collection.delete(id).isPersisted.promise
229​
230 // There should be a crud entries for this
231 const crudEntries = await db.getAll<{ op: string }>(`
232 SELECT data ->> 'op' AS op FROM ps_crud ORDER BY id`)
233​
234 expect(crudEntries.length).toBe(6)
235 // We can only group transactions for similar operations
236 expect(crudEntries.map((e) => e.op)).toEqual([
237 `PUT`,
238 `PUT`,
239 `PUT`,
240 `PUT`,
241 `PATCH`,
242 `DELETE`,
243 ])
244 })
245​
246 it(`should handle transactions`, async () => {
247 const db = await createDatabase()
248 await createTestData(db)
249​
250 const collection = createDocumentsCollection(db)
251 await collection.stateWhenReady()
252​
253 expect(collection.size).toBe(3)
254​
255 const seed = await db.getAll<{ id: string; name: string }>(
256 `SELECT id, name FROM documents`,
257 )
258 const initialCrud = await db.getAll<NativeCrudRow>(
259 `SELECT * FROM ps_crud ORDER BY id`,
260 )
261 const expected = [
262 { id: `transaction-doc-0`, type: `documents`, name: `tx-0` },
263 { id: `transaction-doc-1`, type: `documents`, name: `tx-1` },
264 { id: `transaction-doc-2`, type: `documents`, name: `tx-2` },
265 { id: `transaction-doc-3`, type: `documents`, name: `tx-3` },
266 { id: `transaction-doc-4`, type: `documents`, name: `tx-4` },
267 ]
268 try {
269 const addTx = createTransaction({
270 autoCommit: false,
271 mutationFn: async ({ transaction }) => {
272 await new PowerSyncTransactor({ database: db }).applyTransaction(
273 transaction,
274 )
275 },
276 })
277​
278 addTx.mutate(() => {
279 for (let i = 0; i < 5; i++) {
280 collection.insert({ id: `transaction-doc-${i}`, name: `tx-${i}` })
281 }
282 })
283​
284 await addTx.commit()
285 await addTx.isPersisted.promise
286​
287 expect(collection.size).toBe(8)
288​
289 // fetch the ps_crud items
290 // There should be a crud entries for this
291 const crudEntries = await db.getAll<NativeCrudRow>(`
292 SELECT * FROM ps_crud ORDER BY id`)
293 expect(crudEntries.slice(0, initialCrud.length)).toEqual(initialCrud)
294 const newCrud = crudEntries.slice(initialCrud.length)
295 expectTransactionCrud(newCrud, expected)
296 expect(() =>
297 expectTransactionCrud(newCrud.slice(1), expected),
298 ).toThrow()
299 expect(() =>
300 expectTransactionCrud(
301 [...newCrud.slice(0, -1), newCrud[0]!],
302 expected,
303 ),
304 ).toThrow()
305 const expectedRows = sortTransactionRows([
306 ...[`one`, `two`, `three`].map((name) => ({
307 id: seed.find((row) => row.name === name)!.id,
308 name,
309 author: null,
310 created_at: null,
311 })),
312 ...expected.map(({ id, name }) => ({
313 id,
314 name,
315 author: null,
316 created_at: null,
317 })),
318 ])
319 expect(
320 sortTransactionRows(
321 await db.getAll<{ id: string }>(
322 `SELECT id, name, author, created_at FROM documents`,
323 ),
324 ),
325 ).toEqual(expectedRows)
326 expect(
327 sortTransactionRows(
328 collection.toArray.map(({ id, name, author, created_at }) => ({
329 id,
330 name,
331 author,
332 created_at,
333 })),
334 ),
335 ).toEqual(expectedRows)
336​
337 const lastTransactionId = crudEntries[crudEntries.length - 1]?.tx_id
338 /**
339 * The last items, created in the same transaction, should be in the same
340 * PowerSync transaction.
341 */
342 expect(
343 crudEntries
344 .reverse()
345 .slice(0, 5)
346 .every((crudEntry) => crudEntry.tx_id == lastTransactionId),
347 ).true
348 } finally {
349 await collection.cleanup()
350 }
351 })
352​
353 it(`should complete transactions that delete one key and insert another (same-millisecond tie)`, async () => {
354 const db = await createDatabase()
355​
356 const options = powerSyncCollectionOptions({
357 database: db,
358 table: APP_SCHEMA.props.documents,
359 })
360 const collection = createCollection(options)
361 onTestFinished(() => collection.cleanup())
362 await collection.stateWhenReady()
363​
364 // Seed the row which will be deleted in the transaction
365 await collection.insert({ id: `a`, name: `row a` }).isPersisted.promise
366​
367 const { trackedTableName } = options.utils.getMeta()
368​
369 class SameMillisecondTransactor extends PowerSyncTransactor {
370 protected override async handleDelete(
371 mutation: PendingMutation<any>,
372 context: LockContext,
373 waitForCompletion?: boolean,
374 ) {
375 const result = await super.handleDelete(
376 mutation,
377 context,
378 waitForCompletion,
379 )
380 // Simulate the same-millisecond tie: ensure the delete's diff row
381 // wins the `ORDER BY timestamp DESC` readback of the insert below.
382 await context.execute(
383 `UPDATE ${trackedTableName} SET timestamp = '9999-12-31T23:59:59.999Z'`,
384 )
385 return result
386 }
387 }
388​
389 const transactor = new SameMillisecondTransactor({ database: db })
390​
391 const tx = createTransaction({
392 autoCommit: false,
393 mutationFn: async ({ transaction }) => {
394 await transactor.applyTransaction(transaction)
395 },
396 })
397​
398 tx.mutate(() => {
399 collection.delete(`a`)
400 collection.insert({ id: `b`, name: `row b` })
401 })
402​
403 const outcome = await Promise.race([
404 tx.commit().then(() => `persisted` as const),
405 new Promise<`timed out`>((resolve) =>
406 setTimeout(() => resolve(`timed out`), 2_000),
407 ),
408 ])
409 expect(outcome).toBe(`persisted`)
410​
411 const documents = await db.getAll<{ id: string }>(
412 `SELECT id FROM documents`,
413 )
414 expect(documents.map((doc) => doc.id)).toEqual([`b`])
415 })
416​
417 it(`should handle transactions with multiple collections`, async () => {
418 const db = await createDatabase()
419 await createTestData(db)
420​
421 const documentsCollection = createDocumentsCollection(db)
422​
423 const usersCollection = createCollection(
424 powerSyncCollectionOptions({
425 database: db,
426 table: APP_SCHEMA.props.users,
427 }),
428 )
429 onTestFinished(() => usersCollection.cleanup())
430​
431 await documentsCollection.stateWhenReady()
432 await usersCollection.stateWhenReady()
433​
434 expect(documentsCollection.size).toBe(3)
435 expect(usersCollection.size).toBe(0)
436​
437 const seed = await db.getAll<{ id: string; name: string }>(
438 `SELECT id, name FROM documents`,
439 )
440 const initialCrud = await db.getAll<NativeCrudRow>(
441 `SELECT * FROM ps_crud ORDER BY id`,
442 )
443 const expected = [
444 { id: `mixed-doc-0`, type: `documents`, name: `tx-0` },
445 { id: `mixed-user-0`, type: `users`, name: `user` },
446 { id: `mixed-doc-1`, type: `documents`, name: `tx-1` },
447 { id: `mixed-user-1`, type: `users`, name: `user` },
448 { id: `mixed-doc-2`, type: `documents`, name: `tx-2` },
449 { id: `mixed-user-2`, type: `users`, name: `user` },
450 { id: `mixed-doc-3`, type: `documents`, name: `tx-3` },
451 { id: `mixed-user-3`, type: `users`, name: `user` },
452 { id: `mixed-doc-4`, type: `documents`, name: `tx-4` },
453 { id: `mixed-user-4`, type: `users`, name: `user` },
454 ]
455 try {
456 const addTx = createTransaction({
457 autoCommit: false,
458 mutationFn: async ({ transaction }) => {
459 await new PowerSyncTransactor({ database: db }).applyTransaction(
460 transaction,
461 )
462 },
463 })
464​
465 addTx.mutate(() => {
466 for (let i = 0; i < 5; i++) {
467 documentsCollection.insert({
468 id: `mixed-doc-${i}`,
469 name: `tx-${i}`,
470 })
471 usersCollection.insert({ id: `mixed-user-${i}`, name: `user` })
472 }
473 })
474​
475 await addTx.commit()
476 await addTx.isPersisted.promise
477​
478 expect(documentsCollection.size).toBe(8)
479 expect(usersCollection.size).toBe(5)
480​
481 // fetch the ps_crud items
482 // There should be a crud entries for this
483 const crudEntries = await db.getAll<NativeCrudRow>(`
484 SELECT * FROM ps_crud ORDER BY id`)
485 expect(crudEntries.slice(0, initialCrud.length)).toEqual(initialCrud)
486 const newCrud = crudEntries.slice(initialCrud.length)
487 expectTransactionCrud(newCrud, expected)
488 const corrupted = structuredClone(newCrud)
489 corrupted[0]!.data = JSON.stringify({
490 id: `wrong-row`,
491 type: `documents`,
492 op: `PUT`,
493 data: { name: `tx-0` },
494 })
495 expect(() => expectTransactionCrud(corrupted, expected)).toThrow()
496 const expectedDocuments = sortTransactionRows([
497 ...[`one`, `two`, `three`].map((name) => ({
498 id: seed.find((row) => row.name === name)!.id,
499 name,
500 author: null,
501 created_at: null,
502 })),
503 ...expected
504 .filter((row) => row.type === `documents`)
505 .map(({ id, name }) => ({
506 id,
507 name,
508 author: null,
509 created_at: null,
510 })),
511 ])
512 const expectedUsers = sortTransactionRows(
513 expected
514 .filter((row) => row.type === `users`)
515 .map(({ id, name }) => ({ id, name, active: null })),
516 )
517 expect(
518 sortTransactionRows(
519 await db.getAll<{ id: string }>(
520 `SELECT id, name, author, created_at FROM documents`,
521 ),
522 ),
523 ).toEqual(expectedDocuments)
524 expect(
525 sortTransactionRows(
526 documentsCollection.toArray.map(
527 ({ id, name, author, created_at }) => ({
528 id,
529 name,
530 author,
531 created_at,
532 }),
533 ),
534 ),
535 ).toEqual(expectedDocuments)
536 expect(
537 sortTransactionRows(
538 await db.getAll<{ id: string }>(
539 `SELECT id, name, active FROM users`,
540 ),
541 ),
542 ).toEqual(expectedUsers)
543 expect(
544 sortTransactionRows(
545 usersCollection.toArray.map(({ id, name, active }) => ({
546 id,
547 name,
548 active,
549 })),
550 ),
551 ).toEqual(expectedUsers)
552​
553 const lastTransactionId = crudEntries[crudEntries.length - 1]?.tx_id
554 /**
555 * The last items, created in the same transaction, should be in the same
556 * PowerSync transaction.
557 */
558 expect(
559 crudEntries
560 .reverse()
561 .slice(0, 10)
562 .every((crudEntry) => crudEntry.tx_id == lastTransactionId),
563 ).true
564 } finally {
565 await documentsCollection.cleanup()
566 await usersCollection.cleanup()
567 }
568 })
569​
570 /**
571 * Metadata provided by the collection operation should be persisted to the database if supported by the SQLite table.
572 */
573 it(`should persist collection operation metadata`, async () => {
574 const db = await createDatabase()
575​
576 const collection = createDocumentsCollection(db)
577 await collection.stateWhenReady()
578​
579 const metadata = {
580 text: `some text`,
581 number: 123,
582 boolean: true,
583 }
584 const id = randomUUID()
585 await collection.insert(
586 {
587 id,
588 name: `new`,
589 author: `somebody`,
590 },
591 {
592 metadata,
593 },
594 ).isPersisted.promise
595​
596 // Now do an update
597 await collection.update(
598 id,
599 { metadata: metadata },
600 (d) => (d.name = `updatedNew`),
601 ).isPersisted.promise
602​
603 await collection.delete(id, { metadata }).isPersisted.promise
604​
605 // There should be a crud entries for this
606 const crudBatch = await db.getCrudBatch(100)
607 expect(crudBatch).toBeDefined()
608 const crudEntries = crudBatch!.crud
609​
610 // The metadata should be available in the CRUD entries for upload
611 const stringifiedMetadata = JSON.stringify(metadata)
612 expect(crudEntries.length).toBe(3)
613 expect(crudEntries[0]!.metadata).toEqual(stringifiedMetadata)
614 expect(crudEntries[1]!.metadata).toEqual(stringifiedMetadata)
615 expect(crudEntries[2]!.metadata).toEqual(stringifiedMetadata)
616​
617 // Verify the item is deleted from SQLite
618 const documents = await db.getAll(`
619 SELECT * FROM documents`)
620 expect(documents.length).toBe(0)
621 })
622 })
623​
624 describe(`General use`, () => {
625 it(`should rollback transactions on error`, async () => {
626 const db = await createDatabase()
627​
628 const options = powerSyncCollectionOptions({
629 database: db,
630 table: APP_SCHEMA.props.documents,
631 })
632​
633 // This will cause the transactor to fail when writing to SQLite
634 vi.spyOn(options.utils, `getMeta`).mockImplementation(() => ({
635 tableName: `fakeTable`,
636 trackedTableName: `error`,
637 metadataIsTracked: true,
638 serializeValue: () => ({}) as any,
639 }))
640 // Create two collections for the same table
641 const collection = createCollection(options)
642​
643 onTestFinished(() => collection.cleanup())
644 const addTx = createTransaction({
645 autoCommit: false,
646 mutationFn: async ({ transaction }) => {
647 await new PowerSyncTransactor({ database: db }).applyTransaction(
648 transaction,
649 )
650 },
651 })
652​
653 expect(collection.size).eq(0)
654 await collection.stateWhenReady()
655​
656 const id = randomUUID()
657 addTx.mutate(() => {
658 collection.insert({
659 id,
660 name: `aname`,
661 })
662 })
663​
664 // This should be present in the optimistic state, but should be reverted when attempting to persist
665 expect(collection.size).eq(1)
666​
667 try {
668 await addTx.commit()
669 await addTx.isPersisted.promise
670 expect.fail(`Should have thrown an error`)
671 } catch (error) {
672 expect(error).toBeDefined()
673 // The collection should be in a clean state
674 expect(collection.size).toBe(0)
675 }
676 })
677​
678 it(`should work with live queries`, async () => {
679 const db = await createDatabase()
680​
681 // Create two collections for the same table
682 const collection = createDocumentsCollection(db)
683​
684 await collection.stateWhenReady()
685​
686 const liveDocuments = createCollection(
687 liveQueryCollectionOptions({
688 query: (q) =>
689 q
690 .from({ document: collection })
691 .where(({ document }) => eq(document.name, `book`))
692 .select(({ document }) => ({
693 id: document.id,
694 name: document.name,
695 })),
696 }),
697 )
698​
699 expect(liveDocuments.size).eq(0)
700​
701 const bookNames = new Set<string>()
702​
703 liveDocuments.subscribeChanges((changes) => {
704 changes
705 .map((change) => change.value.name)
706 .filter((name): name is string => name !== undefined)
707 .forEach((change) => bookNames.add(change))
708 })
709​
710 await collection.insert({
711 id: randomUUID(),
712 name: `notabook`,
713 }).isPersisted.promise
714 await collection.insert({
715 id: randomUUID(),
716 name: `book`,
717 }).isPersisted.promise
718​
719 expect(collection.size).eq(2)
720 await vi.waitFor(
721 () => {
722 expect(Array.from(bookNames)).deep.equals([`book`])
723 },
724 { timeout: 1000 },
725 )
726 })
727 })
728​
729 describe(`Multiple Clients`, () => {
730 it(`should sync updates between multiple clients`, async () => {
731 const db = await createDatabase()
732​
733 // Create two collections for the same table
734 const collectionA = createDocumentsCollection(db)
735 await collectionA.stateWhenReady()
736​
737 const collectionB = createDocumentsCollection(db)
738 await collectionB.stateWhenReady()
739​
740 await createTestData(db)
741​
742 // Both collections should have the data present after insertion
743 await vi.waitFor(
744 () => {
745 expect(collectionA.size).eq(3)
746 expect(collectionB.size).eq(3)
747 },
748 { timeout: 1000 },
749 )
750 })
751 })
752​
753 describe(`Lifecycle`, () => {
754 it(`should cleanup resources`, async () => {
755 const db = await createDatabase()
756 const collectionOptions = powerSyncCollectionOptions({
757 database: db,
758 table: APP_SCHEMA.props.documents,
759 })
760​
761 const meta = collectionOptions.utils.getMeta()
762​
763 const tableExists = async (): Promise<boolean> => {
764 const result = await db.writeLock(async (tx) => {
765 return tx.get<{ count: number }>(
766 `
767 SELECT COUNT(*) as count
768 FROM sqlite_temp_master
769 WHERE type='table' AND name = ?
770 `,
771 [meta.trackedTableName],
772 )
773 })
774 return result.count > 0
775 }
776​
777 const collection = createCollection(collectionOptions)
778 await collection.stateWhenReady()
779 expect(await tableExists()).true
780​
781 await collection.cleanup()
782​
783 // It seems that even though `cleanup` is async, the sync disposer cannot be async
784 // We wait for the table to be deleted
785 await vi.waitFor(
786 async () => {
787 expect(await tableExists()).false
788 },
789 { timeout: 1000 },
790 )
791 })
792 })
793})