-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlite3_driver_example.js
92 lines (63 loc) · 1.85 KB
/
sqlite3_driver_example.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
90
/*
EXAMPLE OF USAGE:
first require:
const DBDriver = require(path.resolve(appRoot.path, "backend_of_frontend", "src", "drivers", "db"));
then
// select
let db = await DBDriver.connect();
let users = await db.query("SELECT * FROM users");
console.log(users);
// update or insert
db.runStatement("UPDATE tbl SET name = ? WHERE id = ?", "bar", 2);
*/
"use strict";
const path = require("path");
const sqlite3 = require('sqlite3').verbose();
const appRoot = require("app-root-path");
const dbFilePath = path.resolve(appRoot.path, "db", "easytask.db");
var db;
function openDatabase() {
return new Promise(function(resolve, reject){
// The default value is OPEN_READWRITE | OPEN_CREATE | OPEN_FULLMUTEX.
db = new sqlite3.Database(dbFilePath, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the easytask database.');
});
resolve(db);
});
}
function runStatement(query, params) {
return new Promise(function(resolve, reject) {
db.run(query, params, function(err) {
if(err) {
reject(err);
}
resolve(db);
});
});
}
function all(query, params) {
return new Promise(function(resolve, reject) {
db.all(query, params, function(err, rows) {
if(err) {
reject(err);
}
resolve(rows);
});
});
}
module.exports = {
connect: async function () {
let db = await openDatabase();
return this;
},
runStatement: async function (query, params) {
await runStatement(query, params);
},
query: async function(sql, params) {
let rows = await all(sql, params);
return rows;
}
};