Skip to content

fix(pg-core): prevent double JSON.parse in jsonb mapFromDriverValue (#5485)#5487

Open
guoyangzhen wants to merge 1 commit intodrizzle-team:mainfrom
guoyangzhen:fix-jsonb-double-parse
Open

fix(pg-core): prevent double JSON.parse in jsonb mapFromDriverValue (#5485)#5487
guoyangzhen wants to merge 1 commit intodrizzle-team:mainfrom
guoyangzhen:fix-jsonb-double-parse

Conversation

@guoyangzhen
Copy link

Problem

The pg driver automatically parses JSON/JSONB columns using JSON.parse. When a JSONB column contains a JSON string value like "0.1", the driver returns it as the JavaScript string "0.1".

The current mapFromDriverValue in PgJsonb calls JSON.parse on all string values, which incorrectly converts JSON strings:

// Store: JSON.stringify("0.1") → DB has: "\"0.1\""
// pg driver returns: "0.1" (JavaScript string)
// Current code: JSON.parse("0.1") → 0.1 (WRONG - number instead of string)

This causes silent data corruption for any JSONB column storing numeric-looking strings.

Root Cause

override mapFromDriverValue(value: T["data"] | string): T["data"] {
  if (typeof value === "string") {
    try {
      return JSON.parse(value);  // ← Double-parses already-parsed values
    } catch {
      return value as T["data"];
    }
  }
  return value;
}

Fix

Only parse strings that look like raw JSON objects/arrays (starting with { or [), which indicates the driver returned unparsed JSON. String values from already-parsed JSON are returned as-is.

Related

Fixes #5485

The pg driver automatically parses JSON/JSONB columns using JSON.parse.
When a JSONB column contains a string value like "0.1", the driver
returns it as the JavaScript string "0.1".

The previous code called JSON.parse on all string values, which incorrectly
converted JSON strings like "0.1" to numbers (0.1).

This fix only parses strings that look like raw JSON objects or arrays
(starting with { or [), which indicates the driver didn't auto-parse.
String values from already-parsed JSON are returned as-is.

Fixes drizzle-team#5485
@AlexBlokh
Copy link
Contributor

this is something that will be properly fixed for all drivers and dialects and column types with the new reworked codecs system we gonna ship via codecs branch really soon, that've been a major problem which took time to design a proper solution for

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: node-postgres driver implicitly converts numeric looking strings to numbers

2 participants