Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

pg-serializer-finite-decoder.ts

74 lines2.5 KB

1/**
2 * Independent decoder for the serializer's flat finite-value text dialect. The
3 * PostgreSQL serializer oracle (pg-serializer-oracle.property.test.ts) compares
4 * production output against inputs through it.
5 */
6export type FiniteArrayValue = string | number | boolean | null
7​
8export function parseFiniteNumber(text: string): number {
9 const match = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.exec(text)
10 // Comparing the full match also rejects a final newline before JavaScript's $.
11 if (match?.[0] !== text || !Number.isFinite(Number(text))) {
12 throw new Error(`invalid finite numeric output: ${JSON.stringify(text)}`)
13 }
14 return Number(text)
16​
17/**
18 * Decode the existing serializer's flat finite-value dialect, not arbitrary SQL.
19 * Quoted text is distinct from unquoted NULL, boolean, and numeric tokens.
20 * Grammar authority: PostgreSQL 18, sections 8.15.2 and 8.15.6:
21 * https://www.postgresql.org/docs/18/arrays.html#ARRAYS-IO
22 * No casts, nested dimensions, server ranges, or provider NULL policy are modeled.
23 */
24export function parseFiniteArray(text: string): Array<FiniteArrayValue> {
25 const values: Array<FiniteArrayValue> = []
26 let position = 1
27 const invalid = () =>
28 new Error(
29 `invalid flat array output at ${position}: ${JSON.stringify(text)}`,
30 )
31 if (text[0] !== `{`) throw invalid()
32 if (text === `{}`) return values
33​
34 while (position < text.length) {
35 if (text[position] === `"`) {
36 position++
37 let value = ``
38 let closed = false
39 while (position < text.length) {
40 const character = text[position++]!
41 if (character === `"`) {
42 closed = true
43 break
44 }
45 if (character === `\\`) {
46 if (position === text.length) throw invalid()
47 value += text[position++]!
48 } else {
49 value += character
50 }
51 }
52 if (!closed) throw invalid()
53 values.push(value)
54 } else {
55 const start = position
56 while (
57 position < text.length &&
58 text[position] !== `,` &&
59 text[position] !== `}`
60 )
61 position++
62 const token = text.slice(start, position)
63 if (token === `NULL`) values.push(null)
64 else if (token === `true`) values.push(true)
65 else if (token === `false`) values.push(false)
66 else values.push(parseFiniteNumber(token))
67 }
68​
69 const separator = text[position++]
70 if (separator === `}` && position === text.length) return values
71 if (separator !== `,`) throw invalid()
72 }
73 throw invalid()