forked from zadam/trilium-db-compare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql.js
89 lines (66 loc) · 1.88 KB
/
sql.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
"use strict";
async function getSingleResult(db, query, params = []) {
return await wrap(db, async db => db.get(query, ...params));
}
async function getSingleResultOrNull(db, query, params = []) {
const all = await wrap(db, async db => db.all(query, ...params));
return all.length > 0 ? all[0] : null;
}
async function getSingleValue(db, query, params = []) {
const row = await getSingleResultOrNull(db, query, params);
if (!row) {
return null;
}
return row[Object.keys(row)[0]];
}
async function getResults(db, query, params = []) {
return await wrap(db, async db => db.all(query, ...params));
}
async function getIndexed(db, column, query, params = []) {
const results = await getResults(db, query, params);
const map = {};
for (const row of results) {
map[row[column]] = row;
}
return map;
}
async function getMap(db, query, params = []) {
const map = {};
const results = await getResults(db, query, params);
for (const row of results) {
const keys = Object.keys(row);
map[row[keys[0]]] = row[keys[1]];
}
return map;
}
async function getFlattenedResults(db, key, query, params = []) {
const list = [];
const result = await getResults(db, query, params);
for (const row of result) {
list.push(row[key]);
}
return list;
}
async function execute(db, query, params = []) {
return await wrap(db, async db => db.run(query, ...params));
}
async function wrap(db, func) {
const thisError = new Error();
try {
return await func(db);
}
catch (e) {
console.error("Error executing query. Inner exception: " + e.stack + thisError.stack);
throw thisError;
}
}
module.exports = {
getSingleValue,
getSingleResult,
getSingleResultOrNull,
getResults,
getIndexed,
getMap,
getFlattenedResults,
execute
};