76 lines
2.0 KiB
JavaScript
Executable File
76 lines
2.0 KiB
JavaScript
Executable File
require("dotenv").config({ path: require("path").resolve(__dirname, "../.env") });
|
|
|
|
const mysql = require("mysql2");
|
|
const pool = mysql.createPool({
|
|
// connectionLimit: process.env.CONNECTIONLIMIT,
|
|
host: process.env.DBHOST,
|
|
port: process.env.DBPORT,
|
|
user: process.env.DBUSER,
|
|
password: process.env.DBPASSWORD,
|
|
database: process.env.DATABASE,
|
|
connectionLimit: 10,
|
|
connectTimeout: 20000,
|
|
acquireTimeout: 20000,
|
|
// acquireTimeout: Number(process.env.ACQRTIMEOUT), // in ms
|
|
});
|
|
|
|
pool.getConnection((err, conn) => {
|
|
if (err) {
|
|
if (err.code === "PROTOCOL_CONNECTION_LOST") {
|
|
console.error("Koneksi database ditutup.");
|
|
}
|
|
if (err.code === "ER_CON_COUNT_ERROR") {
|
|
console.error("Basis data memiliki terlalu banyak koneksi.");
|
|
}
|
|
if (err.code === "ECONNREFUSED") {
|
|
console.error("Koneksi database ditolak.");
|
|
}
|
|
console.error(err);
|
|
}
|
|
if (conn) conn.release();
|
|
return;
|
|
});
|
|
|
|
// pool.on('acquire', function (connection) {
|
|
// console.log('Connection %d acquired', connection.threadId);
|
|
// });
|
|
|
|
// pool.on('connection', function (connection) {
|
|
// console.log('Connection %d connect', connection.threadId);
|
|
// });
|
|
|
|
// pool.on('release', function (connection) {
|
|
// console.log('Connection %d released', connection.threadId);
|
|
// });
|
|
|
|
// // --- The Deadlock Optimizer ---
|
|
// // This function wraps your queries and retries them if a deadlock occurs
|
|
// const queryWithRetry = async (sql, params, retries = 3) => {
|
|
// for (let attempt = 1; attempt <= retries; attempt++) {
|
|
// try {
|
|
// return await pool.execute(sql, params);
|
|
// } catch (err) {
|
|
// const isDeadlock = err.code === 'ER_LOCK_DEADLOCK' || err.errno === 1213;
|
|
|
|
// if (isDeadlock && attempt < retries) {
|
|
// console.warn(`Deadlock detected. Retry attempt ${attempt}...`);
|
|
// // Wait slightly longer each time (Exponential Backoff)
|
|
// await new Promise(res => setTimeout(res, attempt * 100));
|
|
// continue;
|
|
// }
|
|
// throw err; // If not a deadlock or out of retries, throw
|
|
// }
|
|
// }
|
|
// };
|
|
|
|
// module.exports = {
|
|
// pool,
|
|
// query: queryWithRetry
|
|
// };
|
|
|
|
|
|
module.exports = pool;
|
|
|
|
|
|
|