-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
94 lines (81 loc) · 1.97 KB
/
Copy pathdb.js
File metadata and controls
94 lines (81 loc) · 1.97 KB
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
91
92
93
94
const initSqlJs = require('sql.js');
const fs = require('fs');
const path = require('path');
let _dbInstance = null;
let _dbPath = null;
/**
* Thin synchronous wrapper around sql.js that mimics better-sqlite3 API subset.
*/
class DbWrapper {
constructor(sqlDb, filePath) {
this._db = sqlDb;
this._path = filePath;
}
exec(sql) {
this._db.run(sql);
this._save();
}
prepare(sql) {
return new StatementWrapper(this._db, sql, this);
}
close() {
this._save();
this._db.close();
}
pragma() { /* no-op for compatibility */ }
_save() {
if (this._path) {
const data = this._db.export();
fs.writeFileSync(this._path, Buffer.from(data));
}
}
}
class StatementWrapper {
constructor(db, sql, wrapper) {
this._db = db;
this._sql = sql;
this._wrapper = wrapper;
}
run(...params) {
this._db.run(this._sql, params);
// Query last_insert_rowid BEFORE save (export may reset state)
const lastId = this._db.exec("SELECT last_insert_rowid() as id");
const lastInsertRowid = lastId.length > 0 ? lastId[0].values[0][0] : 0;
const changes = this._db.getRowsModified();
this._wrapper._save();
return { lastInsertRowid, changes };
}
get(...params) {
const stmt = this._db.prepare(this._sql);
stmt.bind(params);
if (stmt.step()) {
const row = stmt.getAsObject();
stmt.free();
return row;
}
stmt.free();
return undefined;
}
all(...params) {
const results = [];
const stmt = this._db.prepare(this._sql);
stmt.bind(params);
while (stmt.step()) {
results.push(stmt.getAsObject());
}
stmt.free();
return results;
}
}
async function openDatabase(filePath) {
const SQL = await initSqlJs();
let db;
if (fs.existsSync(filePath)) {
const buffer = fs.readFileSync(filePath);
db = new SQL.Database(buffer);
} else {
db = new SQL.Database();
}
return new DbWrapper(db, filePath);
}
module.exports = { openDatabase };