Skip to content

Commit 6d8c005

Browse files
committed
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
1 parent c78b302 commit 6d8c005

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

packages/pg/lib/utils.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,9 @@ const prepareValue = function (val, seen) {
6464
return buf.slice(val.byteOffset, val.byteOffset + val.byteLength) // Node.js v4 does not support those Buffer.from params
6565
}
6666
if (isDate(val)) {
67+
if (isNaN(val.getTime())) {
68+
throw new Error('date is invalid')
69+
}
6770
if (defaults.parseInputDatesAsUTC) {
6871
return dateToStringUTC(val)
6972
} else {

packages/pg/test/unit/utils-tests.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,22 @@ test('prepareValues: undefined prepared properly', function () {
9494
assert.strictEqual(out, null)
9595
})
9696

97+
test('prepareValues: invalid date throws an error', function () {
98+
const invalidDate = new Date(undefined)
99+
assert.throws(
100+
() => utils.prepareValue(invalidDate),
101+
/date is invalid/
102+
)
103+
})
104+
105+
test('prepareValues: invalid date (NaN) does not produce NaN string', function () {
106+
const invalidDate = new Date('not a date')
107+
assert.throws(
108+
() => utils.prepareValue(invalidDate),
109+
/date is invalid/
110+
)
111+
})
112+
97113
test('prepareValue: null prepared properly', function () {
98114
const out = utils.prepareValue(null)
99115
assert.strictEqual(out, null)

0 commit comments

Comments
 (0)