Skip to content

Commit

Permalink
refactor(database): use mysql2/promise
Browse files Browse the repository at this point in the history
Better code-flow.
Other minor changes to config.
Remove profiling (temp).
  • Loading branch information
thelindat committed Jul 11, 2023
1 parent 32d6148 commit fa0068e
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 63 deletions.
17 changes: 6 additions & 11 deletions src/config/index.ts → src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ export let mysql_ui = GetConvar('mysql_ui', 'false') === 'true';
export let mysql_slow_query_warning = GetConvarInt('mysql_slow_query_warning', 200);
export let mysql_debug: boolean | string[];

function setDebug() {
export function setDebug() {
mysql_ui = GetConvar('mysql_ui', 'false') === 'true';
mysql_slow_query_warning = GetConvarInt('mysql_slow_query_warning', 200);

try {
const debug = GetConvar('mysql_debug', 'false');
mysql_debug = debug === 'false' ? false : JSON.parse(debug);
Expand All @@ -13,14 +16,6 @@ function setDebug() {
}
}

setDebug();

setInterval(() => {
setDebug();
mysql_ui = GetConvar('mysql_ui', 'false') === 'true';
mysql_slow_query_warning = GetConvarInt('mysql_slow_query_warning', 200);
}, 1000);

export const mysql_transaction_isolation_level = (() => {
const query = 'SET TRANSACTION ISOLATION LEVEL';
switch (GetConvarInt('mysql_transaction_isolation_level', 2)) {
Expand Down Expand Up @@ -103,7 +98,7 @@ RegisterCommand(
case 'add':
if (!Array.isArray(mysql_debug)) mysql_debug = [];
mysql_debug.push(args[1]);
SetConvar('mysql_debug', JSON.stringify(mysql_debug))
SetConvar('mysql_debug', JSON.stringify(mysql_debug));
return console.log(`^3Added ${args[1]} to mysql_debug^0`);

case 'remove':
Expand All @@ -112,7 +107,7 @@ RegisterCommand(
if (index === -1) return;
mysql_debug.splice(index, 1);
if (mysql_debug.length === 0) mysql_debug = false;
SetConvar('mysql_debug', JSON.stringify(mysql_debug) || 'false')
SetConvar('mysql_debug', JSON.stringify(mysql_debug) || 'false');
return console.log(`^3Removed ${args[1]} from mysql_debug^0`);
}

Expand Down
25 changes: 19 additions & 6 deletions src/database/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createPool, Pool } from 'mysql2';
import { connectionOptions, mysql_transaction_isolation_level } from '../config';
import { createPool, Pool } from 'mysql2/promise';
import { connectionOptions, mysql_transaction_isolation_level, setDebug } from '../config';
import { typeCast } from '../utils/typeCast';

let pool: Pool;
Expand All @@ -18,20 +18,33 @@ export async function waitForConnection() {
}
}

setTimeout(() => {
setDebug();

setInterval(() => {
setDebug();
}, 1000);

setTimeout(async () => {
pool = createPool({
connectTimeout: 60000,
trace: false,
supportBigNumbers: true,
...connectionOptions,
typeCast,
namedPlaceholders: false, // we use our own named-placeholders patch, disable mysql2s
});

pool.query(mysql_transaction_isolation_level, (err) => {
if (err) return console.error(`^3Unable to establish a connection to the database!\n^3[${err}]^0`);
const connection = await pool.getConnection();

try {
connection.query(mysql_transaction_isolation_level);
console.log(`^2Database server connection established!^0`);
isServerConnected = true;
});
} catch (err) {
console.error(`^3Unable to establish a connection to the database!\n^3[${err}]^0`);
}

connection.release()
});

export { pool, isServerConnected };
76 changes: 38 additions & 38 deletions src/database/rawExecute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,57 +30,57 @@ export const rawExecute = (
return new Promise(async (resolve, reject) => {
if (!isServerConnected) await waitForConnection();

pool.getConnection((err, connection) => {
if (err) return reject(err.message);
const connection = await pool.getConnection().catch((err) => {
return reject(err.message);
});

const parametersLength = parameters.length == 0 ? 1 : parameters.length;
if (!connection) return;

for (let index = 0; index < parametersLength; index++) {
const executionTime = process.hrtime();
const values = parameters[index];
const parametersLength = parameters.length == 0 ? 1 : parameters.length;

if (values && placeholders > values.length) {
for (let i = values.length; i < placeholders; i++) {
values[i] = null;
}
}
for (let index = 0; index < parametersLength; index++) {
const values = parameters[index];

connection.execute(query, values, (err, results: RowDataPacket[][]) => {
if (err) {
connection.release();
return reject(err.message);
}
if (values && placeholders > values.length) {
for (let i = values.length; i < placeholders; i++) {
values[i] = null;
}
}

if (cb) {
if (results.length > 1) {
for (const value of results) {
response.push(parseResponse(type, value));
}
} else response.push(parseResponse(type, results));
}
try {
const [result] = await connection.execute(query, values);

logQuery(invokingResource, query, process.hrtime(executionTime)[1] / 1e6, values as typeof parameters);
if (cb) {
if (Array.isArray(result) && result.length > 1) {
for (const value of result) {
response.push(parseResponse(type, value));
}
} else response.push(parseResponse(type, result));
}

if (index === parametersLength - 1) {
connection.release();
if (index === parametersLength - 1) {
connection.release();

if (cb) {
if (response.length === 1) {
if (unpack && type === null) {
if (response[0][0] && Object.keys(response[0][0]).length === 1) {
resolve(Object.values(response[0][0])[0]);
} else resolve(response[0][0]);
} else {
resolve(response[0]);
}
if (cb) {
if (response.length === 1) {
if (unpack && type === null) {
if (response[0][0] && Object.keys(response[0][0]).length === 1) {
resolve(Object.values(response[0][0])[0]);
} else resolve(response[0][0]);
} else {
resolve(response);
resolve(response[0]);
}
} else {
resolve(response);
}
}
});
}
} catch (err: any) {
reject(err.message);
} finally {
connection.release();
}
});
}
})
.then(async (response) => {
if (cb)
Expand Down
18 changes: 14 additions & 4 deletions src/database/rawQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { logQuery } from '../logger';
import type { CFXCallback, CFXParameters } from '../types';
import type { QueryType } from '../types';
import { scheduleTick } from '../utils/scheduleTick';
import { RowDataPacket } from 'mysql2';

export const rawQuery = (
type: QueryType,
Expand All @@ -25,12 +26,21 @@ export const rawQuery = (
return new Promise(async (resolve, reject) => {
if (!isServerConnected) await waitForConnection();

pool.query(query, parameters, (err, result, _, executionTime) => {
if (err) return reject(err);
const connection = await pool.getConnection().catch((err) => {
return reject(err.message);
});

if (!connection) return;

try {
const [result] = await connection.query(query, parameters);

logQuery(invokingResource, query, executionTime, parameters);
resolve(cb ? parseResponse(type, result) : null);
});
} catch (err) {
reject(err);
} finally {
connection.release();
}
})
.then(async (result) => {
if (cb)
Expand Down
8 changes: 4 additions & 4 deletions src/database/rawTransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,20 @@ export const rawTransaction = async (
parameters: CFXParameters,
callback?: (result: boolean) => void
) => {
if (!isServerConnected) await waitForConnection()
if (!isServerConnected) await waitForConnection();

scheduleTick();

const { transactions, cb } = parseTransaction(invokingResource, queries, parameters, callback);
const connection = await pool.promise().getConnection();
const connection = await pool.getConnection();
let response = false;

try {
await connection.beginTransaction();

for (const transaction of transactions) {
const [result, fields, executionTime] = await connection.query(transaction.query, transaction.params);
logQuery(invokingResource, transaction.query, executionTime, transaction.params);
const [result, fields] = await connection.query(transaction.query, transaction.params);
// logQuery(invokingResource, transaction.query, transaction.params);
}

await connection.commit();
Expand Down

0 comments on commit fa0068e

Please sign in to comment.