-
Notifications
You must be signed in to change notification settings - Fork 31
/
mysqlDriver.js
64 lines (54 loc) · 1.71 KB
/
mysqlDriver.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
var promisify = require('./promisify');
var optionalRequire = require("./optionalRequire");
var debug = require('debug')('sworm:mysql');
var paramRegex = require('./paramRegex')
module.exports = function() {
var mysql = optionalRequire("mysql");
return {
query: function(query, params, options) {
var self = this;
var paramList = [];
if (params) {
query = query.replace(paramRegex, function(_, paramName) {
if (!params.hasOwnProperty(paramName)) {
throw new Error('no such parameter @' + paramName);
} else {
paramList.push(params[paramName]);
}
return '?';
});
}
return promisify(function(cb) {
debug(query, paramList);
return self.connection.query(query, paramList, cb)
}).then(function (result) {
if (options.insert || options.statement) {
return {
id: params.hasOwnProperty(options.id) ? params[options.id] : result.insertId,
changes: result.affectedRows + result.changedRows
}
} else {
return result
}
})
},
insert: function(query, params, options) {
return this.query(query, params, options)
},
connect: function(config) {
var self = this;
config.config.multipleStatements = true;
self.connection = mysql.createConnection(config.config);
return promisify(function(cb) {
return self.connection.connect(cb);
});
},
close: function() {
var self = this;
return promisify(function (cb) { self.connection.end(cb); });
},
insertEmpty: function(meta) {
return 'insert into ' + meta.table + ' () values ()';
}
};
};