mirror of
https://github.com/darksaid98/oxmysql.git
synced 2026-12-01 14:38:50 +00:00
Merge pull request #232 from overextended/dev
This commit is contained in:
22 files changed
+1221
-814
No files matched your search
@@ -57,12 +57,10 @@ jobs:
|
||||
|
||||
- name: Bundle files
|
||||
run: |
|
||||
mkdir -p ./temp/oxmysql
|
||||
mkdir -p ./temp/oxmysql/web/
|
||||
mkdir -p ./temp/oxmysql/lib/
|
||||
mkdir -p ./temp/oxmysql/{web,lib}
|
||||
cp ./{LICENSE,README.md,fxmanifest.lua,ui.lua} ./temp/oxmysql
|
||||
cp ./lib/MySQL.lua ./temp/oxmysql/lib
|
||||
cp -r ./dist ./temp/oxmysql
|
||||
cp -r ./dist ./logger ./temp/oxmysql
|
||||
cp -r ./web/build ./temp/oxmysql/web/
|
||||
cd ./temp && zip -r ../oxmysql.zip ./oxmysql
|
||||
|
||||
|
||||
@@ -7,13 +7,13 @@ A FiveM resource to communicate with a MySQL database using [node-mysql2](https:
|
||||

|
||||

|
||||
|
||||
## 📚 Documentation
|
||||
|
||||
https://overextended.dev/oxmysql
|
||||
|
||||
## 💾 Download
|
||||
|
||||
https://github.com/overextended/oxmysql/releases/latest/download/oxmysql.zip
|
||||
## 🔗 Links
|
||||
- 💾 [Download](https://github.com/overextended/oxmysql/releases/latest/download/oxmysql.zip)
|
||||
- Download the latest release directly.
|
||||
- 📚 [Documentation](https://overextended.dev/oxmysql)
|
||||
- For installation, setup, and everything else.
|
||||
- 📦 [npm](https://www.npmjs.com/package/@overextended/oxmysql)
|
||||
- Use our npm package for enhanced functionality and TypeScript support.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
@@ -24,9 +24,9 @@ https://github.com/overextended/oxmysql/releases/latest/download/oxmysql.zip
|
||||
- Support for URI connection strings and semicolon separated values.
|
||||
- Improved parameter checking and error handling.
|
||||
|
||||
## npm Package
|
||||
## 🧾 Logging
|
||||
|
||||
https://www.npmjs.com/package/@overextended/oxmysql
|
||||
We have included a module for submitting error logs to [Fivemanage](https://fivemanage.com/?ref=overextended), a cloud management service tailored for game servers. Additional logging options and support for other services will be available in the future.
|
||||
|
||||
## Lua Language Server
|
||||
|
||||
|
||||
@@ -37,7 +37,10 @@ dependencies {
|
||||
}
|
||||
|
||||
client_script 'ui.lua'
|
||||
server_script 'dist/build.js'
|
||||
server_scripts {
|
||||
'dist/build.js',
|
||||
'logger/fivemanage.js'
|
||||
}
|
||||
|
||||
files {
|
||||
'web/build/index.html',
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// https://fivemanage.com/?ref=overextended
|
||||
|
||||
const apiKey = GetConvar('FIVEMANAGE_LOGS_API_KEY', '');
|
||||
const endpoint = 'https://api.fivemanage.com/api/logs/batch';
|
||||
|
||||
const headers = {
|
||||
['Content-Type']: 'application/json',
|
||||
['Authorization']: apiKey,
|
||||
['User-Agent']: 'oxmysql',
|
||||
};
|
||||
|
||||
const batchedLogs = [];
|
||||
|
||||
async function sendLogs() {
|
||||
try {
|
||||
const body = JSON.stringify(batchedLogs);
|
||||
batchedLogs.length = 0;
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
body: body,
|
||||
headers: headers,
|
||||
});
|
||||
|
||||
if (response.ok) return;
|
||||
|
||||
console.error(`Failed to submit logs to fivemanage - ${response.status} ${response.statusText}`);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async function logger(level, resource, message, metadata) {
|
||||
if (!apiKey) return;
|
||||
|
||||
if (batchedLogs.length === 0) setTimeout(sendLogs, 500);
|
||||
|
||||
batchedLogs.push({
|
||||
level: level,
|
||||
message: message,
|
||||
resource: resource,
|
||||
metadata: metadata,
|
||||
});
|
||||
}
|
||||
|
||||
function errorEvent(data) {
|
||||
delete data.err.sqlMessage;
|
||||
logger('error', data.resource, `${data.resource} was unable to execute a query!`, data.err);
|
||||
}
|
||||
|
||||
on('oxmysql:error', errorEvent);
|
||||
on('oxmysql:transaction-error', errorEvent);
|
||||
+9
-9
@@ -25,19 +25,19 @@
|
||||
"postinstall": "patch-package && pnpm bootstrap"
|
||||
},
|
||||
"dependencies": {
|
||||
"@citizenfx/server": "2.0.5132-1",
|
||||
"@milahu/patch-package": "^6.4.14",
|
||||
"@types/node": "^17.0.45",
|
||||
"mysql2": "3.5.1",
|
||||
"mysql2": "3.11.0",
|
||||
"named-placeholders": "^1.1.3",
|
||||
"node-fetch": "^3.3.1",
|
||||
"prettier": "^2.8.8"
|
||||
"node-fetch": "^3.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"esbuild": "^0.20.0",
|
||||
"@citizenfx/server": "2.0.5132-1",
|
||||
"@types/node": "^17.0.45",
|
||||
"esbuild": "^0.21.5",
|
||||
"lerna": "^4.0.0",
|
||||
"postinstall-postinstall": "^2.1.0",
|
||||
"pretty-quick": "^3.1.3",
|
||||
"typescript": "^5.3.3"
|
||||
"prettier": "^2.8.8",
|
||||
"pretty-quick": "^3.3.1",
|
||||
"typescript": "^5.5.4"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
# generated by patch-package 6.4.14
|
||||
#
|
||||
# declared package:
|
||||
# mysql2: 3.5.1
|
||||
# mysql2: 3.10.2
|
||||
#
|
||||
diff --git a/node_modules/mysql2/lib/connection.js b/node_modules/mysql2/lib/connection.js
|
||||
index d6ad7a4..ceac670 100644
|
||||
index 113fc7d..3a997a4 100644
|
||||
--- a/node_modules/mysql2/lib/connection.js
|
||||
+++ b/node_modules/mysql2/lib/connection.js
|
||||
@@ -32,7 +32,7 @@ const CharsetToEncoding = require('./constants/charset_encodings.js');
|
||||
@@ -16,7 +16,7 @@ index d6ad7a4..ceac670 100644
|
||||
|
||||
class Connection extends EventEmitter {
|
||||
constructor(opts) {
|
||||
@@ -521,7 +521,7 @@ class Connection extends EventEmitter {
|
||||
@@ -524,7 +524,7 @@ class Connection extends EventEmitter {
|
||||
sql: sql,
|
||||
values: values
|
||||
};
|
||||
@@ -25,7 +25,7 @@ index d6ad7a4..ceac670 100644
|
||||
return SqlString.format(
|
||||
opts.sql,
|
||||
opts.values,
|
||||
@@ -543,20 +543,20 @@ class Connection extends EventEmitter {
|
||||
@@ -546,20 +546,20 @@ class Connection extends EventEmitter {
|
||||
}
|
||||
|
||||
_resolveNamedPlaceholders(options) {
|
||||
@@ -60,7 +60,7 @@ index d6ad7a4..ceac670 100644
|
||||
}
|
||||
|
||||
query(sql, values, cb) {
|
||||
@@ -566,7 +566,7 @@ class Connection extends EventEmitter {
|
||||
@@ -569,7 +569,7 @@ class Connection extends EventEmitter {
|
||||
} else {
|
||||
cmdQuery = Connection.createQuery(sql, values, cb, this.config);
|
||||
}
|
||||
@@ -69,7 +69,7 @@ index d6ad7a4..ceac670 100644
|
||||
const rawSql = this.format(cmdQuery.sql, cmdQuery.values !== undefined ? cmdQuery.values : []);
|
||||
cmdQuery.sql = rawSql;
|
||||
return this.addCommand(cmdQuery);
|
||||
@@ -634,26 +634,27 @@ class Connection extends EventEmitter {
|
||||
@@ -644,26 +644,27 @@ class Connection extends EventEmitter {
|
||||
options.sql = sql;
|
||||
options.values = values;
|
||||
}
|
||||
@@ -128,10 +128,10 @@ index daf1df9..0862ce1 100644
|
||||
case 'number':
|
||||
type = Types.DOUBLE;
|
||||
diff --git a/node_modules/mysql2/lib/parsers/binary_parser.js b/node_modules/mysql2/lib/parsers/binary_parser.js
|
||||
index bbd2959..80ab00d 100644
|
||||
index c80bf96..da453ca 100644
|
||||
--- a/node_modules/mysql2/lib/parsers/binary_parser.js
|
||||
+++ b/node_modules/mysql2/lib/parsers/binary_parser.js
|
||||
@@ -72,7 +72,7 @@ function readCodeFor(field, config, options, fieldNum) {
|
||||
@@ -75,7 +75,7 @@ function readCodeFor(field, config, options, fieldNum) {
|
||||
|
||||
default:
|
||||
if (field.characterSet === Charsets.BINARY) {
|
||||
@@ -140,29 +140,35 @@ index bbd2959..80ab00d 100644
|
||||
}
|
||||
return `packet.readLengthCodedString(fields[${fieldNum}].encoding)`;
|
||||
}
|
||||
diff --git a/node_modules/mysql2/lib/parsers/text_parser.js b/node_modules/mysql2/lib/parsers/text_parser.js
|
||||
index 49a128c..7eafb2c 100644
|
||||
--- a/node_modules/mysql2/lib/parsers/text_parser.js
|
||||
+++ b/node_modules/mysql2/lib/parsers/text_parser.js
|
||||
@@ -85,6 +85,7 @@ function compile(fields, options, config) {
|
||||
@@ -92,6 +92,7 @@ function compile(fields, options, config) {
|
||||
db: field.schema,
|
||||
table: field.table,
|
||||
name: field.name,
|
||||
+ charset: field.characterSet,
|
||||
string: function(encoding = field.encoding) {
|
||||
string: function (encoding = field.encoding) {
|
||||
if (field.columnType === Types.JSON && encoding === field.encoding) {
|
||||
// Since for JSON columns mysql always returns charset 63 (BINARY),
|
||||
diff --git a/node_modules/mysql2/lib/pool.js b/node_modules/mysql2/lib/pool.js
|
||||
index db54a7a..f104061 100644
|
||||
--- a/node_modules/mysql2/lib/pool.js
|
||||
+++ b/node_modules/mysql2/lib/pool.js
|
||||
@@ -155,7 +155,8 @@ class Pool extends EventEmitter {
|
||||
});
|
||||
} catch (e) {
|
||||
conn.release();
|
||||
- throw e;
|
||||
+ // throw e;
|
||||
+ return cb(e);
|
||||
}
|
||||
});
|
||||
return cmdQuery;
|
||||
diff --git a/node_modules/mysql2/lib/parsers/text_parser.js b/node_modules/mysql2/lib/parsers/text_parser.js
|
||||
index f66a185..55c8b63 100644
|
||||
--- a/node_modules/mysql2/lib/parsers/text_parser.js
|
||||
+++ b/node_modules/mysql2/lib/parsers/text_parser.js
|
||||
@@ -88,6 +88,7 @@ function compile(fields, options, config) {
|
||||
db: field.schema,
|
||||
table: field.table,
|
||||
name: field.name,
|
||||
+ charset: field.characterSet,
|
||||
string: function (encoding = field.encoding) {
|
||||
if (field.columnType === Types.JSON && encoding === field.encoding) {
|
||||
// Since for JSON columns mysql always returns charset 63 (BINARY),
|
||||
diff --git a/node_modules/mysql2/typings/mysql/lib/parsers/typeCast.d.ts b/node_modules/mysql2/typings/mysql/lib/parsers/typeCast.d.ts
|
||||
index 65bfaa8..52ab677 100644
|
||||
--- a/node_modules/mysql2/typings/mysql/lib/parsers/typeCast.d.ts
|
||||
+++ b/node_modules/mysql2/typings/mysql/lib/parsers/typeCast.d.ts
|
||||
@@ -43,6 +43,7 @@ export type Field = Type & {
|
||||
db: string;
|
||||
table: string;
|
||||
name: string;
|
||||
+ charset: number;
|
||||
string: (encoding?: BufferEncoding | string | undefined) => string | null;
|
||||
buffer: () => Buffer | null;
|
||||
geometry: () => Geometry | Geometry[] | null;
|
||||
Generated
+835
-571
File diff suppressed because it is too large.
Load diff
+7
-5
@@ -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]+))?)?([^?#]+)?(?:\\?([^#]*))?$'
|
||||
@@ -55,7 +56,7 @@ const parseUri = (connectionString: string) => {
|
||||
password: authTarget[1] || undefined,
|
||||
host: splitMatchGroups[3],
|
||||
port: parseInt(splitMatchGroups[4]),
|
||||
database: splitMatchGroups[5].replace(/^\/+/, ''),
|
||||
database: splitMatchGroups[5]?.replace(/^\/+/, ''),
|
||||
...(splitMatchGroups[6] &&
|
||||
splitMatchGroups[6].split('&').reduce<Record<string, string>>((connectionInfo, parameter) => {
|
||||
const [key, value] = parameter.split('=');
|
||||
@@ -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
|
||||
@@ -105,12 +106,13 @@ export const connectionOptions = (() => {
|
||||
connectTimeout: 60000,
|
||||
trace: false,
|
||||
supportBigNumbers: true,
|
||||
jsonStrings: true,
|
||||
...options,
|
||||
typeCast,
|
||||
namedPlaceholders: false, // we use our own named-placeholders patch, disable mysql2s
|
||||
flags: flags,
|
||||
};
|
||||
})();
|
||||
}
|
||||
|
||||
RegisterCommand(
|
||||
'oxmysql_debug',
|
||||
|
||||
+66
-56
@@ -1,65 +1,75 @@
|
||||
import { createPool, Pool, PoolConnection, RowDataPacket } from 'mysql2/promise';
|
||||
import { connectionOptions, mysql_transaction_isolation_level } from '../config';
|
||||
import type { Connection, PoolConnection, TypeCast } from 'mysql2/promise';
|
||||
import { scheduleTick } from '../utils/scheduleTick';
|
||||
import { sleep } from '../utils/sleep';
|
||||
import { pool } from './pool';
|
||||
import type { CFXParameters } from 'types';
|
||||
import { typeCastExecute } from 'utils/typeCast';
|
||||
|
||||
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({
|
||||
sql: query,
|
||||
values: values,
|
||||
typeCast: typeCastExecute,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
beginTransaction() {
|
||||
this.transaction = true;
|
||||
return this.connection.beginTransaction();
|
||||
}
|
||||
|
||||
rollback() {
|
||||
delete this.transaction;
|
||||
return this.connection.rollback();
|
||||
}
|
||||
|
||||
commit() {
|
||||
delete this.transaction;
|
||||
return 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,45 @@
|
||||
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`);
|
||||
|
||||
if (config.multipleStatements) {
|
||||
console.warn(`multipleStatements is enabled. Used incorrectly, this option may cause SQL injection.\nSee https://github.com/overextended/oxmysql/issues/102)`)
|
||||
}
|
||||
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import { logError, logQuery, profileBatchStatements, runProfiler } from '../logger';
|
||||
import { logError, logQuery } from '../logger';
|
||||
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';
|
||||
import { profileBatchStatements, runProfiler } from 'profiler';
|
||||
|
||||
export const rawExecute = async (
|
||||
invokingResource: string,
|
||||
@@ -29,7 +31,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 +50,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 +89,5 @@ export const rawExecute = async (
|
||||
}
|
||||
} catch (err: any) {
|
||||
logError(invokingResource, cb, isPromise, err, query, parameters);
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
};
|
||||
@@ -1,13 +1,14 @@
|
||||
import { parseArguments } from '../utils/parseArguments';
|
||||
import { setCallback } from '../utils/setCallback';
|
||||
import { parseResponse } from '../utils/parseResponse';
|
||||
import { logQuery, logError, runProfiler } from '../logger';
|
||||
import { logQuery, logError } 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';
|
||||
import { runProfiler } from 'profiler';
|
||||
|
||||
export const rawQuery = async (
|
||||
type: QueryType,
|
||||
@@ -25,17 +26,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 +59,5 @@ export const rawQuery = async (
|
||||
}
|
||||
} catch (err: any) {
|
||||
logError(invokingResource, cb, isPromise, err, query, parameters, true);
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
};
|
||||
@@ -1,9 +1,10 @@
|
||||
import { getPoolConnection } from './connection';
|
||||
import { logError, logQuery, profileBatchStatements, runProfiler } from '../logger';
|
||||
import { getConnection } from './connection';
|
||||
import { logError, logQuery } from '../logger';
|
||||
import { CFXCallback, CFXParameters, TransactionQuery } from '../types';
|
||||
import { parseTransaction } from '../utils/parseTransaction';
|
||||
import { setCallback } from '../utils/setCallback';
|
||||
import { performance } from 'perf_hooks';
|
||||
import { profileBatchStatements, runProfiler } from 'profiler';
|
||||
|
||||
const transactionError = (queries: { query: string; params?: CFXParameters }[], parameters: CFXParameters) => {
|
||||
`${queries.map((query) => `${query.query} ${JSON.stringify(query.params || [])}`).join('\n')}\n${JSON.stringify(
|
||||
@@ -27,7 +28,7 @@ export const rawTransaction = async (
|
||||
return logError(invokingResource, cb, isPromise, err);
|
||||
}
|
||||
|
||||
const connection = await getPoolConnection();
|
||||
using connection = await getConnection();
|
||||
|
||||
if (!connection) return;
|
||||
|
||||
@@ -68,8 +69,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];
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { PoolConnection, 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';
|
||||
@@ -31,56 +30,6 @@ export function logError(
|
||||
console.error(output);
|
||||
}
|
||||
|
||||
export const profilerStatements = [
|
||||
'SET profiling_history_size = 0',
|
||||
'SET profiling = 0',
|
||||
'SET profiling_history_size = 100',
|
||||
'SET profiling = 1',
|
||||
];
|
||||
|
||||
/**
|
||||
* Executes MySQL queries to fetch accurate query profiling results when `mysql_debug` is enabled.
|
||||
*/
|
||||
export async function runProfiler(connection: PoolConnection, invokingResource: string) {
|
||||
if (!mysql_debug) return;
|
||||
|
||||
if (Array.isArray(mysql_debug) && !mysql_debug.includes(invokingResource)) return;
|
||||
|
||||
for (const statement of profilerStatements) await connection.query(statement);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function profileBatchStatements(
|
||||
connection: PoolConnection,
|
||||
invokingResource: string,
|
||||
query: string | { query: string; params?: CFXParameters }[],
|
||||
parameters: CFXParameters | null,
|
||||
offset: number
|
||||
) {
|
||||
const [profiler] = <RowDataPacket[]>(
|
||||
await connection.query(
|
||||
'SELECT FORMAT(SUM(DURATION) * 1000, 4) AS `duration` FROM INFORMATION_SCHEMA.PROFILING GROUP BY QUERY_ID'
|
||||
)
|
||||
);
|
||||
|
||||
for (const statement of profilerStatements) await connection.query(statement);
|
||||
|
||||
if (profiler.length === 0) return;
|
||||
|
||||
if (typeof query === 'string' && parameters)
|
||||
for (let i = 0; i < profiler.length; i++) {
|
||||
logQuery(invokingResource, query, parseFloat(profiler[i].duration), parameters[offset + i]);
|
||||
}
|
||||
else if (typeof query === 'object')
|
||||
for (let i = 0; i < profiler.length; i++) {
|
||||
const transaction = query[offset + i];
|
||||
if (transaction)
|
||||
logQuery(invokingResource, transaction.query, parseFloat(profiler[i].duration), transaction.params);
|
||||
else break;
|
||||
}
|
||||
}
|
||||
|
||||
interface QueryData {
|
||||
date: number;
|
||||
query: string;
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { mysql_debug } from 'config';
|
||||
import type { MySql } from 'database';
|
||||
import { logQuery } from 'logger';
|
||||
import type { RowDataPacket } from 'mysql2';
|
||||
import type { CFXParameters } from 'types';
|
||||
|
||||
const profilerStatements = [
|
||||
'SET profiling_history_size = 0',
|
||||
'SET profiling = 0',
|
||||
'SET profiling_history_size = 100',
|
||||
'SET profiling = 1',
|
||||
];
|
||||
|
||||
/**
|
||||
* Executes MySQL queries to enable accurate query profiling results when `mysql_debug` is enabled.
|
||||
*/
|
||||
export async function runProfiler(connection: MySql, invokingResource: string) {
|
||||
if (!mysql_debug) return;
|
||||
|
||||
if (Array.isArray(mysql_debug) && !mysql_debug.includes(invokingResource)) return;
|
||||
|
||||
for (const statement of profilerStatements) await connection.query(statement);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the duration of the last 100 queries and resets profiling history.
|
||||
*/
|
||||
export async function profileBatchStatements(
|
||||
connection: MySql,
|
||||
invokingResource: string,
|
||||
query: string | { query: string; params?: CFXParameters }[],
|
||||
parameters: CFXParameters | null,
|
||||
offset: number
|
||||
) {
|
||||
const profiler = <RowDataPacket[]>(
|
||||
await connection.query(
|
||||
'SELECT FORMAT(SUM(DURATION) * 1000, 4) AS `duration` FROM INFORMATION_SCHEMA.PROFILING GROUP BY QUERY_ID'
|
||||
)
|
||||
);
|
||||
|
||||
for (const statement of profilerStatements) await connection.query(statement);
|
||||
|
||||
if (profiler.length === 0) return;
|
||||
|
||||
if (typeof query === 'string' && parameters) {
|
||||
for (let i = 0; i < profiler.length; i++) {
|
||||
logQuery(invokingResource, query, parseFloat(profiler[i].duration), parameters[offset + i]);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof query === 'object') {
|
||||
for (let i = 0; i < profiler.length; i++) {
|
||||
const transaction = query[offset + i];
|
||||
|
||||
if (!transaction) break;
|
||||
|
||||
logQuery(invokingResource, transaction.query, parseFloat(profiler[i].duration), transaction.params);
|
||||
}
|
||||
}
|
||||
}
|
||||
+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;
|
||||
|
||||
+38
-18
@@ -1,41 +1,61 @@
|
||||
import { FieldPacket } from 'mysql2';
|
||||
import type { TypeCastField, TypeCastNext } from 'mysql2/promise';
|
||||
|
||||
const BINARY_CHARSET = 63;
|
||||
|
||||
type Field = {
|
||||
type: string;
|
||||
length: number;
|
||||
packet: FieldPacket;
|
||||
charset: number;
|
||||
string: () => string;
|
||||
buffer: () => number[];
|
||||
};
|
||||
|
||||
export const typeCast = (field: Field, next: () => void) => {
|
||||
/**
|
||||
* node-mysql2 v3.9.0 introduced (breaking) typecasting for execute methods.
|
||||
*/
|
||||
export function typeCastExecute(field: TypeCastField, next: TypeCastNext) {
|
||||
switch (field.type) {
|
||||
case 'DATETIME':
|
||||
case 'DATETIME2':
|
||||
case 'TIMESTAMP':
|
||||
case 'TIMESTAMP2':
|
||||
case 'NEWDATE':
|
||||
return new Date(field.string()).getTime();
|
||||
case 'DATE':
|
||||
return new Date(field.string() + ' 00:00:00').getTime();
|
||||
case 'NEWDATE': {
|
||||
const value = field.string();
|
||||
return value ? new Date(value).getTime() : null;
|
||||
}
|
||||
case 'DATE': {
|
||||
const value = field.string();
|
||||
return value ? new Date(value + ' 00:00:00').getTime() : null;
|
||||
}
|
||||
default:
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* mysql-async compatible typecasting.
|
||||
*/
|
||||
export function typeCast(field: TypeCastField, next: TypeCastNext) {
|
||||
switch (field.type) {
|
||||
case 'DATETIME':
|
||||
case 'DATETIME2':
|
||||
case 'TIMESTAMP':
|
||||
case 'TIMESTAMP2':
|
||||
case 'NEWDATE': {
|
||||
const value = field.string();
|
||||
return value ? new Date(value).getTime() : null;
|
||||
}
|
||||
case 'DATE': {
|
||||
const value = field.string();
|
||||
return value ? new Date(value + ' 00:00:00').getTime() : null;
|
||||
}
|
||||
case 'TINY':
|
||||
return field.length === 1 ? field.string() === '1' : next();
|
||||
case 'BIT':
|
||||
return field.length === 1 ? field.buffer()[0] === 1 : field.buffer()[0];
|
||||
return field.length === 1 ? field.buffer()?.[0] === 1 : field.buffer()?.[0];
|
||||
case 'TINY_BLOB':
|
||||
case 'MEDIUM_BLOB':
|
||||
case 'LONG_BLOB':
|
||||
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();
|
||||
default:
|
||||
return next();
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user