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

powersync.ts

480 lines15.9 KB

1import { DiffTriggerOperation, sanitizeSQL } from '@powersync/common'
2import { PendingOperationStore } from './PendingOperationStore'
3import { PowerSyncTransactor } from './PowerSyncTransactor'
4import { DEFAULT_BATCH_SIZE } from './definitions'
5import { asPowerSyncRecord, mapOperation } from './helpers'
6import { convertTableToSchema } from './schema'
7import { serializeForSQLite } from './serialization'
8import type {
9 AnyTableColumnType,
10 ExtractedTable,
11 ExtractedTableColumns,
12 MapBaseColumnType,
13 OptionalExtractedTable,
14} from './helpers'
15import type {
16 BasePowerSyncCollectionConfig,
17 ConfigWithArbitraryCollectionTypes,
18 ConfigWithSQLiteInputType,
19 ConfigWithSQLiteTypes,
20 CustomSQLiteSerializer,
21 EnhancedPowerSyncCollectionConfig,
22 InferPowerSyncOutputType,
23 PowerSyncCollectionConfig,
24 PowerSyncCollectionUtils,
25} from './definitions'
26import type { PendingOperation } from './PendingOperationStore'
27import type { SyncConfig } from '@tanstack/db'
28import type { StandardSchemaV1 } from '@standard-schema/spec'
29import type { Table, TriggerDiffRecord } from '@powersync/common'
30​
31/**
32 * Creates PowerSync collection options for use with a standard Collection.
33 *
34 * @template TTable - The SQLite-based typing
35 * @template TSchema - The validation schema type (optionally supports a custom input type)
36 * @param config - Configuration options for the PowerSync collection
37 * @returns Collection options with utilities
38 */
39​
40// Overload 1: No schema is provided
41​
42/**
43 * Creates a PowerSync collection configuration with basic default validation.
44 * Input and Output types are the SQLite column types.
45 *
46 * @example
47 * ```typescript
48 * const APP_SCHEMA = new Schema({
49 * documents: new Table({
50 * name: column.text,
51 * }),
52 * })
53 *
54 * type Document = (typeof APP_SCHEMA)["types"]["documents"]
55 *
56 * const db = new PowerSyncDatabase({
57 * database: {
58 * dbFilename: "test.sqlite",
59 * },
60 * schema: APP_SCHEMA,
61 * })
62 *
63 * const collection = createCollection(
64 * powerSyncCollectionOptions({
65 * database: db,
66 * table: APP_SCHEMA.props.documents
67 * })
68 * )
69 * ```
70 */
71export function powerSyncCollectionOptions<TTable extends Table = Table>(
72 config: BasePowerSyncCollectionConfig<TTable, never> & ConfigWithSQLiteTypes,
73): EnhancedPowerSyncCollectionConfig<
74 TTable,
75 OptionalExtractedTable<TTable>,
76 never
78​
79// Overload 2: Schema is provided and the TInput matches SQLite types.
80​
81/**
82 * Creates a PowerSync collection configuration with schema validation.
83 *
84 * The input types satisfy the SQLite column types.
85 *
86 * The output types are defined by the provided schema. This schema can enforce additional
87 * validation or type transforms.
88 * Arbitrary output typed mutations are encoded to SQLite for persistence. We provide a basic standard
89 * serialization implementation to serialize column values. Custom or advanced types require providing additional
90 * serializer specifications. Partial column overrides can be supplied to `serializer`.
91 *
92 * @example
93 * ```typescript
94 * import { z } from "zod"
95 *
96 * // The PowerSync SQLite schema
97 * const APP_SCHEMA = new Schema({
98 * documents: new Table({
99 * name: column.text,
100 * // Dates are stored as ISO date strings in SQLite
101 * created_at: column.text
102 * }),
103 * })
104 *
105 * // Advanced Zod validations. The output type of this schema
106 * // is constrained to the SQLite schema of APP_SCHEMA
107 * const schema = z.object({
108 * id: z.string(),
109 * // Notice that `name` is not nullable (is required) here and it has additional validation
110 * name: z.string().min(3, { message: "Should be at least 3 characters" }).nullable(),
111 * // The input type is still the SQLite string type. While collections will output smart Date instances.
112 * created_at: z.string().transform(val => new Date(val))
113 * })
114 *
115 * const collection = createCollection(
116 * powerSyncCollectionOptions({
117 * database: db,
118 * table: APP_SCHEMA.props.documents,
119 * schema,
120 * serializer: {
121 * // The default is toISOString, this is just to demonstrate custom overrides
122 * created_at: (outputValue) => outputValue.toISOString(),
123 * },
124 * })
125 * )
126 * ```
127 */
128export function powerSyncCollectionOptions<
129 TTable extends Table,
130 TSchema extends StandardSchemaV1<
131 // TInput is the SQLite types. We can use the supplied schema to validate sync input
132 OptionalExtractedTable<TTable>,
133 AnyTableColumnType<TTable>
134 >,
135>(
136 config: BasePowerSyncCollectionConfig<TTable, TSchema> &
137 ConfigWithSQLiteInputType<TTable, TSchema>,
138): EnhancedPowerSyncCollectionConfig<
139 TTable,
140 InferPowerSyncOutputType<TTable, TSchema>,
141 TSchema
142> & {
143 schema: TSchema
145​
146// Overload 3: Schema is provided with arbitrary TInput and TOutput
147/**
148 * Creates a PowerSync collection configuration with schema validation.
149 *
150 * The input types are not linked to the internal SQLite table types. This can
151 * give greater flexibility, e.g. by accepting rich types as input for `insert` or `update` operations.
152 * An additional `deserializationSchema` is required in order to process incoming SQLite updates to the output type.
153 *
154 * The output types are defined by the provided schema. This schema can enforce additional
155 * validation or type transforms.
156 * Arbitrary output typed mutations are encoded to SQLite for persistence. We provide a basic standard
157 * serialization implementation to serialize column values. Custom or advanced types require providing additional
158 * serializer specifications. Partial column overrides can be supplied to `serializer`.
159 *
160 * @example
161 * ```typescript
162 * import { z } from "zod"
163 *
164 * // The PowerSync SQLite schema
165 * const APP_SCHEMA = new Schema({
166 * documents: new Table({
167 * name: column.text,
168 * // Booleans are represented as integers in SQLite
169 * is_active: column.integer
170 * }),
171 * })
172 *
173 * // Advanced Zod validations.
174 * // We accept boolean values as input for operations and expose Booleans in query results
175 * const schema = z.object({
176 * id: z.string(),
177 * isActive: z.boolean(), // TInput and TOutput are boolean
178 * })
179 *
180 * // The deserializationSchema converts the SQLite synced INTEGER (0/1) values to booleans.
181 * const deserializationSchema = z.object({
182 * id: z.string(),
183 * isActive: z.number().nullable().transform((val) => val == null ? true : val > 0),
184 * })
185 *
186 * const collection = createCollection(
187 * powerSyncCollectionOptions({
188 * database: db,
189 * table: APP_SCHEMA.props.documents,
190 * schema,
191 * deserializationSchema,
192 * })
193 * )
194 * ```
195 */
196export function powerSyncCollectionOptions<
197 TTable extends Table,
198 TSchema extends StandardSchemaV1<
199 // The input and output must have the same keys, the value types can be arbitrary
200 AnyTableColumnType<TTable>,
201 AnyTableColumnType<TTable>
202 >,
203>(
204 config: BasePowerSyncCollectionConfig<TTable, TSchema> &
205 ConfigWithArbitraryCollectionTypes<TTable, TSchema>,
206): EnhancedPowerSyncCollectionConfig<
207 TTable,
208 InferPowerSyncOutputType<TTable, TSchema>,
209 TSchema
210> & {
211 utils: PowerSyncCollectionUtils<TTable>
212 schema: TSchema
214​
215/**
216 * Implementation of powerSyncCollectionOptions that handles both schema and non-schema configurations.
217 */
218​
219export function powerSyncCollectionOptions<
220 TTable extends Table,
221 TSchema extends StandardSchemaV1<any> = never,
222>(config: PowerSyncCollectionConfig<TTable, TSchema>) {
223 const {
224 database,
225 table,
226 schema: inputSchema,
227 syncBatchSize = DEFAULT_BATCH_SIZE,
228 ...restConfig
229 } = config
230​
231 const deserializationSchema =
232 `deserializationSchema` in config ? config.deserializationSchema : null
233 const serializer = `serializer` in config ? config.serializer : undefined
234 const onDeserializationError =
235 `onDeserializationError` in config
236 ? config.onDeserializationError
237 : undefined
238​
239 // The SQLite table type
240 type TableType = ExtractedTable<TTable>
241​
242 // The collection output type
243 type OutputType = InferPowerSyncOutputType<TTable, TSchema>
244​
245 const { viewName, trackMetadata: metadataIsTracked } = table
246​
247 /**
248 * Deserializes data from the incoming sync stream
249 */
250 const deserializeSyncRow = (value: TableType): OutputType => {
251 const validationSchema = deserializationSchema || schema
252 const validation = validationSchema[`~standard`].validate(value)
253 if (`value` in validation) {
254 return validation.value
255 } else if (`issues` in validation) {
256 const issueMessage = `Failed to validate incoming data for ${viewName}. Issues: ${validation.issues.map((issue) => `${issue.path} - ${issue.message}`)}`
257 database.logger.error(issueMessage)
258 onDeserializationError!(validation)
259 throw new Error(issueMessage)
260 } else {
261 const unknownErrorMessage = `Unknown deserialization error for ${viewName}`
262 database.logger.error(unknownErrorMessage)
263 onDeserializationError!({ issues: [{ message: unknownErrorMessage }] })
264 throw new Error(unknownErrorMessage)
265 }
266 }
267​
268 // We can do basic runtime validations for columns if not explicit schema has been provided
269 const schema = inputSchema ?? (convertTableToSchema(table) as TSchema)
270 /**
271 * The onInsert, onUpdate, and onDelete handlers should only return
272 * after we have written the changes to TanStack DB.
273 * We currently only write to TanStack DB from a diff trigger.
274 * We wait for the diff trigger to observe the change,
275 * and only then return from the on[X] handlers.
276 * This ensures that when the transaction is reported as
277 * complete to the caller, the in-memory state is already
278 * consistent with the database.
279 */
280 const pendingOperationStore = PendingOperationStore.GLOBAL
281 // Keep the tracked table unique in case of multiple tabs.
282 const trackedTableName = `__${viewName}_tracking_${Math.floor(
283 Math.random() * 0xffffffff,
284 )
285 .toString(16)
286 .padStart(8, `0`)}`
287​
288 const transactor = new PowerSyncTransactor({
289 database,
290 })
291​
292 /**
293 * "sync"
294 * Notice that this describes the Sync between the local SQLite table
295 * and the in-memory tanstack-db collection.
296 */
297 const sync: SyncConfig<OutputType, string> = {
298 sync: (params) => {
299 const { begin, write, commit, markReady } = params
300 const abortController = new AbortController()
301​
302 // The sync function needs to be synchronous
303 async function start() {
304 database.logger.info(
305 `Sync is starting for ${viewName} into ${trackedTableName}`,
306 )
307 database.onChangeWithCallback(
308 {
309 onChange: async () => {
310 await database
311 .writeTransaction(async (context) => {
312 begin()
313 const operations = await context.getAll<TriggerDiffRecord>(
314 `SELECT * FROM ${trackedTableName} ORDER BY timestamp ASC`,
315 )
316 const pendingOperations: Array<PendingOperation> = []
317​
318 for (const op of operations) {
319 const { id, operation, timestamp, value } = op
320 const parsedValue = deserializeSyncRow({
321 id,
322 ...JSON.parse(value),
323 })
324 const parsedPreviousValue =
325 op.operation == DiffTriggerOperation.UPDATE
326 ? deserializeSyncRow({
327 id,
328 ...JSON.parse(op.previous_value),
329 })
330 : undefined
331 write({
332 type: mapOperation(operation),
333 value: parsedValue,
334 previousValue: parsedPreviousValue,
335 })
336 pendingOperations.push({
337 id,
338 operation,
339 timestamp,
340 tableName: viewName,
341 })
342 }
343​
344 // clear the current operations
345 await context.execute(`DELETE FROM ${trackedTableName}`)
346​
347 commit()
348 pendingOperationStore.resolvePendingFor(pendingOperations)
349 })
350 .catch((error) => {
351 database.logger.error(
352 `An error has been detected in the sync handler`,
353 error,
354 )
355 })
356 },
357 },
358 {
359 signal: abortController.signal,
360 triggerImmediate: false,
361 tables: [trackedTableName],
362 },
363 )
364​
365 const disposeTracking = await database.triggers.createDiffTrigger({
366 source: viewName,
367 destination: trackedTableName,
368 when: {
369 [DiffTriggerOperation.INSERT]: `TRUE`,
370 [DiffTriggerOperation.UPDATE]: `TRUE`,
371 [DiffTriggerOperation.DELETE]: `TRUE`,
372 },
373 hooks: {
374 beforeCreate: async (context) => {
375 let currentBatchCount = syncBatchSize
376 let cursor = 0
377 while (currentBatchCount == syncBatchSize) {
378 begin()
379 const batchItems = await context.getAll<TableType>(
380 sanitizeSQL`SELECT * FROM ${viewName} LIMIT ? OFFSET ?`,
381 [syncBatchSize, cursor],
382 )
383 currentBatchCount = batchItems.length
384 cursor += currentBatchCount
385 for (const row of batchItems) {
386 write({
387 type: `insert`,
388 value: deserializeSyncRow(row),
389 })
390 }
391 commit()
392 }
393 markReady()
394 database.logger.info(
395 `Sync is ready for ${viewName} into ${trackedTableName}`,
396 )
397 },
398 },
399 })
400​
401 // If the abort controller was aborted while processing the request above
402 if (abortController.signal.aborted) {
403 await disposeTracking()
404 } else {
405 abortController.signal.addEventListener(
406 `abort`,
407 () => {
408 disposeTracking()
409 },
410 { once: true },
411 )
412 }
413 }
414​
415 start().catch((error) =>
416 database.logger.error(
417 `Could not start syncing process for ${viewName} into ${trackedTableName}`,
418 error,
419 ),
420 )
421​
422 return () => {
423 database.logger.info(
424 `Sync has been stopped for ${viewName} into ${trackedTableName}`,
425 )
426 abortController.abort()
427 }
428 },
429 // Expose the getSyncMetadata function
430 getSyncMetadata: undefined,
431 }
432​
433 const getKey = (record: OutputType) => asPowerSyncRecord(record).id
434​
435 const outputConfig: EnhancedPowerSyncCollectionConfig<
436 TTable,
437 OutputType,
438 TSchema
439 > = {
440 ...restConfig,
441 schema,
442 getKey,
443 // Syncing should start immediately since we need to monitor the changes for mutations
444 startSync: true,
445 sync,
446 onInsert: async (params) => {
447 // The transaction here should only ever contain a single insert mutation
448 return await transactor.applyTransaction(params.transaction)
449 },
450 onUpdate: async (params) => {
451 // The transaction here should only ever contain a single update mutation
452 return await transactor.applyTransaction(params.transaction)
453 },
454 onDelete: async (params) => {
455 // The transaction here should only ever contain a single delete mutation
456 return await transactor.applyTransaction(params.transaction)
457 },
458 utils: {
459 getMeta: () => ({
460 tableName: viewName,
461 trackedTableName,
462 metadataIsTracked,
463 serializeValue: (value) =>
464 serializeForSQLite(
465 value,
466 // This is required by the input generic
467 table as Table<
468 MapBaseColumnType<InferPowerSyncOutputType<TTable, TSchema>>
469 >,
470 // Coerce serializer to the shape that corresponds to the Table constructed from OutputType
471 serializer as CustomSQLiteSerializer<
472 OutputType,
473 ExtractedTableColumns<Table<MapBaseColumnType<OutputType>>>
474 >,
475 ),
476 }),
477 },
478 }
479 return outputConfig