import * as mysql from "mysql2"; import { event } from "./eventHandler.js"; import { Debug, Log, Warn, Err, logger, profilerDone } from "./loggerUtility.js"; let pool; export let queryCount = 0; export const setup = ({ user, host, database, password, connectionLimit }) => { /** * Creates a MySQL connection pool with the provided configuration options. * @param {Object} config - The configuration object for creating the pool. * @param {string} config.host - The host of the MySQL server. * @param {string} config.user - The user to authenticate as. * @param {string} config.database - The name of the database to use for the connection. * @param {string} config.password - The password of the user. * @param {boolean} config.waitForConnections - Determines if the pool should wait for connections. * @param {number} config.connectionLimit - The maximum number of connections to create at once. * @param {number} config.maxIdle - The maximum number of idle connections */ pool = mysql.createPool({ host, user, database, password, waitForConnections: true, connectionLimit, maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit` idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000 queueLimit: 0, enableKeepAlive: true, keepAliveInitialDelay: 0, }); try{ runPrepQuery("SELECT 1 FROM linkshells", [], (r,f,e) => { if(!e) { event.emit("DATABASE_CONNECTED"); } else { Err('MYSQL_FAILED_NO_TABLES') event.emit("MYSQL_FAILED_NO_TABLES"); event.emit("MYSQL_FAILED_TO_CONNECT"); } }) } catch (e) { console.log(e) event.emit("MYSQL_FAILED_TO_CONNECT"); } }; export const runPrepQuery = (sql, data, callback) => { /** * Establishes a connection to the MySQL database pool and executes a SQL query. * @param {Error} err - The error object returned from the connection attempt. * @param {Connection} conn - The connection object to the MySQL database pool. * @returns None */ pool.getConnection((err, conn) => { if (err) { Err(`MYSQL ERROR (${err?.errno}): ${err?.code} ${err?.sqlMessage}`); if (queryCount === 0) { event.emit("MYSQL_FAILED_TO_CONNECT"); } } if (!err) { conn.execute(sql, data, (e, r, f) => { if (typeof callback === "function") callback(r, f, e); queryCount++; pool.releaseConnection(conn); }); } else if (typeof callback === "function") callback(false, false, err); }); }; export const numRows = (rows) => { /** * Returns the number of rows if rows exist, otherwise returns false. * @param {Array} rows - The array of rows to check. * @returns {number|boolean} The number of rows if rows exist, otherwise false. */ if (rows) return rows.length; return false; };