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
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/pages/apis/_meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
"pool": "pg.Pool",
"result": "pg.Result",
"types": "pg.Types",
"cursor": "Cursor"
"cursor": "Cursor",
"utilities": "Utilities"
}
30 changes: 30 additions & 0 deletions docs/pages/apis/utilities.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
---
title: Utilities
---
import { Alert } from '/components/alert.tsx'

## Utility Functions
### pg.escapeIdentifier

Escapes a string as a [SQL identifier](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS).

```js
const { escapeIdentifier } = require('pg')
const escapedIdentifier = escapeIdentifier('FooIdentifier')
console.log(escapedIdentifier) // '"FooIdentifier"'
```


### pg.escapeLiteral

<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](/apis/client#clientquery) API for more information.
</Alert>

Escapes a string as a [SQL literal](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS).

```js
const { escapeLiteral } = require('pg')
const escapedLiteral = escapeLiteral("hello 'world'")
console.log(escapedLiteral) // "'hello ''world'''"
```
31 changes: 0 additions & 31 deletions packages/pg/lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -456,37 +456,6 @@ class Client extends EventEmitter {
return this._types.getTypeParser(oid, format)
}

// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
escapeIdentifier(str) {
return '"' + str.replace(/"/g, '""') + '"'
}

// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
escapeLiteral(str) {
var hasBackslash = false
var escaped = "'"

for (var i = 0; i < str.length; i++) {
var c = str[i]
if (c === "'") {
escaped += c + c
} else if (c === '\\') {
escaped += c + c
hasBackslash = true
} else {
escaped += c
}
}

escaped += "'"

if (hasBackslash === true) {
escaped = ' E' + escaped
}

return escaped
}

_pulseQueryQueue() {
if (this.readyForQuery === true) {
this.activeQuery = this.queryQueue.shift()
Expand Down
3 changes: 3 additions & 0 deletions packages/pg/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ var defaults = require('./defaults')
var Connection = require('./connection')
var Pool = require('pg-pool')
const { DatabaseError } = require('pg-protocol')
const { escapeIdentifier, escapeLiteral } = require('./utils')

const poolFactory = (Client) => {
return class BoundPool extends Pool {
Expand All @@ -23,6 +24,8 @@ var PG = function (clientConstructor) {
this.Connection = Connection
this.types = require('pg-types')
this.DatabaseError = DatabaseError
this.escapeIdentifier = escapeIdentifier
this.escapeLiteral = escapeLiteral
Comment on lines +27 to +28
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just new though, right? Why?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is new yes, as for why your previous comment suggested that the escape* methods be exported on pg, this adds them as exports to the pg object. On my end it looks like the github diff viewer annoyingly cuts off the part where it shows these belonging to PG, but looking at the full file it shows the rest of the context.

Is there an issue with exporting them this way?

}

if (typeof process.env.NODE_PG_FORCE_NATIVE !== 'undefined') {
Expand Down
34 changes: 34 additions & 0 deletions packages/pg/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,38 @@ const postgresMd5PasswordHash = function (user, password, salt) {
return 'md5' + outer
}

// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
const escapeIdentifier = function (str) {
return '"' + str.replace(/"/g, '""') + '"'
}

const escapeLiteral = function (str) {
var hasBackslash = false
var escaped = "'"

for (var i = 0; i < str.length; i++) {
var c = str[i]
if (c === "'") {
escaped += c + c
} else if (c === '\\') {
escaped += c + c
hasBackslash = true
} else {
escaped += c
}
}

escaped += "'"

if (hasBackslash === true) {
escaped = ' E' + escaped
}

return escaped
}



module.exports = {
prepareValue: function prepareValueWrapper(value) {
// this ensures that extra arguments do not get passed into prepareValue
Expand All @@ -184,4 +216,6 @@ module.exports = {
normalizeQueryConfig,
postgresMd5PasswordHash,
md5,
escapeIdentifier,
escapeLiteral
}
65 changes: 0 additions & 65 deletions packages/pg/test/unit/client/escape-tests.js

This file was deleted.

53 changes: 53 additions & 0 deletions packages/pg/test/unit/utils-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,3 +239,56 @@ test('prepareValue: can safely be used to map an array of values including those
var out = values.map(utils.prepareValue)
assert.deepEqual(out, [1, 'test', 'zomgcustom!'])
})

var testEscapeLiteral = function (testName, input, expected) {
test(testName, function () {
var actual = utils.escapeLiteral(input)
assert.equal(expected, actual)
})
}
testEscapeLiteral('escapeLiteral: no special characters', 'hello world', "'hello world'")

testEscapeLiteral('escapeLiteral: contains double quotes only', 'hello " world', "'hello \" world'")

testEscapeLiteral('escapeLiteral: contains single quotes only', "hello ' world", "'hello '' world'")

testEscapeLiteral('escapeLiteral: contains backslashes only', 'hello \\ world', " E'hello \\\\ world'")

testEscapeLiteral('escapeLiteral: contains single quotes and double quotes', 'hello \' " world', "'hello '' \" world'")

testEscapeLiteral('escapeLiteral: contains double quotes and backslashes', 'hello \\ " world', " E'hello \\\\ \" world'")

testEscapeLiteral('escapeLiteral: contains single quotes and backslashes', "hello \\ ' world", " E'hello \\\\ '' world'")

testEscapeLiteral(
'escapeLiteral: contains single quotes, double quotes, and backslashes',
'hello \\ \' " world',
" E'hello \\\\ '' \" world'"
)

var testEscapeIdentifier = function (testName, input, expected) {
test(testName, function () {
var actual = utils.escapeIdentifier(input)
assert.equal(expected, actual)
})
}

testEscapeIdentifier('escapeIdentifier: no special characters', 'hello world', '"hello world"')

testEscapeIdentifier('escapeIdentifier: contains double quotes only', 'hello " world', '"hello "" world"')

testEscapeIdentifier('escapeIdentifier: contains single quotes only', "hello ' world", '"hello \' world"')

testEscapeIdentifier('escapeIdentifier: contains backslashes only', 'hello \\ world', '"hello \\ world"')

testEscapeIdentifier('escapeIdentifier: contains single quotes and double quotes', 'hello \' " world', '"hello \' "" world"')

testEscapeIdentifier('escapeIdentifier: contains double quotes and backslashes', 'hello \\ " world', '"hello \\ "" world"')

testEscapeIdentifier('escapeIdentifier: contains single quotes and backslashes', "hello \\ ' world", '"hello \\ \' world"')

testEscapeIdentifier(
'escapeIdentifier: contains single quotes, double quotes, and backslashes',
'hello \\ \' " world',
'"hello \\ \' "" world"'
)