From 6d8c005c3edaffe5af4ccc184d4d4d5224abb1c2 Mon Sep 17 00:00:00 2001 From: terminalchai Date: Fri, 17 Apr 2026 01:01:06 +0530 Subject: [PATCH] fix(pg): throw on invalid Date instead of serializing NaN string new Date(undefined) and new Date('invalid') produce an invalid Date object whose getTime() returns NaN. Previously prepareValue() would pass such a date straight through to dateToString() / dateToStringUTC() which format each NaN component with padStart(), producing the meaningless string '0NaN-NaN-NaNTNaN:NaN:NaN.NaN+NaN:NaN' that Postgres cannot parse. Add an isNaN(val.getTime()) guard in the isDate branch of prepareValue() and throw an informative error immediately, so callers discover the bug at the JS level rather than receiving a cryptic Postgres error. Fixes #3318 --- packages/pg/lib/utils.js | 3 +++ packages/pg/test/unit/utils-tests.js | 16 ++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/packages/pg/lib/utils.js b/packages/pg/lib/utils.js index e23a55e9a..5f88919b0 100644 --- a/packages/pg/lib/utils.js +++ b/packages/pg/lib/utils.js @@ -64,6 +64,9 @@ const prepareValue = function (val, seen) { return buf.slice(val.byteOffset, val.byteOffset + val.byteLength) // Node.js v4 does not support those Buffer.from params } if (isDate(val)) { + if (isNaN(val.getTime())) { + throw new Error('date is invalid') + } if (defaults.parseInputDatesAsUTC) { return dateToStringUTC(val) } else { diff --git a/packages/pg/test/unit/utils-tests.js b/packages/pg/test/unit/utils-tests.js index 5f75f6c2d..e81ee729c 100644 --- a/packages/pg/test/unit/utils-tests.js +++ b/packages/pg/test/unit/utils-tests.js @@ -94,6 +94,22 @@ test('prepareValues: undefined prepared properly', function () { assert.strictEqual(out, null) }) +test('prepareValues: invalid date throws an error', function () { + const invalidDate = new Date(undefined) + assert.throws( + () => utils.prepareValue(invalidDate), + /date is invalid/ + ) +}) + +test('prepareValues: invalid date (NaN) does not produce NaN string', function () { + const invalidDate = new Date('not a date') + assert.throws( + () => utils.prepareValue(invalidDate), + /date is invalid/ + ) +}) + test('prepareValue: null prepared properly', function () { const out = utils.prepareValue(null) assert.strictEqual(out, null)