Skip to content

Commit

Permalink
feat: treat JSON null as a literal null
Browse files Browse the repository at this point in the history
  • Loading branch information
gajus committed Aug 6, 2019
1 parent 6cbff37 commit 9807aac
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 17 deletions.
14 changes: 6 additions & 8 deletions .README/QUERY_BUILDING.md
Expand Up @@ -426,7 +426,7 @@ Produces:

```

Serializes value and binds it as an array, e.g.
Serializes value and binds it as a JSON string literal, e.g.

```js
await connection.query(sql`
Expand All @@ -447,14 +447,12 @@ Produces:

```

This is a convenience function equivalent to:
#### Difference from `JSON.stringify`

```js
await connection.query(sql`
SELECT (${JSON.stringify([1, 2, 3])}})
`);

```
|Input|`sql.json`|`JSON.stringify`|
|---|---|---|
|`undefined`|Throws `InvalidInputError` error.|`undefined`|
|`null`|`null`|`"null"` (string literal)|

### `sql.raw`

Expand Down
15 changes: 7 additions & 8 deletions README.md
Expand Up @@ -1568,7 +1568,7 @@ Produces:

```
Serializes value and binds it as an array, e.g.
Serializes value and binds it as a JSON string literal, e.g.
```js
await connection.query(sql`
Expand All @@ -1589,14 +1589,13 @@ Produces:

```
This is a convenience function equivalent to:
<a name="slonik-query-building-sql-json-difference-from-json-stringify"></a>
#### Difference from <code>JSON.stringify</code>
```js
await connection.query(sql`
SELECT (${JSON.stringify([1, 2, 3])}})
`);

```
|Input|`sql.json`|`JSON.stringify`|
|---|---|---|
|`undefined`|Throws `InvalidInputError` error.|`undefined`|
|`null`|`null`|`"null"` (string literal)|
<a name="slonik-query-building-sql-raw"></a>
### <code>sql.raw</code>
Expand Down
9 changes: 8 additions & 1 deletion src/sqlFragmentFactories/createJsonSqlFragment.js
Expand Up @@ -4,13 +4,20 @@ import type {
JsonSqlTokenType,
SqlFragmentType,
} from '../types';
import {
InvalidInputError,
} from '../errors';

export default (token: JsonSqlTokenType, greatestParameterPosition: number): SqlFragmentType => {
if (token.value === undefined) {
throw new InvalidInputError('json value must not be undefined.');
}

// @todo Do not add `::json` as it will fail if an attempt is made to insert to jsonb-type column.
return {
sql: '$' + (greatestParameterPosition + 1),
values: [
JSON.stringify(token.value),
token.value === null ? null : JSON.stringify(token.value),
],
};
};
12 changes: 12 additions & 0 deletions test/slonik/templateTags/sql/json.js
Expand Up @@ -20,6 +20,18 @@ test('creates a value list', (t) => {
});
});

test('passes null unstringified', (t) => {
const query = sql`SELECT ${sql.json(null)}`;

t.deepEqual(query, {
sql: 'SELECT $1',
type: SqlToken,
values: [
null,
],
});
});

test('the resulting object is immutable', (t) => {
const token = sql.json({
foo: 'bar',
Expand Down

0 comments on commit 9807aac

Please sign in to comment.