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

definitions.ts

328 lines10.3 KB

1import type { CommonPowerSyncDatabase, Table } from '@powersync/common'
2import type { StandardSchemaV1 } from '@standard-schema/spec'
3import type {
4 BaseCollectionConfig,
5 CleanupFn,
6 CollectionConfig,
7 InferSchemaOutput,
8 LoadSubsetOptions,
9} from '@tanstack/db'
10import type {
11 AnyTableColumnType,
12 ExtractedTable,
13 OptionalExtractedTable,
14 PowerSyncRecord,
15} from './helpers'
16​
17/**
18 * Small helper which determines the output type if:
19 * - Standard SQLite types are to be used OR
20 * - If the provided schema should be used.
21 */
22export type InferPowerSyncOutputType<
23 TTable extends Table = Table,
24 TSchema extends StandardSchemaV1<PowerSyncRecord> = never,
25> = [TSchema] extends [never]
26 ? ExtractedTable<TTable>
27 : InferSchemaOutput<TSchema>
28​
29/**
30 * A mapping type for custom serialization of object properties to SQLite-compatible values.
31 *
32 * This type allows you to override, for keys in the input object (`TOutput`), a function that transforms
33 * the value to the corresponding SQLite type (`TSQLite`). Keys not specified will use the default SQLite serialization.
34 *
35 * ## Generics
36 * - `TOutput`: The input object type, representing the row data to be serialized.
37 * - `TSQLite`: The target SQLite-compatible type for each property, typically inferred from the table schema.
38 *
39 * ## Usage
40 * Use this type to define a map of serialization functions for specific keys when you need custom handling
41 * (e.g., converting complex objects, formatting dates, or handling enums).
42 *
43 * Example:
44 * ```ts
45 * const serializer: CustomSQLiteSerializer<MyRowType, MySQLiteType> = {
46 * createdAt: (date) => date.toISOString(),
47 * status: (status) => status ? 1 : 0,
48 * meta: (meta) => JSON.stringify(meta),
49 * };
50 * ```
51 *
52 * ## Behavior
53 * - Each key maps to a function that receives the value and returns the SQLite-compatible value.
54 * - Used by `serializeForSQLite` to override default serialization for specific columns.
55 */
56export type CustomSQLiteSerializer<
57 TOutput extends Record<string, unknown>,
58 TSQLite extends Record<string, unknown>,
59> = Partial<{
60 [Key in keyof TOutput]: (
61 value: TOutput[Key],
62 ) => Key extends keyof TSQLite ? TSQLite[Key] : never
63}>
64​
65export type SerializerConfig<
66 TOutput extends Record<string, unknown>,
67 TSQLite extends Record<string, unknown>,
68> = {
69 /**
70 * Optional partial serializer object for customizing how individual columns are serialized for SQLite.
71 *
72 * This should be a partial map of column keys to serialization functions, following the
73 * {@link CustomSQLiteSerializer} type. Each function receives the column value and returns a value
74 * compatible with SQLite storage.
75 *
76 * If not provided for a column, the default behavior is used:
77 * - `TEXT`: Strings are stored as-is; Dates are converted to ISO strings; other types are JSON-stringified.
78 * - `INTEGER`/`REAL`: Numbers are stored as-is; booleans are mapped to 1/0.
79 *
80 * Use this option to override serialization for specific columns, such as formatting dates, handling enums,
81 * or serializing complex objects.
82 *
83 * Example:
84 * ```typescript
85 * serializer: {
86 * createdAt: (date) => date.getTime(), // Store as timestamp
87 * meta: (meta) => JSON.stringify(meta), // Custom object serialization
88 * }
89 * ```
90 */
91 serializer?: CustomSQLiteSerializer<TOutput, TSQLite>
92​
93 /**
94 * Application logic should ensure that incoming synced data is always valid.
95 * Failing to deserialize and apply incoming changes results in data inconsistency - which is a fatal error.
96 * Use this callback to react to deserialization errors.
97 */
98 onDeserializationError: (error: StandardSchemaV1.FailureResult) => void
100​
101/**
102 * Config for when TInput and TOutput are both the SQLite types.
103 */
104export type ConfigWithSQLiteTypes = {}
105​
106/**
107 * Config where TInput is the SQLite types while TOutput can be defined by TSchema.
108 * We can use the same schema to validate TInput and incoming SQLite changes.
109 */
110export type ConfigWithSQLiteInputType<
111 TTable extends Table,
112 TSchema extends StandardSchemaV1<
113 // TInput is the SQLite types.
114 OptionalExtractedTable<TTable>,
115 AnyTableColumnType<TTable>
116 >,
117> = SerializerConfig<
118 StandardSchemaV1.InferOutput<TSchema>,
119 ExtractedTable<TTable>
120> & {
121 schema: TSchema
123​
124/**
125 * Config where TInput and TOutput have arbitrarily typed values.
126 * The keys of the types need to equal the SQLite types.
127 * Since TInput is not the SQLite types, we require a schema in order to deserialize incoming SQLite updates. The schema should validate from SQLite to TOutput.
128 */
129export type ConfigWithArbitraryCollectionTypes<
130 TTable extends Table,
131 TSchema extends StandardSchemaV1<
132 // The input and output must have the same keys, the value types can be arbitrary
133 AnyTableColumnType<TTable>,
134 AnyTableColumnType<TTable>
135 >,
136> = SerializerConfig<
137 StandardSchemaV1.InferOutput<TSchema>,
138 ExtractedTable<TTable>
139> & {
140 schema: TSchema
141 /**
142 * Schema for deserializing and validating input data from the sync stream.
143 *
144 * This schema defines how to transform and validate data coming from SQLite types (as stored in the database)
145 * into the desired output types (`TOutput`) expected by your application or validation logic.
146 *
147 * The generic parameters allow for arbitrary input and output types, so you can specify custom conversion rules
148 * for each column. This is especially useful when your application expects richer types (e.g., Date, enums, objects)
149 * than what SQLite natively supports.
150 *
151 * Use this to ensure that incoming data from the sync stream is properly converted and validated before use.
152 *
153 * Example:
154 * ```typescript
155 * deserializationSchema: z.object({
156 * createdAt: z.preprocess((val) => new Date(val as string), z.date()),
157 * meta: z.preprocess((val) => JSON.parse(val as string), z.object({ ... })),
158 * })
159 * ```
160 *
161 * This enables robust type safety and validation for incoming data, bridging the gap between SQLite storage
162 * and your application's expected types.
163 */
164 deserializationSchema: StandardSchemaV1<
165 ExtractedTable<TTable>,
166 StandardSchemaV1.InferOutput<TSchema>
167 >
169/**
170 * Eager sync mode hooks.
171 * Called once when the collection sync starts and stops.
172 */
173export type EagerSyncHooks = {
174 syncMode?: 'eager'
175 /**
176 * Called when the collection sync starts.
177 * Use this to set up external data sources (e.g. subscribing to a sync stream).
178 *
179 * @returns A cleanup function that is called when the collection sync is cleaned up.
180 */
181 onLoad?: () => CleanupFn | void | Promise<CleanupFn | void>
182 onLoadSubset?: never
184​
185/**
186 * On-demand sync mode hooks.
187 * Called each time a subset is loaded or unloaded in response to live query changes.
188 */
189export type OnDemandSyncHooks = {
190 syncMode: 'on-demand'
191 onLoad?: never
192 /**
193 * Called when a subset of data is requested by a live query.
194 * Use this to set up external data sources for the requested subset
195 * (e.g. subscribing to a sync stream with parameters derived from the query predicate).
196 *
197 * @returns A cleanup function that is called when the subset is unloaded.
198 */
199​
200 onLoadSubset?: (
201 options: LoadSubsetOptions,
202 ) => CleanupFn | void | Promise<CleanupFn | void>
204​
205export type BasePowerSyncCollectionConfig<
206 TTable extends Table = Table,
207 TSchema extends StandardSchemaV1<any> = never,
208> = Omit<
209 BaseCollectionConfig<
210 InferPowerSyncOutputType<TTable, TSchema>,
211 string,
212 TSchema
213 >,
214 `onInsert` | `onUpdate` | `onDelete` | `getKey` | `syncMode`
215> & {
216 /** The PowerSync schema Table definition */
217 table: TTable
218 /** The PowerSync database instance */
219 database: CommonPowerSyncDatabase
220 /**
221 * The maximum number of documents to read from the SQLite table
222 * in a single batch during the initial sync between PowerSync and the
223 * in-memory TanStack DB collection.
224 *
225 * @remarks
226 * - Defaults to {@link DEFAULT_BATCH_SIZE} if not specified.
227 * - Larger values reduce the number of round trips to the storage
228 * engine but increase memory usage per batch.
229 * - Smaller values may lower memory usage and allow earlier
230 * streaming of initial results, at the cost of more query calls.
231 */
232 syncBatchSize?: number
233} & (EagerSyncHooks | OnDemandSyncHooks)
234​
235/**
236 * Configuration interface for PowerSync collection options.
237 * @template TTable - The PowerSync table schema definition
238 * @template TSchema - The validation schema type
239 */
240/**
241 * Configuration options for creating a PowerSync collection.
242 *
243 * @example
244 * ```typescript
245 * const APP_SCHEMA = new Schema({
246 * documents: new Table({
247 * name: column.text,
248 * }),
249 * })
250 *
251 * const db = new PowerSyncDatabase({
252 * database: {
253 * dbFilename: "test.sqlite",
254 * },
255 * schema: APP_SCHEMA,
256 * })
257 *
258 * const collection = createCollection(
259 * powerSyncCollectionOptions({
260 * database: db,
261 * table: APP_SCHEMA.props.documents
262 * })
263 * )
264 * ```
265 */
266export type PowerSyncCollectionConfig<
267 TTable extends Table = Table,
268 TSchema extends StandardSchemaV1<any> = never,
269> = BasePowerSyncCollectionConfig<TTable, TSchema> &
270 (
271 | ConfigWithSQLiteTypes
272 | ConfigWithSQLiteInputType<TTable, TSchema>
273 | ConfigWithArbitraryCollectionTypes<TTable, TSchema>
274 )
275​
276/**
277 * Metadata for the PowerSync Collection.
278 */
279export type PowerSyncCollectionMeta<TTable extends Table = Table> = {
280 /**
281 * The SQLite table representing the collection.
282 */
283 tableName: string
284 /**
285 * The internal table used to track diffs for the collection.
286 */
287 trackedTableName: string
288​
289 /**
290 * Serializes a collection value to the SQLite type
291 */
292 serializeValue: (value: any) => ExtractedTable<TTable>
293​
294 /**
295 * Whether the PowerSync table tracks metadata.
296 */
297 metadataIsTracked: boolean
299​
300/**
301 * A CollectionConfig which includes utilities for PowerSync.
302 */
303export type EnhancedPowerSyncCollectionConfig<
304 TTable extends Table,
305 OutputType extends Record<string, unknown> = Record<string, unknown>,
306 TSchema extends StandardSchemaV1 = never,
307> = CollectionConfig<
308 OutputType,
309 string,
310 TSchema,
311 PowerSyncCollectionUtils<TTable>
312> & {
313 id?: string
314 utils: PowerSyncCollectionUtils<TTable>
315 schema?: TSchema
317​
318/**
319 * Collection-level utilities for PowerSync.
320 */
321export type PowerSyncCollectionUtils<TTable extends Table = Table> = {
322 getMeta: () => PowerSyncCollectionMeta<TTable>
324​
325/**
326 * Default value for {@link PowerSyncCollectionConfig#syncBatchSize}.
327 */
328export const DEFAULT_BATCH_SIZE = 1000