sql-string-escape
Version:
Simple SQL string escape.
56 lines (35 loc) • 2.28 kB
Markdown
# sql-string-scape [](http://travis-ci.org/thlorenz/sql-escape-string)
Simple SQL string escape.
```js
const escapeString = require('sql-string-escape')
const sqlString = "Sup'er"
console.log(escapeString(sqlString)) // => Sup''er
```
## Installation
npm install sql-string-escape
## Note
Original implementation from [sqlstring](https://github.com/mysqljs/sqlstring) with the added
option of supporting or not supporting backslash.
## [API](https://thlorenz.github.io/sql-escape-string)
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
### escapeString
Escapes the given string to protect against SQL injection attacks.
By default it assumes that backslashes are not supported as they are not part of the standard SQL spec.
Quoting from the [SQLlite web site](https://sqlite.org/lang_expr.html):
> C-style escapes using the backslash character are not supported because they are not standard SQL.
This means three things:
- backslashes and double quotes `"` are not escaped by default
- single quotes are escaped via `''` instead of `\'`
- your sql engine should throw an error when encountering a backslash escape
as part of a string, unless it is a literal backslash, i.e. `'backslash: \\'`.
It is recommended to set the `backslashSupported` option `true` if your SQL
engine supports it. In that case backslash sequences are escaped and single
and double quotes are escaped via a backslash, i.e. `'\''`.
**Parameters**
- `val` **[String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** the original string to be used in a SQL query
- `$0` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** opts
- `$0.backslashSupported` **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?** if `true` backslashes are supported (optional, default `false`)
- `opts`
Returns **[String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** the original string escaped wrapped in single quotes, i.e. `'mystring'`
## License
MIT