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

collection-schema.test.ts

478 lines14.9 KB

1import { randomUUID } from 'node:crypto'
2import { tmpdir } from 'node:os'
3import { PowerSyncDatabase, Schema, Table, column } from '@powersync/node'
4import { SchemaValidationError, createCollection } from '@tanstack/db'
5import { describe, expect, it, onTestFinished, vi } from 'vitest'
6import { z } from 'zod'
7import { powerSyncCollectionOptions } from '../src'
8import { TEST_DATABASE_IMPLEMENTATION } from './test-db-implementation'
9import type { StandardSchemaV1 } from '@standard-schema/spec'
10​
11const APP_SCHEMA = new Schema({
12 documents: new Table({
13 name: column.text,
14 author: column.text,
15 created_at: column.text, // Will be mapped to Date
16 archived: column.integer, // Will be mapped to Boolean
17 }),
18})
19​
20const describePowerSyncSchema = TEST_DATABASE_IMPLEMENTATION
21 ? describe
22 : describe.skip
23​
24describePowerSyncSchema(`PowerSync Schema Integration`, () => {
25 async function createDatabase() {
26 const db = new PowerSyncDatabase({
27 database: {
28 dbFilename: `test.sqlite`,
29 dbLocation: tmpdir(),
30 implementation: TEST_DATABASE_IMPLEMENTATION,
31 },
32 schema: APP_SCHEMA,
33 })
34 onTestFinished(async () => {
35 await db.disconnectAndClear()
36 await db.close()
37 })
38 // Initial clear in case a test might have failed
39 await db.disconnectAndClear()
40 return db
41 }
42​
43 function createDocumentsCollection(db: PowerSyncDatabase) {
44 const collection = createCollection(
45 powerSyncCollectionOptions({
46 database: db,
47 // We get typing and a default validator from this
48 table: APP_SCHEMA.props.documents,
49 }),
50 )
51 onTestFinished(() => collection.cleanup())
52 return collection
53 }
54​
55 describe(`schema`, () => {
56 function expectInsertValidation(
57 action: () => unknown,
58 message: string,
59 issue: { message: string; path: Array<string> },
60 ) {
61 let error: unknown
62 try {
63 action()
64 } catch (caught) {
65 error = caught
66 }
67 expect(error).toBeInstanceOf(SchemaValidationError)
68 expect(error).toMatchObject({
69 type: `insert`,
70 message: expect.stringContaining(message),
71 issues: expect.arrayContaining([issue]),
72 })
73 }
74​
75 /**
76 * When using the SQLite types for TInput and TOutput, we provide a basic schema validator.
77 */
78 it(`should use basic runtime validations from automatic SQLite schema`, async () => {
79 const db = await createDatabase()
80​
81 // the collection should infer types and validate with the schema
82 const collection = createDocumentsCollection(db)
83 try {
84 await collection.stateWhenReady()
85 const first = collection.insert({ id: randomUUID(), name: `aname` })
86 const second = collection.insert({ id: randomUUID(), name: null })
87 expect(collection.size).eq(2)
88 await Promise.all([first.when(`settled`), second.when(`settled`)])
89​
90 expectInsertValidation(
91 () => collection.insert({} as any),
92 `id field must be a string`,
93 { message: `id field must be a string`, path: [`id`] },
94 )
95 expect(collection.size).eq(2)
96 } finally {
97 await collection.cleanup()
98 }
99 })
100​
101 /**
102 * The TInput value can enforce additional validations.
103 * This example uses the SQLite types as TInput and TOutput.
104 */
105 it(`should allow for advanced input validations`, async () => {
106 const db = await createDatabase()
107​
108 const errorMessage = `Name must be at least 3 characters`
109 /**
110 * This has additional validations on TInput.
111 * These validations will be applied for mutations: e.g. `insert`, `update`/
112 * Validations include:
113 * - `name`, `author` and `created_at` are required
114 * - `name` must be at least 3 characters long
115 */
116 const schema = z.object({
117 id: z.string(),
118 name: z.string().min(3, { message: errorMessage }),
119 archived: z.number(),
120 author: z.string(),
121 created_at: z.string(),
122 })
123​
124 const collection = createCollection(
125 powerSyncCollectionOptions({
126 database: db,
127 table: APP_SCHEMA.props.documents,
128 schema,
129 onDeserializationError: () => {},
130 }),
131 )
132 try {
133 expectInsertValidation(
134 () =>
135 collection.insert({
136 id: randomUUID(),
137 name: `2`,
138 author: `name`,
139 created_at: new Date().toISOString(),
140 archived: 0,
141 }),
142 errorMessage,
143 { message: errorMessage, path: [`name`] },
144 )
145 expect(collection.size).eq(0)
146 expectInsertValidation(
147 () => collection.insert({} as any),
148 `Invalid input: expected string, received undefined - path: id`,
149 {
150 message: `Invalid input: expected string, received undefined`,
151 path: [`id`],
152 },
153 )
154 expect(collection.size).eq(0)
155 } finally {
156 await collection.cleanup()
157 }
158 })
159​
160 /**
161 * In this example the TInput and TOutput types are different.
162 * In this example we use the SQLite types as the input. We don't need an additional deserialization schema.
163 */
164 it(`should allow custom/transformed input types - Input is SQLite`, async () => {
165 const db = await createDatabase()
166​
167 /**
168 * The input for `created_at` is string, while it's presented as a `Date` in TOutput
169 */
170 const schema = z.object({
171 id: z.string(),
172 name: z.string().nullable(),
173 archived: z.number().nullable(),
174 author: z.string().nullable(),
175 created_at: z
176 .string()
177 .nullable()
178 .transform((val) => val && new Date(val)),
179 })
180​
181 const collection = createCollection(
182 powerSyncCollectionOptions({
183 database: db,
184 table: APP_SCHEMA.props.documents,
185 schema,
186 onDeserializationError: () => {},
187 }),
188 )
189 const testDate = new Date(`2024-03-14T01:59:26.535Z`)
190 const id = randomUUID()
191 try {
192 const result = collection.insert({
193 id,
194 name: `document`,
195 author: `nanme`,
196 created_at: testDate.toISOString(),
197 archived: 0,
198 })
199 const item = collection.get(id)
200 expect(item?.created_at instanceof Date).true
201 expect(
202 item?.created_at instanceof Date
203 ? item.created_at.getTime()
204 : undefined,
205 ).eq(1710381566535)
206 await result.when(`settled`)
207 expect(
208 await db.getAll(
209 `SELECT id, name, author, created_at, archived FROM documents WHERE id = ?`,
210 [id],
211 ),
212 ).toEqual([
213 {
214 id,
215 name: `document`,
216 author: `nanme`,
217 created_at: `2024-03-14T01:59:26.535Z`,
218 archived: 0,
219 },
220 ])
221​
222 await db.execute(
223 `INSERT INTO documents (id, name, author, created_at, archived) VALUES (?, ?, ?, ?, ?)`,
224 [`inbound-sqlite`, `inbound`, `peer`, `2025-06-07T08:09:10.123Z`, 1],
225 )
226 await vi.waitFor(() => {
227 const inbound = collection.get(`inbound-sqlite`)
228 expect(inbound?.created_at).toBeInstanceOf(Date)
229 expect(inbound).toMatchObject({
230 id: `inbound-sqlite`,
231 name: `inbound`,
232 author: `peer`,
233 archived: 1,
234 })
235 expect(
236 inbound?.created_at instanceof Date
237 ? inbound.created_at.getTime()
238 : undefined,
239 ).toBe(1749283750123)
240 })
241 } finally {
242 await collection.cleanup()
243 }
244 })
245​
246 /**
247 * In this example the TInput and TOutput types are different.
248 * In this example we use custom types for TInput. This requires an additional schema for validating
249 * incoming items from the sync stream (which is typed as SQLite)
250 */
251 it(`should allow custom/transformed input types - Input is different from SQLite`, async () => {
252 const db = await createDatabase()
253​
254 /**
255 * The input for `created_at` is unix epoch, while it's presented as a `Date` in TOutput
256 */
257 const schema = z.object({
258 id: z.string(),
259 name: z.string().nullable(),
260 // We want to use booleans as the input here
261 archived: z.boolean().nullable(),
262 author: z.string().nullable(),
263 created_at: z.date().nullable(),
264 })
265​
266 const collection = createCollection(
267 powerSyncCollectionOptions({
268 database: db,
269 table: APP_SCHEMA.props.documents,
270 schema,
271 /**
272 * This needs to convert the SQLite types (which are different from TInput in this case)
273 * to TOutput
274 */
275 deserializationSchema: z.object({
276 id: z.string(),
277 name: z.string().nullable(),
278 archived: z
279 .number()
280 .nullable()
281 .transform((val) => (val ? val != 0 : null)),
282 author: z.string().nullable(),
283 // In this case val is an ISO date string from SQLite
284 created_at: z
285 .string()
286 .nullable()
287 .transform((val) => (val ? new Date(val) : null)),
288 }),
289 onDeserializationError: () => {},
290 }),
291 )
292 const testDate = new Date(`2024-03-14T01:59:26.535Z`)
293 const id = randomUUID()
294 try {
295 const result = collection.insert({
296 id,
297 name: `document`,
298 author: `nanme`,
299 created_at: testDate,
300 archived: false,
301 })
302 const item = collection.get(id)
303 expect(item?.created_at instanceof Date).true
304 expect(item?.created_at?.getTime()).eq(1710381566535)
305 expect(item?.archived).toBe(false)
306 await result.when(`settled`)
307 expect(
308 await db.getAll(
309 `SELECT id, name, author, created_at, archived FROM documents WHERE id = ?`,
310 [id],
311 ),
312 ).toEqual([
313 {
314 id,
315 name: `document`,
316 author: `nanme`,
317 created_at: `2024-03-14T01:59:26.535Z`,
318 archived: 0,
319 },
320 ])
321​
322 await db.execute(
323 `INSERT INTO documents (id, name, author, created_at, archived) VALUES (?, ?, ?, ?, ?)`,
324 [`inbound-custom`, `inbound`, `peer`, `2025-06-07T08:09:10.123Z`, 0],
325 )
326 await vi.waitFor(() => {
327 const inbound = collection.get(`inbound-custom`)
328 expect(inbound?.created_at).toBeInstanceOf(Date)
329 // This fixture's configured transform maps SQLite zero to null.
330 expect(inbound).toMatchObject({
331 id: `inbound-custom`,
332 name: `inbound`,
333 author: `peer`,
334 archived: null,
335 })
336 expect(inbound?.created_at?.getTime()).toBe(1749283750123)
337 })
338 } finally {
339 await collection.cleanup()
340 }
341 })
342​
343 /**
344 * In this example we contain a TOutput field type which requires custom serialization for SQLite
345 */
346 it(`should allow for custom serializers`, async () => {
347 const db = await createDatabase()
348​
349 class MyDataClass {
350 constructor(public options: { value: string }) {}
351 }
352​
353 /**
354 * Here name is stored as a Buffer. We can't serialize this to SQLite automatically.
355 * We need to provide a serializer.
356 */
357 const schema = z.object({
358 id: z.string(),
359 name: z
360 .string()
361 .nullable()
362 .transform((value) => (value ? new MyDataClass({ value }) : null)),
363 archived: z.number().nullable(),
364 author: z.string().nullable(),
365 created_at: z.string().nullable(),
366 })
367​
368 const collection = createCollection(
369 powerSyncCollectionOptions({
370 database: db,
371 table: APP_SCHEMA.props.documents,
372 schema,
373 // This is used to serialize to SQLite
374 serializer: {
375 name: (holder) => holder?.options.value || null,
376 },
377 deserializationSchema: schema,
378 onDeserializationError: () => {},
379 }),
380 )
381 const id = randomUUID()
382 try {
383 const result = collection.insert({
384 id,
385 name: `document`,
386 author: `name`,
387 created_at: `2024-03-14T01:59:26.535Z`,
388 archived: 0,
389 })
390 const item = collection.get(id)
391 await result.when(`settled`)
392 expect(item?.name instanceof MyDataClass).true
393 expect(item?.name?.options.value).eq(`document`)
394 expect(
395 await db.getAll(
396 `SELECT id, name, author, created_at, archived FROM documents WHERE id = ?`,
397 [id],
398 ),
399 ).toEqual([
400 {
401 id,
402 name: `document`,
403 author: `name`,
404 created_at: `2024-03-14T01:59:26.535Z`,
405 archived: 0,
406 },
407 ])
408​
409 await db.execute(
410 `INSERT INTO documents (id, name, author, created_at, archived) VALUES (?, ?, ?, ?, ?)`,
411 [`inbound-class`, `from-sql`, `peer`, `2025-06-07T08:09:10.123Z`, 1],
412 )
413 await vi.waitFor(() => {
414 const inbound = collection.get(`inbound-class`)
415 expect(inbound?.name).toBeInstanceOf(MyDataClass)
416 expect(inbound?.name?.options.value).toBe(`from-sql`)
417 expect(inbound).toMatchObject({
418 id: `inbound-class`,
419 author: `peer`,
420 created_at: `2025-06-07T08:09:10.123Z`,
421 archived: 1,
422 })
423 })
424 } finally {
425 await collection.cleanup()
426 }
427 })
428​
429 /**
430 * We sync data which cannot be validated by the schema. This is a fatal error.
431 */
432 it(`should catch deserialization errors`, async () => {
433 const db = await createDatabase()
434​
435 /**
436 * Here name is stored as a Buffer. We can't serialize this to SQLite automatically.
437 * We need to provide a serializer.
438 */
439 const schema = z.object({
440 id: z.string(),
441 name: z.string(),
442 archived: z.number(),
443 author: z.string(),
444 created_at: z.string(),
445 })
446​
447 const onError = vi.fn((() => {}) as (
448 error: StandardSchemaV1.FailureResult,
449 ) => void)
450​
451 const collection = createCollection(
452 powerSyncCollectionOptions({
453 database: db,
454 table: APP_SCHEMA.props.documents,
455 schema,
456 onDeserializationError: onError,
457 }),
458 )
459 onTestFinished(() => collection.cleanup())
460​
461 await collection.stateWhenReady()
462​
463 // The columns are not nullable in the schema
464 // Write invalid data to SQLite, this simulates a sync
465 await db.execute(`INSERT INTO documents(id) VALUES(uuid())`)
466​
467 await vi.waitFor(
468 () => {
469 const issues = onError.mock.lastCall?.[0]?.issues
470 expect(issues).toBeDefined()
471 // Each column which should have been defined
472 expect(issues?.length).eq(4)
473 },
474 { timeout: 1000 },
475 )
476 })
477 })
478})