mirror of
https://github.com/darksaid98/oxmysql.git
synced 2026-12-01 14:38:50 +00:00
refactor(db/connection): set and get active connections
This commit is contained in:
1 parent
572c6ede88
commit
a876f92ead
1 file changed
+16
-4
@@ -1,4 +1,4 @@
|
||||
import { createPool, Pool, RowDataPacket } from 'mysql2/promise';
|
||||
import { createPool, Pool, PoolConnection, RowDataPacket } from 'mysql2/promise';
|
||||
import { connectionOptions, mysql_transaction_isolation_level } from '../config';
|
||||
import { scheduleTick } from '../utils/scheduleTick';
|
||||
import { sleep } from '../utils/sleep';
|
||||
@@ -13,6 +13,8 @@ export async function waitForConnection() {
|
||||
}
|
||||
}
|
||||
|
||||
const activeConnections: Record<string, PoolConnection> = {};
|
||||
|
||||
export async function createConnectionPool() {
|
||||
try {
|
||||
pool = createPool(connectionOptions);
|
||||
@@ -21,6 +23,16 @@ export async function createConnectionPool() {
|
||||
connection.query(mysql_transaction_isolation_level);
|
||||
});
|
||||
|
||||
pool.on('acquire', (conn) => {
|
||||
const connectionId: number = (conn as any).connectionId;
|
||||
activeConnections[connectionId] = conn;
|
||||
});
|
||||
|
||||
pool.on('release', (conn) => {
|
||||
const connectionId: number = (conn as any).connectionId;
|
||||
delete activeConnections[connectionId];
|
||||
});
|
||||
|
||||
const connection = await pool.getConnection();
|
||||
const [result] = await (<Promise<RowDataPacket[]>>connection.query('SELECT VERSION() as version'));
|
||||
dbVersion = `^5[${result[0].version}]`;
|
||||
@@ -38,10 +50,10 @@ export async function createConnectionPool() {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPoolConnection() {
|
||||
if (!isServerConnected) await waitForConnection()
|
||||
export async function getPoolConnection(id?: number) {
|
||||
if (!isServerConnected) await waitForConnection();
|
||||
|
||||
scheduleTick();
|
||||
|
||||
return pool.getConnection();
|
||||
return id ? activeConnections[id] : pool.getConnection();
|
||||
}
|
||||
Reference in new issue
Block a user