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

collection-schema.test.ts

367 lines10.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 /**
57 * When using the SQLite types for TInput and TOutput, we provide a basic schema validator.
58 */
59 it(`should use basic runtime validations from automatic SQLite schema`, async () => {
60 const db = await createDatabase()
61​
62 // the collection should infer types and validate with the schema
63 const collection = createDocumentsCollection(db)
64 await collection.stateWhenReady()
65​
66 collection.insert({
67 id: randomUUID(),
68 name: `aname`,
69 })
70​
71 collection.insert({
72 id: randomUUID(),
73 name: null,
74 })
75​
76 expect(collection.size).eq(2)
77​
78 // should validate inputs
79 try {
80 collection.insert({} as any)
81 } catch (ex) {
82 expect(ex instanceof SchemaValidationError).true
83 if (ex instanceof SchemaValidationError) {
84 expect(ex.message).contains(`id field must be a string`)
85 }
86 }
87 })
88​
89 /**
90 * The TInput value can enforce additional validations.
91 * This example uses the SQLite types as TInput and TOutput.
92 */
93 it(`should allow for advanced input validations`, async () => {
94 const db = await createDatabase()
95​
96 const errorMessage = `Name must be at least 3 characters`
97 /**
98 * This has additional validations on TInput.
99 * These validations will be applied for mutations: e.g. `insert`, `update`/
100 * Validations include:
101 * - `name`, `author` and `created_at` are required
102 * - `name` must be at least 3 characters long
103 */
104 const schema = z.object({
105 id: z.string(),
106 name: z.string().min(3, { message: errorMessage }),
107 archived: z.number(),
108 author: z.string(),
109 created_at: z.string(),
110 })
111​
112 const collection = createCollection(
113 powerSyncCollectionOptions({
114 database: db,
115 table: APP_SCHEMA.props.documents,
116 schema,
117 onDeserializationError: () => {},
118 }),
119 )
120 onTestFinished(() => collection.cleanup())
121​
122 try {
123 collection.insert({
124 id: randomUUID(),
125 name: `2`,
126 author: `name`,
127 created_at: new Date().toISOString(),
128 archived: 0,
129 })
130 expect.fail(`Should throw a validation error`)
131 } catch (ex) {
132 expect(ex instanceof SchemaValidationError).true
133 if (ex instanceof SchemaValidationError) {
134 expect(ex.message).contains(errorMessage)
135 }
136 }
137​
138 expect(collection.size).eq(0)
139​
140 // should validate inputs
141 try {
142 collection.insert({} as any)
143 } catch (ex) {
144 expect(ex instanceof SchemaValidationError).true
145 if (ex instanceof SchemaValidationError) {
146 expect(ex.message).contains(`Required - path: id`)
147 }
148 }
149 })
150​
151 /**
152 * In this example the TInput and TOutput types are different.
153 * In this example we use the SQLite types as the input. We don't need an additional deserialization schema.
154 */
155 it(`should allow custom/transformed input types - Input is SQLite`, async () => {
156 const db = await createDatabase()
157​
158 /**
159 * The input for `created_at` is string, while it's presented as a `Date` in TOutput
160 */
161 const schema = z.object({
162 id: z.string(),
163 name: z.string().nullable(),
164 archived: z.number().nullable(),
165 author: z.string().nullable(),
166 created_at: z
167 .string()
168 .nullable()
169 .transform((val) => val && new Date(val)),
170 })
171​
172 const collection = createCollection(
173 powerSyncCollectionOptions({
174 database: db,
175 table: APP_SCHEMA.props.documents,
176 schema,
177 onDeserializationError: () => {},
178 }),
179 )
180 onTestFinished(() => collection.cleanup())
181​
182 const testDate = new Date()
183 const id = randomUUID()
184 collection.insert({
185 id,
186 name: `document`,
187 author: `nanme`,
188 created_at: testDate.toISOString(),
189 archived: 0,
190 })
191​
192 const item = collection.get(id)
193​
194 expect(item?.created_at instanceof Date).true
195 expect(item?.created_at?.toLocaleString()).eq(testDate.toLocaleString())
196 })
197​
198 /**
199 * In this example the TInput and TOutput types are different.
200 * In this example we use custom types for TInput. This requires an additional schema for validating
201 * incoming items from the sync stream (which is typed as SQLite)
202 */
203 it(`should allow custom/transformed input types - Input is different from SQLite`, async () => {
204 const db = await createDatabase()
205​
206 /**
207 * The input for `created_at` is unix epoch, while it's presented as a `Date` in TOutput
208 */
209 const schema = z.object({
210 id: z.string(),
211 name: z.string().nullable(),
212 // We want to use booleans as the input here
213 archived: z.boolean().nullable(),
214 author: z.string().nullable(),
215 created_at: z.date().nullable(),
216 })
217​
218 const collection = createCollection(
219 powerSyncCollectionOptions({
220 database: db,
221 table: APP_SCHEMA.props.documents,
222 schema,
223 /**
224 * This needs to convert the SQLite types (which are different from TInput in this case)
225 * to TOutput
226 */
227 deserializationSchema: z.object({
228 id: z.string(),
229 name: z.string().nullable(),
230 archived: z
231 .number()
232 .nullable()
233 .transform((val) => (val ? val != 0 : null)),
234 author: z.string().nullable(),
235 // In this case val is an ISO date string from SQLite
236 created_at: z
237 .string()
238 .nullable()
239 .transform((val) => (val ? new Date(val) : null)),
240 }),
241 onDeserializationError: () => {},
242 }),
243 )
244 onTestFinished(() => collection.cleanup())
245​
246 const testDate = new Date()
247 const id = randomUUID()
248 collection.insert({
249 id,
250 name: `document`,
251 author: `nanme`,
252 created_at: new Date(),
253 archived: false,
254 })
255​
256 const item = collection.get(id)
257​
258 expect(item?.created_at instanceof Date).true
259 expect(item?.created_at?.toLocaleString()).eq(testDate.toLocaleString())
260 })
261​
262 /**
263 * In this example we contain a TOutput field type which requires custom serialization for SQLite
264 */
265 it(`should allow for custom serializers`, async () => {
266 const db = await createDatabase()
267​
268 class MyDataClass {
269 constructor(public options: { value: string }) {}
270 }
271​
272 /**
273 * Here name is stored as a Buffer. We can't serialize this to SQLite automatically.
274 * We need to provide a serializer.
275 */
276 const schema = z.object({
277 id: z.string(),
278 name: z
279 .string()
280 .nullable()
281 .transform((value) => (value ? new MyDataClass({ value }) : null)),
282 archived: z.number().nullable(),
283 author: z.string().nullable(),
284 created_at: z.string().nullable(),
285 })
286​
287 const collection = createCollection(
288 powerSyncCollectionOptions({
289 database: db,
290 table: APP_SCHEMA.props.documents,
291 schema,
292 // This is used to serialize to SQLite
293 serializer: {
294 name: (holder) => holder?.options.value || null,
295 },
296 deserializationSchema: schema,
297 onDeserializationError: () => {},
298 }),
299 )
300 onTestFinished(() => collection.cleanup())
301​
302 const id = randomUUID()
303​
304 const result = collection.insert({
305 id,
306 name: `document`,
307 author: `name`,
308 created_at: new Date().toISOString(),
309 archived: 0,
310 })
311​
312 const item = collection.get(id)
313 await result.isPersisted.promise
314 expect(item?.name instanceof MyDataClass).true
315 expect(item?.name?.options.value).eq(`document`)
316 })
317​
318 /**
319 * We sync data which cannot be validated by the schema. This is a fatal error.
320 */
321 it(`should catch deserialization errors`, async () => {
322 const db = await createDatabase()
323​
324 /**
325 * Here name is stored as a Buffer. We can't serialize this to SQLite automatically.
326 * We need to provide a serializer.
327 */
328 const schema = z.object({
329 id: z.string(),
330 name: z.string(),
331 archived: z.number(),
332 author: z.string(),
333 created_at: z.string(),
334 })
335​
336 const onError = vi.fn((() => {}) as (
337 error: StandardSchemaV1.FailureResult,
338 ) => void)
339​
340 const collection = createCollection(
341 powerSyncCollectionOptions({
342 database: db,
343 table: APP_SCHEMA.props.documents,
344 schema,
345 onDeserializationError: onError,
346 }),
347 )
348 onTestFinished(() => collection.cleanup())
349​
350 await collection.stateWhenReady()
351​
352 // The columns are not nullable in the schema
353 // Write invalid data to SQLite, this simulates a sync
354 await db.execute(`INSERT INTO documents(id) VALUES(uuid())`)
355​
356 await vi.waitFor(
357 () => {
358 const issues = onError.mock.lastCall?.[0]?.issues
359 expect(issues).toBeDefined()
360 // Each column which should have been defined
361 expect(issues?.length).eq(4)
362 },
363 { timeout: 1000 },
364 )
365 })
366 })
367})