Open History to see the last commit
1/**
2 * # Does a PowerSync Collection preserve the database's independent truth?
3 *
4 * Collection updates change only their authored fields. A newer disjoint
5 * SQLite field must survive. Persistence waits for diff observation of each
6 * Collection's effective writes. A native SQLite and unmocked-watcher witness
7 * covers a tracked-metadata Collection.update. Direct transactor probes also
8 * cover a synthetic trailing no-op and tracked metadata-only mutation;
9 * Collection.update does not create these zero-field mutations. Public rows
10 * expose exactly the declared PowerSync view, and equality compares transformed
11 * schema output rather than raw SQLite rows.
12 *
13 * The PowerSync Collection guide promises SQLite mirroring and transaction
14 * persistence; the public PowerSyncTransactor API persists the whole
15 * Transaction. These tests stop at local SQLite and Collection observation,
16 * not remote backend upload.
17 *
18 * The reference laws are small: compose disjoint patches by changed field,
19 * derive readable keys from the declared view, and derive public values from
20 * the supplied Standard Schema. The production path uses a real native SQLite
21 * database, PowerSync CRUD rows, Collection sync, watcher callbacks, and the
22 * adapter comparator. A held watcher is the only timing control.
23 *
24 * The pure tests calibrate comparisons and cleanup failure reporting. The
25 * production tests reach native SQLite before comparing rows, patches,
26 * metadata, logging, or cleanup.
27 * Held callbacks test the adapter after controlled delivery; ordinary and
28 * tracked-metadata Collection writes exercise the native watcher without
29 * invoking its callback from the test. Neither held delivery nor local CRUD
30 * queue inspection proves remote backend upload. The suite skips when the
31 * native test database implementation is unavailable.
32 */
33import { randomUUID } from 'node:crypto'
34import { tmpdir } from 'node:os'
35import {
36 LogLevels,
37 PowerSyncDatabase,
38 Schema,
39 Table,
40 column,
41} from '@powersync/node'
42import { createCollection, createTransaction } from '@tanstack/db'
43import { afterEach, describe, expect, it, vi } from 'vitest'
44import { z } from 'zod'
45import { powerSyncCollectionOptions } from '../src'
46import { PowerSyncTransactor } from '../src/PowerSyncTransactor'
47import { TEST_DATABASE_IMPLEMENTATION } from './test-db-implementation'
48import type { WatchOnChangeHandler } from '@powersync/common'
49import type { PowerSyncLogger } from '@powersync/node'
50
51// Without a SQLite binding the oracle would silently not run, so fail loudly.
52if (TEST_DATABASE_IMPLEMENTATION === undefined) {
53 throw new Error(
54 `PowerSync correctness oracle needs a SQLite binding: install better-sqlite3, or run on Node 24+ where node:sqlite is available`,
55 )
56}
57
58type CrudRow = { data: string }
59
60async function createDatabase(schema: Schema, logger?: PowerSyncLogger) {
61 const db = new PowerSyncDatabase({
62 schema,
63 database: {
64 dbFilename: `correctness-oracle-${randomUUID()}.sqlite`,
65 dbLocation: tmpdir(),
66 implementation: TEST_DATABASE_IMPLEMENTATION,
67 },
68 logger,
69 })
70 await db.disconnectAndClear()
71 return db
72}
73
74function holdAdapterChanges(db: PowerSyncDatabase) {
75 const handlers = new Map<string, WatchOnChangeHandler>()
76 vi.spyOn(db, `onChangeWithCallback`).mockImplementation(
77 (candidate, options) => {
78 const table = options?.tables?.[0]
79 if (!table) throw new Error(`adapter did not name a tracked table`)
80 if (!candidate)
81 throw new Error(`adapter did not register a change handler`)
82 handlers.set(table, candidate)
83 return () => {}
84 },
85 )
86 return {
87 expectReached: (table?: string) =>
88 expect(table ? handlers.has(table) : handlers.size > 0).toBe(true),
89 flush: async (table?: string) => {
90 const watchedTable = table ?? handlers.keys().next().value
91 if (watchedTable === undefined)
92 throw new Error(`adapter did not register a tracked table`)
93 const handler = handlers.get(watchedTable)
94 if (!handler)
95 throw new Error(`adapter did not register its change handler`)
96 await handler.onChange({ changedTables: [watchedTable] })
97 },
98 }
99}
100
101function observeUpdate(
102 sqliteRow: { assignee: string | null; done: number },
103 patch: { op: string; data: Record<string, unknown> },
104) {
105 return { sqliteRow, patch: { op: patch.op, data: patch.data } }
106}
107
108function observeViewKeys(
109 viewRow: Record<string, unknown>,
110 collectionRow: Record<string, unknown>,
111) {
112 return {
113 view: Object.keys(viewRow).sort(),
114 collection: Object.keys(collectionRow)
115 .filter((key) => !key.startsWith(`$`))
116 .sort(),
117 }
118}
119
120async function cleanupAfterOracle(
121 failure: { error: unknown } | undefined,
122 cleanups: Array<() => Promise<unknown> | unknown>,
123): Promise<void> {
124 const cleanupErrors: Array<unknown> = []
125 for (const cleanup of cleanups) {
126 try {
127 await cleanup()
128 } catch (error) {
129 cleanupErrors.push(error)
130 }
131 }
132 if (cleanupErrors.length > 0) {
133 throw new AggregateError(
134 cleanupErrors,
135 failure
136 ? `Oracle failed and cleanup also failed`
137 : `Oracle cleanup failed`,
138 failure ? { cause: failure.error } : undefined,
139 )
140 }
141}
142
143describe(`PowerSync correctness oracle`, () => {
144 afterEach(() => vi.restoreAllMocks())
145
146 it(`rejects stale full-row patches and undeclared public keys`, () => {
147 expect(
148 observeUpdate(
149 { assignee: null, done: 1 },
150 { op: `PATCH`, data: { assignee: null, done: 1 } },
151 ),
152 ).not.toEqual(
153 observeUpdate(
154 { assignee: `alice`, done: 1 },
155 { op: `PATCH`, data: { done: 1 } },
156 ),
157 )
158 expect(
159 observeViewKeys(
160 { id: `t1`, title: `Write report` },
161 { id: `t1`, title: `Write report`, priority: `high` },
162 ),
163 ).not.toEqual({
164 view: [`id`, `title`],
165 collection: [`id`, `title`],
166 })
167 })
168
169 it(`retains the primary oracle failure and each cleanup failure`, async () => {
170 let primary: unknown
171 try {
172 expect({ id: `wrong` }).toEqual({ id: `expected` })
173 } catch (error) {
174 primary = error
175 }
176 expect(primary).toBeInstanceOf(Error)
177 const firstCleanup = new Error(`Collection cleanup failed`)
178 const secondCleanup = new Error(`database close failed`)
179 const attempted: Array<string> = []
180 let reported: unknown
181
182 try {
183 await cleanupAfterOracle({ error: primary }, [
184 () => {
185 attempted.push(`Collection`)
186 throw firstCleanup
187 },
188 () => {
189 attempted.push(`database`)
190 throw secondCleanup
191 },
192 ])
193 } catch (error) {
194 reported = error
195 }
196
197 expect(attempted).toEqual([`Collection`, `database`])
198 expect(reported).toBeInstanceOf(AggregateError)
199 expect((reported as AggregateError).cause).toBe(primary)
200 expect((reported as AggregateError).errors).toEqual([
201 firstCleanup,
202 secondCleanup,
203 ])
204 })
205
206 it(`preserves a newer disjoint SQLite field across a collection update`, async () => {
207 const schema = new Schema({
208 todos: new Table({
209 title: column.text,
210 assignee: column.text,
211 done: column.integer,
212 }),
213 })
214 const db = await createDatabase(schema)
215 await db.execute(
216 `INSERT INTO todos (id, title, assignee, done) VALUES ('t1', 'Write report', NULL, 0)`,
217 )
218 const heldChanges = holdAdapterChanges(db)
219 const collection = createCollection(
220 powerSyncCollectionOptions({
221 database: db,
222 table: schema.props.todos,
223 }),
224 )
225
226 let failure: { error: unknown } | undefined
227 try {
228 await collection.preload()
229 heldChanges.expectReached()
230
231 await db.execute(`UPDATE todos SET assignee = 'alice' WHERE id = 't1'`)
232 expect(collection.get(`t1`)?.assignee).toBeNull()
233
234 const transaction = collection.update(`t1`, (draft) => {
235 draft.done = 1
236 })
237
238 let rowBeforeFlush: { assignee: string | null; done: number } | null =
239 null
240 await vi.waitFor(async () => {
241 rowBeforeFlush = await db.get<{
242 assignee: string | null
243 done: number
244 }>(`SELECT assignee, done FROM todos WHERE id = 't1'`)
245 expect(rowBeforeFlush.done).toBe(1)
246 })
247
248 await heldChanges.flush()
249 await transaction.when(`settled`)
250
251 const crud = await db.getAll<CrudRow>(
252 `SELECT data FROM ps_crud ORDER BY id`,
253 )
254 const finalPatch = JSON.parse(crud.at(-1)!.data) as {
255 op: string
256 data: Record<string, unknown>
257 }
258
259 expect(observeUpdate(rowBeforeFlush!, finalPatch)).toEqual(
260 observeUpdate(
261 { assignee: `alice`, done: 1 },
262 { op: `PATCH`, data: { done: 1 } },
263 ),
264 )
265 } catch (error) {
266 failure = { error }
267 throw error
268 } finally {
269 await cleanupAfterOracle(failure, [
270 () => collection.cleanup(),
271 () => db.disconnectAndClear(),
272 () => db.close(),
273 ])
274 }
275 })
276
277 it(`direct transactor waits for an effective update before a synthetic trailing no-op`, async () => {
278 const schema = new Schema({
279 todos: new Table({ title: column.text, done: column.integer }),
280 })
281 const db = await createDatabase(schema)
282 await db.execute(
283 `INSERT INTO todos (id, title, done) VALUES ('t1', 'Write report', 0)`,
284 )
285 const heldChanges = holdAdapterChanges(db)
286 const collection = createCollection(
287 powerSyncCollectionOptions({ database: db, table: schema.props.todos }),
288 )
289
290 const transaction = createTransaction({
291 autoCommit: false,
292 mutationFn: async () => {},
293 })
294 let failure: { error: unknown } | undefined
295 try {
296 await collection.preload()
297 heldChanges.expectReached()
298 transaction.mutate(() =>
299 collection.update(`t1`, (draft) => {
300 draft.done = 1
301 }),
302 )
303 const effective = transaction.mutations[0]!
304 const trailingNoop = {
305 ...effective,
306 mutationId: `${effective.mutationId}-noop`,
307 original: effective.modified,
308 changes: {},
309 }
310 const transactor = new PowerSyncTransactor({ database: db })
311 let persistenceFulfilled = false
312 const persistence = transactor
313 .applyTransaction({
314 mutations: [effective, trailingNoop],
315 } as never)
316 .then(() => {
317 persistenceFulfilled = true
318 })
319
320 await vi.waitFor(async () => {
321 expect(
322 await db.get<{ done: number }>(
323 `SELECT done FROM todos WHERE id = 't1'`,
324 ),
325 ).toEqual({ done: 1 })
326 })
327 for (let turn = 0; turn < 10; turn++) await Promise.resolve()
328 expect(persistenceFulfilled).toBe(false)
329
330 await heldChanges.flush()
331 await persistence
332 expect(persistenceFulfilled).toBe(true)
333 } catch (error) {
334 failure = { error }
335 throw error
336 } finally {
337 await cleanupAfterOracle(failure, [
338 () => transaction.rollback(),
339 () => collection.cleanup(),
340 () => db.disconnectAndClear(),
341 () => db.close(),
342 ])
343 }
344 })
345
346 it(`waits for both Collections in a mixed transaction after one watcher flushes`, async () => {
347 const schema = new Schema({
348 todos: new Table({ done: column.integer }),
349 labels: new Table({ name: column.text }),
350 })
351 const db = await createDatabase(schema)
352 await db.execute(`INSERT INTO todos (id, done) VALUES ('t1', 0)`)
353 await db.execute(`INSERT INTO labels (id, name) VALUES ('l1', 'before')`)
354 const heldChanges = holdAdapterChanges(db)
355 const todos = createCollection(
356 powerSyncCollectionOptions({ database: db, table: schema.props.todos }),
357 )
358 const labels = createCollection(
359 powerSyncCollectionOptions({ database: db, table: schema.props.labels }),
360 )
361 const transaction = createTransaction({
362 autoCommit: false,
363 mutationFn: async () => {},
364 })
365
366 let failure: { error: unknown } | undefined
367 try {
368 await todos.preload()
369 await labels.preload()
370 const todosTracking = todos.utils.getMeta().trackedTableName
371 const labelsTracking = labels.utils.getMeta().trackedTableName
372 heldChanges.expectReached(todosTracking)
373 heldChanges.expectReached(labelsTracking)
374 transaction.mutate(() => {
375 todos.update(`t1`, (draft) => {
376 draft.done = 1
377 })
378 labels.update(`l1`, (draft) => {
379 draft.name = `after`
380 })
381 })
382 expect(
383 transaction.mutations.map((mutation) => mutation.collection.id),
384 ).toEqual([todos.id, labels.id])
385
386 const persistenceState = {
387 outcome: `pending` as `pending` | `fulfilled` | `rejected`,
388 error: undefined as unknown,
389 }
390 const persistence = new PowerSyncTransactor({ database: db })
391 .applyTransaction(transaction)
392 .then(
393 () => {
394 persistenceState.outcome = `fulfilled`
395 },
396 (error: unknown) => {
397 persistenceState.outcome = `rejected`
398 persistenceState.error = error
399 },
400 )
401
402 await vi.waitFor(async () => {
403 expect(
404 await db.get<{ done: number }>(
405 `SELECT done FROM todos WHERE id = 't1'`,
406 ),
407 ).toEqual({ done: 1 })
408 expect(
409 await db.get<{ name: string }>(
410 `SELECT name FROM labels WHERE id = 'l1'`,
411 ),
412 ).toEqual({ name: `after` })
413 })
414
415 // Waiting only for the globally final mutation would settle here.
416 await heldChanges.flush(labelsTracking)
417 for (let turn = 0; turn < 10; turn++) await Promise.resolve()
418 expect(persistenceState.outcome).toBe(`pending`)
419
420 await heldChanges.flush(todosTracking)
421 await persistence
422 expect(persistenceState).toEqual({
423 outcome: `fulfilled`,
424 error: undefined,
425 })
426 } catch (error) {
427 failure = { error }
428 throw error
429 } finally {
430 await cleanupAfterOracle(failure, [
431 () => transaction.rollback(),
432 () => todos.cleanup(),
433 () => labels.cleanup(),
434 () => db.disconnectAndClear(),
435 () => db.close(),
436 ])
437 }
438 })
439
440 it(`direct transactor persists a synthetic tracked metadata-only mutation and waits for its diff`, async () => {
441 const schema = new Schema({
442 todos: new Table(
443 { title: column.text, done: column.integer },
444 { trackMetadata: true },
445 ),
446 })
447 const db = await createDatabase(schema)
448 await db.execute(
449 `INSERT INTO todos (id, title, done) VALUES ('t1', 'Write report', 0)`,
450 )
451 const heldChanges = holdAdapterChanges(db)
452 const collection = createCollection(
453 powerSyncCollectionOptions({ database: db, table: schema.props.todos }),
454 )
455 const transaction = createTransaction({
456 autoCommit: false,
457 mutationFn: async () => {},
458 })
459
460 let failure: { error: unknown } | undefined
461 try {
462 await collection.preload()
463 heldChanges.expectReached()
464 transaction.mutate(() =>
465 collection.update(`t1`, (draft) => {
466 draft.done = 1
467 }),
468 )
469 const template = transaction.mutations[0]!
470 const metadata = { source: `correctness-oracle` }
471 const metadataOnly = {
472 ...template,
473 mutationId: `${template.mutationId}-metadata`,
474 modified: template.original,
475 changes: {},
476 metadata,
477 }
478 const transactor = new PowerSyncTransactor({ database: db })
479 let persistenceFulfilled = false
480 const persistence = transactor
481 .applyTransaction({ mutations: [metadataOnly] } as never)
482 .then(() => {
483 persistenceFulfilled = true
484 })
485
486 await vi.waitFor(async () => {
487 const batch = await db.getCrudBatch(100)
488 expect(batch?.crud.at(-1)?.metadata).toBe(JSON.stringify(metadata))
489 })
490 for (let turn = 0; turn < 10; turn++) await Promise.resolve()
491 expect(persistenceFulfilled).toBe(false)
492
493 await heldChanges.flush()
494 await persistence
495 expect(persistenceFulfilled).toBe(true)
496 } catch (error) {
497 failure = { error }
498 throw error
499 } finally {
500 await cleanupAfterOracle(failure, [
501 () => transaction.rollback(),
502 () => collection.cleanup(),
503 () => db.disconnectAndClear(),
504 () => db.close(),
505 ])
506 }
507 })
508
509 it(`persists a metadata-bearing Collection update through the native watcher`, async () => {
510 const schema = new Schema({
511 todos: new Table(
512 { title: column.text, done: column.integer },
513 { trackMetadata: true },
514 ),
515 })
516 const db = await createDatabase(schema)
517 await db.execute(
518 `INSERT INTO todos (id, title, done) VALUES ('t1', 'Write report', 0)`,
519 )
520 // Forward unchanged callbacks to the SDK while recording genuine delivery;
521 // this test never invokes the registered handler itself.
522 const originalOnChange = db.onChangeWithCallback.bind(db)
523 const watcherDeliveries: Array<ReadonlyArray<string>> = []
524 const watcherRegistration = vi
525 .spyOn(db, `onChangeWithCallback`)
526 .mockImplementation((handler, options) => {
527 if (!handler) throw new Error(`adapter did not register a watcher`)
528 return originalOnChange(
529 {
530 ...handler,
531 onChange: async (event) => {
532 watcherDeliveries.push([...event.changedTables])
533 await handler.onChange(event)
534 },
535 },
536 options,
537 )
538 })
539 const collection = createCollection(
540 powerSyncCollectionOptions({ database: db, table: schema.props.todos }),
541 )
542
543 let failure: { error: unknown } | undefined
544 try {
545 await collection.preload()
546 expect(watcherRegistration).toHaveBeenCalled()
547 watcherDeliveries.length = 0
548
549 const metadata = { source: `Collection.update` }
550 await collection
551 .update(`t1`, { metadata }, (draft) => {
552 draft.done = 1
553 })
554 .when(`settled`)
555
556 expect(
557 watcherDeliveries.some((tables) =>
558 tables.includes(collection.utils.getMeta().trackedTableName),
559 ),
560 ).toBe(true)
561
562 expect(
563 await db.get<{ done: number }>(
564 `SELECT done FROM todos WHERE id = 't1'`,
565 ),
566 ).toEqual({ done: 1 })
567 expect(collection.get(`t1`)?.done).toBe(1)
568 const batch = await db.getCrudBatch(100)
569 expect(batch?.crud.at(-1)?.metadata).toBe(JSON.stringify(metadata))
570 const crud = await db.getAll<CrudRow>(
571 `SELECT data FROM ps_crud ORDER BY id`,
572 )
573 const patch = JSON.parse(crud.at(-1)!.data) as {
574 op: string
575 data: Record<string, unknown>
576 }
577 expect({ op: patch.op, data: patch.data }).toEqual({
578 op: `PATCH`,
579 data: { done: 1 },
580 })
581 } catch (error) {
582 failure = { error }
583 throw error
584 } finally {
585 await cleanupAfterOracle(failure, [
586 () => collection.cleanup(),
587 () => db.disconnectAndClear(),
588 () => db.close(),
589 ])
590 }
591 })
592
593 it(`persists explicit falsey field changes without treating them as absent`, async () => {
594 const schema = new Schema({
595 flags: new Table({
596 label: column.text,
597 note: column.text,
598 count: column.integer,
599 active: column.integer,
600 }),
601 })
602 const db = await createDatabase(schema)
603 await db.execute(
604 `INSERT INTO flags (id, label, note, count, active) VALUES ('f1', 'before', 'owner', 1, 1)`,
605 )
606 const outputSchema = z.object({
607 id: z.string(),
608 label: z.string().nullable(),
609 note: z.string().nullable(),
610 count: z.number().nullable(),
611 active: z.boolean().nullable(),
612 })
613 const collection = createCollection(
614 powerSyncCollectionOptions({
615 database: db,
616 table: schema.props.flags,
617 schema: outputSchema,
618 deserializationSchema: z.object({
619 id: z.string(),
620 label: z.string().nullable(),
621 note: z.string().nullable(),
622 count: z.number().nullable(),
623 active: z
624 .number()
625 .nullable()
626 .transform((value) => (value == null ? null : value !== 0)),
627 }),
628 onDeserializationError: () => {},
629 }),
630 )
631
632 let failure: { error: unknown } | undefined
633 try {
634 await collection.preload()
635 await collection
636 .update(`f1`, (draft) => {
637 draft.label = ``
638 draft.note = null
639 draft.count = 0
640 draft.active = false
641 })
642 .when(`settled`)
643
644 const crud = await db.getAll<CrudRow>(
645 `SELECT data FROM ps_crud ORDER BY id`,
646 )
647 const patch = JSON.parse(crud.at(-1)!.data) as {
648 op: string
649 data: Record<string, unknown>
650 }
651 expect({ op: patch.op, data: patch.data }).toEqual({
652 op: `PATCH`,
653 data: { label: ``, note: null, count: 0, active: 0 },
654 })
655 } catch (error) {
656 failure = { error }
657 throw error
658 } finally {
659 await cleanupAfterOracle(failure, [
660 () => collection.cleanup(),
661 () => db.disconnectAndClear(),
662 () => db.close(),
663 ])
664 }
665 })
666
667 it(`initializes and cleans up with a structured logger`, async () => {
668 const schema = new Schema({ todos: new Table({ title: column.text }) })
669 const records: Array<{
670 level: number
671 message: string
672 error?: unknown
673 }> = []
674 const db = await createDatabase(schema, {
675 log: (record) => records.push(record),
676 })
677 await db.execute(`INSERT INTO todos (id, title) VALUES ('t1', 'before')`)
678 const collection = createCollection(
679 powerSyncCollectionOptions({ database: db, table: schema.props.todos }),
680 )
681 const ignoredMetadata = { ignored: true }
682
683 let failure: { error: unknown } | undefined
684 try {
685 await collection.preload()
686 await collection
687 .update(`t1`, { metadata: ignoredMetadata }, (draft) => {
688 draft.title = `after`
689 })
690 .when(`settled`)
691 await collection.cleanup()
692
693 expect(
694 records.some(
695 (record) =>
696 record.level === LogLevels.info &&
697 record.message.includes(`Sync is ready`),
698 ),
699 ).toBe(true)
700 expect(
701 records.some(
702 (record) =>
703 record.level === LogLevels.warn &&
704 record.message.includes(`does not track metadata`) &&
705 record.error === ignoredMetadata,
706 ),
707 ).toBe(true)
708 expect(
709 records.some(
710 (record) =>
711 record.level === LogLevels.info &&
712 record.message.includes(`Sync has been stopped`),
713 ),
714 ).toBe(true)
715 expect(
716 records.filter((record) => record.level >= LogLevels.error),
717 ).toEqual([])
718 } catch (error) {
719 failure = { error }
720 throw error
721 } finally {
722 await cleanupAfterOracle(failure, [
723 () => collection.cleanup(),
724 () => db.disconnectAndClear(),
725 () => db.close(),
726 ])
727 }
728 })
729
730 it(`keeps collection keys congruent with the declared PowerSync view`, async () => {
731 const schema = new Schema({ todos: new Table({ title: column.text }) })
732 const db = await createDatabase(schema)
733 await db.execute(
734 `INSERT INTO todos (id, title) VALUES ('t1', 'Write report')`,
735 )
736 const heldChanges = holdAdapterChanges(db)
737 const createDiffTrigger = vi.spyOn(db.triggers, `createDiffTrigger`)
738 const collection = createCollection(
739 powerSyncCollectionOptions({
740 database: db,
741 table: schema.props.todos,
742 }),
743 )
744
745 let failure: { error: unknown } | undefined
746 try {
747 await collection.preload()
748 heldChanges.expectReached()
749 expect(createDiffTrigger).toHaveBeenCalled()
750 expect(createDiffTrigger.mock.calls[0]![0].columns).toEqual([`title`])
751
752 await db.writeTransaction(async (tx) => {
753 await tx.execute(
754 `UPDATE ps_data__todos SET data = json_set(data, '$.priority', 'high', '$.title', NULL) WHERE id = 't1'`,
755 )
756 })
757 await heldChanges.flush()
758
759 const viewRow = await db.get<Record<string, unknown>>(
760 `SELECT * FROM todos WHERE id = 't1'`,
761 )
762 const collectionRow = collection.get(`t1`) as unknown as Record<
763 string,
764 unknown
765 >
766 expect(viewRow.title).toBeNull()
767 expect(collectionRow.title).toBeNull()
768
769 let persistenceError: unknown
770 const persistenceState = { settled: false }
771 const persistence = collection
772 .update(`t1`, (draft) => {
773 draft.title = `Write report today`
774 })
775 .when(`settled`)
776 .catch((error: unknown) => {
777 persistenceError = error
778 })
779 .finally(() => {
780 persistenceState.settled = true
781 })
782
783 await vi.waitFor(async () => {
784 const row = await db.get<{ title: string }>(
785 `SELECT title FROM todos WHERE id = 't1'`,
786 )
787 expect(
788 persistenceState.settled || row.title === `Write report today`,
789 ).toBe(true)
790 })
791 if (!persistenceState.settled) await heldChanges.flush()
792 await persistence
793
794 expect(observeViewKeys(viewRow, collectionRow)).toEqual({
795 view: [`id`, `title`],
796 collection: [`id`, `title`],
797 })
798 expect(collectionRow).not.toHaveProperty(`priority`)
799 expect(persistenceError).toBeUndefined()
800 } catch (error) {
801 failure = { error }
802 throw error
803 } finally {
804 await cleanupAfterOracle(failure, [
805 () => collection.cleanup(),
806 () => db.disconnectAndClear(),
807 () => db.close(),
808 ])
809 }
810 })
811
812 it(`passes an empty declared-column list for an id-only table`, async () => {
813 const schema = new Schema({ ids: new Table({}) })
814 const db = await createDatabase(schema)
815 const createDiffTrigger = vi.spyOn(db.triggers, `createDiffTrigger`)
816 const collection = createCollection(
817 powerSyncCollectionOptions({ database: db, table: schema.props.ids }),
818 )
819
820 let failure: { error: unknown } | undefined
821 try {
822 await collection.preload()
823 expect(createDiffTrigger).toHaveBeenCalled()
824 expect(createDiffTrigger.mock.calls[0]![0].columns).toEqual([])
825 } catch (error) {
826 failure = { error }
827 throw error
828 } finally {
829 await cleanupAfterOracle(failure, [
830 () => collection.cleanup(),
831 () => db.disconnectAndClear(),
832 () => db.close(),
833 ])
834 }
835 })
836
837 it(`compares transformed schema output rather than raw SQLite rows`, async () => {
838 const schema = new Schema({
839 todos: new Table({
840 title: column.text,
841 created_at: column.text,
842 }),
843 })
844 const db = await createDatabase(schema)
845 await db.execute(
846 `INSERT INTO todos (id, title, created_at) VALUES ('newer', 'newer', '2024-06-01T00:00:00.000Z')`,
847 )
848 await db.execute(
849 `INSERT INTO todos (id, title, created_at) VALUES ('older', 'older', '2024-01-01T00:00:00.000Z')`,
850 )
851 await db.execute(
852 `INSERT INTO todos (id, title, created_at) VALUES ('undated', 'undated', NULL)`,
853 )
854 const compare = vi.fn(
855 (left: Date | null, right: Date | null) =>
856 (left?.getTime() ?? Number.NEGATIVE_INFINITY) -
857 (right?.getTime() ?? Number.NEGATIVE_INFINITY),
858 )
859 const collection = createCollection(
860 powerSyncCollectionOptions({
861 database: db,
862 table: schema.props.todos,
863 schema: z.object({
864 id: z.string(),
865 title: z.string().nullable(),
866 created_at: z
867 .string()
868 .nullable()
869 .transform((value) => (value ? new Date(value) : null)),
870 }),
871 onDeserializationError: () => {},
872 compare: (left, right) => compare(left.created_at, right.created_at),
873 }),
874 )
875
876 let failure: { error: unknown } | undefined
877 try {
878 await expect(collection.preload()).resolves.toBeUndefined()
879 expect(compare).toHaveBeenCalled()
880 expect([...collection.keys()]).toEqual([`undated`, `older`, `newer`])
881 } catch (error) {
882 failure = { error }
883 throw error
884 } finally {
885 await cleanupAfterOracle(failure, [
886 () => collection.cleanup(),
887 () => db.disconnectAndClear(),
888 () => db.close(),
889 ])
890 }
891 })
892})