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 AnyTableColumnType,
6 ExtractedTable,
7 ExtractedTableColumns,
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 * ## Parameters
17 * - `value`: The object to serialize (row data).
18 * - `tableSchema`: The schema describing the SQLite table columns and types.
19 * - `customSerializer`: An optional map of custom serialization functions for specific keys.
20 *
21 * ## Behavior
22 * - For each key in `value`, finds the corresponding column in `tableSchema`.
23 * - If a custom serializer is provided for a key, it is used to transform the value.
24 * - Otherwise, values are mapped according to the column type:
25 * - `TEXT`: Strings are passed through; Dates are converted to ISO strings; other types are JSON-stringified.
26 * - `INTEGER`/`REAL`: Numbers are passed through; booleans are mapped to 1/0; other types are coerced to numbers.
27 * - Throws if a column type is unknown or a value cannot be converted.
28 *
29 * ## Returns
30 * - An object with the same keys as `value`, with values transformed for SQLite compatibility.
31 *
32 * ## Errors
33 * - Throws if a key in `value` does not exist in the schema.
34 * - Throws if a value cannot be converted to the required SQLite type.
35 */
36export function serializeForSQLite<TTable extends Table>(
37 value: AnyTableColumnType<TTable>,
38 tableSchema: TTable,
39 customSerializer: CustomSQLiteSerializer<
40 AnyTableColumnType<TTable>,
41 ExtractedTableColumns<TTable>
42 > = {},
43): ExtractedTable<TTable> {
44 return Object.fromEntries(
45 // eslint-disable-next-line no-shadow
46 Object.entries(value).map(([key, value]) => {
47 // First get the output schema type
48 const outputType =
49 key == `id`
50 ? ColumnType.TEXT
51 : tableSchema.columns.find((column) => column.name == key)?.type
52 if (!outputType) {
53 throw new Error(`Could not find schema for ${key} column.`)
54 }
55
56 if (value == null) {
57 return [key, value]
58 }
59
60 const customTransform = customSerializer[key]
61 if (customTransform) {
62 return [key, customTransform(value)]
63 }
64
65 // Map to the output
66 switch (outputType) {
67 case ColumnType.TEXT:
68 if (typeof value == `string`) {
69 return [key, value]
70 } else if (value instanceof Date) {
71 return [key, value.toISOString()]
72 } else {
73 return [key, JSON.stringify(value)]
74 }
75 case ColumnType.INTEGER:
76 case ColumnType.REAL:
77 if (typeof value == `number`) {
78 return [key, value]
79 } else if (typeof value == `boolean`) {
80 return [key, value ? 1 : 0]
81 } else {
82 const numberValue = Number(value)
83 if (isNaN(numberValue)) {
84 throw new Error(
85 `Could not convert ${key}=${value} to a number for SQLite`,
86 )
87 }
88 return [key, numberValue]
89 }
90 }
91 }),
92 ) as ExtractedTable<TTable>
93}