Skip to content

Commit 758b5ee

Browse files
committed
Undefined values throws
1 parent 87b0943 commit 758b5ee

File tree

3 files changed

+25
-9
lines changed

3 files changed

+25
-9
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,11 @@ Query errors will also contain the `query` string and the `parameters` which are
519519

520520
There are also the following errors specifically for this library.
521521

522+
##### UNDEFINED_VALUE
523+
> Undefined values are not allowed
524+
525+
Postgres.js won't accept `undefined` as values in tagged template queries since it becomes ambigious what to do with the value. If you want to set something to null, use `null` explicitly.
526+
522527
##### MESSAGE_NOT_SUPPORTED
523528
> X (X) is not supported
524529

lib/index.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -366,11 +366,9 @@ function Postgres(a, b) {
366366

367367
function parseRaw(query, str, args = []) {
368368
const types = []
369-
, xargs = args.map(x => {
370-
const type = getType(x)
371-
types.push(type.type)
372-
return type
373-
})
369+
, xargs = []
370+
371+
args.forEach(x => parseValue(x, xargs, types))
374372

375373
return {
376374
sig: !query.dynamic && types + str,
@@ -446,6 +444,9 @@ function Postgres(a, b) {
446444
}
447445

448446
function parseValue(x, xargs, types) {
447+
if (x === undefined)
448+
throw errors.generic({ code: 'UNDEFINED_VALUE', message: 'Undefined values are not allowed' })
449+
449450
return Array.isArray(x)
450451
? x.reduce((acc, x) => acc + (acc ? ',' : '') + addValue(x, xargs, types), '')
451452
: addValue(x, xargs, types)

tests/index.js

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,6 @@ t('null', async() =>
8282
[null, (await sql`select ${ null } as x`)[0].x]
8383
)
8484

85-
t('undefined to null', async() =>
86-
[null, (await sql`select ${ undefined } as x`)[0].x]
87-
)
88-
8985
t('Integer', async() =>
9086
['1', (await sql`select ${ 1 } as x`)[0].x]
9187
)
@@ -256,6 +252,20 @@ t('Helpers in Transaction', async() => {
256252
))[0].x]
257253
})
258254

255+
t('Undefined values throws', async() => {
256+
let error
257+
258+
await sql`
259+
select ${ undefined } as x
260+
`.catch(x => error = x.code)
261+
262+
return ['UNDEFINED_VALUE', error]
263+
})
264+
265+
t('Null sets to null', async() =>
266+
[null, (await sql`select ${ null } as x`)[0].x]
267+
)
268+
259269
t('Throw syntax error', async() =>
260270
['42601', (await sql`wat 1`.catch(x => x)).code]
261271
)

0 commit comments

Comments
 (0)