-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
76 lines (68 loc) · 1.71 KB
/
database.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
const sqlite3 = require('sqlite3').verbose();
var db;
exports.db = db;
exports.open = function (path) {
return new Promise(function (resolve) {
this.db = new sqlite3.Database(path, function (err) {
if (err) reject('Open error: ' + err.message);
else resolve(path + ' opened');
});
});
};
// any query: insert/delete/update
exports.run = function (query) {
return new Promise(function (resolve, reject) {
this.db.run(query, function (err) {
if (err) reject(err.message);
else resolve(true);
});
});
};
// first row read
exports.get = function (query, params) {
return new Promise(function (resolve, reject) {
this.db.get(query, params, function (err, row) {
if (err) reject('Read error: ' + err.message);
else {
resolve(row);
}
});
});
};
// set of rows read
exports.all = function (query, params) {
return new Promise(function (resolve, reject) {
if (params == undefined) params = [];
this.db.all(query, params, function (err, rows) {
if (err) reject('Read error: ' + err.message);
else {
resolve(rows);
}
});
});
};
// each row returned one by one
exports.each = function (query, params, action) {
return new Promise(function (resolve, reject) {
var db = this.db;
db.serialize(function () {
db.each(query, params, function (err, row) {
if (err) reject('Read error: ' + err.message);
else {
if (row) {
action(row);
}
}
});
db.get('', function (err, row) {
resolve(true);
});
});
});
};
exports.close = function () {
return new Promise(function (resolve, reject) {
this.db.close();
resolve(true);
});
};