Skip to content

Commit d6a8cb5

Browse files
committed
feat: sql.join
1 parent f58cd4f commit d6a8cb5

File tree

4 files changed

+19
-0
lines changed

4 files changed

+19
-0
lines changed

README.md

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

345+
Multiple fragments can be joined together with `sql.join` to create more complex dynamic queries:
346+
```js
347+
const columns = ['id', 'name', 'age'].map(name => sql(name))
348+
sql`select ${sql.join(', ', columns)} from users where
349+
345350
### SQL functions
346351
Using keywords or calling functions dynamically is also possible by using ``` sql`` ``` fragments.
347352
```js

src/index.js

+5
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,10 @@ function Postgres(a, b) {
318319
return new Parameter(x, 3802)
319320
}
320321

322+
function join(sep, xs) {
323+
return xs.flatMap((x, i) => i ? [sep, x] : x)
324+
}
325+
321326
function array(x, type) {
322327
if (!Array.isArray(x))
323328
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)