mirror of
https://github.com/darksaid98/oxmysql.git
synced 2026-12-01 14:38:50 +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
+5
-4
@@ -1,3 +1,4 @@
|
||||
import type { ConnectionOptions } from 'mysql2';
|
||||
import { typeCast } from './utils/typeCast';
|
||||
|
||||
export const mysql_connection_string = GetConvar('mysql_connection_string', '');
|
||||
@@ -39,7 +40,7 @@ export const mysql_transaction_isolation_level = (() => {
|
||||
}
|
||||
})();
|
||||
|
||||
const parseUri = (connectionString: string) => {
|
||||
function parseUri(connectionString: string) {
|
||||
const splitMatchGroups = connectionString.match(
|
||||
new RegExp(
|
||||
'^(?:([^:/?#.]+):)?(?://(?:([^/?#]*)@)?([\\w\\d\\-\\u0100-\\uffff.%]*)(?::([0-9]+))?)?([^?#]+)?(?:\\?([^#]*))?$'
|
||||
@@ -65,11 +66,11 @@ const parseUri = (connectionString: string) => {
|
||||
};
|
||||
|
||||
return options;
|
||||
};
|
||||
}
|
||||
|
||||
export let convertNamedPlaceholders: null | ((query: string, parameters: Record<string, any>) => [string, any[]]);
|
||||
|
||||
export const connectionOptions = (() => {
|
||||
export function getConnectionOptions(): ConnectionOptions {
|
||||
const options: Record<string, any> = mysql_connection_string.includes('mysql://')
|
||||
? parseUri(mysql_connection_string)
|
||||
: mysql_connection_string
|
||||
@@ -110,7 +111,7 @@ export const connectionOptions = (() => {
|
||||
namedPlaceholders: false, // we use our own named-placeholders patch, disable mysql2s
|
||||
flags: flags,
|
||||
};
|
||||
})();
|
||||
}
|
||||
|
||||
RegisterCommand(
|
||||
'oxmysql_debug',
|
||||
|
||||
+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;
|
||||
|
||||
+8
-7
@@ -1,15 +1,20 @@
|
||||
import type { CFXCallback, CFXParameters, TransactionQuery } from './types';
|
||||
import { rawQuery, rawExecute, rawTransaction, isServerConnected, waitForConnection } from './database';
|
||||
import { rawQuery, rawExecute, rawTransaction, pool } from './database';
|
||||
import { startTransaction } from 'database/startTransaction';
|
||||
import { sleep } from 'utils/sleep';
|
||||
import ghmatti from './compatibility/ghmattimysql';
|
||||
import mysqlAsync from './compatibility/mysql-async';
|
||||
import('./update');
|
||||
|
||||
const MySQL = {} as Record<string, Function>;
|
||||
|
||||
MySQL.isReady = () => {
|
||||
return isServerConnected;
|
||||
return pool ? true : false;
|
||||
};
|
||||
|
||||
MySQL.awaitConnection = async () => {
|
||||
await waitForConnection();
|
||||
while (!pool) await sleep(0);
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -118,10 +123,6 @@ function provide(resourceName: string, method: string, cb: Function) {
|
||||
on(`__cfx_export_${resourceName}_${method}`, (setCb: Function) => setCb(cb));
|
||||
}
|
||||
|
||||
import ghmatti from './compatibility/ghmattimysql';
|
||||
import mysqlAsync from './compatibility/mysql-async';
|
||||
import { startTransaction } from 'database/startTransaction';
|
||||
|
||||
for (const key in MySQL) {
|
||||
const exp = MySQL[key];
|
||||
|
||||
|
||||
+5
-5
@@ -1,7 +1,7 @@
|
||||
import { PoolConnection, RowDataPacket } from 'mysql2/promise';
|
||||
import type { RowDataPacket } from 'mysql2/promise';
|
||||
import { mysql_debug, mysql_log_size, mysql_slow_query_warning, mysql_ui } from '../config';
|
||||
import type { CFXCallback, CFXParameters } from '../types';
|
||||
import { dbVersion } from '../database';
|
||||
import { MySql, dbVersion } from '../database';
|
||||
|
||||
export function logError(
|
||||
invokingResource: string,
|
||||
@@ -41,7 +41,7 @@ export const profilerStatements = [
|
||||
/**
|
||||
* Executes MySQL queries to fetch accurate query profiling results when `mysql_debug` is enabled.
|
||||
*/
|
||||
export async function runProfiler(connection: PoolConnection, invokingResource: string) {
|
||||
export async function runProfiler(connection: MySql, invokingResource: string) {
|
||||
if (!mysql_debug) return;
|
||||
|
||||
if (Array.isArray(mysql_debug) && !mysql_debug.includes(invokingResource)) return;
|
||||
@@ -52,13 +52,13 @@ export async function runProfiler(connection: PoolConnection, invokingResource:
|
||||
}
|
||||
|
||||
export async function profileBatchStatements(
|
||||
connection: PoolConnection,
|
||||
connection: MySql,
|
||||
invokingResource: string,
|
||||
query: string | { query: string; params?: CFXParameters }[],
|
||||
parameters: CFXParameters | null,
|
||||
offset: number
|
||||
) {
|
||||
const [profiler] = <RowDataPacket[]>(
|
||||
const profiler = <RowDataPacket[]>(
|
||||
await connection.query(
|
||||
'SELECT FORMAT(SUM(DURATION) * 1000, 4) AS `duration` FROM INFORMATION_SCHEMA.PROFILING GROUP BY QUERY_ID'
|
||||
)
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
"noImplicitAny": true,
|
||||
"module": "es2020",
|
||||
"target": "es2021",
|
||||
"lib": ["es2021"],
|
||||
"lib": ["es2021", "esnext.disposable"],
|
||||
"resolveJsonModule": true,
|
||||
"esModuleInterop": true,
|
||||
"noEmit": true,
|
||||
|
||||
+9
-4
@@ -1,8 +1,13 @@
|
||||
import { RowDataPacket, ResultSetHeader, OkPacket } from 'mysql2';
|
||||
import type { OkPacket, ResultSetHeader, RowDataPacket, ProcedureCallPacket } from 'mysql2';
|
||||
|
||||
type SQLResponse = RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader;
|
||||
|
||||
export type QueryResponse = SQLResponse | SQLResponse[] | RowDataPacket;
|
||||
export type QueryResponse =
|
||||
| OkPacket
|
||||
| ResultSetHeader
|
||||
| ResultSetHeader[]
|
||||
| RowDataPacket[]
|
||||
| RowDataPacket[][]
|
||||
| OkPacket[]
|
||||
| ProcedureCallPacket;
|
||||
|
||||
export type QueryType = 'execute' | 'insert' | 'update' | 'scalar' | 'single' | null;
|
||||
|
||||
|
||||
@@ -1,30 +1,20 @@
|
||||
import { OkPacket, RowDataPacket } from 'mysql2';
|
||||
import { ResultSetHeader, RowDataPacket } from 'mysql2';
|
||||
import type { QueryResponse, QueryType } from '../types';
|
||||
|
||||
const isOkPacket = (result: QueryResponse, insertId?: boolean): result is OkPacket =>
|
||||
insertId ? (result as OkPacket).insertId !== undefined : (result as OkPacket).affectedRows !== undefined;
|
||||
|
||||
const isRowDataPacket = (result: QueryResponse): result is RowDataPacket[] =>
|
||||
(result as RowDataPacket[]).length !== undefined;
|
||||
|
||||
const isRowDataPacketArray = (result: QueryResponse): result is RowDataPacket[][] =>
|
||||
(result as RowDataPacket[][]).length !== undefined &&
|
||||
(result as RowDataPacket[][])[0] !== undefined &&
|
||||
Object.values((result as RowDataPacket[][])[0])[0] !== undefined;
|
||||
|
||||
export const parseResponse = (type: QueryType, result: QueryResponse): any => {
|
||||
switch (type) {
|
||||
case 'insert':
|
||||
return isOkPacket(result) ? result.insertId : null;
|
||||
return (result as ResultSetHeader)?.insertId || null;
|
||||
|
||||
case 'update':
|
||||
return isOkPacket(result) ? result.affectedRows : null;
|
||||
return (result as ResultSetHeader)?.affectedRows || null;
|
||||
|
||||
case 'single':
|
||||
return isRowDataPacket(result) ? result[0] : null;
|
||||
return (result as RowDataPacket[])?.[0] || null;
|
||||
|
||||
case 'scalar':
|
||||
return isRowDataPacketArray(result) ? Object.values(result[0])[0] : null;
|
||||
const row = (result as RowDataPacket[])?.[0];
|
||||
return (row && Object.values(row)[0]) || null;
|
||||
|
||||
default:
|
||||
return result || null;
|
||||
|
||||
@@ -31,7 +31,7 @@ export const typeCast = (field: Field, next: () => void) => {
|
||||
case 'BLOB':
|
||||
if (field.charset === BINARY_CHARSET) {
|
||||
const value = field.buffer();
|
||||
if (value === null) return [value]
|
||||
if (value === null) return [value];
|
||||
return [...value];
|
||||
}
|
||||
return field.string();
|
||||
|
||||
Reference in new issue
Block a user