Skip to content

Commit 738beb7

Browse files
committed
add note for postgre prepared statements
1 parent 728fc2c commit 738beb7

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

README.md

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
A simple yet powerful module to allow you to use ES6 tagged template strings for prepared/escaped statements in mysql/mysql2 and postgres (and with simple, I mean only 7 lines of code!).
1+
A simple yet powerful module to allow you to use ES6 tagged template strings for prepared/escaped statements in [mysql](https://www.npmjs.com/package/mysql) / [mysql2](https://www.npmjs.com/package/mysql2) and [postgres](https://www.npmjs.com/package/pq) (and with simple, I mean only 7 lines of code!).
22

3-
Examples (callbacks omitted):
3+
Example for escaping queries (callbacks omitted):
44
```js
55
let SQL = require('sql-template-strings');
66

@@ -14,7 +14,7 @@ pg.query('SELECT author FROM books WHERE name = $1', [book]);
1414
// is equivalent to
1515
pg.query(SQL`SELECT author FROM books WHERE name = ${book}`);
1616
```
17-
17+
For mysql2 prepared statements, just replace `query` with `execute`.
1818
This might not seem like a big deal, but when you do an INSERT with a lot columns writing all the placeholders becomes a nightmare:
1919

2020
```js
@@ -30,5 +30,19 @@ db.query(SQL`
3030
VALUES (${name}, ${author}, ${isbn}, ${category}, ${recommendedAge}, ${pages}, ${price})
3131
`);
3232
```
33+
Also template strings support line breaks, while normal strings do not.
34+
35+
Please note that postgre requires prepared statements to be named, otherwise the parameters will be escaped and replaced on the client side.
36+
You can still use SQL template strings though, you just need to assign a name to the query before using it:
37+
```js
38+
// old way
39+
pg.query({name: 'my_query', text: 'SELECT author FROM books WHERE name = $1', values: [book]});
40+
41+
//with template strings
42+
let query = SQL`SELECT author FROM books WHERE name = ${book}`;
43+
query.name = 'my_query';
44+
pg.query(query);
3345

34-
Also template strings support line breaks.
46+
// or using lodash
47+
pg.query(_.assign(SQL`SELECT author FROM books WHERE name = ${book}`, {name: 'my_query'}))
48+
```

0 commit comments

Comments
 (0)