Skip to content

Commit ebd414f

Browse files
committed
Refactor SQL to use a for loop
Previously join() and reduce() where used. The new form should make it easier to add new features and may improve performance.
1 parent 7d36a85 commit ebd414f

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
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!).
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).
22

33
Example for escaping queries (callbacks omitted):
44
```js

index.js

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
11
'use strict'
2-
module.exports = function SQL (strings) {
3-
return {
4-
sql: strings.join('?'), // for mysql / mysql2
5-
text: strings.reduce((previous, current, i) => previous + '$' + i + current), // for postgres
6-
values: Array.from(arguments).slice(1) // since node doesnt support argument unpacking yet
2+
3+
function SQL (strings) {
4+
let args = Array.from(arguments).slice(1)
5+
let sql = '' // for mysql/mysql2
6+
let text = '' // for postgres
7+
let values = args
8+
for (let i = 0, length = strings.length; i < length; i++) {
9+
sql += strings[i]
10+
text += strings[i]
11+
if (i < length - 1) {
12+
sql += '?'
13+
text += '$' + (i + 1)
14+
}
715
}
16+
return {sql, text, values}
817
}
18+
19+
module.exports = SQL

0 commit comments

Comments
 (0)