Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document client.escapeIdentifier and client.escapeLiteral #2954

Merged
merged 5 commits into from
May 2, 2023
Merged
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
39 changes: 39 additions & 0 deletions docs/pages/apis/client.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
---
title: pg.Client
---
import { Alert } from '/components/alert.tsx'

## new Client

Expand Down Expand Up @@ -256,6 +257,44 @@ client

_note: end returning a promise is only available in pg7.0 and above_

## client.escapeIdentifier

Escapes a string as a [SQL identifier](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS). There are two ways of using this method:

First, this can be used on an existing instance of `Client`:
```js
const escpaedIdentifier = client.escapeIdentifier('FooIdentifier')
console.log(escpaedIdentifier) // '"FooIdentifier"'
TheConner marked this conversation as resolved.
Show resolved Hide resolved
```

Alternatively, this can be used via `Client.prototype`:
```js
const { Client } = require('pg')
const escpaedIdentifier = Client.prototype.escapeIdentifier('Bar"Identifier')
console.log(escpaedIdentifier) // '"Bar""Identifier"'
TheConner marked this conversation as resolved.
Show resolved Hide resolved
```

## client.escapeLiteral

Escapes a string as a [SQL literal](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS). There are two ways of using this method:

<Alert>
**Note**: Instead of manually escaping SQL literals, it is recommended to use parameterized queries. Refer to [parameterized queries](/features/queries#parameterized-query) and the [client.query](#clientquery) API for more information.
</Alert>

First, this can be used on an existing instance of `Client`:
```js
const escapedLiteral = client.escapeLiteral("hello 'world'")
console.log(escapedLiteral) // "Hello ''world''"
TheConner marked this conversation as resolved.
Show resolved Hide resolved
```

Alternatively, this can be used via `Client.prototype`:
```js
const { Client } = require('pg')
const escapedLiteral = Client.prototype.escapeLiteral("hello \\ ' world")
console.log(escapedLiteral) // " E'hello \\\\ '' world'"
```

## events

### error
Expand Down