Open History to see the last commit
1import { ColumnInfo, GetExtensions, Row, Schema, Value } from './types'
2import { ParserNullValueError } from './error'
3
4type Token = string
5type NullableToken = Token | null
6export type ParseFunction<Extensions = never> = (
7 value: Token,
8 additionalInfo?: Omit<ColumnInfo, `type` | `dims`>
9) => Value<Extensions>
10type NullableParseFunction<Extensions = never> = (
11 value: NullableToken,
12 additionalInfo?: Omit<ColumnInfo, `type` | `dims`>
13) => Value<Extensions>
14/**
15 * @typeParam Extensions - Additional types that can be parsed by this parser beyond the standard SQL types.
16 * Defaults to no additional types.
17 */
18export type Parser<Extensions = never> = {
19 [key: string]: ParseFunction<Extensions>
20}
21
22export type TransformFunction<Extensions = never> = (
23 message: Row<Extensions>
24) => Row<Extensions>
25
26const parseNumber = (value: string) => Number(value)
27const parseBool = (value: string) => value === `true` || value === `t`
28const parseBigInt = (value: string) => BigInt(value)
29const parseJson = (value: string) => JSON.parse(value)
30const identityParser: ParseFunction = (v: string) => v
31
32export const defaultParser: Parser = {
33 int2: parseNumber,
34 int4: parseNumber,
35 int8: parseBigInt,
36 bool: parseBool,
37 float4: parseNumber,
38 float8: parseNumber,
39 json: parseJson,
40 jsonb: parseJson,
41}
42
43// Taken from: https://github.com/electric-sql/pglite/blob/main/packages/pglite/src/types.ts#L233-L279
44export function pgArrayParser<Extensions>(
45 value: Token,
46 parser?: NullableParseFunction<Extensions>
47): Value<Extensions> {
48 let i = 0
49 let char = null
50 let str = ``
51 let quoted = false
52 let last = 0
53 let p: string | undefined = undefined
54
55 function extractValue(x: Token, start: number, end: number) {
56 let val: Token | null = x.slice(start, end)
57 val = val === `NULL` ? null : val
58 return parser ? parser(val) : val
59 }
60
61 function loop(x: string): Array<Value<Extensions>> {
62 const xs = []
63 for (; i < x.length; i++) {
64 char = x[i]
65 if (quoted) {
66 if (char === `\\`) {
67 str += x[++i]
68 } else if (char === `"`) {
69 xs.push(parser ? parser(str) : str)
70 str = ``
71 quoted = x[i + 1] === `"`
72 last = i + 2
73 } else {
74 str += char
75 }
76 } else if (char === `"`) {
77 quoted = true
78 } else if (char === `{`) {
79 last = ++i
80 xs.push(loop(x))
81 } else if (char === `}`) {
82 quoted = false
83 last < i && xs.push(extractValue(x, last, i))
84 last = i + 1
85 break
86 } else if (char === `,` && p !== `}` && p !== `"`) {
87 xs.push(extractValue(x, last, i))
88 last = i + 1
89 }
90 p = char
91 }
92 last < i && xs.push(xs.push(extractValue(x, last, i + 1)))
93 return xs
94 }
95
96 return loop(value)[0]
97}
98
99export class MessageParser<T extends Row<unknown>> {
100 private parser: Parser<GetExtensions<T>>
101 private transformer?: TransformFunction<GetExtensions<T>>
102 constructor(
103 parser?: Parser<GetExtensions<T>>,
104 transformer?: TransformFunction<GetExtensions<T>>
105 ) {
106 // Merge the provided parser with the default parser
107 // to use the provided parser whenever defined
108 // and otherwise fall back to the default parser
109 this.parser = { ...defaultParser, ...parser }
110 this.transformer = transformer
111 }
112
113 parse<Result>(messages: string, schema: Schema): Result {
114 return JSON.parse(messages, (key, value) => {
115 // typeof value === `object` && value !== null
116 // is needed because there could be a column named `value`
117 // and the value associated to that column will be a string or null.
118 // But `typeof null === 'object'` so we need to make an explicit check.
119 // We also parse the `old_value`, which appears on updates when `replica=full`.
120 if (
121 (key === `value` || key === `old_value`) &&
122 typeof value === `object` &&
123 value !== null
124 ) {
125 return this.transformMessageValue(value, schema)
126 }
127 return value
128 }) as Result
129 }
130
131 /**
132 * Parse an array of ChangeMessages from a snapshot response.
133 * Applies type parsing and transformations to the value and old_value properties.
134 */
135 parseSnapshotData<Result>(
136 messages: Array<unknown>,
137 schema: Schema
138 ): Array<Result> {
139 return messages.map((message) => {
140 const msg = message as Record<string, unknown>
141
142 // Transform the value property if it exists
143 if (msg.value && typeof msg.value === `object` && msg.value !== null) {
144 msg.value = this.transformMessageValue(msg.value, schema)
145 }
146
147 // Transform the old_value property if it exists
148 if (
149 msg.old_value &&
150 typeof msg.old_value === `object` &&
151 msg.old_value !== null
152 ) {
153 msg.old_value = this.transformMessageValue(msg.old_value, schema)
154 }
155
156 return msg as Result
157 })
158 }
159
160 /**
161 * Transform a message value or old_value object by parsing its columns.
162 */
163 private transformMessageValue(
164 value: unknown,
165 schema: Schema
166 ): Row<GetExtensions<T>> {
167 const row = value as Record<string, Value<GetExtensions<T>>>
168 Object.keys(row).forEach((key) => {
169 row[key] = this.parseRow(key, row[key] as NullableToken, schema)
170 })
171
172 return this.transformer ? this.transformer(row) : row
173 }
174
175 // Parses the message values using the provided parser based on the schema information
176 private parseRow(
177 key: string,
178 value: NullableToken,
179 schema: Schema
180 ): Value<GetExtensions<T>> {
181 const columnInfo = schema[key]
182 if (!columnInfo) {
183 // We don't have information about the value
184 // so we just return it
185 return value
186 }
187
188 // Copy the object but don't include `dimensions` and `type`
189 const { type: typ, dims: dimensions, ...additionalInfo } = columnInfo
190
191 // Pick the right parser for the type
192 // and support parsing null values if needed
193 // if no parser is provided for the given type, just return the value as is
194 const typeParser = this.parser[typ] ?? identityParser
195 const parser = makeNullableParser(typeParser, columnInfo, key)
196
197 if (dimensions && dimensions > 0) {
198 // It's an array
199 const nullablePgArrayParser = makeNullableParser(
200 (value, _) => pgArrayParser(value, parser),
201 columnInfo,
202 key
203 )
204 return nullablePgArrayParser(value)
205 }
206
207 return parser(value, additionalInfo)
208 }
209}
210
211function makeNullableParser<Extensions>(
212 parser: ParseFunction<Extensions>,
213 columnInfo: ColumnInfo,
214 columnName?: string
215): NullableParseFunction<Extensions> {
216 const isNullable = !(columnInfo.not_null ?? false)
217 // The sync service contains `null` value for a column whose value is NULL
218 // but if the column value is an array that contains a NULL value
219 // then it will be included in the array string as `NULL`, e.g.: `"{1,NULL,3}"`
220 return (value: NullableToken) => {
221 if (value === null) {
222 if (!isNullable) {
223 throw new ParserNullValueError(columnName ?? `unknown`)
224 }
225 return null
226 }
227 return parser(value, columnInfo)
228 }
229}