Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,37 @@ select * from users
select * from users where user_id = $1
```

Use a combination of `sql()` and ` sql`` ` to access fields in `json` or `jsonb`:

```js
const filter = someCondition
? sql`${sql('notifications')}->>'email' = TRUE`
: sql`${sql('2FA')}->>'email' = TRUE`;

await sql`
select * from users
where ${filter};
`

// Which results in:
select * from users where "notifications"->>'email' = TRUE;
// OR
select * from users where "2FA"->>'email' = TRUE;
```

To dynamically combine multiple conditions, use [Array `reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce); [Array `join`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) does not work because its output is a string (an interpolated value) instead of a `Fragment`:

```js
const conditions = []

if (foo) conditions.push(sql`foo = ${foo}`)

await sql`
select * from users
where ${conditions.reduce((clause, condition) => sql`${clause} AND ${condition}`)};
`
```

### Dynamic ordering

```js
Expand Down