mirror of
https://github.com/darksaid98/oxmysql.git
synced 2026-12-02 06:28:54 +00:00
refactor(database): add new connection class and misc tweaks
Use disposable symbol to ensure connection cleanup. Improvements to internal types. Code splitting and removal of redundant variables.
This commit is contained in:
1 parent
19d55a21ed
commit
c38f646bb9
14 files changed
+162
-125
No files matched your search
+61
-56
@@ -1,65 +1,70 @@
|
||||
import { createPool, Pool, PoolConnection, RowDataPacket } from 'mysql2/promise';
|
||||
import { connectionOptions, mysql_transaction_isolation_level } from '../config';
|
||||
import type { Connection, PoolConnection } from 'mysql2/promise';
|
||||
import { scheduleTick } from '../utils/scheduleTick';
|
||||
import { sleep } from '../utils/sleep';
|
||||
import { pool } from './pool';
|
||||
import type { CFXParameters } from 'types';
|
||||
|
||||
export let pool: Pool;
|
||||
export let isServerConnected = false;
|
||||
export let dbVersion = '';
|
||||
(Symbol as any).dispose ??= Symbol('Symbol.dispose');
|
||||
|
||||
export async function waitForConnection() {
|
||||
while (!isServerConnected) {
|
||||
await sleep(0);
|
||||
const activeConnections: Record<string, MySql> = {};
|
||||
|
||||
interface PromisePoolConnection extends Connection {
|
||||
connection: PoolConnection;
|
||||
release: PoolConnection['release'];
|
||||
}
|
||||
|
||||
export class MySql {
|
||||
id: number;
|
||||
connection: PromisePoolConnection;
|
||||
transaction?: boolean;
|
||||
|
||||
constructor(connection: PromisePoolConnection) {
|
||||
this.id = connection.connection.threadId;
|
||||
this.connection = connection;
|
||||
activeConnections[this.id] = this;
|
||||
}
|
||||
|
||||
async query(query: string, values: CFXParameters = []) {
|
||||
scheduleTick();
|
||||
|
||||
const [result] = await this.connection.query(query, values);
|
||||
return result;
|
||||
}
|
||||
|
||||
async execute(query: string, values: CFXParameters = []) {
|
||||
scheduleTick();
|
||||
|
||||
const [result] = await this.connection.execute(query, values);
|
||||
return result;
|
||||
}
|
||||
|
||||
beginTransaction() {
|
||||
this.transaction = true;
|
||||
return this.connection.beginTransaction();
|
||||
}
|
||||
|
||||
rollback() {
|
||||
delete this.transaction;
|
||||
return this.connection.rollback();
|
||||
}
|
||||
|
||||
commit() {
|
||||
delete this.transaction;
|
||||
this.connection.commit();
|
||||
}
|
||||
|
||||
[Symbol.dispose]() {
|
||||
if (this.transaction) this.commit();
|
||||
|
||||
delete activeConnections[this.id];
|
||||
this.connection.release();
|
||||
}
|
||||
}
|
||||
|
||||
const activeConnections: Record<string, PoolConnection> = {};
|
||||
export async function getConnection(connectionId?: number) {
|
||||
while (!pool) await sleep(0);
|
||||
|
||||
export async function createConnectionPool() {
|
||||
try {
|
||||
pool = createPool(connectionOptions);
|
||||
|
||||
pool.on('connection', (connection) => {
|
||||
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}]`;
|
||||
|
||||
connection.release();
|
||||
console.log(`${dbVersion} ^2Database server connection established!^0`);
|
||||
|
||||
isServerConnected = true;
|
||||
} catch (err: any) {
|
||||
isServerConnected = false;
|
||||
|
||||
const message = err.message.includes('auth_gssapi_client')
|
||||
? `Server requests authentication using unknown plugin auth_gssapi_client.\nSee https://github.com/overextended/oxmysql/issues/213.`
|
||||
: err.message;
|
||||
|
||||
console.log(
|
||||
`^3Unable to establish a connection to the database (${err.code})!\n^1Error${
|
||||
err.errno ? ` ${err.errno}` : ''
|
||||
}: ${message}^0`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPoolConnection(id?: number) {
|
||||
if (!isServerConnected) await waitForConnection();
|
||||
|
||||
scheduleTick();
|
||||
|
||||
return id ? activeConnections[id] : pool.getConnection();
|
||||
return connectionId
|
||||
? activeConnections[connectionId]
|
||||
: new MySql((await pool.getConnection()) as unknown as PromisePoolConnection);
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
import { setDebug } from '../config';
|
||||
import { sleep } from '../utils/sleep';
|
||||
import { createConnectionPool, isServerConnected } from './connection';
|
||||
import { pool, createConnectionPool } from './pool';
|
||||
|
||||
setTimeout(async () => {
|
||||
setDebug();
|
||||
|
||||
while (!isServerConnected) {
|
||||
while (!pool) {
|
||||
await createConnectionPool();
|
||||
|
||||
if (!isServerConnected) await sleep(30000);
|
||||
if (!pool) await sleep(30000);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -20,3 +20,4 @@ export * from './connection';
|
||||
export * from './rawQuery';
|
||||
export * from './rawExecute';
|
||||
export * from './rawTransaction';
|
||||
export * from './pool';
|
||||
@@ -0,0 +1,40 @@
|
||||
import { getConnectionOptions, mysql_transaction_isolation_level } from 'config';
|
||||
import { createPool } from 'mysql2/promise';
|
||||
import type { Pool, RowDataPacket } from 'mysql2/promise';
|
||||
import { getConnection } from './connection';
|
||||
|
||||
export let pool: Pool;
|
||||
export let dbVersion = '';
|
||||
|
||||
export async function createConnectionPool() {
|
||||
const config = getConnectionOptions();
|
||||
|
||||
try {
|
||||
pool = createPool(config);
|
||||
|
||||
pool.on('connection', (connection) => {
|
||||
connection.query(mysql_transaction_isolation_level);
|
||||
});
|
||||
|
||||
using conn = await getConnection();
|
||||
|
||||
const result = await conn.query('SELECT VERSION() as version') as RowDataPacket[];
|
||||
dbVersion = `^5[${result[0].version}]`;
|
||||
|
||||
console.log(`${dbVersion} ^2Database server connection established!^0`);
|
||||
} catch (err: any) {
|
||||
const message = err.message.includes('auth_gssapi_client')
|
||||
? `Server requests authentication using unknown plugin auth_gssapi_client.\nSee https://github.com/overextended/oxmysql/issues/213.`
|
||||
: err.message;
|
||||
|
||||
console.log(
|
||||
`^3Unable to establish a connection to the database (${err.code})!\n^1Error${
|
||||
err.errno ? ` ${err.errno}` : ''
|
||||
}: ${message}^0`
|
||||
);
|
||||
|
||||
if (config.password) config.password = '******';
|
||||
|
||||
console.log(config);
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,11 @@ import { logError, logQuery, profileBatchStatements, runProfiler } from '../logg
|
||||
import { CFXCallback, CFXParameters, QueryType } from '../types';
|
||||
import { parseResponse } from '../utils/parseResponse';
|
||||
import { executeType, parseExecute } from '../utils/parseExecute';
|
||||
import { getPoolConnection } from './connection';
|
||||
import { getConnection } from './connection';
|
||||
import { setCallback } from '../utils/setCallback';
|
||||
import { performance } from 'perf_hooks';
|
||||
import validateResultSet from 'utils/validateResultSet';
|
||||
import { RowDataPacket } from 'mysql2';
|
||||
|
||||
export const rawExecute = async (
|
||||
invokingResource: string,
|
||||
@@ -29,7 +30,7 @@ export const rawExecute = async (
|
||||
return logError(invokingResource, cb, isPromise, err, query, parameters);
|
||||
}
|
||||
|
||||
const connection = await getPoolConnection(connectionId);
|
||||
using connection = await getConnection(connectionId);
|
||||
|
||||
if (!connection) return;
|
||||
|
||||
@@ -48,11 +49,11 @@ export const rawExecute = async (
|
||||
}
|
||||
|
||||
const startTime = !hasProfiler && performance.now();
|
||||
const [result] = await connection.execute(query, values);
|
||||
const result = await connection.execute(query, values);
|
||||
|
||||
if (Array.isArray(result) && result.length > 1) {
|
||||
for (const value of result) {
|
||||
response.push(unpack ? parseResponse(type, value) : value);
|
||||
response.push(unpack ? parseResponse(type, value as RowDataPacket[]) : value);
|
||||
}
|
||||
} else response.push(unpack ? parseResponse(type, result) : result);
|
||||
|
||||
@@ -87,7 +88,5 @@ export const rawExecute = async (
|
||||
}
|
||||
} catch (err: any) {
|
||||
logError(invokingResource, cb, isPromise, err, query, parameters);
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
};
|
||||
@@ -4,7 +4,7 @@ import { parseResponse } from '../utils/parseResponse';
|
||||
import { logQuery, logError, runProfiler } from '../logger';
|
||||
import type { CFXCallback, CFXParameters } from '../types';
|
||||
import type { QueryType } from '../types';
|
||||
import { getPoolConnection } from './connection';
|
||||
import { getConnection } from './connection';
|
||||
import { RowDataPacket } from 'mysql2';
|
||||
import { performance } from 'perf_hooks';
|
||||
import validateResultSet from 'utils/validateResultSet';
|
||||
@@ -25,17 +25,17 @@ export const rawQuery = async (
|
||||
return logError(invokingResource, cb, isPromise, err, query, parameters);
|
||||
}
|
||||
|
||||
const connection = await getPoolConnection(connectionId);
|
||||
using connection = await getConnection(connectionId);
|
||||
|
||||
if (!connection) return;
|
||||
|
||||
try {
|
||||
const hasProfiler = await runProfiler(connection, invokingResource);
|
||||
const startTime = !hasProfiler && performance.now();
|
||||
const [result] = await connection.query(query, parameters);
|
||||
const result = await connection.query(query, parameters);
|
||||
|
||||
if (hasProfiler) {
|
||||
const [profiler] = <RowDataPacket[]>(
|
||||
const profiler = <RowDataPacket[]>(
|
||||
await connection.query('SELECT FORMAT(SUM(DURATION) * 1000, 4) AS `duration` FROM INFORMATION_SCHEMA.PROFILING')
|
||||
);
|
||||
|
||||
@@ -58,7 +58,5 @@ export const rawQuery = async (
|
||||
}
|
||||
} catch (err: any) {
|
||||
logError(invokingResource, cb, isPromise, err, query, parameters, true);
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getPoolConnection } from './connection';
|
||||
import { getConnection } from './connection';
|
||||
import { logError, logQuery, profileBatchStatements, runProfiler } from '../logger';
|
||||
import { CFXCallback, CFXParameters, TransactionQuery } from '../types';
|
||||
import { parseTransaction } from '../utils/parseTransaction';
|
||||
@@ -27,7 +27,7 @@ export const rawTransaction = async (
|
||||
return logError(invokingResource, cb, isPromise, err);
|
||||
}
|
||||
|
||||
const connection = await getPoolConnection();
|
||||
using connection = await getConnection();
|
||||
|
||||
if (!connection) return;
|
||||
|
||||
@@ -68,8 +68,6 @@ export const rawTransaction = async (
|
||||
err: err,
|
||||
resource: invokingResource,
|
||||
});
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
|
||||
if (cb)
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
import { getPoolConnection } from './connection';
|
||||
import { MySql, getConnection } from './connection';
|
||||
import { logError } from '../logger';
|
||||
import { CFXCallback, CFXParameters } from '../types';
|
||||
import { parseArguments } from 'utils/parseArguments';
|
||||
import { PoolConnection } from 'mysql2/promise';
|
||||
|
||||
async function runQuery(conn: PoolConnection | null, sql: string, values: CFXParameters) {
|
||||
async function runQuery(conn: MySql | null, sql: string, values: CFXParameters) {
|
||||
[sql, values] = parseArguments(sql, values);
|
||||
|
||||
try {
|
||||
if (!conn) throw new Error(`Connection used by transaction timed out after 30 seconds.`);
|
||||
|
||||
const [rows] = await conn.query(sql, values);
|
||||
return rows;
|
||||
return await conn.query(sql, values);
|
||||
} catch (err: any) {
|
||||
throw new Error(`Query: ${sql}\n${JSON.stringify(values)}\n${err.message}`);
|
||||
}
|
||||
@@ -23,30 +21,31 @@ export const startTransaction = async (
|
||||
cb?: CFXCallback,
|
||||
isPromise?: boolean
|
||||
) => {
|
||||
let conn: PoolConnection | null = await getPoolConnection();
|
||||
using conn: MySql = await getConnection();
|
||||
let response: boolean | null = false;
|
||||
let closed = false;
|
||||
|
||||
if (!conn) return;
|
||||
|
||||
setTimeout(() => (response = null), 30000);
|
||||
setTimeout(() => (closed = true), 30000);
|
||||
|
||||
try {
|
||||
await conn.beginTransaction();
|
||||
|
||||
const commit = await queries((sql: string, values: CFXParameters) =>
|
||||
runQuery(response === null ? null : conn, sql, values)
|
||||
runQuery(closed ? null : conn, sql, values)
|
||||
);
|
||||
|
||||
if (response === null) throw new Error(`Transaction has timed out after 30 seconds.`);
|
||||
if (closed) throw new Error(`Transaction has timed out after 30 seconds.`);
|
||||
|
||||
response = commit === false ? false : true;
|
||||
response ? conn.commit() : conn.rollback();
|
||||
|
||||
if (!response) conn.rollback();
|
||||
} catch (err: any) {
|
||||
conn.rollback();
|
||||
logError(invokingResource, cb, isPromise, err);
|
||||
} finally {
|
||||
conn.release();
|
||||
conn = null;
|
||||
closed = true;
|
||||
}
|
||||
|
||||
return cb ? cb(response) : response;
|
||||
|
||||
Reference in new issue
Block a user