Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,11 @@ select * from users
select * from users where user_id = $1
```

Multiple fragments can be joined together with `sql.join` to create more complex dynamic queries:
```js
const columns = ['id', 'name', 'age'].map(name => sql(name))
sql`select ${sql.join(', ', columns)} from users where

### SQL functions
Using keywords or calling functions dynamically is also possible by using ``` sql`` ``` fragments.
```js
Expand Down
5 changes: 5 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ function Postgres(a, b) {
notify,
array,
json,
join,
file
})

Expand Down Expand Up @@ -318,6 +319,10 @@ function Postgres(a, b) {
return new Parameter(x, 3802)
}

function join(sep, xs) {
return xs.flatMap((x, i) => i ? [sep, x] : x)
}

function array(x, type) {
if (!Array.isArray(x))
return array(Array.from(arguments))
Expand Down
8 changes: 8 additions & 0 deletions tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2469,6 +2469,14 @@ t('Supports arrays of fragments', async() => {
]
})

t("Joins fragments with a separator", () => {
const fs = [sql`a = ${1}`, sql`b = ${"test"}`]
return [
sql`select * from t where ${ sql.join(sql` and `, fs) }; `.describe().string,
'select * from t where a = $1 and b = $2'
]
});

t('Does not try rollback when commit errors', async() => {
let notice = null
const sql = postgres({ ...options, onnotice: x => notice = x })
Expand Down
1 change: 1 addition & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,7 @@ declare namespace postgres {
file<T extends readonly any[] = Row[]>(path: string | Buffer | URL | number, options?: { cache?: boolean | undefined } | undefined): PendingQuery<T>;
file<T extends readonly any[] = Row[]>(path: string | Buffer | URL | number, args: (ParameterOrJSON<TTypes[keyof TTypes]>)[], options?: { cache?: boolean | undefined } | undefined): PendingQuery<T>;
json(value: JSONValue): Parameter;
join<T extends any[], U extends any[]>(a: PendingQuery<T>, p: PendingQuery<U>): PendingQuery<T>

reserve(): Promise<ReservedSql<TTypes>>
}
Expand Down