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

powersync.ts

805 lines27.0 KB

1import { DiffTriggerOperation, sanitizeSQL } from '@powersync/common'
2import { or, withCollectionConfigFactory } from '@tanstack/db'
3import { compileSQLite } from './sqlite-compiler'
4import { PendingOperationStore } from './PendingOperationStore'
5import { PowerSyncTransactor } from './PowerSyncTransactor'
6import { DEFAULT_BATCH_SIZE } from './definitions'
7import { asPowerSyncRecord, mapOperation } from './helpers'
8import { convertTableToSchema } from './schema'
9import { serializeForSQLite } from './serialization'
10import type {
11 CleanupFn,
12 LoadSubsetOptions,
13 OperationType,
14 SyncAppliedReceipt,
15 SyncConfig,
16} from '@tanstack/db'
17import type {
18 AnyTableColumnType,
19 ExtractedTable,
20 ExtractedTableColumns,
21 MapBaseColumnType,
22 OptionalExtractedTable,
23} from './helpers'
24import type {
25 BasePowerSyncCollectionConfig,
26 ConfigWithArbitraryCollectionTypes,
27 ConfigWithSQLiteInputType,
28 ConfigWithSQLiteTypes,
29 CustomSQLiteSerializer,
30 EnhancedPowerSyncCollectionConfig,
31 InferPowerSyncOutputType,
32 PowerSyncCollectionConfig,
33 PowerSyncCollectionUtils,
34} from './definitions'
35import type { PendingOperation } from './PendingOperationStore'
36import type { StandardSchemaV1 } from '@standard-schema/spec'
37import type { LockContext, Table, TriggerDiffRecord } from '@powersync/common'
38​
39/**
40 * Creates PowerSync collection options for use with a standard Collection.
41 *
42 * @template TTable - The SQLite-based typing
43 * @template TSchema - The validation schema type (optionally supports a custom input type)
44 * @param config - Configuration options for the PowerSync collection
45 * @returns Collection options with utilities
46 */
47​
48// Overload 1: No schema is provided
49​
50/**
51 * Creates a PowerSync collection configuration with basic default validation.
52 * Input and Output types are the SQLite column types.
53 *
54 * @example
55 * ```typescript
56 * const APP_SCHEMA = new Schema({
57 * documents: new Table({
58 * name: column.text,
59 * }),
60 * })
61 *
62 * type Document = (typeof APP_SCHEMA)["types"]["documents"]
63 *
64 * const db = new PowerSyncDatabase({
65 * database: {
66 * dbFilename: "test.sqlite",
67 * },
68 * schema: APP_SCHEMA,
69 * })
70 *
71 * const collection = createCollection(
72 * powerSyncCollectionOptions({
73 * database: db,
74 * table: APP_SCHEMA.props.documents
75 * })
76 * )
77 * ```
78 */
79export function powerSyncCollectionOptions<TTable extends Table = Table>(
80 config: BasePowerSyncCollectionConfig<TTable, never> & ConfigWithSQLiteTypes,
81): EnhancedPowerSyncCollectionConfig<
82 TTable,
83 OptionalExtractedTable<TTable>,
84 never
86​
87// Overload 2: Schema is provided and the TInput matches SQLite types.
88​
89/**
90 * Creates a PowerSync collection configuration with schema validation.
91 *
92 * The input types satisfy the SQLite column types.
93 *
94 * The output types are defined by the provided schema. This schema can enforce additional
95 * validation or type transforms.
96 * Arbitrary output typed mutations are encoded to SQLite for persistence. We provide a basic standard
97 * serialization implementation to serialize column values. Custom or advanced types require providing additional
98 * serializer specifications. Partial column overrides can be supplied to `serializer`.
99 *
100 * @example
101 * ```typescript
102 * import { z } from "zod"
103 *
104 * // The PowerSync SQLite schema
105 * const APP_SCHEMA = new Schema({
106 * documents: new Table({
107 * name: column.text,
108 * // Dates are stored as ISO date strings in SQLite
109 * created_at: column.text
110 * }),
111 * })
112 *
113 * // Advanced Zod validations. The output type of this schema
114 * // is constrained to the SQLite schema of APP_SCHEMA
115 * const schema = z.object({
116 * id: z.string(),
117 * // Notice that `name` is not nullable (is required) here and it has additional validation
118 * name: z.string().min(3, { message: "Should be at least 3 characters" }).nullable(),
119 * // The input type is still the SQLite string type. While collections will output smart Date instances.
120 * created_at: z.string().transform(val => new Date(val))
121 * })
122 *
123 * const collection = createCollection(
124 * powerSyncCollectionOptions({
125 * database: db,
126 * table: APP_SCHEMA.props.documents,
127 * schema,
128 * serializer: {
129 * // The default is toISOString, this is just to demonstrate custom overrides
130 * created_at: (outputValue) => outputValue.toISOString(),
131 * },
132 * })
133 * )
134 * ```
135 */
136export function powerSyncCollectionOptions<
137 TTable extends Table,
138 TSchema extends StandardSchemaV1<
139 // TInput is the SQLite types. We can use the supplied schema to validate sync input
140 OptionalExtractedTable<TTable>,
141 AnyTableColumnType<TTable>
142 >,
143>(
144 config: BasePowerSyncCollectionConfig<TTable, TSchema> &
145 ConfigWithSQLiteInputType<TTable, TSchema>,
146): EnhancedPowerSyncCollectionConfig<
147 TTable,
148 InferPowerSyncOutputType<TTable, TSchema>,
149 TSchema
150> & {
151 schema: TSchema
153​
154// Overload 3: Schema is provided with arbitrary TInput and TOutput
155/**
156 * Creates a PowerSync collection configuration with schema validation.
157 *
158 * The input types are not linked to the internal SQLite table types. This can
159 * give greater flexibility, e.g. by accepting rich types as input for `insert` or `update` operations.
160 * An additional `deserializationSchema` is required in order to process incoming SQLite updates to the output type.
161 *
162 * The output types are defined by the provided schema. This schema can enforce additional
163 * validation or type transforms.
164 * Arbitrary output typed mutations are encoded to SQLite for persistence. We provide a basic standard
165 * serialization implementation to serialize column values. Custom or advanced types require providing additional
166 * serializer specifications. Partial column overrides can be supplied to `serializer`.
167 *
168 * @example
169 * ```typescript
170 * import { z } from "zod"
171 *
172 * // The PowerSync SQLite schema
173 * const APP_SCHEMA = new Schema({
174 * documents: new Table({
175 * name: column.text,
176 * // Booleans are represented as integers in SQLite
177 * is_active: column.integer
178 * }),
179 * })
180 *
181 * // Advanced Zod validations.
182 * // We accept boolean values as input for operations and expose Booleans in query results
183 * const schema = z.object({
184 * id: z.string(),
185 * isActive: z.boolean(), // TInput and TOutput are boolean
186 * })
187 *
188 * // The deserializationSchema converts the SQLite synced INTEGER (0/1) values to booleans.
189 * const deserializationSchema = z.object({
190 * id: z.string(),
191 * isActive: z.number().nullable().transform((val) => val == null ? true : val > 0),
192 * })
193 *
194 * const collection = createCollection(
195 * powerSyncCollectionOptions({
196 * database: db,
197 * table: APP_SCHEMA.props.documents,
198 * schema,
199 * deserializationSchema,
200 * })
201 * )
202 * ```
203 */
204export function powerSyncCollectionOptions<
205 TTable extends Table,
206 TSchema extends StandardSchemaV1<
207 // The input and output must have the same keys, the value types can be arbitrary
208 AnyTableColumnType<TTable>,
209 AnyTableColumnType<TTable>
210 >,
211>(
212 config: BasePowerSyncCollectionConfig<TTable, TSchema> &
213 ConfigWithArbitraryCollectionTypes<TTable, TSchema>,
214): EnhancedPowerSyncCollectionConfig<
215 TTable,
216 InferPowerSyncOutputType<TTable, TSchema>,
217 TSchema
218> & {
219 utils: PowerSyncCollectionUtils<TTable>
220 schema: TSchema
222​
223/**
224 * Implementation of powerSyncCollectionOptions that handles both schema and non-schema configurations.
225 */
226​
227export function powerSyncCollectionOptions<
228 TTable extends Table,
229 TSchema extends StandardSchemaV1<any> = never,
230>(
231 config: PowerSyncCollectionConfig<TTable, TSchema>,
232): ReturnType<typeof createPowerSyncCollectionConfig<TTable, TSchema>> {
233 const outputConfig = createPowerSyncCollectionConfig(config)
234 return withCollectionConfigFactory(outputConfig, () =>
235 createPowerSyncCollectionConfig(config),
236 )
238​
239function createPowerSyncCollectionConfig<
240 TTable extends Table,
241 TSchema extends StandardSchemaV1<any> = never,
242>(config: PowerSyncCollectionConfig<TTable, TSchema>) {
243 const {
244 database,
245 table,
246 schema: inputSchema,
247 syncBatchSize = DEFAULT_BATCH_SIZE,
248 syncMode = 'eager',
249 ...restConfig
250 } = config
251​
252 const deserializationSchema =
253 `deserializationSchema` in config ? config.deserializationSchema : null
254 const serializer = `serializer` in config ? config.serializer : undefined
255 const onDeserializationError =
256 `onDeserializationError` in config
257 ? config.onDeserializationError
258 : undefined
259​
260 // The SQLite table type
261 type TableType = ExtractedTable<TTable>
262​
263 // The collection output type
264 type OutputType = InferPowerSyncOutputType<TTable, TSchema>
265​
266 const { viewName, trackMetadata: metadataIsTracked } = table
267​
268 /**
269 * Deserializes data from the incoming sync stream
270 */
271 const deserializeSyncRow = (value: TableType): OutputType => {
272 const validationSchema = deserializationSchema || schema
273 const validation = validationSchema[`~standard`].validate(value)
274 if (`value` in validation) {
275 return validation.value
276 } else if (`issues` in validation) {
277 const issueMessage = `Failed to validate incoming data for ${viewName}. Issues: ${validation.issues.map((issue) => `${issue.path} - ${issue.message}`)}`
278 database.logger.error(issueMessage)
279 onDeserializationError!(validation)
280 throw new Error(issueMessage)
281 } else {
282 const unknownErrorMessage = `Unknown deserialization error for ${viewName}`
283 database.logger.error(unknownErrorMessage)
284 onDeserializationError!({ issues: [{ message: unknownErrorMessage }] })
285 throw new Error(unknownErrorMessage)
286 }
287 }
288​
289 // We can do basic runtime validations for columns if not explicit schema has been provided
290 const schema = inputSchema ?? (convertTableToSchema(table) as TSchema)
291 /**
292 * The onInsert, onUpdate, and onDelete handlers should only return
293 * after we have written the changes to TanStack DB.
294 * We currently only write to TanStack DB from a diff trigger.
295 * We wait for the diff trigger to observe the change,
296 * and only then return from the on[X] handlers.
297 * This ensures that when the transaction is reported as
298 * complete to the caller, the in-memory state is already
299 * consistent with the database.
300 */
301 const pendingOperationStore = PendingOperationStore.GLOBAL
302 // Keep the tracked table unique in case of multiple tabs.
303 const trackedTableName = `__${viewName}_tracking_${Math.floor(
304 Math.random() * 0xffffffff,
305 )
306 .toString(16)
307 .padStart(8, `0`)}`
308​
309 const transactor = new PowerSyncTransactor({
310 database,
311 })
312​
313 /**
314 * "sync"
315 * Notice that this describes the Sync between the local SQLite table
316 * and the in-memory tanstack-db collection.
317 */
318 const sync: SyncConfig<OutputType, string> = {
319 sync: (params) => {
320 const { begin, write, collection, commit, markReady, markError } = params
321 const abortController = new AbortController()
322​
323 let disposeTracking:
324 | ((options?: { context?: LockContext }) => Promise<void>)
325 | null = null
326​
327 if (syncMode === `eager`) {
328 return runEagerSync()
329 } else {
330 return runOnDemandSync()
331 }
332​
333 /**
334 * Disposes the current diff trigger, if one is active, and clears the
335 * tracking state.
336 */
337 async function safelyDisposeTracking(
338 context?: LockContext,
339 ): Promise<void> {
340 const dispose = disposeTracking
341 if (!dispose) {
342 return
343 }
344​
345 disposeTracking = null
346 await dispose(context ? { context } : undefined)
347 }
348​
349 async function createDiffTrigger(
350 options: {
351 setupContext?: LockContext
352 immediate?: boolean
353 when: Record<DiffTriggerOperation, string>
354 writeType: (rowId: string) => OperationType
355 batchQuery: (
356 lockContext: LockContext,
357 batchSize: number,
358 cursor: number,
359 ) => Promise<Array<TableType>>
360 },
361 appliedReceipts: Array<SyncAppliedReceipt>,
362 ) {
363 const { setupContext, immediate, when, writeType, batchQuery } = options
364​
365 return await database.triggers.createDiffTrigger({
366 source: viewName,
367 destination: trackedTableName,
368 setupContext,
369 when,
370 hooks: {
371 beforeCreate: async (context) => {
372 let currentBatchCount = syncBatchSize
373 let cursor = 0
374 while (currentBatchCount == syncBatchSize) {
375 begin(immediate ? { immediate: true } : undefined)
376​
377 const batchItems = await batchQuery(
378 context,
379 syncBatchSize,
380 cursor,
381 )
382 currentBatchCount = batchItems.length
383 cursor += currentBatchCount
384 for (const row of batchItems) {
385 write({
386 type: writeType(row.id),
387 value: deserializeSyncRow(row),
388 })
389 }
390 appliedReceipts.push(commit())
391 }
392 database.logger.info(
393 `Sync is ready for ${viewName} into ${trackedTableName}`,
394 )
395 },
396 },
397 })
398 }
399​
400 async function flushDiffRecords(): Promise<void> {
401 const ignoredReceipts: Array<SyncAppliedReceipt> = []
402 await database
403 .writeTransaction(async (context) => {
404 await flushDiffRecordsWithContext(context, ignoredReceipts)
405 })
406 .catch((error) => {
407 database.logger.error(
408 `An error has been detected in the sync handler`,
409 error,
410 )
411 })
412 }
413​
414 // We can use this directly if we want to pair a flush with dispose+recreate diff trigger.
415 async function flushDiffRecordsWithContext(
416 context: LockContext,
417 appliedReceipts: Array<SyncAppliedReceipt>,
418 ): Promise<void> {
419 // There is nothing to flush if no tracking table is currently active.
420 if (!disposeTracking) {
421 return
422 }
423​
424 try {
425 begin()
426 const operations = await context.getAll<TriggerDiffRecord>(
427 `SELECT * FROM ${trackedTableName} ORDER BY operation_id ASC`,
428 )
429 const pendingOperations: Array<PendingOperation> = []
430​
431 for (const op of operations) {
432 const { id, operation, timestamp, value } = op
433 const parsedValue = deserializeSyncRow({
434 id,
435 ...JSON.parse(value),
436 })
437 const parsedPreviousValue =
438 op.operation == DiffTriggerOperation.UPDATE
439 ? deserializeSyncRow({
440 id,
441 ...JSON.parse(op.previous_value),
442 })
443 : undefined
444 write({
445 type: mapOperation(operation),
446 value: parsedValue,
447 previousValue: parsedPreviousValue,
448 })
449 pendingOperations.push({
450 id,
451 operation,
452 timestamp,
453 tableName: viewName,
454 })
455 }
456​
457 // clear the current operations
458 await context.execute(`DELETE FROM ${trackedTableName}`)
459​
460 const applied = commit()
461 appliedReceipts.push(applied)
462 // Mutation persistence is what releases the Collection's FIFO gate.
463 // Confirm these local operations after the sync transaction is
464 // staged; waiting for its applied receipt would deadlock the user
465 // transaction that currently parks it.
466 pendingOperationStore.resolvePendingFor(pendingOperations)
467 } catch (error) {
468 database.logger.error(
469 `An error has been detected in the sync handler`,
470 error,
471 )
472 }
473 }
474​
475 // The sync function needs to be synchronous.
476 async function start(afterOnChangeRegistered?: () => Promise<void>) {
477 database.logger.info(
478 `Sync is starting for ${viewName} into ${trackedTableName}`,
479 )
480 database.onChangeWithCallback(
481 {
482 onChange: async () => {
483 await flushDiffRecords()
484 },
485 },
486 {
487 signal: abortController.signal,
488 triggerImmediate: false,
489 tables: [trackedTableName],
490 },
491 )
492​
493 await afterOnChangeRegistered?.()
494​
495 // If the abort controller was aborted while processing the request above
496 if (abortController.signal.aborted) {
497 await safelyDisposeTracking()
498 } else {
499 abortController.signal.addEventListener(
500 `abort`,
501 async () => {
502 await safelyDisposeTracking()
503 },
504 { once: true },
505 )
506 }
507 }
508​
509 // Eager mode.
510 // Registers a diff trigger for the entire table.
511 function runEagerSync() {
512 let onUnload: CleanupFn | void | null = null
513​
514 start(async () => {
515 onUnload = await restConfig.onLoad?.()
516​
517 const appliedReceipts: Array<SyncAppliedReceipt> = []
518 disposeTracking = await createDiffTrigger(
519 {
520 // Initial eager hydration must make the source usable before
521 // PowerSync can persist a mutation queued during startup.
522 immediate: true,
523 when: {
524 [DiffTriggerOperation.INSERT]: `TRUE`,
525 [DiffTriggerOperation.UPDATE]: `TRUE`,
526 [DiffTriggerOperation.DELETE]: `TRUE`,
527 },
528 writeType: (_rowId: string) => `insert`,
529 batchQuery: (
530 lockContext: LockContext,
531 batchSize: number,
532 cursor: number,
533 ) =>
534 lockContext.getAll<TableType>(
535 sanitizeSQL`SELECT * FROM ${viewName} LIMIT ? OFFSET ?`,
536 [batchSize, cursor],
537 ),
538 },
539 appliedReceipts,
540 )
541 await Promise.all(appliedReceipts)
542 markReady()
543 }).catch((error) => {
544 database.logger.error(
545 `Could not start syncing process for ${viewName} into ${trackedTableName}`,
546 error,
547 )
548 if (collection.status === `loading`) {
549 markError(error)
550 }
551 })
552​
553 return () => {
554 database.logger.info(
555 `Sync has been stopped for ${viewName} into ${trackedTableName}`,
556 )
557 abortController.abort()
558 onUnload?.()
559 }
560 }
561​
562 // On-demand mode.
563 // Registers a diff trigger for the active WHERE expressions.
564 function runOnDemandSync() {
565 const unloadSubsetCallbacks = new Map<LoadSubsetOptions, CleanupFn>()
566 const releasedSubsets = new WeakSet<LoadSubsetOptions>()
567 let stopped = false
568 const hasStopped = () => stopped
569​
570 start().catch((error) =>
571 database.logger.error(
572 `Could not start syncing process for ${viewName} into ${trackedTableName}`,
573 error,
574 ),
575 )
576​
577 // Tracks all active WHERE expressions for on-demand sync filtering.
578 // Each loadSubset call pushes its predicate; unloadSubset removes it.
579 const activeWhereExpressions: Array<LoadSubsetOptions['where']> = []
580​
581 const loadSubset = async (
582 options?: LoadSubsetOptions,
583 ): Promise<void> => {
584 if (hasStopped()) return
585 const appliedReceipts: Array<SyncAppliedReceipt> = []
586​
587 if (options) {
588 activeWhereExpressions.push(options.where)
589 const cleanup = await restConfig.onLoadSubset?.(options)
590 if (hasStopped()) {
591 cleanup?.()
592 return
593 }
594 if (cleanup) {
595 if (releasedSubsets.has(options) || options.signal?.aborted) {
596 cleanup()
597 } else {
598 unloadSubsetCallbacks.set(options, cleanup)
599 }
600 }
601 }
602​
603 // No predicates remain, so stop tracking entirely. Both calls are no-ops
604 // when no tracking table is currently active.
605 if (activeWhereExpressions.length === 0) {
606 await database.writeLock(async (ctx) => {
607 await flushDiffRecordsWithContext(ctx, appliedReceipts)
608 await safelyDisposeTracking(ctx)
609 })
610 await Promise.all(appliedReceipts)
611 return
612 }
613​
614 const combinedWhere =
615 activeWhereExpressions.length === 1
616 ? activeWhereExpressions[0]
617 : or(
618 activeWhereExpressions[0],
619 activeWhereExpressions[1],
620 ...activeWhereExpressions.slice(2),
621 )
622​
623 const compiledNewData = compileSQLite(
624 { where: combinedWhere },
625 { jsonColumn: 'NEW.data' },
626 )
627​
628 const compiledOldData = compileSQLite(
629 { where: combinedWhere },
630 { jsonColumn: 'OLD.data' },
631 )
632​
633 const compiledView = compileSQLite({ where: combinedWhere })
634​
635 const newDataWhenClause = toInlinedWhereClause(compiledNewData)
636 const oldDataWhenClause = toInlinedWhereClause(compiledOldData)
637 const viewWhereClause = toInlinedWhereClause(compiledView)
638​
639 await database.writeLock(async (ctx) => {
640 // Replace any active tracking with one covering the new set of
641 // predicates.
642 await flushDiffRecordsWithContext(ctx, appliedReceipts)
643 await safelyDisposeTracking(ctx)
644​
645 disposeTracking = await createDiffTrigger(
646 {
647 setupContext: ctx,
648 when: {
649 [DiffTriggerOperation.INSERT]: newDataWhenClause,
650 [DiffTriggerOperation.UPDATE]: `(${newDataWhenClause}) OR (${oldDataWhenClause})`,
651 [DiffTriggerOperation.DELETE]: oldDataWhenClause,
652 },
653 writeType: (rowId: string) =>
654 collection.has(rowId) ? `update` : `insert`,
655 batchQuery: (
656 lockContext: LockContext,
657 batchSize: number,
658 cursor: number,
659 ) =>
660 lockContext.getAll<TableType>(
661 `SELECT * FROM ${viewName} WHERE ${viewWhereClause} LIMIT ? OFFSET ?`,
662 [batchSize, cursor],
663 ),
664 },
665 appliedReceipts,
666 )
667 })
668 await Promise.all(appliedReceipts)
669 }
670​
671 const toInlinedWhereClause = (compiled: {
672 where?: string
673 params: Array<unknown>
674 }): string => {
675 if (!compiled.where) return 'TRUE'
676 const sqlParts = compiled.where.split('?')
677 return sanitizeSQL(
678 sqlParts as unknown as TemplateStringsArray,
679 ...compiled.params,
680 )
681 }
682​
683 const unloadSubset = async (options: LoadSubsetOptions) => {
684 releasedSubsets.add(options)
685 unloadSubsetCallbacks.get(options)?.()
686 unloadSubsetCallbacks.delete(options)
687​
688 const idx = activeWhereExpressions.indexOf(options.where)
689 if (idx !== -1) {
690 activeWhereExpressions.splice(idx, 1)
691 }
692​
693 // Evict rows that were exclusively loaded by the departing predicate.
694 // These are rows matching the departing WHERE that are no longer covered
695 // by any remaining active predicate.
696 const compiledDeparting = compileSQLite({ where: options.where })
697 const departingWhereSQL = toInlinedWhereClause(compiledDeparting)
698​
699 let evictionSQL: string
700 if (activeWhereExpressions.length === 0) {
701 evictionSQL = `SELECT id FROM ${viewName} WHERE ${departingWhereSQL}`
702 } else {
703 const combinedRemaining =
704 activeWhereExpressions.length === 1
705 ? activeWhereExpressions[0]!
706 : or(
707 activeWhereExpressions[0],
708 activeWhereExpressions[1],
709 ...activeWhereExpressions.slice(2),
710 )
711 const compiledRemaining = compileSQLite({
712 where: combinedRemaining,
713 })
714 const remainingWhereSQL = toInlinedWhereClause(compiledRemaining)
715 evictionSQL = `SELECT id FROM ${viewName} WHERE (${departingWhereSQL}) AND NOT (${remainingWhereSQL})`
716 }
717​
718 const rowsToEvict = await database.getAll<{ id: string }>(evictionSQL)
719 if (rowsToEvict.length > 0) {
720 begin()
721 for (const { id } of rowsToEvict) {
722 write({ type: `delete`, key: id })
723 }
724 // Eviction does not establish new subset coverage. Keep trigger
725 // replacement in the same unload turn even when this delete waits
726 // behind a persisting mutation; the later load tracks its own
727 // establishing receipts.
728 void commit()
729 }
730​
731 // Recreate the diff trigger for the remaining active WHERE expressions.
732 await loadSubset()
733 }
734​
735 markReady()
736​
737 return {
738 cleanup: () => {
739 stopped = true
740 database.logger.info(
741 `Sync has been stopped for ${viewName} into ${trackedTableName}`,
742 )
743 abortController.abort()
744 for (const cleanup of unloadSubsetCallbacks.values()) cleanup()
745 unloadSubsetCallbacks.clear()
746 activeWhereExpressions.length = 0
747 },
748 loadSubset: (options: LoadSubsetOptions) => loadSubset(options),
749 unloadSubset: (options: LoadSubsetOptions) => unloadSubset(options),
750 }
751 }
752 },
753 // Expose the getSyncMetadata function
754 getSyncMetadata: undefined,
755 }
756​
757 const getKey = (record: OutputType) => asPowerSyncRecord(record).id
758​
759 const outputConfig: EnhancedPowerSyncCollectionConfig<
760 TTable,
761 OutputType,
762 TSchema
763 > = {
764 ...restConfig,
765 schema,
766 getKey,
767 // Syncing should start immediately since we need to monitor the changes for mutations
768 startSync: true,
769 syncMode,
770 sync,
771 onInsert: async (params) => {
772 // The transaction here should only ever contain a single insert mutation
773 return await transactor.applyTransaction(params.transaction)
774 },
775 onUpdate: async (params) => {
776 // The transaction here should only ever contain a single update mutation
777 return await transactor.applyTransaction(params.transaction)
778 },
779 onDelete: async (params) => {
780 // The transaction here should only ever contain a single delete mutation
781 return await transactor.applyTransaction(params.transaction)
782 },
783 utils: {
784 getMeta: () => ({
785 tableName: viewName,
786 trackedTableName,
787 metadataIsTracked,
788 serializeValue: (value) =>
789 serializeForSQLite(
790 value,
791 // This is required by the input generic
792 table as Table<
793 MapBaseColumnType<InferPowerSyncOutputType<TTable, TSchema>>
794 >,
795 // Coerce serializer to the shape that corresponds to the Table constructed from OutputType
796 serializer as CustomSQLiteSerializer<
797 OutputType,
798 ExtractedTableColumns<Table<MapBaseColumnType<OutputType>>>
799 >,
800 ),
801 }),
802 },
803 }
804 return outputConfig