Skip to content

Commit 3dde443

Browse files
authored
add support for named var like :var1 in sql stmt
1 parent 8f56b8c commit 3dde443

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

lib/query.js

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,35 @@ Query.prototype.submit = function (connection) {
152152
if (this.text && previous && this.text !== previous) {
153153
return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`)
154154
}
155-
if (this.values && !Array.isArray(this.values)) {
156-
return new Error('Query values must be an array')
157-
}
155+
// if (this.values && !Array.isArray(this.values)) {
156+
// return new Error('Query values must be an array')
157+
// }
158+
if (this.values && !(Array.isArray(this.values)||typeof this.values == 'object') ){
159+
// const err = new Error('Query values must be an array or object')
160+
// connection.emit('error', err)
161+
// connection.emit('readyForQuery')
162+
// return
163+
return new Error('Query values must be an array or object');
164+
}
165+
if(!Array.isArray(this.values)){
166+
var sql = this.text
167+
, data = this.values
168+
, values = []
169+
;
170+
this.text = sql.replace(/(:)?:(\w+)/g, function($0, $1, key) {
171+
// lookbehind is not supported by node js 6.11.
172+
// this.text = sql.replace(/(?<!:):{1}([a-zA-Z][\w]*)/g, function(_, key) {
173+
if($1) return $0;
174+
if (key in data) {
175+
values.push(data[key])
176+
return '$' + values.length
177+
} else {
178+
throw new Error('Missing value for statement.\n' + key + ' not provided for statement:\n' + sql + '\nthis was provided:\n' + JSON.stringify(data))
179+
}
180+
});
181+
this.values = values;
182+
}
183+
158184
if (this.requiresPreparation()) {
159185
this.prepare(connection)
160186
} else {

0 commit comments

Comments
 (0)