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

### Dynamic fragments
Multiple fragments can be joined together with `sql.join` to create more complex dynamic queries:

```js
// this could be built dynamically
let expressions = [sql`name is not null`, sql`age > 50`]
const separator = and ? sql` and ` : sql` or `
sql`select * from from users where ${
sql.join(separator, expressions)
}`
```

### SQL functions
Using keywords or calling functions dynamically is also possible by using ``` sql`` ``` fragments.
```js
Expand Down
9 changes: 9 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,14 @@ function Postgres(a, b) {
return new Parameter(x, 3802)
}

function join(sep, xs) {
return xs.flatMap((x, i) => {
if (i === 0) return x
if (Array.isArray(x)) return [sep, ...x]
return [sep, 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