From f06e6fcf420142ebfe0981b715dac36b6f0d6ce6 Mon Sep 17 00:00:00 2001 From: Jacob Smith <3012099+JakobJingleheimer@users.noreply.github.com> Date: Mon, 13 Oct 2025 17:17:14 -0400 Subject: [PATCH 1/2] doc: add dynamic filtering examples Added examples for filtering and combining conditions in SQL queries using JavaScript. --- README.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/README.md b/README.md index b04ac21c..23935622 100644 --- a/README.md +++ b/README.md @@ -342,6 +342,44 @@ select * from users select * from users where user_id = $1 ``` +Use a combination of `sql()` and ` sql`` ` to filter against JSON(B): + +```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}`) + +switch (bar) { + case A: + conditions.push(sql`bar IS NOT NULL`) + break + // … +} + +await sql` + select * from users + where ${conditions.reduce((clause, condition) => sql`${clause} AND ${condition}`)}; +` +``` + ### Dynamic ordering ```js From 8f8a1d71f5d33ea95a7ed07ef32da007280c1892 Mon Sep 17 00:00:00 2001 From: Jacob Smith <3012099+JakobJingleheimer@users.noreply.github.com> Date: Tue, 14 Oct 2025 04:23:46 -0400 Subject: [PATCH 2/2] fixup!: apply suggestions from code review Co-authored-by: Karl Horky --- README.md | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 23935622..c976f9c3 100644 --- a/README.md +++ b/README.md @@ -342,7 +342,7 @@ select * from users select * from users where user_id = $1 ``` -Use a combination of `sql()` and ` sql`` ` to filter against JSON(B): +Use a combination of `sql()` and ` sql`` ` to access fields in `json` or `jsonb`: ```js const filter = someCondition @@ -354,7 +354,7 @@ await sql` where ${filter}; ` -// which results in: +// Which results in: select * from users where "notifications"->>'email' = TRUE; // OR select * from users where "2FA"->>'email' = TRUE; @@ -367,13 +367,6 @@ const conditions = [] if (foo) conditions.push(sql`foo = ${foo}`) -switch (bar) { - case A: - conditions.push(sql`bar IS NOT NULL`) - break - // … -} - await sql` select * from users where ${conditions.reduce((clause, condition) => sql`${clause} AND ${condition}`)};