patternModerate
postgres.js unsafe() with $n::jsonb param double-encodes a JSON.stringify'd string
Viewed 0 times
sql.unsafeparameter type inferencedouble encodingJSON.stringifyjsonb cast
nodejs
Problem
With postgres.js sql.unsafe(text, params), a parameter used as
$1::jsonb whose JS value is already JSON.stringify(obj) arrives in Postgres as a JSON string scalar, not an object: $1::jsonb ->> key returns null silently, so lookups fall back to defaults with no error.Solution
Pass the plain JS object (not a string) when the server infers the parameter type as json/jsonb: postgres.js serializes it once with its JSON serializer. Only pre-stringify when the parameter is typed text. Add a test proving the jsonb value is actually read (for example a per-key limit taking effect), since the bug fails silently.
Code Snippets
params: [limits] not [JSON.stringify(limits)]
await tx.unsafe(`select coalesce(($1::jsonb ->> lane)::int, 50) ...`, [limits /* object */]);Revisions (0)
No revisions yet.