Open History to see the last commit
1/**
2 * Serialize values for Electric SQL subset parameters.
3 *
4 * IMPORTANT: Electric expects RAW values, NOT SQL-formatted literals.
5 * Electric handles all type casting and escaping on the server side.
6 * The params Record<string, string> contains the actual values as strings,
7 * and Electric will parse/cast them based on the column type in the WHERE clause.
8 *
9 * @param value - The value to serialize
10 * @returns The raw value as a string (no SQL formatting/quoting)
11 */
12export function serialize(value: unknown): string {
13 // Handle null/undefined - return empty string
14 // Electric interprets empty string as NULL in typed column context
15 if (value === null || value === undefined) {
16 return ``
17 }
18
19 // Handle strings - return as-is (NO quotes, Electric handles escaping)
20 if (typeof value === `string`) {
21 return value
22 }
23
24 // Handle numbers - convert to string
25 if (typeof value === `number`) {
26 return value.toString()
27 }
28
29 // Handle bigints - convert to string
30 if (typeof value === `bigint`) {
31 return value.toString()
32 }
33
34 // Handle booleans - return as lowercase string
35 if (typeof value === `boolean`) {
36 return value ? `true` : `false`
37 }
38
39 // Handle dates - return ISO format (NO quotes)
40 if (value instanceof Date) {
41 return value.toISOString()
42 }
43
44 // Handle arrays - for = ANY() operator, serialize as Postgres array literal
45 // Format: {val1,val2,val3} with proper escaping
46 if (Array.isArray(value)) {
47 // Postgres array literal format uses curly braces
48 const elements = value.map((item) => {
49 if (item === null || item === undefined) {
50 return `NULL`
51 }
52 if (typeof item === `string`) {
53 // Escape quotes and backslashes for Postgres array literals
54 const escaped = item.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`)
55 return `"${escaped}"`
56 }
57 return serialize(item)
58 })
59 return `{${elements.join(`,`)}}`
60 }
61
62 // Safely stringify the value for the error message
63 // JSON.stringify can't handle BigInt and other types, so we use a try-catch
64 let valueStr: string
65 try {
66 valueStr = JSON.stringify(value)
67 } catch {
68 valueStr = String(value)
69 }
70 throw new Error(`Cannot serialize value: ${valueStr}`)
71}