This repository has been archived by the owner on Oct 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
117 lines (114 loc) · 3.09 KB
/
index.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import sqlite3 from "sqlite3";
const NAME = "cf-sqlite3";
const EMPTY_ARRAY = [];
export default function (databaseFile) {
let isTransactionActive = false;
const db = new sqlite3.Database(databaseFile, (err) => {
if (err != null) {
console.error(err.message);
throw err;
}
});
return {
all: async function (query, args, callback) {
return await new Promise((resolve, reject) => {
console.log(NAME, "all", query, args);
db.all(query, args ?? EMPTY_ARRAY, function (err, rows) {
if (err != null) {
console.error(err.message);
reject(err);
return;
}
if (rows == null || rows.length == 0) {
resolve([]);
return;
}
if (callback != null) {
resolve(callback(rows));
} else {
resolve(rows);
}
});
});
},
beginTransaction: async function () {
if (!isTransactionActive) {
isTransactionActive = true;
await new Promise((resolve, reject) => {
console.log(NAME, "beginTransaction");
db.exec("BEGIN TRANSACTION;", (err) => {
if (err != null) {
console.error(err.message);
reject(err);
return;
}
resolve();
});
});
}
},
commitTransaction: async function () {
if (isTransactionActive) {
isTransactionActive = false;
await new Promise((resolve, reject) => {
console.log(NAME, "commitTransaction");
db.exec("COMMIT TRANSACTION;", (err) => {
if (err != null) {
console.error(err.message);
reject(err);
return;
}
resolve();
});
});
}
},
exec: async function (query) {
await new Promise((resolve, reject) => {
console.log(NAME, "exec", query);
db.exec(query, (err) => {
if (err != null) {
console.error(err.message);
reject(err);
return;
}
resolve();
});
});
},
get: async function (query, args, callback) {
return await new Promise((resolve, reject) => {
console.log(NAME, "get", query, args);
db.get(query, args ?? EMPTY_ARRAY, function (err, row) {
if (err != null) {
console.error(err.message);
reject(err);
return;
}
if (row == null) {
resolve(null);
return;
}
if (callback != null) {
resolve(callback(row));
} else {
resolve(row);
}
});
});
},
run: async function (query, args) {
return await new Promise((resolve, reject) => {
console.log(NAME, "run", query, args);
db.run(query, args ?? EMPTY_ARRAY, function (err) {
if (err != null) {
console.error(err.message);
reject(err);
return;
}
resolve(this.lastID);
});
});
},
};
}