-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
72 lines (62 loc) · 1.93 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
const sqlite3 = require('sqlite3').verbose();
let db;
// Open the database connection
async function openDB(databaseFile) {
if(db) return;
return new Promise((resolve, reject) => {
db = new sqlite3.Database(databaseFile, (err) => {
if (err) {
reject(`Failed to open database: ${err.message}`);
} else {
resolve(`Database opened successfully`);
}
});
});
}
// Insert a new row
async function insert(data) {
const columns = Object.keys(data).join(", ");
const placeholders = Object.keys(data).map(() => "?").join(", ");
const values = Object.values(data);
const sql = `INSERT INTO results (${columns}) VALUES (${placeholders})`;
return new Promise((resolve, reject) => {
db.run(sql, values, function (err) {
if (err) {
reject(`Insert failed: ${err.message}`);
} else {
resolve(this.lastID);
}
});
});
}
// Update an existing row by ID
async function update(data) {
const columns = Object.keys(data).filter((key) => key !== "filename");
const placeholders = columns.map((key) => `${key} = ?`).join(", ");
const values = columns.map((key) => data[key]);
values.push(data.filename);
const sql = `UPDATE results SET ${placeholders} WHERE filename = ?`;
return new Promise((resolve, reject) => {
db.run(sql, values, function (err) {
if (err) {
reject(`Update failed: ${err.message}`);
} else {
resolve(this.changes);
}
});
});
}
// Get all rows from a
async function getAll() {
const sql = `SELECT * FROM results`;
return new Promise((resolve, reject) => {
db.all(sql, [], (err, rows) => {
if (err) {
reject(`Get all failed: ${err.message}`);
} else {
resolve(rows);
}
});
});
}
module.exports = { openDB, insert, update, getAll };