Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions packages/db/src/query/key-by.ts
Original file line number Diff line number Diff line change
@@ -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"

Expand All @@ -16,7 +17,7 @@ export function processKeyBy(
resultPipeline = resultPipeline.pipe(
keyBy((row: Record<string, unknown>) => {
if (Array.isArray(keyByParam)) {
// Multiple columns - extract values and JSON stringify
// Multiple columns - extract values and stringify
const keyValues: Record<string, unknown> = {}
for (const keyColumn of keyByParam) {
// Remove @ prefix if present
Expand All @@ -32,7 +33,7 @@ export function processKeyBy(
)
}
}
return JSON.stringify(keyValues)
return valueToKey(keyValues)
} else {
// Single column
// Remove @ prefix if present
Expand All @@ -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)
}
}
})
Expand Down
24 changes: 24 additions & 0 deletions packages/db/src/query/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down