drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅
https://orm.drizzle.team
Apache License 2.0
24.54k stars 643 forks source link

[BUG]: jsonb values are double-JSON.parse()'d on select #3018

Open legitmaxwu opened 1 month ago

legitmaxwu commented 1 month ago

What version of drizzle-orm are you using?

0.33.0

What version of drizzle-kit are you using?

0.23.0

Describe the Bug

I'm using drizzle + node postgres.

When I store a string e.g. "10.5" under a jsonb column, I expect it to be returned as "10.5" in string format. Instead it's returned as 10.5

This is probably because node-postgres does JSON.parse once, and then the jsonb column does it again.

Expected behavior

When I store a string e.g. "10.5" under a jsonb column, I expect it to be returned as "10.5" in string format.

Environment & setup

drizzle + node postgres computer: macos

legitmaxwu commented 1 month ago

to work around this for now, either create a customJsonb type like this:

import { customType } from "drizzle-orm/pg-core";

const jsonb = customType<{
  data: unknown;
  driverData: string;
  config: undefined;
}>({
  dataType() {
    return `jsonb`;
  },
  fromDriver(value: string): unknown {
    return value;
  },
  toDriver(value: unknown): string {
    return JSON.stringify(value);
  },
});

OR remove JSON.parse from node-postgres's jsonb type parser via:

import { types } from "pg";

types.setTypeParser(types.builtins.JSONB, (val) => val);