MySQLDriver.js
2 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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MySQLDriver = void 0;
class MySQLDriver {
mysql;
config;
conn;
constructor(config) {
this.mysql = require("promise-mysql");
this.config = config;
}
checkConnection() {
if (this.conn == null)
throw new Error("MySQL not connected to the database");
}
async connect() {
this.conn = await this.mysql.createConnection(this.config);
}
async prepare(table) {
this.checkConnection();
await this.conn?.query(`CREATE TABLE IF NOT EXISTS ${table} (ID TEXT, json TEXT)`);
}
async getAllRows(table) {
this.checkConnection();
const results = await this.conn?.query(`SELECT * FROM ${table}`);
return results.map((row) => ({
id: row.ID,
value: JSON.parse(row.json),
}));
}
async getRowByKey(table, key) {
this.checkConnection();
const results = await this.conn?.query(`SELECT json FROM ${table} WHERE ID = ?`, [key]);
if (results.length == 0)
return null;
return JSON.parse(results[0].json);
}
async setRowByKey(table, key, value, update) {
const stringifiedJson = JSON.stringify(value);
if (update) {
await this.conn?.query(`UPDATE ${table} SET json = (?) WHERE ID = (?)`, [stringifiedJson, key]);
}
else {
await this.conn?.query(`INSERT INTO ${table} (ID,json) VALUES (?,?)`, [key, stringifiedJson]);
}
return value;
}
async deleteAllRows(table) {
this.checkConnection();
const result = await this.conn?.query(`DELETE FROM ${table}`);
return result.affectedRows;
}
async deleteRowByKey(table, key) {
this.checkConnection();
const result = await this.conn?.query(`DELETE FROM ${table} WHERE ID=?`, [key]);
return result.affectedRows;
}
}
exports.MySQLDriver = MySQLDriver;
//# sourceMappingURL=MySQLDriver.js.map