Skip to content

Commit d23700d

Browse files
committed
1 parent 6ec85a4 commit d23700d

File tree

4 files changed

+30
-0
lines changed

4 files changed

+30
-0
lines changed

README.md

+12
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,18 @@ select * from users
342342
select * from users where user_id = $1
343343
```
344344

345+
### Dynamic fragments
346+
Multiple fragments can be joined together with `sql.join` to create more complex dynamic queries:
347+
348+
```js
349+
// this could be built dynamically
350+
let expressions = [sql`name is not null`, sql`age > 50`]
351+
const separator = and ? sql` and ` : sql` or `
352+
sql`select * from from users where ${
353+
sql.join(separator, expressions)
354+
}`
355+
```
356+
345357
### SQL functions
346358
Using keywords or calling functions dynamically is also possible by using ``` sql`` ``` fragments.
347359
```js

src/index.js

+9
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ function Postgres(a, b) {
9898
notify,
9999
array,
100100
json,
101+
join,
101102
file
102103
})
103104

@@ -318,6 +319,14 @@ function Postgres(a, b) {
318319
return new Parameter(x, 3802)
319320
}
320321

322+
function join(sep, xs) {
323+
return xs.flatMap((x, i) => {
324+
if (i === 0) return x
325+
if (Array.isArray(x)) return [sep, ...x]
326+
return [sep, x]
327+
})
328+
}
329+
321330
function array(x, type) {
322331
if (!Array.isArray(x))
323332
return array(Array.from(arguments))

tests/index.js

+8
Original file line numberDiff line numberDiff line change
@@ -2469,6 +2469,14 @@ t('Supports arrays of fragments', async() => {
24692469
]
24702470
})
24712471

2472+
t("Joins fragments with a separator", () => {
2473+
const fs = [sql`a = ${1}`, sql`b = ${"test"}`]
2474+
return [
2475+
sql`select * from t where ${ sql.join(sql` and `, fs) }`.describe().string,
2476+
'select * from t where a = $1 and b = $2'
2477+
]
2478+
});
2479+
24722480
t('Does not try rollback when commit errors', async() => {
24732481
let notice = null
24742482
const sql = postgres({ ...options, onnotice: x => notice = x })

types/index.d.ts

+1
Original file line numberDiff line numberDiff line change
@@ -702,6 +702,7 @@ declare namespace postgres {
702702
file<T extends readonly any[] = Row[]>(path: string | Buffer | URL | number, options?: { cache?: boolean | undefined } | undefined): PendingQuery<T>;
703703
file<T extends readonly any[] = Row[]>(path: string | Buffer | URL | number, args: (ParameterOrJSON<TTypes[keyof TTypes]>)[], options?: { cache?: boolean | undefined } | undefined): PendingQuery<T>;
704704
json(value: JSONValue): Parameter;
705+
join<T extends any[], U extends any[]>(a: PendingQuery<T>, p: PendingQuery<U>): PendingQuery<T>
705706

706707
reserve(): Promise<ReservedSql<TTypes>>
707708
}

0 commit comments

Comments
 (0)