diff --git a/packages/db/src/query/key-by.ts b/packages/db/src/query/key-by.ts index 1ac7f8be6c..dc17428253 100644 --- a/packages/db/src/query/key-by.ts +++ b/packages/db/src/query/key-by.ts @@ -1,4 +1,5 @@ import { keyBy } from "@electric-sql/d2ts" +import { valueToKey } from "./utils" import type { IStreamBuilder } from "@electric-sql/d2ts" import type { Query } from "./schema" @@ -16,7 +17,7 @@ export function processKeyBy( resultPipeline = resultPipeline.pipe( keyBy((row: Record) => { if (Array.isArray(keyByParam)) { - // Multiple columns - extract values and JSON stringify + // Multiple columns - extract values and stringify const keyValues: Record = {} for (const keyColumn of keyByParam) { // Remove @ prefix if present @@ -32,7 +33,7 @@ export function processKeyBy( ) } } - return JSON.stringify(keyValues) + return valueToKey(keyValues) } else { // Single column // Remove @ prefix if present @@ -47,11 +48,11 @@ export function processKeyBy( } const keyValue = row[columnName] - // Use the value directly if it's a string or number, otherwise JSON stringify + // Use the value directly if it's a string or number, otherwise stringify if (typeof keyValue === `string` || typeof keyValue === `number`) { return keyValue } else { - return JSON.stringify(keyValue) + return valueToKey(keyValue) } } }) diff --git a/packages/db/src/query/utils.ts b/packages/db/src/query/utils.ts index 44ebeca85f..e58be4bde0 100644 --- a/packages/db/src/query/utils.ts +++ b/packages/db/src/query/utils.ts @@ -44,6 +44,30 @@ export function isComparable( ) } +export function valueToKey(value: any): string { + return JSON.stringify(value, (key, val) => { + if (typeof val === `bigint`) { + return `__bigint__${val.toString()}` + } + if (typeof val === `symbol`) { + return `__symbol__${val.toString()}` + } + if (typeof val === `function`) { + return `__function__${val.toString()}` + } + if (typeof val === `undefined`) { + return `__undefined__` + } + if (val instanceof Set) { + return `__set__${JSON.stringify(Array.from(val))}` + } + if (val instanceof Map) { + return `__map__${JSON.stringify(Array.from(val.entries()))}` + } + return val + }) +} + /** * Performs a comparison between two values, ensuring they are of compatible types * @param left The left operand