-
Notifications
You must be signed in to change notification settings - Fork 31
/
sqliteDriver.js
89 lines (79 loc) · 2.21 KB
/
sqliteDriver.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var promisify = require('./promisify');
var optionalRequire = require("./optionalRequire");
var debug = require('debug')('sworm:sqlite');
var urlUtils = require('url')
module.exports = function() {
var sqlite = optionalRequire('sqlite3');
return {
query: function(query, params, options) {
var self = this;
var sqliteParams = {};
if (params) {
Object.keys(params).forEach(function (key) {
sqliteParams['@' + key] = params[key];
});
}
if (options.statement || options.insert) {
return new Promise(function (fulfil, reject) {
debug(query, sqliteParams);
self.connection.run(query, sqliteParams, function (error) {
if (error) {
reject(error);
} else {
fulfil({
id: params.hasOwnProperty(options.id) ? params[options.id] : this.lastID,
changes: this.changes
});
}
});
});
} else if (options.exec || options.multiline) {
return promisify(function (cb) {
debug(query, sqliteParams);
self.connection.exec(query, cb);
});
} else {
return promisify(function (cb) {
debug(query, sqliteParams);
self.connection.all(query, sqliteParams, cb);
});
}
},
insert: function(query, params, options) {
return this.query(query, params, options)
},
connect: function(options) {
var self = this;
var config = parseConfig(options)
return promisify(function(cb) {
if (options.mode) {
self.connection = new sqlite.Database(config.filename, config.mode, cb);
} else {
self.connection = new sqlite.Database(config.filename, cb);
}
});
},
close: function() {
var self = this;
return promisify(function (cb) {
return self.connection.close(cb);
});
}
};
};
function parseConfig(options) {
if (options.url) {
var url = urlUtils.parse(options.url)
if (url.protocol) {
return {
filename: url.pathname
}
} else {
return {
filename: options.url
}
}
} else {
return options.config
}
}