Skip to content

Concurrent inserts with json result in some being written in string format #937

@alexcouper

Description

@alexcouper

When run concurrently, this lib seems to insert jsonb data as a string rather than an object.

I've been able to reproduce down to a minimal example.

Steps to reproduce

  1. Create a table named "dodgy_json"
create table "dodgy_json" (
    "id" uuid not null default gen_random_uuid(),
    "created_at" timestamp with time zone not null default now(),
    "dodgy" jsonb not null
);
  1. Use this test and ensure it works:
import postgres from "postgres";

let sql: postgres.Sql;

describe("dodgy sql json 1", () => {
  beforeAll(async () => {
    sql = postgres(process.env.DATABASE_URL!, { ssl: true });
  });
  afterAll(async () => {
    sql.end();
  });

  for (let i = 0; i < 20; i++) {
    it("tests dodgy json", async () => {
      const jsonReady = sql.json({
        foo: "bar",
      });
      const obj =
        await sql`INSERT INTO dodgy_json(dodgy) VALUES (${jsonReady}) RETURNING id;`;
      const check =
        await sql`SELECT jsonb_typeof(dodgy) from dodgy_json WHERE id=${obj[0]!.id};`;
      expect(check[0]!.jsonb_typeof).toBe("object");
    });
  }
});
jest sql.test.ts
  1. Copy this test file into 3 different files and run them concurrently using jest
cp sql.test.ts sql2.test.ts
cp sql.test.ts sql3.test.ts
jest sql*
  1. See that you have errors
dodgy sql json 1 › tests dodgy json

    expect(received).toBe(expected) // Object.is equality

    Expected: "object"
    Received: "string"

      24 |         await sql`SELECT jsonb_typeof(dodgy) from dodgy_json WHERE id=${obj[0]!.id};`;
    > 25 |       expect(check[0]!.jsonb_typeof).toBe("object");
         |                                      ^
      26 |     });
      27 |   }
      28 | });

      ```

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions