1+ import { serialize } from "./pg-serializer"
2+ import type { ExternalSubsetParamsRecord } from "@electric-sql/client"
13import type { IR , OnLoadMoreOptions } from "@tanstack/db"
24
5+ export type CompiledSqlRecord = Omit < ExternalSubsetParamsRecord , `params`> & {
6+ params ?: Array < unknown >
7+ }
8+
39export function compileSQL < T > (
410 options : OnLoadMoreOptions
511) : ExternalSubsetParamsRecord {
612 const { where, orderBy, limit } = options
713
814 const params : Array < T > = [ ]
9- const compiledSQL : ExternalSubsetParamsRecord = { params }
15+ const compiledSQL : CompiledSqlRecord = { params }
1016
1117 if ( where ) {
1218 // TODO: this only works when the where expression's PropRefs directly reference a column of the collection
@@ -22,7 +28,20 @@ export function compileSQL<T>(
2228 compiledSQL . limit = limit
2329 }
2430
25- return compiledSQL
31+ // Serialize the values in the params array into PG formatted strings
32+ // and transform the array into a Record<string, string>
33+ const paramsRecord = params . reduce (
34+ ( acc , param , index ) => {
35+ acc [ `${ index + 1 } ` ] = serialize ( param )
36+ return acc
37+ } ,
38+ { } as Record < string , string >
39+ )
40+
41+ return {
42+ ...compiledSQL ,
43+ params : paramsRecord ,
44+ }
2645}
2746
2847/**
@@ -134,15 +153,12 @@ function getOpName(name: string): string {
134153 concat : `CONCAT` ,
135154 coalesce : `COALESCE` ,
136155 }
137- return opNames [ name as keyof typeof opNames ] || name
138- }
139156
140- // TODO: remove this type once we rebase on top of Ilia's PR
141- // that type will be exported by Ilia's PR
142- export type ExternalSubsetParamsRecord = {
143- where ?: string
144- params ?: Record < string , any >
145- limit ?: number
146- offset ?: number
147- orderBy ?: string
157+ const opName = opNames [ name as keyof typeof opNames ]
158+
159+ if ( ! opName ) {
160+ throw new Error ( `Unknown operator/function: ${ name } ` )
161+ }
162+
163+ return opName
148164}
0 commit comments