MCPcopy Index your code
hub / github.com/TanStack/db / serializeForSQLite

Function serializeForSQLite

packages/powersync-db-collection/src/serialization.ts:40–102  ·  view source on GitHub ↗
(
  value: TOutput,
  tableSchema: TTable,
  customSerializer: Partial<
    CustomSQLiteSerializer<TOutput, ExtractedTableColumns<TTable>>
  > = {},
)

Source from the content-addressed store, hash-verified

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]

Callers 1

Calls 2

mapMethod · 0.45
entriesMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…