Skip to content

Bug: Bun.SQL serializes Date parameters via .toString() instead of .toISOString() for prepare:false #29010

Closed

Description

@heiwen

What version of Bun is running?

1.3.11

What platform is your computer?

Darwin 25.2.0 arm64 arm

What steps can reproduce the bug?

Description

When a JavaScript Date object is passed as a query parameter to Bun.SQL with prepare: false — either in a template-literal query or inside a row object passed to sql(rows) — Bun serializes it using Date.prototype.toString() (locale / timezone-dependent string) instead of Date.prototype.toISOString() (RFC 3339 / ISO 8601).

This does not reproduce with prepare: true (the default): when prepared statements are enabled, Bun receives the server's ParameterDescription before encoding the Bind message, so it has type information and uses the correct binary path. With prepare: false, Parse and Bind are pipelined with no type info available, and Date falls through to a toString() fallback.

Most databases, including PostgreSQL and GreptimeDB, cannot parse the locale format and return a parse error.

Reproduction

import { SQL } from 'bun';
const sql = new SQL('postgres://user@localhost:5432/db', { prepare: false });

const t = new Date('2024-01-15T12:30:45.000Z');

// In a WHERE clause parameter:
const rows = await sql`SELECT * FROM my_table WHERE created_at = ${t}`;
// Sends: "Mon Jan 15 2024 12:30:45 GMT+0000 (Coordinated Universal Time)"
// PostgreSQL error: invalid input syntax for type timestamp

// In a row object passed to sql(rows):
await sql`INSERT INTO my_table ${sql([{ created_at: t }])}`;
// Same incorrect serialization

The workaround is to call .toISOString() manually at every parameter site, or to convert dates before building row objects:

// Workaround
await sql`SELECT * FROM my_table WHERE created_at = ${t.toISOString()}`;

Expected behavior

Date objects should be serialized as an ISO 8601 / RFC 3339 string when sent as query parameters — a format PostgreSQL-compatible databases can parse. Both other major JS drivers do this:

  • postgres.js hardcodes .toISOString() in src/types.js (types.date.serialize), always producing a UTC string ending in Z (e.g. "2024-01-15T12:30:45.000Z").
  • pg (node-postgres) builds an ISO 8601 string with the local timezone offset (e.g. "2024-01-15T12:30:45.000-05:00") — not identical to postgres.js, but still ISO 8601 and accepted by PostgreSQL.

Actual behavior

Bun serializes Date as the locale string produced by .toString(), e.g.:

Mon Jan 15 2024 12:30:45 GMT+0000 (Coordinated Universal Time)

This format is rejected by PostgreSQL-compatible databases with errors such as:

Unable to parse datetime: Mon Jan 15 2024 12:30:45 GMT+0000
invalid input syntax for type timestamp

Environment

  • Bun: 1.3.11 (bun --version)
  • Platform: macOS arm64
  • Database: GreptimeDB v1.0.0-rc.2 (PostgreSQL wire protocol), also reproducible against standard PostgreSQL

Notes

  • The issue affects both template-literal parameters (sql\... ${date}`) and row objects passed to sql(rows)` for bulk inserts.
  • sql.unsafe() with a plain string query is not affected (no parameter serialization).
  • The locale string format varies by system timezone, making this a latent bug that may only surface in environments where the timezone offset is non-zero.

Activity

  1. changed the title [-]Bug: Bun.SQL serializes `Date` parameters via `.toString()` instead of `.toISOString()`[/-] [+]Bug: Bun.SQL serializes `Date` parameters via `.toString()` instead of `.toISOString()` for `prepare:false`[/+] on Apr 8, 2026
  2. robobun commented on Apr 8, 2026

    @robobun
    Collaborator

    ✅ Rebased onto main — 1a22fddca5 (single squashed commit).

    CI build 44638 failure is unrelated — the only non-flaky annotation is a Windows ARM64 crash in test/js/bun/util/v8-heap-snapshot.test.ts with "Illegal instruction at address 0x7FF7F64BE060" and 9.13GB peak RSS. That is a Bun runtime panic in the heap-snapshot code path on ARM64 Windows, not touched by this PR.

    This PR only modifies:

    • src/bun.js/bindings/JSValue.zig — widen ISO buffer to [64]u8, fix getDateNowISOString ABI mismatch
    • src/bun.js/bindings/bindings.cpp — JSC__JSValue__toISOString writes to caller buf
    • src/sql/postgres/PostgresRequest.zig — Date → ISO 8601 in writeBind else branch
    • test/regression/issue/29010.test.ts — regression test

    None of these interact with v8 heap snapshots, memory management, or Windows ARM64 codegen. The rest of the annotations (bake stress, bundler_defer, terminal) are the same pre-existing Windows flakes from prior runs, all tagged style: WARNING, context: flaky in the buildkite annotation data.

    Pre-merge checks are all green (Out of Scope warning cleared after the rebase) and coderabbit LGTM with no actionable comments.

  3. added 2 commits that reference this issue on Apr 8, 2026
    1a22fdd
    6b8fadd
  4. heiwen commented on Apr 12, 2026

    @heiwen
    Author

    Linking to the Bun.SQL (Postgres) tracking issue: #15088

  5. added a commit that references this issue on May 1, 2026
    aa933ad
  6. juanluispaz commented on May 29, 2026

    @juanluispaz

    Heads up — the same Date#toString() serialization also reaches PostgreSQL through sql.unsafe(query, params), which the issue description currently excludes ("sql.unsafe() with plain string queries is not affected"). In practice it is, regardless of the prepare setting.

    Repro
    bun --version: 1.3.14 · server: postgres:18-alpine

    import { SQL } from 'bun'
    
    const uri = process.argv[2]!   // postgresql://user:pass@host:port/db
    const d = new Date('2024-01-15T00:00:00Z')
    
    // A) unsafe() with the default prepare:true
    const sqlA = new SQL({ adapter: 'postgres', url: uri })
    try {
        console.log('A) OK ->', await sqlA.unsafe('select $1::date as result', [d]))
    } catch (e) {
        console.log('A) FAILED ->', (e as Error).message)
    }
    
    // B) unsafe() with prepare:false
    const sqlB = new SQL({ adapter: 'postgres', url: uri, prepare: false })
    try {
        console.log('B) OK ->', await sqlB.unsafe('select $1::date as result', [d]))
    } catch (e) {
        console.log('B) FAILED ->', (e as Error).message)
    }
    
    // C) Workaround — pre-ISO the value
    try {
        console.log('C) OK ->', await sqlA.unsafe('select $1::date as result', [d.toISOString()]))
    } catch (e) {
        console.log('C) FAILED ->', (e as Error).message)
    }
    
    await sqlA.close(); await sqlB.close()

    Output

    A) FAILED -> invalid input syntax for type date: "Mon Jan 15 2024 01:00:00 GMT+0100 (Central European Standard Time)"
    B) FAILED -> invalid input syntax for type date: "Mon Jan 15 2024 01:00:00 GMT+0100 (Central European Standard Time)"
    C) OK -> [ { result: "2024-01-15T00:00:00.000Z" } ]
    

    So both prepare:true (the default) and prepare:false reproduce the same serialization; only pre-stringifying via Date#toISOString() works around it. Same root cause and same error wording as the original report, just an additional code path that the current issue scope rules out.

    Would it make sense to widen the scope of this issue (or have #29013 also cover the unsafe(query, params) path) so the fix lands on the shared serializer?

  7. navidemad commented on Sep 2, 2026

    @navidemad

    Still reproducible on Bun 1.4.0 (macOS arm64 and linux x64 in Docker oven/bun:1-alpine), PostgreSQL 16. Two additional data points from a production collector that had to switch to prepare: false to work around #28980:

    1. Date → toString() (as reported):

    PostgresError: time zone "gmt+0200" not recognized
      code: "22023", where: "unnamed portal parameter $7 = '...'"
    

    2. Plain objects bound to a jsonb column are serialized as "[object Object]", so the same workload also fails on JSON columns:

    PostgresError: invalid input syntax for type json
      detail: "Token \"object\" is invalid."
      where: "JSON data, line 1: [object...\nunnamed portal parameter $6 = '...'"
    

    Both happen with the bulk-insert helper (sql`INSERT INTO events ${sql(rows)}`) and with single-parameter queries. With prepare: true the same rows insert fine, so the text-mode parameter encoding path is the only one affected.

    Minimal repro:

    import { SQL } from "bun";
    const sql = new SQL({ url: process.env.DATABASE_URL, prepare: false });
    await sql`CREATE TEMP TABLE t (ts timestamptz, props jsonb)`;
    await sql`INSERT INTO t ${sql([{ ts: new Date(), props: { a: 1 } }])}`;
    // -> 22023 time zone "gmt+0200" not recognized (or 22P02 on props if ts is fixed first)

    Workaround we shipped: pre-serialize on our side (date.toISOString() and JSON.stringify(obj)), PostgreSQL casts the text to timestamptz / jsonb itself. It would be good for the prepare: false path to use the same encoders as the prepared path (ISO 8601 for Date, JSON for objects/arrays).

  8. added a commit that references this issue on Sep 8, 2026
    a66d8aa
  9. tetsuodev commented on Oct 12, 2026

    @tetsuodev

    time columns fail too, with a different message, and both cases reach query builders that bind through sql.unsafe() with the default prepare:

    import { SQL } from "bun";
    
    const sql = new SQL("postgres://postgres:postgres@localhost:5432/postgres");
    
    await sql`drop table if exists events`;
    await sql`create table events (day date, at time)`;
    
    const now = new Date("2026-10-09T21:30:00Z");
    
    for (const column of ["day", "at"]) {
      try {
        await sql.unsafe(`insert into events (${column}) values ($1)`, [now]);
        console.log(column, "ok");
      } catch (error) {
        console.log(column, error.code, error.message);
      }
    }
    
    await sql.close();
    day ERR_POSTGRES_SERVER_ERROR invalid input syntax for type date: "Fri Oct 09 2026 21:30:00 GMT+0000 (Coordinated Universal Time)"
    at ERR_POSTGRES_SERVER_ERROR time out of range
    

    Bun 1.4.3, PostgreSQL 18.6, run with TZ=UTC.

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