Open History to see the last commit
1import { ColumnType } from '@powersync/common'
2import type { Table } from '@powersync/common'
3import type { CustomSQLiteSerializer } from './definitions'
4import type {
5 ExtractedTable,
6 ExtractedTableColumns,
7 MapBaseColumnType,
8} from './helpers'
9
10/**
11 * Serializes an object for persistence to a SQLite table, mapping its values to appropriate SQLite types.
12 *
13 * This function takes an object representing a row, a table schema, and an optional custom serializer map.
14 * It returns a new object with values transformed to be compatible with SQLite column types.
15 *
16 * ## Generics
17 * - `TOutput`: The shape of the input object, typically matching the row data.
18 * - `TTable`: The table schema, which must match the keys of `TOutput`.
19 *
20 * ## Parameters
21 * - `value`: The object to serialize (row data).
22 * - `tableSchema`: The schema describing the SQLite table columns and types.
23 * - `customSerializer`: An optional map of custom serialization functions for specific keys.
24 *
25 * ## Behavior
26 * - For each key in `value`, finds the corresponding column in `tableSchema`.
27 * - If a custom serializer is provided for a key, it is used to transform the value.
28 * - Otherwise, values are mapped according to the column type:
29 * - `TEXT`: Strings are passed through; Dates are converted to ISO strings; other types are JSON-stringified.
30 * - `INTEGER`/`REAL`: Numbers are passed through; booleans are mapped to 1/0; other types are coerced to numbers.
31 * - Throws if a column type is unknown or a value cannot be converted.
32 *
33 * ## Returns
34 * - An object with the same keys as `value`, with values transformed for SQLite compatibility.
35 *
36 * ## Errors
37 * - Throws if a key in `value` does not exist in the schema.
38 * - Throws if a value cannot be converted to the required SQLite type.
39 */
40export function serializeForSQLite<
41 TOutput extends Record<string, unknown>,
42 // The keys should match
43 TTable extends Table<MapBaseColumnType<TOutput>> = Table<
44 MapBaseColumnType<TOutput>
45 >,
46>(
47 value: TOutput,
48 tableSchema: TTable,
49 customSerializer: Partial<
50 CustomSQLiteSerializer<TOutput, ExtractedTableColumns<TTable>>
51 > = {},
52): ExtractedTable<TTable> {
53 return Object.fromEntries(
54 // eslint-disable-next-line no-shadow
55 Object.entries(value).map(([key, value]) => {
56 // First get the output schema type
57 const outputType =
58 key == `id`
59 ? ColumnType.TEXT
60 : tableSchema.columns.find((column) => column.name == key)?.type
61 if (!outputType) {
62 throw new Error(`Could not find schema for ${key} column.`)
63 }
64
65 if (value == null) {
66 return [key, value]
67 }
68
69 const customTransform = customSerializer[key]
70 if (customTransform) {
71 return [key, customTransform(value as TOutput[string])]
72 }
73
74 // Map to the output
75 switch (outputType) {
76 case ColumnType.TEXT:
77 if (typeof value == `string`) {
78 return [key, value]
79 } else if (value instanceof Date) {
80 return [key, value.toISOString()]
81 } else {
82 return [key, JSON.stringify(value)]
83 }
84 case ColumnType.INTEGER:
85 case ColumnType.REAL:
86 if (typeof value == `number`) {
87 return [key, value]
88 } else if (typeof value == `boolean`) {
89 return [key, value ? 1 : 0]
90 } else {
91 const numberValue = Number(value)
92 if (isNaN(numberValue)) {
93 throw new Error(
94 `Could not convert ${key}=${value} to a number for SQLite`,
95 )
96 }
97 return [key, numberValue]
98 }
99 }
100 }),
101 )
102}