Skip to content

bun:sql incorrectly serializes JS arrays in sql(object) for PostgreSQL array columns #29551

Closed
tetsujs/tetsu
#116

Description

@janilowski

What version of Bun is running?

1.3.13

What platform is your computer?

Linux 6.19.11-200.fc43.x86_64 x86_64 unknown

What steps can reproduce the bug?

Run this with a valid DATABASE_URL pointing to PostgreSQL:

import { sql } from "bun";

const payload = {
  licenses: ["A"],
  driver: ["B"],
  medical_checkup: "2024-01-01",
};

const rows = await sql.begin(async (tx) => {
  await tx`CREATE TEMP TABLE _bun_obj_test (
    licenses text[],
    driver text[],
    medical_checkup date
  )`;

  return await tx`
    INSERT INTO _bun_obj_test ${sql(payload)}
    RETURNING licenses, driver, medical_checkup
  `;
});

console.log(rows);

Example command:

```bash
bun --env-file .env.development -e 'import { sql } from "bun";
const payload = { licenses: ["A"], driver: ["B"], medical_checkup: "2024-01-01" };
const rows = await sql.begin(async (tx) => {
  await tx`CREATE TEMP TABLE _bun_obj_test (licenses text[], driver text[], medical_checkup date)`;
  return await tx`INSERT INTO _bun_obj_test ${sql(payload)} RETURNING licenses, driver, medical_checkup`;
});
console.log(rows);'

What is the expected behavior?

sql(payload) should either:

  • correctly serialize JS arrays for PostgreSQL array columns so the insert succeeds, or
  • throw a clear Bun-side error before sending malformed values to PostgreSQL if this usage is unsupported.

What do you see instead?

PostgreSQL receives malformed array values and returns:

PostgresError: malformed array literal: "A"
    errno: "22P02",
   detail: "Array value must start with \"{\" or dimension information.",
 severity: "ERROR",
    where: "unnamed portal parameter $1 = '...'",
     file: "arrayfuncs.c",
  routine: "array_in",
     code: "ERR_POSTGRES_SERVER_ERROR"

Additional information

This issue is specifically about sql(object).

It is not a request for sql.array(...) as a workaround.

The problem is that sql(object) currently accepts object properties whose values are JS arrays, but appears to serialize them as malformed scalar/string values (for example "A" or "A,B") instead of a valid PostgreSQL array representation for text[] columns.

If arrays in sql(object) are unsupported, Bun should reject them explicitly before sending the query. (I would however advocate for the support of JS arrays since that has the potential to improve DX by dramatically shortening some SQL queries).

https://bun.report/1.3.13/la1bf2e2cegmIg0ggC42yp8E+oxGg35p6E285jpEujuipE4ujjpE09qx5D_23gplE23gplE23gplE23gplEsupplEstiplEsupplE23gplEmsohlEwv+80F2rm74F_A2AA

Activity

  1. github-actions commented on Apr 21, 2026

    @github-actions
    Contributor

    Found 3 possible duplicate issues:

    1. sql() helper incorrectly formats PostgreSQL array columns, causing "malformed array literal" error #22155
    2. Incorrect format with SQL for Arrays for PSQL #22281
    3. Bun.sql Does Not Properly Support PostgreSQL TEXT[] Columns in Parameterized Queries #17798

    This issue will be automatically closed as a duplicate in 3 days.

    • If your issue is a duplicate, please close it and 👍 the existing issue instead
    • To prevent auto-closure, add a comment or 👎 this comment

    🤖 Generated with Claude Code

  2. janilowski commented on Apr 21, 2026

    @janilowski
    Author

    These look related, especially #22155 and #22281, and I agree they appear to describe the same underlying sql(object) / PostgreSQL array-column bug. The problem is that all three suggested issues are currently closed, while this still reproduces on Bun 1.3.13.

    For clarity, this is specifically about sql(object) accepting JS arrays for PostgreSQL array columns and then sending malformed values that PostgreSQL rejects with malformed array literal.

  3. robobun commented on Apr 21, 2026

    @robobun
    Collaborator

    ✅ Reproduced — sql({ text_col: ["A"] }) sent comma-joined "A,B" to Postgres, which rejected it as a malformed text[] literal. Same bug affected int[], bool[], date[], jsonb[], bytea[], etc.

    Fix in #29552 — serializes JS arrays as PostgreSQL text array literals when the server-inferred parameter type is any *_array OID. Scalar jsonb columns with array values continue to stringify as JSON.

  4. added 3 commits that reference this issue on Aug 21, 2026
    2fb65ad
    b569f68
    e8df861
  5. tetsuodev commented on Oct 12, 2026

    @tetsuodev

    I'm hitting this through sql.unsafe() too, which is how query builders pass parameters (Kysely's kysely-postgres-js dialect calls sql.unsafe(query, params)), so every write to an array column fails there. int4[] fails differently from the text types, with a protocol error instead of a malformed literal, uuid[] fails like text[], and sql.array() doesn't help as an unsafe() parameter:

    import { SQL } from "bun";
    
    const sql = new SQL("postgres://postgres:postgres@localhost:5432/postgres");
    
    await sql`drop table if exists arrays`;
    await sql`create table arrays (ints int4[], texts text[], ids uuid[])`;
    
    const inserts = {
      "int4[]": () => sql.unsafe("insert into arrays (ints) values ($1)", [[1, 2]]),
      "text[]": () => sql.unsafe("insert into arrays (texts) values ($1)", [["a", "b"]]),
      "uuid[]": () => sql.unsafe("insert into arrays (ids) values ($1)", [["0199d0b2-7a3c-7cc0-9b7e-3f6a1c2d4e5f"]]),
      "int4[] via sql.array()": () => sql.unsafe("insert into arrays (ints) values ($1)", [sql.array([1, 2], "int4")]),
    };
    
    for (const [label, insert] of Object.entries(inserts)) {
      try {
        await insert();
        console.log(label, "ok");
      } catch (error) {
        console.log(label, error.code, error.message);
      }
    }
    
    await sql.close();
    int4[] ERR_POSTGRES_SERVER_ERROR insufficient data left in message
    text[] ERR_POSTGRES_SERVER_ERROR malformed array literal: "a,b"
    uuid[] ERR_POSTGRES_SERVER_ERROR malformed array literal: "0199d0b2-7a3c-7cc0-9b7e-3f6a1c2d4e5f"
    int4[] via sql.array() ERR_POSTGRES_SERVER_ERROR insufficient data left in message
    

    #33579 and #41976 look like they'd cover these. Bun 1.4.3, PostgreSQL 18.6.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions