2022-05-10 12:36:48 +01:00
|
|
|
const mysql = require("mysql2");
|
2022-08-26 12:52:00 +01:00
|
|
|
const consoleHelper = require("../consoleHelper.js");
|
2020-09-07 19:23:06 +01:00
|
|
|
|
|
|
|
module.exports = class {
|
2022-08-26 12:52:00 +01:00
|
|
|
constructor(databaseAddress, databasePort = 3306, databaseUsername, databasePassword, databaseName, connectedCallback) {
|
2022-01-04 03:39:53 +00:00
|
|
|
this.connectionPool = mysql.createPool({
|
|
|
|
connectionLimit: 128,
|
|
|
|
host: databaseAddress,
|
|
|
|
port: databasePort,
|
|
|
|
user: databaseUsername,
|
|
|
|
password: databasePassword,
|
|
|
|
database: databaseName
|
|
|
|
});
|
2022-08-26 12:52:00 +01:00
|
|
|
|
|
|
|
const classCreationTime = Date.now();
|
|
|
|
this.dbActive = false;
|
|
|
|
if (connectedCallback == null) {
|
|
|
|
this.dbActive = true;
|
|
|
|
} else {
|
|
|
|
const connectionCheckInterval = setInterval(() => {
|
|
|
|
this.query("SELECT name FROM osu_info LIMIT 1")
|
|
|
|
.then(data => {
|
|
|
|
consoleHelper.printBancho(`Connected to database. Took ${Date.now() - classCreationTime}ms`);
|
|
|
|
this.dbActive = true;
|
|
|
|
clearInterval(connectionCheckInterval);
|
|
|
|
|
|
|
|
connectedCallback();
|
|
|
|
})
|
|
|
|
.catch(err => {});
|
|
|
|
}, 167); // Roughly 6 times per sec
|
|
|
|
}
|
2022-01-04 03:39:53 +00:00
|
|
|
}
|
2020-09-07 19:23:06 +01:00
|
|
|
|
2022-05-10 12:36:48 +01:00
|
|
|
query(query = "", data) {
|
|
|
|
const limited = query.includes("LIMIT 1");
|
|
|
|
|
2022-01-04 03:39:53 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
this.connectionPool.getConnection((err, connection) => {
|
|
|
|
if (err) {
|
|
|
|
reject(err);
|
2022-07-05 08:13:20 +01:00
|
|
|
try { connection.release();}
|
|
|
|
catch (e) {
|
|
|
|
console.error("Failed to release mysql connection", err);
|
|
|
|
}
|
2022-01-04 03:39:53 +00:00
|
|
|
} else {
|
2022-05-10 12:36:48 +01:00
|
|
|
// Use old query
|
|
|
|
if (data == null) {
|
|
|
|
connection.query(query, (err, data) => {
|
|
|
|
if (err) {
|
|
|
|
reject(err);
|
|
|
|
connection.release();
|
|
|
|
} else {
|
|
|
|
dataReceived(resolve, data, limited);
|
|
|
|
connection.release();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
// Use new prepared statements w/ placeholders
|
|
|
|
else {
|
|
|
|
connection.execute(query, data, (err, data) => {
|
|
|
|
if (err) {
|
|
|
|
reject(err);
|
|
|
|
connection.release();
|
|
|
|
} else {
|
|
|
|
dataReceived(resolve, data, limited);
|
|
|
|
connection.release();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2022-01-04 03:39:53 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
2022-05-10 12:36:48 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
function dataReceived(resolveCallback, data, limited = false) {
|
|
|
|
if (limited) resolveCallback(data[0]);
|
|
|
|
else resolveCallback(data);
|
2020-09-07 19:23:06 +01:00
|
|
|
}
|