mirror of
https://github.com/darksaid98/oxmysql.git
synced 2026-12-02 06:28:54 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af75f140ac | ||
|
|
8f7fc7bee7 | ||
|
|
64fd6249ba | ||
|
|
47a33bbba7 | ||
|
|
d54bcae363 | ||
|
|
75eedcbb09 |
No files matched your search
+2
-5
@@ -111,6 +111,7 @@ dist
|
|||||||
.vscode-test
|
.vscode-test
|
||||||
|
|
||||||
# yarn v2
|
# yarn v2
|
||||||
|
yarn.lock
|
||||||
.yarn/cache
|
.yarn/cache
|
||||||
.yarn/unplugged
|
.yarn/unplugged
|
||||||
.yarn/build-state.yml
|
.yarn/build-state.yml
|
||||||
@@ -118,8 +119,4 @@ dist
|
|||||||
.pnp.*
|
.pnp.*
|
||||||
|
|
||||||
# FiveM
|
# FiveM
|
||||||
.yarn.installed
|
.yarn.installed
|
||||||
|
|
||||||
# Wrapper
|
|
||||||
lib/MySQL.js
|
|
||||||
lib/MySQL.d.ts
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
. "$(dirname "$0")/_/husky.sh"
|
|
||||||
|
|
||||||
yarn commitlint --edit
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
. "$(dirname "$0")/_/husky.sh"
|
|
||||||
|
|
||||||
yarn pretty-quick --staged
|
|
||||||
@@ -6,6 +6,8 @@ Oxmysql is an alternative to the unmaintained mysql-async/ghmattimysql resources
|
|||||||
|
|
||||||
As of v1.9.0 the preferred method of utilising oxmysql is via lib/MySQL, which can be loaded by adding `@oxmysql/lib/MySQL.lua` to your resource manifests. This resource should be 100% backwards compatible with mysql-async functionality on top of providing newer export wrappers and functionality.
|
As of v1.9.0 the preferred method of utilising oxmysql is via lib/MySQL, which can be loaded by adding `@oxmysql/lib/MySQL.lua` to your resource manifests. This resource should be 100% backwards compatible with mysql-async functionality on top of providing newer export wrappers and functionality.
|
||||||
|
|
||||||
|
Refer to [issue #77](https://github.com/overextended/oxmysql/issues/77) for information on replacing your queries from older versions of oxmysql or ghmattimysql.
|
||||||
|
|
||||||
### Features
|
### Features
|
||||||
- Support for URI connection strings and semicolon separated values
|
- Support for URI connection strings and semicolon separated values
|
||||||
- Asynchronous queries utilising mysql2/promises connection pool
|
- Asynchronous queries utilising mysql2/promises connection pool
|
||||||
@@ -62,4 +64,4 @@ instead of using
|
|||||||
<br><br><br><br><br>
|
<br><br><br><br><br>
|
||||||
<hr>
|
<hr>
|
||||||
<p align='center'><a href='https://discord.io/overextended'>Discord</a></p>
|
<p align='center'><a href='https://discord.io/overextended'>Discord</a></p>
|
||||||
<hr>
|
<hr>
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
extends: ['@commitlint/config-conventional'],
|
|
||||||
rules: {
|
|
||||||
'subject-case': [2, 'always', 'sentence-case'],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
+3
-9
@@ -3,7 +3,7 @@ game 'common'
|
|||||||
|
|
||||||
name 'oxmysql'
|
name 'oxmysql'
|
||||||
description 'Database wrapper for FiveM utilising node-mysql2 offering improved performance and security.'
|
description 'Database wrapper for FiveM utilising node-mysql2 offering improved performance and security.'
|
||||||
version '1.9.0'
|
version '1.9.2'
|
||||||
url 'https://github.com/overextended/oxmysql'
|
url 'https://github.com/overextended/oxmysql'
|
||||||
author 'overextended'
|
author 'overextended'
|
||||||
|
|
||||||
@@ -11,14 +11,8 @@ dependencies {
|
|||||||
'/server:5104',
|
'/server:5104',
|
||||||
}
|
}
|
||||||
|
|
||||||
client_script 'ui.lua'
|
server_scripts {
|
||||||
server_script 'dist/build.js'
|
'dist/server/build.js',
|
||||||
|
|
||||||
files {
|
|
||||||
'ui/build/index.html',
|
|
||||||
'ui/build/**/*'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ui_page 'ui/build/index.html'
|
|
||||||
|
|
||||||
provide 'mysql-async'
|
provide 'mysql-async'
|
||||||
-105
@@ -1,105 +0,0 @@
|
|||||||
type Query = string | number;
|
|
||||||
type Params = Record<string, unknown> | unknown[];
|
|
||||||
type Callback<T> = (result: T | null) => void;
|
|
||||||
|
|
||||||
type Transaction = {
|
|
||||||
query: Query;
|
|
||||||
} & ({ parameters?: Params } | { values?: Params });
|
|
||||||
|
|
||||||
const Wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
||||||
const assert = (condition: boolean, message: string) => {
|
|
||||||
if (!condition) throw new TypeError(message);
|
|
||||||
};
|
|
||||||
|
|
||||||
const QueryStorage: string[] = [];
|
|
||||||
|
|
||||||
const safeArgs = (
|
|
||||||
query: Transaction[] | string[] | Query,
|
|
||||||
parameters?: Params,
|
|
||||||
cb?: Callback<any>,
|
|
||||||
transaction?: true
|
|
||||||
) => {
|
|
||||||
if (typeof query === 'number') query = QueryStorage[query];
|
|
||||||
|
|
||||||
if (transaction) assert(Array.isArray(query), `Transaction query expects an array, received ${typeof query}`);
|
|
||||||
else assert(typeof query === 'string', `Query expects a string, received ${typeof query}`);
|
|
||||||
|
|
||||||
if (parameters !== undefined)
|
|
||||||
assert(
|
|
||||||
typeof parameters === 'object' || Array.isArray(parameters),
|
|
||||||
`Params expects object or array, received ${typeof parameters}`
|
|
||||||
);
|
|
||||||
|
|
||||||
if (cb !== undefined) assert(typeof cb === 'function', `Callback expects function, received ${typeof cb}`);
|
|
||||||
|
|
||||||
return [query, parameters, cb];
|
|
||||||
};
|
|
||||||
|
|
||||||
function store(query: string) {
|
|
||||||
assert(typeof query !== 'string', `Query expects a string, received ${typeof query}`);
|
|
||||||
|
|
||||||
return QueryStorage.push(query);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ready(callback: () => void) {
|
|
||||||
setImmediate(() => {
|
|
||||||
while (GetResourceState('oxmysql') !== 'started') Wait(50);
|
|
||||||
callback();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function query<T = any>(query: Query, parameters?: Params): Promise<T | null>;
|
|
||||||
function query<T = any>(query: Query, parameters?: Params, cb?: Callback<T>): void;
|
|
||||||
function query<T = any>(query: Query, parameters?: Params, cb?: Callback<T>): Promise<T | null> | void {
|
|
||||||
if (cb) return exports.oxmysql.query(...safeArgs(query, parameters, cb));
|
|
||||||
return exports.oxmysql.query_async(...safeArgs(query, parameters));
|
|
||||||
}
|
|
||||||
|
|
||||||
function single<T = Record<string | number, any>>(query: Query, parameters?: Params): Promise<T | null>;
|
|
||||||
function single<T = Record<string | number, any>>(query: Query, parameters?: Params, cb?: Callback<T>): void;
|
|
||||||
function single<T = Record<string | number, any>>(
|
|
||||||
query: Query,
|
|
||||||
parameters?: Params,
|
|
||||||
cb?: Callback<T>
|
|
||||||
): Promise<T | null> | void {
|
|
||||||
if (cb) return exports.oxmysql.single(...safeArgs(query, parameters, cb));
|
|
||||||
return exports.oxmysql.single_async(...safeArgs(query, parameters));
|
|
||||||
}
|
|
||||||
|
|
||||||
function scalar<T = unknown>(query: Query, parameters?: Params): Promise<T | null>;
|
|
||||||
function scalar<T = unknown>(query: Query, parameters?: Params, cb?: Callback<T>): void;
|
|
||||||
function scalar<T = unknown>(query: Query, parameters?: Params, cb?: Callback<T>): Promise<T | null> | void {
|
|
||||||
if (cb) return exports.oxmysql.scalar(...safeArgs(query, parameters, cb));
|
|
||||||
return exports.oxmysql.scalar_async(...safeArgs(query, parameters));
|
|
||||||
}
|
|
||||||
|
|
||||||
function update(query: Query, parameters?: Params): Promise<number | null>;
|
|
||||||
function update(query: Query, parameters?: Params, cb?: Callback<number>): void;
|
|
||||||
function update(query: Query, parameters?: Params, cb?: Callback<number>): Promise<number | null> | void {
|
|
||||||
if (cb) return exports.oxmysql.update(...safeArgs(query, parameters, cb));
|
|
||||||
return exports.oxmysql.update_async(...safeArgs(query, parameters));
|
|
||||||
}
|
|
||||||
|
|
||||||
function insert(query: Query, parameters?: Params): Promise<number | null>;
|
|
||||||
function insert(query: Query, parameters?: Params, cb?: Callback<number>): void;
|
|
||||||
function insert(query: Query, parameters?: Params, cb?: Callback<number>): Promise<number | null> | void {
|
|
||||||
if (cb) return exports.oxmysql.insert(...safeArgs(query, parameters, cb));
|
|
||||||
return exports.oxmysql.insert_async(...safeArgs(query, parameters));
|
|
||||||
}
|
|
||||||
|
|
||||||
function prepare<T = unknown>(query: Query, parameters?: Params): Promise<T | null>;
|
|
||||||
function prepare<T = unknown>(query: Query, parameters?: Params, cb?: Callback<T>): void;
|
|
||||||
function prepare<T = unknown>(query: Query, parameters?: Params, cb?: Callback<T>): Promise<T | null> | void {
|
|
||||||
if (cb) return exports.oxmysql.prepare(...safeArgs(query, parameters, cb));
|
|
||||||
return exports.oxmysql.prepare_async(...safeArgs(query, parameters));
|
|
||||||
}
|
|
||||||
|
|
||||||
function transaction(query: Query, parameters?: Params): Promise<boolean>;
|
|
||||||
function transaction(query: Query, parameters?: Params, cb?: Callback<boolean>): void;
|
|
||||||
function transaction(query: Query, parameters?: Params, cb?: Callback<boolean>): Promise<boolean> | void {
|
|
||||||
if (cb) return exports.oxmysql.transaction(...safeArgs(query, parameters, cb, true));
|
|
||||||
return exports.oxmysql.transaction_async(...safeArgs(query, parameters, undefined, true));
|
|
||||||
}
|
|
||||||
|
|
||||||
export { store, query, single, scalar, update, insert, transaction, prepare, ready };
|
|
||||||
export default { store, query, single, scalar, update, insert, transaction, prepare, ready };
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
--- EmmyLua Annotations / VSCode Lua Language Server
|
|
||||||
--- https://marketplace.visualstudio.com/items?itemName=sumneko.lua
|
|
||||||
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters? table|function
|
|
||||||
---@param cb? function
|
|
||||||
---@return number affectedRows
|
|
||||||
function MySQL.update(query, parameters, cb) end
|
|
||||||
MySQL.Async.execute = MySQL.update
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters? table
|
|
||||||
---@return number affectedRows
|
|
||||||
function MySQL.update.await(query, parameters) end
|
|
||||||
MySQL.Sync.execute = MySQL.update.await
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters? table|function
|
|
||||||
---@param cb? function
|
|
||||||
---@return table<unknown, unknown> | nil result
|
|
||||||
function MySQL.query(query, parameters, cb) end
|
|
||||||
MySQL.Async.fetchAll = MySQL.query
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters? table
|
|
||||||
---@return table<unknown, unknown> | nil result
|
|
||||||
function MySQL.query.await(query, parameters) end
|
|
||||||
MySQL.Sync.fetchAll = MySQL.query.await
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters? table|function
|
|
||||||
---@param cb? function
|
|
||||||
---@return any column
|
|
||||||
function MySQL.scalar(query, parameters, cb) end
|
|
||||||
MySQL.Async.fetchScalar = MySQL.scalar
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters? table
|
|
||||||
---@return any column
|
|
||||||
function MySQL.scalar.await(query, parameters) end
|
|
||||||
MySQL.Sync.fetchScalar = MySQL.scalar.await
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters? table|function
|
|
||||||
---@param cb? function
|
|
||||||
---@return table<string, any> row
|
|
||||||
function MySQL.single(query, parameters, cb) end
|
|
||||||
MySQL.Async.fetchSingle = MySQL.single
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters? table
|
|
||||||
---@return table<string, any> row
|
|
||||||
function MySQL.single.await(query, parameters) end
|
|
||||||
MySQL.Sync.fetchSingle = MySQL.single.await
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters? table|function
|
|
||||||
---@param cb? function
|
|
||||||
---@return number insertId
|
|
||||||
function MySQL.insert(query, parameters, cb) end
|
|
||||||
MySQL.Async.insert = MySQL.insert
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters? table
|
|
||||||
---@return number insertId
|
|
||||||
function MySQL.insert.async(query, parameters) end
|
|
||||||
MySQL.Sync.insert = MySQL.insert.await
|
|
||||||
|
|
||||||
---@param queries table
|
|
||||||
---@param parameters? table|function
|
|
||||||
---@param cb? function
|
|
||||||
---@return boolean success
|
|
||||||
function MySQL.transaction(queries, parameters, cb) end
|
|
||||||
MySQL.Async.transaction = MySQL.transaction
|
|
||||||
|
|
||||||
---@param queries table
|
|
||||||
---@param parameters? table
|
|
||||||
---@return boolean success
|
|
||||||
function MySQL.transaction.await(queries, parameters) end
|
|
||||||
MySQL.Sync.transaction = MySQL.transaction.await
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters table
|
|
||||||
---@param cb? function
|
|
||||||
---@return unknown result
|
|
||||||
function MySQL.prepare(query, parameters, cb) end
|
|
||||||
MySQL.Async.prepare = MySQL.prepare
|
|
||||||
|
|
||||||
---@param query string
|
|
||||||
---@param parameters table
|
|
||||||
---@return unknown result
|
|
||||||
function MySQL.prepare.await(query, parameters) end
|
|
||||||
MySQL.Sync.prepare = MySQL.prepare.await
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"module": "CommonJS",
|
|
||||||
"target": "ESNext",
|
|
||||||
"moduleResolution": "node",
|
|
||||||
"types": ["@citizenfx/server", "@types/node"],
|
|
||||||
"declaration": true
|
|
||||||
},
|
|
||||||
"files": ["MySQL.ts"]
|
|
||||||
}
|
|
||||||
+11
-26
@@ -4,35 +4,20 @@
|
|||||||
"description": "FXServer to MySQL communication via node-mysql2",
|
"description": "FXServer to MySQL communication via node-mysql2",
|
||||||
"repository": "[email protected]:overextended/oxmysql.git",
|
"repository": "[email protected]:overextended/oxmysql.git",
|
||||||
"author": "dunak-debug <[email protected]>",
|
"author": "dunak-debug <[email protected]>",
|
||||||
"license": "LGPL-3.0-or-later",
|
"license": "GPL-3.0-or-later",
|
||||||
"main": "lib/MySQL.js",
|
"type": "module",
|
||||||
"types": "lib/MySQL.d.ts",
|
"private": true,
|
||||||
"files": [
|
|
||||||
"lib/MySQL.js",
|
|
||||||
"lib/MySQL.d.ts"
|
|
||||||
],
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "esbuild --bundle --platform=node --target=node16.9.1 src/index.ts --outfile=dist/build.js",
|
"build": "esbuild --bundle --platform=node --target=node16.9.1 src/server/index.js --outfile=dist/server/build.js",
|
||||||
"watch": "esbuild --watch --bundle --platform=node --target=node16.9.1 src/index.ts --outfile=dist/build.js",
|
"watch": "esbuild --watch --bundle --platform=node --target=node16.9.1 src/server/index.js --outfile=dist/server/build.js",
|
||||||
"lib": "tsc --project lib/tsconfig.lib.json",
|
"postinstall": "patch-package"
|
||||||
"postinstall": "patch-package",
|
|
||||||
"prepare": "husky install"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@citizenfx/server": "^2.0.5132-1",
|
"@citizenfx/server": "latest",
|
||||||
"@types/node": "^17.0.4",
|
|
||||||
"mysql2": "^2.3.3",
|
|
||||||
"node-fetch": "^3.1.0",
|
|
||||||
"prettier": "^2.5.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@commitlint/cli": "^16.0.2",
|
|
||||||
"@commitlint/config-conventional": "^16.0.0",
|
|
||||||
"esbuild": "^0.14.7",
|
"esbuild": "^0.14.7",
|
||||||
"husky": "^7.0.0",
|
"mysql2": "^2.3.3",
|
||||||
"patch-package": "^6.4.7",
|
"patch-package": "^6.4.7",
|
||||||
"postinstall-postinstall": "^2.1.0",
|
"postinstall-postinstall": "^2.1.0"
|
||||||
"pretty-quick": "^3.1.3",
|
},
|
||||||
"typescript": "^4.5.4"
|
"devDependencies": {}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -192,7 +192,7 @@ index c612f66..02dbe22 100644
|
|||||||
case 'number':
|
case 'number':
|
||||||
type = Types.DOUBLE;
|
type = Types.DOUBLE;
|
||||||
diff --git a/node_modules/mysql2/promise.d.ts b/node_modules/mysql2/promise.d.ts
|
diff --git a/node_modules/mysql2/promise.d.ts b/node_modules/mysql2/promise.d.ts
|
||||||
index 6ab3d6f..64246e8 100644
|
index 6ab3d6f..68bc9cb 100644
|
||||||
--- a/node_modules/mysql2/promise.d.ts
|
--- a/node_modules/mysql2/promise.d.ts
|
||||||
+++ b/node_modules/mysql2/promise.d.ts
|
+++ b/node_modules/mysql2/promise.d.ts
|
||||||
@@ -25,41 +25,15 @@ export interface Connection extends EventEmitter {
|
@@ -25,41 +25,15 @@ export interface Connection extends EventEmitter {
|
||||||
@@ -257,10 +257,9 @@ index 6ab3d6f..64246e8 100644
|
|||||||
- query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader>(
|
- query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader>(
|
||||||
- options: QueryOptions,
|
- options: QueryOptions,
|
||||||
- values: any | any[] | { [param: string]: any }
|
- values: any | any[] | { [param: string]: any }
|
||||||
- ): Promise<[T, FieldPacket[]]>;
|
|
||||||
+ sql_or_options: string | QueryOptions,
|
+ sql_or_options: string | QueryOptions,
|
||||||
+ values?: any | any[] | { [param: string]: any },
|
+ values?: any | any[] | { [param: string]: any },
|
||||||
+ ): Promise<[T, FieldPacket[], number]>;
|
): Promise<[T, FieldPacket[]]>;
|
||||||
|
|
||||||
execute<
|
execute<
|
||||||
T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader
|
T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader
|
||||||
|
|||||||
@@ -1,41 +0,0 @@
|
|||||||
export const resourceName = GetCurrentResourceName();
|
|
||||||
export const scheduleTick = () => ScheduleResourceTick(resourceName);
|
|
||||||
|
|
||||||
export const mysql_debug = GetConvar('mysql_debug', 'false') === 'true';
|
|
||||||
export const mysql_ui = GetConvar('mysql_ui', 'false') === 'true';
|
|
||||||
export const mysql_slow_query_warning = GetConvarInt('mysql_slow_query_warning', 200);
|
|
||||||
export const mysql_connection_string = GetConvar('mysql_connection_string', '');
|
|
||||||
|
|
||||||
export const mysql_transaction_isolation_level = (() => {
|
|
||||||
const query = 'SET TRANSACTION ISOLATION LEVEL';
|
|
||||||
switch (GetConvarInt('mysql_transaction_isolation_level', 2)) {
|
|
||||||
case 1:
|
|
||||||
return `${query} REPEATABLE READ`;
|
|
||||||
case 2:
|
|
||||||
return `${query} READ COMMITTED`;
|
|
||||||
case 3:
|
|
||||||
return `${query} READ UNCOMMITTED`;
|
|
||||||
case 4:
|
|
||||||
return `${query} SERIALIZABLE`;
|
|
||||||
default:
|
|
||||||
return `${query} READ COMMITTED`;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
export const connectionOptions = (() => {
|
|
||||||
if (mysql_connection_string.includes('mysql://')) return { uri: mysql_connection_string };
|
|
||||||
|
|
||||||
const options = mysql_connection_string
|
|
||||||
.replace(/(?:host(?:name)|ip|server|data\s?source|addr(?:ess)?)=/gi, 'host=')
|
|
||||||
.replace(/(?:user\s?(?:id|name)?|uid)=/gi, 'user=')
|
|
||||||
.replace(/(?:pwd|pass)=/gi, 'password=')
|
|
||||||
.replace(/(?:db)=/gi, 'database=')
|
|
||||||
.split(';')
|
|
||||||
.reduce<Record<string, string>>((connectionInfo, parameter) => {
|
|
||||||
const [key, value] = parameter.split('=');
|
|
||||||
connectionInfo[key] = value;
|
|
||||||
return connectionInfo;
|
|
||||||
}, {});
|
|
||||||
|
|
||||||
return options;
|
|
||||||
})();
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import { createPool, QueryError } from 'mysql2/promise';
|
|
||||||
import { connectionOptions, mysql_transaction_isolation_level } from '../config';
|
|
||||||
import { typeCast } from '../utils/typeCast';
|
|
||||||
|
|
||||||
const pool = createPool({
|
|
||||||
connectTimeout: 60000,
|
|
||||||
...connectionOptions,
|
|
||||||
typeCast,
|
|
||||||
});
|
|
||||||
|
|
||||||
pool
|
|
||||||
.query(mysql_transaction_isolation_level)
|
|
||||||
.then(() => console.log(`^2Database server connection established!^0`))
|
|
||||||
.catch((e: QueryError) =>
|
|
||||||
setInterval(() => console.error(`^3Unable to establish a connection to the database! [${e.code}]\n${e.message}^0`), 5000)
|
|
||||||
);
|
|
||||||
|
|
||||||
export { pool };
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
import { QueryError } from 'mysql2';
|
|
||||||
import { pool } from '.';
|
|
||||||
import { scheduleTick } from '../config';
|
|
||||||
import { logQuery } from '../logger';
|
|
||||||
import { CFXCallback, CFXParameters, QueryResponse } from '../types';
|
|
||||||
import { parseExecute } from '../utils/parseExecute';
|
|
||||||
|
|
||||||
export const rawExecute = async (
|
|
||||||
invokingResource: string,
|
|
||||||
query: string,
|
|
||||||
parameters: CFXParameters | CFXParameters[],
|
|
||||||
cb?: CFXCallback
|
|
||||||
) => {
|
|
||||||
const type = parseExecute(query);
|
|
||||||
|
|
||||||
if (!type) throw new Error(`Prepared statements only accept SELECT, INSERT, UPDATE, and DELETE methods!`);
|
|
||||||
|
|
||||||
if (!Array.isArray(parameters))
|
|
||||||
throw new Error(`Parameters expected an array but received ${typeof parameters} instead`);
|
|
||||||
|
|
||||||
scheduleTick();
|
|
||||||
|
|
||||||
const connection = await pool.getConnection();
|
|
||||||
let result: QueryResponse;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const executionTime = process.hrtime();
|
|
||||||
|
|
||||||
if (!parameters.every(Array.isArray)) parameters = [[...parameters]];
|
|
||||||
|
|
||||||
const results = [];
|
|
||||||
|
|
||||||
for (const params of parameters) {
|
|
||||||
results.push((await connection.execute(query, params))[0]);
|
|
||||||
|
|
||||||
logQuery(invokingResource, query, process.hrtime(executionTime)[1] / 1e6, params as typeof parameters);
|
|
||||||
}
|
|
||||||
|
|
||||||
result = results;
|
|
||||||
|
|
||||||
//TODO any giggle
|
|
||||||
if (results.length === 1) {
|
|
||||||
if (type === 'execute') {
|
|
||||||
if ((results as any)[0][0] && Object.keys((results as any)[0][0]).length === 1)
|
|
||||||
result = Object.values((results as any)[0][0])[0] as any;
|
|
||||||
else result = (results as any)[0][0];
|
|
||||||
} else {
|
|
||||||
result = results[0];
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
result = results;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cb) return result;
|
|
||||||
} catch (e) {
|
|
||||||
throw new Error(`${invokingResource} was unable to execute a query!
|
|
||||||
${(e as QueryError).message}
|
|
||||||
${(e as any).sql || `${query} ${JSON.stringify(parameters)}`}`);
|
|
||||||
} finally {
|
|
||||||
connection.release();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cb) cb(result);
|
|
||||||
};
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
import { pool } from '.';
|
|
||||||
import { parseArguments } from '../utils/parseArguments';
|
|
||||||
import { scheduleTick } from '../config';
|
|
||||||
import { parseResponse } from '../utils/parseResponse';
|
|
||||||
import { logQuery } from '../logger';
|
|
||||||
import type { CFXCallback, CFXParameters } from '../types';
|
|
||||||
import type { QueryType } from '../types';
|
|
||||||
|
|
||||||
export const rawQuery = async (type: QueryType, invokingResource: string, query: string, parameters: CFXParameters, cb?: CFXCallback) => {
|
|
||||||
scheduleTick();
|
|
||||||
|
|
||||||
try {
|
|
||||||
[query, parameters, cb] = parseArguments(invokingResource, query, parameters, cb);
|
|
||||||
|
|
||||||
const [result, _, executionTime] = await pool.query(query, parameters);
|
|
||||||
|
|
||||||
logQuery(invokingResource, query, executionTime, parameters);
|
|
||||||
|
|
||||||
const response = parseResponse(type, result);
|
|
||||||
|
|
||||||
return cb ? cb(response) : response;
|
|
||||||
} catch (e) {
|
|
||||||
throw new Error(
|
|
||||||
`${invokingResource} was unable to execute a query!\n${(e as Error).message}\n${
|
|
||||||
(e as any).sql || `${query} ${JSON.stringify(parameters)}`
|
|
||||||
}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
import { pool } from '.';
|
|
||||||
import { scheduleTick } from '../config';
|
|
||||||
import { logQuery } from '../logger';
|
|
||||||
import { CFXParameters, TransactionQuery } from '../types';
|
|
||||||
import { parseTransaction } from '../utils/parseTransaction';
|
|
||||||
|
|
||||||
const transactionError = (queries: { query: string; params: CFXParameters }[], parameters: CFXParameters) =>
|
|
||||||
`${queries.map((query) => `${query.query} ${JSON.stringify(query.params || [])}`).join('\n')}\n${JSON.stringify(parameters)}`;
|
|
||||||
|
|
||||||
export const rawTransaction = async (
|
|
||||||
invokingResource: string,
|
|
||||||
queries: TransactionQuery[] | string[],
|
|
||||||
parameters: CFXParameters,
|
|
||||||
callback?: (result: boolean) => void
|
|
||||||
) => {
|
|
||||||
scheduleTick();
|
|
||||||
|
|
||||||
const { transactions, cb } = parseTransaction(invokingResource, queries, parameters, callback);
|
|
||||||
|
|
||||||
const connection = await pool.getConnection();
|
|
||||||
|
|
||||||
try {
|
|
||||||
const executionTime = process.hrtime();
|
|
||||||
|
|
||||||
await connection.beginTransaction();
|
|
||||||
|
|
||||||
for (const transaction of transactions) await connection.query(transaction.query, transaction.params);
|
|
||||||
|
|
||||||
await connection.commit();
|
|
||||||
|
|
||||||
logQuery(invokingResource, 'TRANSACTION', process.hrtime(executionTime)[1] / 1e6, parameters);
|
|
||||||
|
|
||||||
return cb ? cb(true) : true;
|
|
||||||
} catch (e) {
|
|
||||||
await connection.rollback();
|
|
||||||
|
|
||||||
console.error(
|
|
||||||
`${invokingResource} was unable to execute a transaction!\n${(e as Error).message}\n${
|
|
||||||
(e as any).sql || `${transactionError(transactions, parameters)}`
|
|
||||||
}^0`
|
|
||||||
);
|
|
||||||
|
|
||||||
return cb ? cb(false) : false;
|
|
||||||
} finally {
|
|
||||||
connection.release();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
import { CFXCallback, CFXParameters, TransactionQuery } from './types';
|
|
||||||
import { rawQuery } from './database/rawQuery';
|
|
||||||
import { rawTransaction } from './database/rawTransaction';
|
|
||||||
import { rawExecute } from './database/rawExecute';
|
|
||||||
|
|
||||||
//TODO
|
|
||||||
import('./update');
|
|
||||||
|
|
||||||
global.exports(
|
|
||||||
'query',
|
|
||||||
(query: string, parameters: CFXParameters, cb: CFXCallback, invokingResource = GetInvokingResource()) => {
|
|
||||||
rawQuery(null, invokingResource, query, parameters, cb);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports('query_async', (query: string, parameters: CFXParameters, invokingResource = GetInvokingResource()) =>
|
|
||||||
rawQuery(null, invokingResource, query, parameters)
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports(
|
|
||||||
'single',
|
|
||||||
(query: string, parameters: CFXParameters, cb: CFXCallback, invokingResource = GetInvokingResource()) => {
|
|
||||||
rawQuery('single', invokingResource, query, parameters, cb);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports('single_async', (query: string, parameters: CFXParameters, invokingResource = GetInvokingResource()) =>
|
|
||||||
rawQuery('single', invokingResource, query, parameters)
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports(
|
|
||||||
'scalar',
|
|
||||||
(query: string, parameters: CFXParameters, cb: CFXCallback, invokingResource = GetInvokingResource()) => {
|
|
||||||
rawQuery('scalar', invokingResource, query, parameters, cb);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports('scalar_async', (query: string, parameters: CFXParameters, invokingResource = GetInvokingResource()) =>
|
|
||||||
rawQuery('scalar', invokingResource, query, parameters)
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports(
|
|
||||||
'update',
|
|
||||||
(query: string, parameters: CFXParameters, cb: CFXCallback, invokingResource = GetInvokingResource()) => {
|
|
||||||
rawQuery('update', invokingResource, query, parameters, cb);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports('update_async', (query: string, parameters: CFXParameters, invokingResource = GetInvokingResource()) =>
|
|
||||||
rawQuery('update', invokingResource, query, parameters)
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports(
|
|
||||||
'insert',
|
|
||||||
(query: string, parameters: CFXParameters, cb: CFXCallback, invokingResource = GetInvokingResource()) => {
|
|
||||||
rawQuery('insert', invokingResource, query, parameters, cb);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports('insert_async', (query: string, parameters: CFXParameters, invokingResource = GetInvokingResource()) =>
|
|
||||||
rawQuery('insert', invokingResource, query, parameters)
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports(
|
|
||||||
'transaction',
|
|
||||||
(
|
|
||||||
queries: TransactionQuery[] | string[],
|
|
||||||
parameters: CFXParameters,
|
|
||||||
cb: (result: boolean) => void,
|
|
||||||
invokingResource = GetInvokingResource()
|
|
||||||
) => {
|
|
||||||
rawTransaction(invokingResource, queries, parameters, cb);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports(
|
|
||||||
'transaction_async',
|
|
||||||
(queries: TransactionQuery[] | string[], parameters: CFXParameters, invokingResource = GetInvokingResource()) =>
|
|
||||||
rawTransaction(invokingResource, queries, parameters)
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports(
|
|
||||||
'prepare',
|
|
||||||
(
|
|
||||||
query: string,
|
|
||||||
parameters: CFXParameters | CFXParameters[],
|
|
||||||
cb: CFXCallback,
|
|
||||||
invokingResource = GetInvokingResource()
|
|
||||||
) => {
|
|
||||||
rawExecute(invokingResource, query, parameters, cb);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
global.exports(
|
|
||||||
'prepare_async',
|
|
||||||
(query: string, parameters: CFXParameters | CFXParameters[], invokingResource = GetInvokingResource()) =>
|
|
||||||
rawExecute(invokingResource, query, parameters)
|
|
||||||
);
|
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
import { mysql_debug, mysql_slow_query_warning, mysql_ui } from '../config';
|
|
||||||
import type { CFXParameters } from '../types';
|
|
||||||
|
|
||||||
interface QueryData {
|
|
||||||
date: number;
|
|
||||||
query: string;
|
|
||||||
executionTime: number;
|
|
||||||
slow?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
type QueryLog = Record<string, QueryData[]>;
|
|
||||||
|
|
||||||
const logStorage: QueryLog = {};
|
|
||||||
|
|
||||||
export const logQuery = (invokingResource: string, query: string, executionTime: number, parameters: CFXParameters) => {
|
|
||||||
if (executionTime >= mysql_slow_query_warning || mysql_debug)
|
|
||||||
console.log(
|
|
||||||
`^3[${mysql_debug ? 'DEBUG' : 'WARNING'}] ${invokingResource} took ${executionTime}ms to execute a query!
|
|
||||||
${query} ${JSON.stringify(parameters)}^0`
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!mysql_ui) return;
|
|
||||||
|
|
||||||
if (logStorage[invokingResource] === undefined) logStorage[invokingResource] = [];
|
|
||||||
logStorage[invokingResource].push({
|
|
||||||
query,
|
|
||||||
executionTime,
|
|
||||||
date: Date.now(),
|
|
||||||
slow: executionTime >= mysql_slow_query_warning ? true : undefined,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
RegisterCommand(
|
|
||||||
'mysql',
|
|
||||||
(source: number) => {
|
|
||||||
if (!mysql_ui) return;
|
|
||||||
|
|
||||||
let totalQueries: number = 0;
|
|
||||||
let totalTime = 0;
|
|
||||||
let slowQueries = 0;
|
|
||||||
let chartData: [
|
|
||||||
{
|
|
||||||
x: number; // Number of queries
|
|
||||||
y: number; // Execution time
|
|
||||||
z: string; // Resource name
|
|
||||||
}
|
|
||||||
] = [
|
|
||||||
{
|
|
||||||
x: 0,
|
|
||||||
y: 0,
|
|
||||||
z: '',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const resource in logStorage) {
|
|
||||||
const queries = logStorage[resource];
|
|
||||||
let totalResourceTime = 0;
|
|
||||||
|
|
||||||
totalQueries += queries.length;
|
|
||||||
totalTime += queries.reduce((totalTime, query) => (totalTime += query.executionTime), 0);
|
|
||||||
slowQueries += queries.reduce((slowQueries, query) => (slowQueries += query.slow ? 1 : 0), 0);
|
|
||||||
totalResourceTime += queries.reduce((totalResourceTime, query) => (totalResourceTime += query.executionTime), 0);
|
|
||||||
chartData.push({ x: queries.length, y: totalResourceTime, z: resource });
|
|
||||||
}
|
|
||||||
|
|
||||||
emitNet(`oxmysql:openUi`, source, {
|
|
||||||
resources: Object.keys(logStorage),
|
|
||||||
totalQueries,
|
|
||||||
slowQueries,
|
|
||||||
totalTime,
|
|
||||||
chartData,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
true
|
|
||||||
);
|
|
||||||
|
|
||||||
const sortQueries = (queries: QueryData[], sort: { id: 'query' | 'executionTime'; desc: boolean }) => {
|
|
||||||
const sortedQueries = [...queries].sort((a, b) => {
|
|
||||||
switch (sort.id) {
|
|
||||||
case 'query':
|
|
||||||
return a.query > b.query ? 1 : -1;
|
|
||||||
case 'executionTime':
|
|
||||||
return a.executionTime - b.executionTime;
|
|
||||||
default:
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return sort.desc ? sortedQueries.reverse() : sortedQueries;
|
|
||||||
};
|
|
||||||
|
|
||||||
onNet(
|
|
||||||
`oxmysql:fetchResource`,
|
|
||||||
(data: { resource: string; pageIndex: number; sortBy?: { id: 'query' | 'executionTime'; desc: boolean }[] }) => {
|
|
||||||
if (typeof data.resource !== 'string') return;
|
|
||||||
|
|
||||||
const sort = data.sortBy ? data.sortBy[0] : false;
|
|
||||||
|
|
||||||
const startRow = data.pageIndex * 12;
|
|
||||||
const endRow = startRow + 12;
|
|
||||||
const queries = sort
|
|
||||||
? sortQueries(logStorage[data.resource], sort).slice(startRow, endRow)
|
|
||||||
: logStorage[data.resource].slice(startRow, endRow);
|
|
||||||
const pageCount = Math.ceil(logStorage[data.resource].length / 12);
|
|
||||||
|
|
||||||
if (!queries) return;
|
|
||||||
|
|
||||||
emitNet(`oxmysql:loadResource`, source, { queries, pageCount });
|
|
||||||
}
|
|
||||||
);
|
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
export const resourceName = GetCurrentResourceName();
|
||||||
|
|
||||||
|
export const mysql_debug = GetConvar('mysql_debug', 'false') === 'true';
|
||||||
|
export const mysql_slow_query_warning = GetConvarInt('mysql_slow_query_warning', 200);
|
||||||
|
export const mysql_connection_string = GetConvar('mysql_connection_string', '');
|
||||||
|
|
||||||
|
export const mysql_transaction_isolation_level = (() => {
|
||||||
|
const query = 'SET TRANSACTION ISOLATION LEVEL';
|
||||||
|
switch (GetConvarInt('mysql_transaction_isolation_level', 2)) {
|
||||||
|
case 1:
|
||||||
|
return `${query} REPEATABLE READ`;
|
||||||
|
case 2:
|
||||||
|
return `${query} READ COMMITTED`;
|
||||||
|
case 3:
|
||||||
|
return `${query} READ UNCOMMITTED`;
|
||||||
|
case 4:
|
||||||
|
return `${query} SERIALIZABLE`;
|
||||||
|
default:
|
||||||
|
return `${query} READ COMMITTED`;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
export const typeCast = (field, next) => {
|
||||||
|
switch (field.type) {
|
||||||
|
case 'DATETIME':
|
||||||
|
case 'DATETIME2':
|
||||||
|
case 'TIMESTAMP':
|
||||||
|
case 'TIMESTAMP2':
|
||||||
|
case 'NEWDATE':
|
||||||
|
case 'DATE':
|
||||||
|
return field.type === 'DATE' ? new Date(field.string() + ' 00:00:00').getTime() : new Date(field.string()).getTime();
|
||||||
|
case 'TINY':
|
||||||
|
return field.length === 1 ? field.string() === '1' : next();
|
||||||
|
case 'BIT':
|
||||||
|
return field.buffer()[0] === 1;
|
||||||
|
default:
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
const hrtime = require('process').hrtime;
|
||||||
|
import { mysql_debug, mysql_slow_query_warning } from '../config.js';
|
||||||
|
import { isReady, scheduleTick, serverReady, preparedTypes, response } from '../utils.js';
|
||||||
|
import pool from './pool.js';
|
||||||
|
|
||||||
|
export default async (invokingResource, query, parameters, cb) => {
|
||||||
|
if (!isReady) serverReady();
|
||||||
|
const type = preparedTypes(query);
|
||||||
|
if (!type) throw new Error(`Prepared statements only accept SELECT, INSERT, UPDATE, and DELETE methods!`);
|
||||||
|
|
||||||
|
scheduleTick();
|
||||||
|
const connection = await pool.getConnection();
|
||||||
|
let results = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
let queryCount = parameters.length;
|
||||||
|
let executionTime = hrtime();
|
||||||
|
|
||||||
|
if (typeof parameters[0] !== 'object') {
|
||||||
|
queryCount = 1;
|
||||||
|
const [result] = await connection.execute(query, parameters);
|
||||||
|
results[0] = response(type, result);
|
||||||
|
} else {
|
||||||
|
for (let i = 0; i < queryCount; i++) {
|
||||||
|
const [result] = await connection.execute(query, parameters[i]);
|
||||||
|
results[i] = response(type, result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
executionTime = hrtime(executionTime)[1] / 1000000;
|
||||||
|
|
||||||
|
if (results.length === 1) {
|
||||||
|
if (type === 'execute') {
|
||||||
|
if (results[0][0] && Object.keys(results[0][0]).length === 1) results = Object.values(results[0][0])[0];
|
||||||
|
else results = results[0][0];
|
||||||
|
} else {
|
||||||
|
results = results[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (executionTime >= mysql_slow_query_warning || mysql_debug)
|
||||||
|
console.log(
|
||||||
|
`^3[${mysql_debug ? 'DEBUG' : 'WARNING'}] ${invokingResource} took ${executionTime}ms to execute ${
|
||||||
|
queryCount > 1 ? queryCount + ' queries' : 'a query'
|
||||||
|
}!
|
||||||
|
${query} ${JSON.stringify(parameters)}^0`
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error(`${invokingResource} was unable to execute a query!
|
||||||
|
${err.message}
|
||||||
|
${err.sql || `${query} ${JSON.stringify(parameters)}`}`);
|
||||||
|
} finally {
|
||||||
|
connection.release();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cb) cb(results);
|
||||||
|
else return results;
|
||||||
|
};
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { createPool } from 'mysql2/promise';
|
||||||
|
import { mysql_connection_string, mysql_transaction_isolation_level, typeCast } from '../config.js';
|
||||||
|
|
||||||
|
const connectionString = (() => {
|
||||||
|
if (mysql_connection_string === '') throw new Error(`^1Missing mysql_connection_string in server.cfg! Refer to the documentation^0`);
|
||||||
|
|
||||||
|
if (mysql_connection_string.includes('mysql://')) return { uri: mysql_connection_string };
|
||||||
|
|
||||||
|
const options = mysql_connection_string
|
||||||
|
.replace(/(?:host(?:name)|ip|server|data\s?source|addr(?:ess)?)=/gi, 'host=')
|
||||||
|
.replace(/(?:user\s?(?:id|name)?|uid)=/gi, 'user=')
|
||||||
|
.replace(/(?:pwd|pass)=/gi, 'password=')
|
||||||
|
.replace(/(?:db)=/gi, 'database=')
|
||||||
|
.split(';')
|
||||||
|
.reduce((connectionInfo, parameter) => {
|
||||||
|
const [key, value] = parameter.split('=');
|
||||||
|
connectionInfo[key] = value;
|
||||||
|
return connectionInfo;
|
||||||
|
}, {});
|
||||||
|
|
||||||
|
return options;
|
||||||
|
})();
|
||||||
|
|
||||||
|
const pool = createPool({
|
||||||
|
typeCast: typeCast,
|
||||||
|
connectTimeout: 60000,
|
||||||
|
...connectionString,
|
||||||
|
});
|
||||||
|
|
||||||
|
pool
|
||||||
|
.query(mysql_transaction_isolation_level)
|
||||||
|
.then(() => {
|
||||||
|
console.log(`^2Database server connection established!^0`);
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error(`^3Unable to establish a connection to the database! [${err.code}]\n${err.message}^0`);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default pool;
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { mysql_debug, mysql_slow_query_warning } from '../config.js';
|
||||||
|
import { isReady, scheduleTick, serverReady, parseArguments, response } from '../utils.js';
|
||||||
|
import pool from './pool.js';
|
||||||
|
|
||||||
|
export default async (type, invokingResource, query, parameters, cb) => {
|
||||||
|
if (!isReady) serverReady();
|
||||||
|
let result, executionTime;
|
||||||
|
|
||||||
|
try {
|
||||||
|
[query, parameters, cb] = parseArguments(invokingResource, query, parameters, cb);
|
||||||
|
scheduleTick();
|
||||||
|
|
||||||
|
[result, _, executionTime] = await pool.query(query, parameters);
|
||||||
|
|
||||||
|
if (executionTime >= mysql_slow_query_warning || mysql_debug)
|
||||||
|
console.log(
|
||||||
|
`^3[${mysql_debug ? 'DEBUG' : 'WARNING'}] ${invokingResource} took ${executionTime}ms to execute a query!
|
||||||
|
${query} ${JSON.stringify(parameters)}^0`
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error(`${invokingResource} was unable to execute a query!
|
||||||
|
${err.message}
|
||||||
|
${err.sql || `${query} ${JSON.stringify(parameters)}`}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cb) cb(response(type, result));
|
||||||
|
else return response(type, result);
|
||||||
|
};
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { mysql_debug, mysql_slow_query_warning } from '../config.js';
|
||||||
|
import { isReady, parseTransaction, scheduleTick, serverReady } from '../utils.js';
|
||||||
|
import pool from './pool.js';
|
||||||
|
const hrtime = require('process').hrtime;
|
||||||
|
|
||||||
|
const transactionError = (queries, parameters) =>
|
||||||
|
`${queries
|
||||||
|
.map((query) =>
|
||||||
|
typeof query === 'string' ? query : `${query.query} ${JSON.stringify(query.values || query.parameters || [])}`
|
||||||
|
)
|
||||||
|
.join('\n')}\n${JSON.stringify(parameters)}`;
|
||||||
|
|
||||||
|
export default async (invokingResource, queries, parameters, cb) => {
|
||||||
|
if (!isReady) serverReady();
|
||||||
|
scheduleTick();
|
||||||
|
const connection = await pool.getConnection();
|
||||||
|
let result;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsedQuery = parseTransaction(invokingResource, queries, parameters);
|
||||||
|
let queryCount = parsedQuery.length;
|
||||||
|
let executionTime = hrtime();
|
||||||
|
|
||||||
|
await connection.beginTransaction();
|
||||||
|
|
||||||
|
for (let i = 0; i < queryCount; i++) {
|
||||||
|
await connection.query(parsedQuery[i].query, parsedQuery[i].params);
|
||||||
|
}
|
||||||
|
|
||||||
|
await connection.commit();
|
||||||
|
|
||||||
|
executionTime = hrtime(executionTime)[1] / 1000000;
|
||||||
|
if (executionTime >= mysql_slow_query_warning || mysql_debug)
|
||||||
|
console.log(
|
||||||
|
`^3[${
|
||||||
|
mysql_debug ? 'DEBUG' : 'WARNING'
|
||||||
|
}] ${invokingResource} took ${executionTime}ms to execute a transaction!\n${transactionError(
|
||||||
|
queries,
|
||||||
|
parameters
|
||||||
|
)}^0`
|
||||||
|
);
|
||||||
|
|
||||||
|
result = true;
|
||||||
|
if (parameters && typeof parameters === 'function') cb = parameters;
|
||||||
|
} catch (error) {
|
||||||
|
await connection.rollback();
|
||||||
|
console.log(
|
||||||
|
`^1[ERROR] ${invokingResource} was unable to execute a transaction!
|
||||||
|
${error.message}
|
||||||
|
${error.sql || `${transactionError(queries, parameters)}`}^0`
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
connection.release();
|
||||||
|
}
|
||||||
|
if (cb) cb(result);
|
||||||
|
else return result;
|
||||||
|
};
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import sql_execute from './db/execute.js';
|
||||||
|
import sql_query from './db/query.js';
|
||||||
|
import sql_transaction from './db/transaction.js';
|
||||||
|
|
||||||
|
let deprecated = (invokingResource) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
console.log(
|
||||||
|
`^3[WARNING] ${invokingResource} triggered a deprecated function! Exports from prior to v1.9.0 will be removed in a future update.
|
||||||
|
Refer to the readme for information on updating.^0`
|
||||||
|
);
|
||||||
|
}, 500);
|
||||||
|
deprecated = undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
global.exports('execute', (query, parameters, cb, invokingResource = GetInvokingResource()) => {
|
||||||
|
if (deprecated !== undefined) deprecated(invokingResource);
|
||||||
|
sql_query('', invokingResource, query, parameters, cb);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('executeSync', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
if (deprecated !== undefined) deprecated(invokingResource);
|
||||||
|
return sql_query('', invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('singleSync', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
if (deprecated !== undefined) deprecated(invokingResource);
|
||||||
|
return sql_query('single', invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
global.exports('scalarSync', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
if (deprecated !== undefined) deprecated(invokingResource);
|
||||||
|
return sql_query('scalar', invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('updateSync', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
if (deprecated !== undefined) deprecated(invokingResource);
|
||||||
|
return sql_query('update', invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('insertSync', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
if (deprecated !== undefined) deprecated(invokingResource);
|
||||||
|
return sql_query('insert', invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('transactionSync', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
if (deprecated !== undefined) deprecated(invokingResource);
|
||||||
|
return sql_transaction(invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('prepareSync', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
if (deprecated !== undefined) deprecated(invokingResource);
|
||||||
|
return sql_execute(invokingResource, query, parameters);
|
||||||
|
});
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import sql_execute from './db/execute.js';
|
||||||
|
import sql_query from './db/query.js';
|
||||||
|
import sql_transaction from './db/transaction.js';
|
||||||
|
require('./versioncheck.js');
|
||||||
|
require('./deprecated.js');
|
||||||
|
|
||||||
|
global.exports('query', (query, parameters, cb, invokingResource = GetInvokingResource()) => {
|
||||||
|
sql_query('', invokingResource, query, parameters, cb);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('query_async', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
return sql_query('', invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('single', (query, parameters, cb, invokingResource = GetInvokingResource()) => {
|
||||||
|
sql_query('single', invokingResource, query, parameters, cb);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('single_async', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
return sql_query('single', invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('scalar', (query, parameters, cb, invokingResource = GetInvokingResource()) => {
|
||||||
|
sql_query('scalar', invokingResource, query, parameters, cb);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('scalar_async', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
return sql_query('scalar', invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('update', (query, parameters, cb, invokingResource = GetInvokingResource()) => {
|
||||||
|
sql_query('update', invokingResource, query, parameters, cb);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('update_async', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
return sql_query('update', invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('insert', (query, parameters, cb, invokingResource = GetInvokingResource()) => {
|
||||||
|
sql_query('insert', invokingResource, query, parameters, cb);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('insert_async', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
return sql_query('insert', invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('transaction', (query, parameters, cb, invokingResource = GetInvokingResource()) => {
|
||||||
|
sql_transaction(invokingResource, query, parameters, cb);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('transaction_async', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
return sql_transaction(invokingResource, query, parameters);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('prepare', (query, parameters, cb, invokingResource = GetInvokingResource()) => {
|
||||||
|
sql_execute(invokingResource, query, parameters, cb);
|
||||||
|
});
|
||||||
|
|
||||||
|
global.exports('prepare_async', (query, parameters, invokingResource = GetInvokingResource()) => {
|
||||||
|
return sql_execute(invokingResource, query, parameters);
|
||||||
|
});
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import { resourceName } from './config.js';
|
||||||
|
const convertNamedPlaceholders = require('named-placeholders')();
|
||||||
|
|
||||||
|
export const scheduleTick = () => {
|
||||||
|
ScheduleResourceTick(resourceName);
|
||||||
|
};
|
||||||
|
|
||||||
|
export let isReady = false;
|
||||||
|
let callbacks = [];
|
||||||
|
|
||||||
|
export let serverReady = async () => {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
if (callbacks.length === 0) {
|
||||||
|
callbacks.push(resolve);
|
||||||
|
const id = setInterval(() => {
|
||||||
|
if (GetResourceState(resourceName) == 'started') {
|
||||||
|
for (let i = 1; i < callbacks.length; i++) {
|
||||||
|
callbacks[i]();
|
||||||
|
}
|
||||||
|
resolve(id);
|
||||||
|
}
|
||||||
|
}, 50);
|
||||||
|
} else callbacks.push(resolve);
|
||||||
|
}).then((id) => {
|
||||||
|
if (id) {
|
||||||
|
clearInterval(id);
|
||||||
|
isReady = true;
|
||||||
|
serverReady = undefined;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseArguments = (invokingResource, query, parameters, cb) => {
|
||||||
|
if (typeof query !== 'string') throw new Error(`Query expected a string but received ${typeof query} instead`);
|
||||||
|
|
||||||
|
if (
|
||||||
|
parameters &&
|
||||||
|
typeof parameters === 'object' &&
|
||||||
|
!Array.isArray(parameters) &&
|
||||||
|
(query.includes(':') || query.includes('@'))
|
||||||
|
) {
|
||||||
|
const placeholders = convertNamedPlaceholders(query, parameters);
|
||||||
|
query = placeholders[0];
|
||||||
|
parameters = placeholders[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cb && typeof cb !== 'function') {
|
||||||
|
cb = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parameters && typeof parameters === 'function') {
|
||||||
|
cb = parameters;
|
||||||
|
parameters = [];
|
||||||
|
} else if (parameters === null || parameters === undefined) parameters = [];
|
||||||
|
|
||||||
|
if (!Array.isArray(parameters)) {
|
||||||
|
let arr = [];
|
||||||
|
Object.entries(parameters).forEach((entry) => {
|
||||||
|
const [key, value] = entry;
|
||||||
|
arr[key - 1] = value;
|
||||||
|
});
|
||||||
|
parameters = arr;
|
||||||
|
} else {
|
||||||
|
const queryParams = query.match(/\?(?!\?)/g);
|
||||||
|
|
||||||
|
if (queryParams !== null) {
|
||||||
|
if (parameters.length === 0) {
|
||||||
|
for (let i = 0; i < queryParams.length; i++) parameters[i] = null;
|
||||||
|
return [query, parameters, cb];
|
||||||
|
}
|
||||||
|
const diff = queryParams.length - parameters.length;
|
||||||
|
|
||||||
|
if (diff > 0) {
|
||||||
|
for (let i = 0; i < diff; i++) parameters[queryParams.length + i] = null;
|
||||||
|
} else if (diff < 0) {
|
||||||
|
throw new Error(`${invokingResource} was unable to execute a query!
|
||||||
|
Expected ${queryParams.length} parameters, but received ${parameters.length}.
|
||||||
|
${`${query} ${JSON.stringify(parameters)}`}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [query, parameters, cb];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseTransaction = (invokingResource, queries, parameters) => {
|
||||||
|
if (!Array.isArray(queries)) throw new Error(`Transaction queries must be array type`);
|
||||||
|
|
||||||
|
const parsedTransaction = queries.map((query) => {
|
||||||
|
const [parsedQuery, parsedParameters] = parseArguments(
|
||||||
|
invokingResource,
|
||||||
|
typeof query === 'object' ? query.query : query,
|
||||||
|
(typeof query === 'object' && (query.parameters || query.values)) || parameters || []
|
||||||
|
);
|
||||||
|
return { query: parsedQuery, params: parsedParameters };
|
||||||
|
});
|
||||||
|
|
||||||
|
return parsedTransaction;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const response = (type, result) => {
|
||||||
|
switch (type) {
|
||||||
|
case 'insert':
|
||||||
|
return result && result.insertId;
|
||||||
|
|
||||||
|
case 'update':
|
||||||
|
return result && result.affectedRows;
|
||||||
|
|
||||||
|
case 'scalar':
|
||||||
|
return result && result[0] && Object.values(result[0])[0];
|
||||||
|
|
||||||
|
case 'single':
|
||||||
|
return result && result[0];
|
||||||
|
|
||||||
|
default:
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const preparedTypes = (query) => {
|
||||||
|
switch (query.replace(/\s.*/, '')) {
|
||||||
|
case 'SELECT':
|
||||||
|
return 'execute';
|
||||||
|
case 'INSERT':
|
||||||
|
return 'insert';
|
||||||
|
case 'UPDATE':
|
||||||
|
return 'update';
|
||||||
|
case 'DELETE':
|
||||||
|
return 'update';
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { resourceName } from './config';
|
||||||
|
const https = require('https');
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
https
|
||||||
|
.request(
|
||||||
|
{
|
||||||
|
hostname: 'raw.githubusercontent.com',
|
||||||
|
port: 443,
|
||||||
|
path: '/overextended/oxmysql/main/lua/fxmanifest.lua',
|
||||||
|
method: 'GET',
|
||||||
|
},
|
||||||
|
(res) => {
|
||||||
|
if (res.statusCode === 200) {
|
||||||
|
res.on('data', (data) => {
|
||||||
|
let currentVersion = GetResourceMetadata(resourceName, 'version', 0).match(/(\d)\.(\d+)\.(\d+)/);
|
||||||
|
let latestVersion = data.toString().match(/(\d)\.(\d+)\.(\d+)/);
|
||||||
|
if (currentVersion[0] !== latestVersion[0]) {
|
||||||
|
let update;
|
||||||
|
|
||||||
|
if (currentVersion[1] < latestVersion[1]) update = 'a major update';
|
||||||
|
else if (currentVersion[2] < latestVersion[2]) update = 'an update';
|
||||||
|
else if (currentVersion[3] < latestVersion[3]) update = 'a patch';
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`^3There is ${update} available for oxmysql - please update to the latest release (current version: ${currentVersion[0]})\r\nhttps://github.com/overextended/oxmysql/releases/download/v${latestVersion[0]}/oxmysql-v${latestVersion[0]}.zip^0`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.end();
|
||||||
|
}, 1000);
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"strict": true,
|
|
||||||
"lib": ["ESNext"],
|
|
||||||
"module": "CommonJS",
|
|
||||||
"target": "ESNext",
|
|
||||||
"moduleResolution": "node",
|
|
||||||
"types": ["@citizenfx/server", "@types/node"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import { RowDataPacket, ResultSetHeader, OkPacket } from 'mysql2';
|
|
||||||
|
|
||||||
type SQLResponse = RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader;
|
|
||||||
|
|
||||||
export type QueryResponse = SQLResponse | SQLResponse[] | RowDataPacket;
|
|
||||||
|
|
||||||
export type QueryType = 'insert' | 'update' | 'scalar' | 'single' | null;
|
|
||||||
|
|
||||||
export type TransactionQuery = {
|
|
||||||
query: string;
|
|
||||||
parameters?: CFXParameters;
|
|
||||||
values?: CFXParameters;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type CFXParameters = Record<string, unknown> | unknown[];
|
|
||||||
|
|
||||||
export type CFXCallback = (result: QueryResponse | number | null) => void;
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
import fetch from 'node-fetch';
|
|
||||||
import { resourceName } from '../config';
|
|
||||||
|
|
||||||
setTimeout(async () => {
|
|
||||||
const response = await fetch(`https://raw.githubusercontent.com/overextended/oxmysql/main/lua/fxmanifest.lua`);
|
|
||||||
|
|
||||||
if (response.status !== 200) return;
|
|
||||||
|
|
||||||
const manifest = await response.text();
|
|
||||||
|
|
||||||
const currentVersion = GetResourceMetadata(resourceName, 'version', 0).match(/(\d)\.(\d+)\.(\d+)/);
|
|
||||||
if (!currentVersion) return;
|
|
||||||
|
|
||||||
const latestVersion = manifest.match(/(\d)\.(\d+)\.(\d+)/);
|
|
||||||
if (!latestVersion) return;
|
|
||||||
|
|
||||||
if (currentVersion[0] === latestVersion[0]) return;
|
|
||||||
|
|
||||||
const updateMessage =
|
|
||||||
currentVersion[3] < latestVersion[3] ? 'patch' : currentVersion[2] < latestVersion[2] ? 'an update' : 'a major update';
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
`^3There is ${updateMessage} available for oxmysql - please update to the latest release (current version: ${currentVersion[0]})\r\nhttps://github.com/overextended/oxmysql/releases/download/v${latestVersion[0]}/oxmysql-v${latestVersion[0]}.zip^0`
|
|
||||||
);
|
|
||||||
}, 1000);
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
import type { CFXCallback, CFXParameters } from '../types';
|
|
||||||
|
|
||||||
const convertNamedPlaceholders = require('named-placeholders')();
|
|
||||||
|
|
||||||
export const parseArguments = (
|
|
||||||
invokingResource: string,
|
|
||||||
query: string,
|
|
||||||
parameters?: CFXParameters,
|
|
||||||
cb?: CFXCallback
|
|
||||||
): [string, CFXParameters, CFXCallback | undefined] => {
|
|
||||||
if (typeof query !== 'string') throw new Error(`Query expected a string but received ${typeof query} instead`);
|
|
||||||
|
|
||||||
const queryParams = query.match(/\?(?!\?)/g);
|
|
||||||
|
|
||||||
if (query.includes(':') || query.includes('@')) {
|
|
||||||
const placeholders = convertNamedPlaceholders(query, parameters);
|
|
||||||
query = placeholders[0];
|
|
||||||
parameters = placeholders[1];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cb && typeof cb !== 'function') cb = undefined;
|
|
||||||
|
|
||||||
if (parameters && typeof parameters === 'function') cb = parameters;
|
|
||||||
|
|
||||||
if (parameters === null || parameters === undefined || typeof parameters === 'function') parameters = [];
|
|
||||||
|
|
||||||
if (!Array.isArray(parameters)) {
|
|
||||||
let arr: unknown[] = [];
|
|
||||||
Object.entries(parameters).forEach((entry) => (arr[parseInt(entry[0]) - 1] = entry[1]));
|
|
||||||
parameters = arr;
|
|
||||||
} else if (queryParams !== null) {
|
|
||||||
if (parameters.length === 0) {
|
|
||||||
for (let i = 0; i < queryParams.length; i++) parameters[i] = null;
|
|
||||||
return [query, parameters, cb];
|
|
||||||
}
|
|
||||||
const diff = queryParams.length - parameters.length;
|
|
||||||
|
|
||||||
if (diff > 0) {
|
|
||||||
for (let i = 0; i < diff; i++) parameters[queryParams.length + i] = null;
|
|
||||||
} else if (diff < 0) {
|
|
||||||
throw new Error(`${invokingResource} was unable to execute a query!
|
|
||||||
Expected ${queryParams.length} parameters, but received ${parameters.length}.
|
|
||||||
${`${query} ${JSON.stringify(parameters)}`}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return [query, parameters, cb];
|
|
||||||
};
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
export const parseExecute = (query: string) => {
|
|
||||||
switch (query.replace(/\s.*/, '')) {
|
|
||||||
case 'SELECT':
|
|
||||||
return 'execute';
|
|
||||||
case 'INSERT':
|
|
||||||
return 'insert';
|
|
||||||
case 'UPDATE':
|
|
||||||
return 'update';
|
|
||||||
case 'DELETE':
|
|
||||||
return 'update';
|
|
||||||
default:
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import { OkPacket, 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): QueryResponse | number | null => {
|
|
||||||
switch (type) {
|
|
||||||
case 'insert':
|
|
||||||
return isOkPacket(result) ? result.insertId : null;
|
|
||||||
|
|
||||||
case 'update':
|
|
||||||
return isOkPacket(result) ? result.affectedRows : null;
|
|
||||||
|
|
||||||
case 'single':
|
|
||||||
return isRowDataPacket(result) ? result[0] : null;
|
|
||||||
|
|
||||||
case 'scalar':
|
|
||||||
return isRowDataPacketArray(result) ? Object.values(result[0])[0] : null;
|
|
||||||
|
|
||||||
default:
|
|
||||||
return result || null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
import { CFXCallback, CFXParameters, TransactionQuery } from '../types';
|
|
||||||
import { parseArguments } from './parseArguments';
|
|
||||||
|
|
||||||
const isTransactionQuery = (query: TransactionQuery | string): query is TransactionQuery => (query as TransactionQuery).query !== undefined;
|
|
||||||
|
|
||||||
export const parseTransaction = (
|
|
||||||
invokingResource: string,
|
|
||||||
queries: TransactionQuery[] | string[],
|
|
||||||
parameters: CFXParameters,
|
|
||||||
cb?: (result: boolean) => void
|
|
||||||
) => {
|
|
||||||
if (!Array.isArray(queries)) throw new Error(`Transaction queries must be array type`);
|
|
||||||
|
|
||||||
if (cb && typeof cb !== 'function') cb = undefined;
|
|
||||||
|
|
||||||
if (parameters && typeof parameters === 'function') cb = parameters;
|
|
||||||
|
|
||||||
if (parameters === null || parameters === undefined || typeof parameters === 'function') parameters = [];
|
|
||||||
|
|
||||||
const transactions = queries.map((query) => {
|
|
||||||
const [parsedQuery, parsedParameters] = parseArguments(
|
|
||||||
invokingResource,
|
|
||||||
isTransactionQuery(query) ? query.query : query,
|
|
||||||
isTransactionQuery(query) ? query.parameters || query.values : parameters || []
|
|
||||||
);
|
|
||||||
return { query: parsedQuery, params: parsedParameters };
|
|
||||||
});
|
|
||||||
|
|
||||||
return { transactions, cb };
|
|
||||||
};
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
type Field = {
|
|
||||||
type: string;
|
|
||||||
length: number;
|
|
||||||
string: () => string;
|
|
||||||
buffer: () => number[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export const typeCast = (field: Field, next: () => void) => {
|
|
||||||
switch (field.type) {
|
|
||||||
case 'DATETIME':
|
|
||||||
case 'DATETIME2':
|
|
||||||
case 'TIMESTAMP':
|
|
||||||
case 'TIMESTAMP2':
|
|
||||||
case 'NEWDATE':
|
|
||||||
case 'DATE':
|
|
||||||
return field.type === 'DATE' ? new Date(field.string() + ' 00:00:00').getTime() : new Date(field.string()).getTime();
|
|
||||||
case 'TINY':
|
|
||||||
return field.length === 1 ? field.string() === '1' : next();
|
|
||||||
case 'BIT':
|
|
||||||
return field.buffer()[0] === 1;
|
|
||||||
default:
|
|
||||||
return next();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
RegisterNetEvent('oxmysql:openUi', function(data)
|
|
||||||
SendNUIMessage({
|
|
||||||
action = 'openUI',
|
|
||||||
data = data
|
|
||||||
})
|
|
||||||
SetNuiFocus(true, true)
|
|
||||||
end)
|
|
||||||
|
|
||||||
RegisterNUICallback('exit', function(_, cb)
|
|
||||||
cb(true)
|
|
||||||
SetNuiFocus(false, false)
|
|
||||||
end)
|
|
||||||
|
|
||||||
RegisterNUICallback('fetchResource', function(data, cb)
|
|
||||||
TriggerServerEvent('oxmysql:fetchResource', data)
|
|
||||||
cb(true)
|
|
||||||
end)
|
|
||||||
|
|
||||||
RegisterNetEvent('oxmysql:loadResource', function(data)
|
|
||||||
SendNUIMessage({
|
|
||||||
action = 'loadResource',
|
|
||||||
data = data
|
|
||||||
})
|
|
||||||
end)
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
|
||||||
|
|
||||||
# dependencies
|
|
||||||
/node_modules
|
|
||||||
/.pnp
|
|
||||||
.pnp.js
|
|
||||||
|
|
||||||
# testing
|
|
||||||
/coverage
|
|
||||||
|
|
||||||
# production
|
|
||||||
/build
|
|
||||||
|
|
||||||
# misc
|
|
||||||
.DS_Store
|
|
||||||
.env.local
|
|
||||||
.env.development.local
|
|
||||||
.env.test.local
|
|
||||||
.env.production.local
|
|
||||||
|
|
||||||
npm-debug.log*
|
|
||||||
yarn-debug.log*
|
|
||||||
yarn-error.log*
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
const path = require("path");
|
|
||||||
module.exports = {
|
|
||||||
webpack: {
|
|
||||||
configure: (webpackConfig) => {
|
|
||||||
// Because CEF has issues with loading source maps properly atm,
|
|
||||||
// lets use the best we can get in line with `eval-source-map`
|
|
||||||
if (webpackConfig.mode === 'development' && process.env.IN_GAME_DEV) {
|
|
||||||
webpackConfig.devtool = 'eval-source-map'
|
|
||||||
webpackConfig.output.path = path.join(__dirname, 'build')
|
|
||||||
}
|
|
||||||
|
|
||||||
return webpackConfig
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
devServer: (devServerConfig) => {
|
|
||||||
if (process.env.IN_GAME_DEV) {
|
|
||||||
// Used for in-game dev mode
|
|
||||||
devServerConfig.devMiddleware.writeToDisk = true
|
|
||||||
}
|
|
||||||
|
|
||||||
return devServerConfig
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "ui",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"homepage": "ui/build",
|
|
||||||
"private": true,
|
|
||||||
"dependencies": {
|
|
||||||
"@chakra-ui/icons": "^1.1.1",
|
|
||||||
"@chakra-ui/react": "^1.7.3",
|
|
||||||
"@emotion/react": "^11",
|
|
||||||
"@emotion/styled": "^11",
|
|
||||||
"@types/jest": "^26.0.24",
|
|
||||||
"@types/node": "^16.11.18",
|
|
||||||
"@types/react": "^17.0.38",
|
|
||||||
"@types/react-dom": "^17.0.11",
|
|
||||||
"@types/react-table": "^7.7.9",
|
|
||||||
"framer-motion": "4.1.17",
|
|
||||||
"react": "^17.0.2",
|
|
||||||
"react-dom": "^17.0.2",
|
|
||||||
"react-router-dom": "6",
|
|
||||||
"react-scripts": "5.0.0",
|
|
||||||
"react-table": "^7.7.0",
|
|
||||||
"typescript": "^4.5.4",
|
|
||||||
"victory": "^36.2.0"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"start": "cross-env PUBLIC_URL=/ craco start",
|
|
||||||
"start:game": "cross-env IN_GAME_DEV=1 craco start",
|
|
||||||
"build": "rimraf build && craco build",
|
|
||||||
"test": "craco test",
|
|
||||||
"eject": "react-scripts eject"
|
|
||||||
},
|
|
||||||
"eslintConfig": {
|
|
||||||
"extends": [
|
|
||||||
"react-app",
|
|
||||||
"react-app/jest"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"browserslist": {
|
|
||||||
"production": [
|
|
||||||
">0.2%",
|
|
||||||
"not dead",
|
|
||||||
"not op_mini all"
|
|
||||||
],
|
|
||||||
"development": [
|
|
||||||
"last 1 chrome version",
|
|
||||||
"last 1 firefox version",
|
|
||||||
"last 1 safari version"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@craco/craco": "^6.4.3",
|
|
||||||
"cross-env": "^7.0.3",
|
|
||||||
"rimraf": "^3.0.2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
||||||
<meta name="theme-color" content="#000000" />
|
|
||||||
<title>NUI React Boilerplate</title>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
|
||||||
<div id="root"></div>
|
|
||||||
<!--
|
|
||||||
This HTML file is a template.
|
|
||||||
If you open it directly in the browser, you will see an empty page.
|
|
||||||
|
|
||||||
You can add webfonts, meta tags, or analytics to this file.
|
|
||||||
The build step will place the bundled scripts into the <body> tag.
|
|
||||||
|
|
||||||
To begin the development, run `npm start` or `yarn start`.
|
|
||||||
To create a production bundle, use `npm run build` or `yarn build`.
|
|
||||||
-->
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
import { Center, Box } from '@chakra-ui/react';
|
|
||||||
import { debugData } from '../utils/debugData';
|
|
||||||
import TopBar from './NavBars/TopBar';
|
|
||||||
import LeftBar from './NavBars/LeftBar';
|
|
||||||
import { Routes, Route, useNavigate } from 'react-router-dom';
|
|
||||||
import Resource from './Resource';
|
|
||||||
import RightBar from './NavBars/RightBar';
|
|
||||||
import MainContent from './MainContent';
|
|
||||||
import { useNuiEvent } from '../hooks/useNuiEvent';
|
|
||||||
|
|
||||||
debugData([
|
|
||||||
{
|
|
||||||
action: 'openUI',
|
|
||||||
data: {
|
|
||||||
resources: ['ox_inventory', 'luke_garages', 'es_extended'],
|
|
||||||
totalQueries: 732,
|
|
||||||
totalTime: 258,
|
|
||||||
slowQueries: 6,
|
|
||||||
chartData: [
|
|
||||||
{ x: 13, y: 350, z: 'ox_inventory' },
|
|
||||||
{ x: 27, y: 752, z: 'es_extended' },
|
|
||||||
{ x: 41, y: 52, z: 'luke_garages' },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
const App: React.FC = () => {
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
useNuiEvent('openUI', () => navigate('/'));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Center w="100%" h="100%">
|
|
||||||
<Box
|
|
||||||
width="60%"
|
|
||||||
height="50%"
|
|
||||||
backgroundColor="#191E26"
|
|
||||||
borderRadius="1vh"
|
|
||||||
color="white"
|
|
||||||
fontFamily="Poppins"
|
|
||||||
userSelect="none"
|
|
||||||
>
|
|
||||||
<TopBar />
|
|
||||||
<LeftBar />
|
|
||||||
<RightBar />
|
|
||||||
<MainContent>
|
|
||||||
<Routes>
|
|
||||||
<Route path="/:resource" element={<Resource />} />
|
|
||||||
<Route path="/" element={<></>} />
|
|
||||||
</Routes>
|
|
||||||
</MainContent>
|
|
||||||
</Box>
|
|
||||||
</Center>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default App;
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import React from 'react';
|
|
||||||
import { Box, Center } from '@chakra-ui/react';
|
|
||||||
|
|
||||||
const MainContent: React.FC = ({ children }) => {
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Center h="95%" alignItems="stretch">
|
|
||||||
<Box h="100%" w="50%" backgroundColor="#1B2129" flex="1" overflowY="scroll">
|
|
||||||
{children}
|
|
||||||
</Box>
|
|
||||||
</Center>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default MainContent;
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
import { Box, VStack } from '@chakra-ui/react';
|
|
||||||
import { useState } from 'react';
|
|
||||||
import { NavLink } from 'react-router-dom';
|
|
||||||
import { useNuiEvent } from '../../hooks/useNuiEvent';
|
|
||||||
import type { InitData } from '../../types';
|
|
||||||
|
|
||||||
const LeftBar: React.FC = () => {
|
|
||||||
const [initData, setInitData] = useState<InitData>({
|
|
||||||
resources: [''],
|
|
||||||
totalQueries: 0,
|
|
||||||
totalTime: 0,
|
|
||||||
slowQueries: 0,
|
|
||||||
chartData: [{ x: 0, y: 0, z: '' }],
|
|
||||||
});
|
|
||||||
|
|
||||||
useNuiEvent<InitData>('openUI', (data) => {
|
|
||||||
setInitData(data);
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box p="1.2vh" fontSize="1.5vh" float="left" w="13%" height="90%" overflowY="scroll">
|
|
||||||
<VStack align="left">
|
|
||||||
{initData.resources.map((resource, index) => (
|
|
||||||
<Box isTruncated key={`${resource}-${index}`}>
|
|
||||||
<NavLink
|
|
||||||
to={resource}
|
|
||||||
style={(state) => ({
|
|
||||||
color: state.isActive ? 'white' : 'grey',
|
|
||||||
})}
|
|
||||||
>
|
|
||||||
<Box _hover={{ color: 'white' }}>{resource}</Box>
|
|
||||||
</NavLink>
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</VStack>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default LeftBar;
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
import { useState } from 'react';
|
|
||||||
import { Box, VStack, Center, Spacer, Flex, Text } from '@chakra-ui/react';
|
|
||||||
import { useNuiEvent } from '../../hooks/useNuiEvent';
|
|
||||||
import { VictoryPie, VictoryTooltip } from 'victory';
|
|
||||||
import type { InitData } from '../../types';
|
|
||||||
|
|
||||||
const RightBar: React.FC = () => {
|
|
||||||
const [initData, setInitData] = useState<InitData>({
|
|
||||||
totalQueries: 0,
|
|
||||||
totalTime: 0,
|
|
||||||
slowQueries: 0,
|
|
||||||
resources: [''],
|
|
||||||
chartData: [{ x: 0, y: 0, z: '' }],
|
|
||||||
});
|
|
||||||
|
|
||||||
// Debug data defined in LeftBar.tsx
|
|
||||||
|
|
||||||
useNuiEvent<InitData>('openUI', (data) => {
|
|
||||||
setInitData(data);
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box float="right" w="20%" h="100%" p="1.2vh">
|
|
||||||
<Center h="100%">
|
|
||||||
<Flex direction="column" h="100%">
|
|
||||||
<Box>
|
|
||||||
<VStack align="left">
|
|
||||||
<Text>Number of queries: {initData.totalQueries}</Text>
|
|
||||||
<Text>Time querying: {Math.trunc(initData.totalTime)} ms</Text>
|
|
||||||
<Text color="#f3eca1">Slow queries: {initData.slowQueries}</Text>
|
|
||||||
</VStack>
|
|
||||||
</Box>
|
|
||||||
<Spacer />
|
|
||||||
<Box>
|
|
||||||
<VictoryPie
|
|
||||||
colorScale="qualitative"
|
|
||||||
data={initData.chartData}
|
|
||||||
labelComponent={<VictoryTooltip flyoutPadding={18} style={{ fontSize: 24 }} cornerRadius={15} />}
|
|
||||||
style={{
|
|
||||||
labels: {
|
|
||||||
fill: 'black',
|
|
||||||
fontFamily: 'Poppins',
|
|
||||||
fontSize: 28,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
labels={({ datum }) => `${datum.z}: ${datum.x} (${Math.trunc(datum.y)}ms)`}
|
|
||||||
labelPlacement="parallel"
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
</Flex>
|
|
||||||
</Center>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default RightBar;
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { Box, Text } from '@chakra-ui/react';
|
|
||||||
|
|
||||||
const TopBar: React.FC = () => {
|
|
||||||
return (
|
|
||||||
<Box w="100%" h="5%">
|
|
||||||
<Text paddingLeft="1.2vh" fontSize="2vh">
|
|
||||||
Resources
|
|
||||||
</Text>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default TopBar;
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
import { useParams } from 'react-router-dom';
|
|
||||||
import { useEffect, useState, useMemo } from 'react';
|
|
||||||
import { fetchNui } from '../utils/fetchNui';
|
|
||||||
import { useNuiEvent } from '../hooks/useNuiEvent';
|
|
||||||
import { Table, Thead, Tbody, Tr, Th, Td, chakra, Flex, IconButton, Text, Spinner, Tooltip } from '@chakra-ui/react';
|
|
||||||
import {
|
|
||||||
TriangleDownIcon,
|
|
||||||
TriangleUpIcon,
|
|
||||||
ArrowLeftIcon,
|
|
||||||
ChevronLeftIcon,
|
|
||||||
ArrowRightIcon,
|
|
||||||
ChevronRightIcon,
|
|
||||||
} from '@chakra-ui/icons';
|
|
||||||
import { useTable, useSortBy, Column, usePagination, useFlexLayout } from 'react-table';
|
|
||||||
|
|
||||||
interface QueryData {
|
|
||||||
date: number;
|
|
||||||
query: string;
|
|
||||||
executionTime: number;
|
|
||||||
slow?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TableData {
|
|
||||||
query: string;
|
|
||||||
executionTime: number;
|
|
||||||
slow?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface NuiData {
|
|
||||||
queries: QueryData[];
|
|
||||||
pageCount: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const Resource: React.FC = () => {
|
|
||||||
const { resource } = useParams();
|
|
||||||
|
|
||||||
const [isLoaded, setIsLoaded] = useState(false);
|
|
||||||
const [resourceData, setResourceData] = useState<QueryData[]>([
|
|
||||||
{
|
|
||||||
date: 0,
|
|
||||||
query: '',
|
|
||||||
executionTime: 0,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
const [totalPages, setTotalPages] = useState(1);
|
|
||||||
|
|
||||||
const data = useMemo<TableData[]>(() => resourceData, [resourceData]);
|
|
||||||
|
|
||||||
const columns = useMemo<Column<TableData>[]>(
|
|
||||||
() => [
|
|
||||||
{
|
|
||||||
Header: 'Query',
|
|
||||||
accessor: 'query',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Header: 'Execution time (ms)',
|
|
||||||
accessor: 'executionTime',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Header: 'Slow',
|
|
||||||
accessor: 'slow',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
const {
|
|
||||||
getTableProps,
|
|
||||||
getTableBodyProps,
|
|
||||||
headerGroups,
|
|
||||||
page,
|
|
||||||
canPreviousPage,
|
|
||||||
canNextPage,
|
|
||||||
pageOptions,
|
|
||||||
pageCount,
|
|
||||||
gotoPage,
|
|
||||||
nextPage,
|
|
||||||
previousPage,
|
|
||||||
state: { pageIndex, sortBy },
|
|
||||||
prepareRow,
|
|
||||||
} = useTable(
|
|
||||||
{
|
|
||||||
columns,
|
|
||||||
data,
|
|
||||||
initialState: { pageSize: 12, hiddenColumns: ['slow'] },
|
|
||||||
manualPagination: true,
|
|
||||||
manualSortBy: true,
|
|
||||||
pageCount: totalPages,
|
|
||||||
autoResetPage: false,
|
|
||||||
},
|
|
||||||
useSortBy,
|
|
||||||
usePagination,
|
|
||||||
useFlexLayout
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchNui('fetchResource', { resource, pageIndex, sortBy });
|
|
||||||
setIsLoaded(false);
|
|
||||||
}, [resource, pageIndex, sortBy]);
|
|
||||||
|
|
||||||
useNuiEvent<NuiData>('loadResource', (data) => {
|
|
||||||
setResourceData(data.queries);
|
|
||||||
setTotalPages(data.pageCount);
|
|
||||||
setIsLoaded(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Flex direction="column" justifyContent="space-between" alignItems="center" h="100%">
|
|
||||||
<Table {...getTableProps()} size="sm">
|
|
||||||
<Thead>
|
|
||||||
{headerGroups.map((header): any => (
|
|
||||||
<Tr {...header.getHeaderGroupProps()}>
|
|
||||||
{header.headers.map((column) => (
|
|
||||||
<Th
|
|
||||||
{...column.getHeaderProps(column.getSortByToggleProps())}
|
|
||||||
color="white"
|
|
||||||
fontFamily="Poppins"
|
|
||||||
borderBottomColor="#313C4A"
|
|
||||||
textAlign="center"
|
|
||||||
>
|
|
||||||
{column.render('Header')}
|
|
||||||
<chakra.span pl="4">
|
|
||||||
{column.isSorted ? (
|
|
||||||
column.isSortedDesc ? (
|
|
||||||
<TriangleDownIcon aria-label="sorted descending" />
|
|
||||||
) : (
|
|
||||||
<TriangleUpIcon aria-label="sorted ascending" />
|
|
||||||
)
|
|
||||||
) : null}
|
|
||||||
</chakra.span>
|
|
||||||
</Th>
|
|
||||||
))}
|
|
||||||
</Tr>
|
|
||||||
))}
|
|
||||||
</Thead>
|
|
||||||
<Tbody {...getTableBodyProps()}>
|
|
||||||
{isLoaded && (
|
|
||||||
<>
|
|
||||||
{page.map((row) => {
|
|
||||||
prepareRow(row);
|
|
||||||
return (
|
|
||||||
<Tr {...row.getRowProps()}>
|
|
||||||
{row.cells.map((cell) => (
|
|
||||||
<Tooltip isDisabled={cell.column.id === 'executionTime'} label={cell.value} openDelay={500}>
|
|
||||||
<Td
|
|
||||||
{...cell.getCellProps()}
|
|
||||||
fontFamily="Poppins"
|
|
||||||
borderBottomColor="#313C4A"
|
|
||||||
color={row.values.slow && '#f3eca1'}
|
|
||||||
isTruncated={cell.column.id === 'query'}
|
|
||||||
textAlign={cell.column.id === 'executionTime' ? 'center' : 'left'}
|
|
||||||
>
|
|
||||||
{cell.render('Cell')}
|
|
||||||
</Td>
|
|
||||||
</Tooltip>
|
|
||||||
))}
|
|
||||||
</Tr>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Tbody>
|
|
||||||
</Table>
|
|
||||||
|
|
||||||
{!isLoaded && <Spinner />}
|
|
||||||
|
|
||||||
<Flex mt={3} justifyContent="center " alignItems="center" p="1.2vh">
|
|
||||||
<Flex>
|
|
||||||
<IconButton
|
|
||||||
icon={<ArrowLeftIcon h={3} w={3} color="black" />}
|
|
||||||
aria-label="Last page"
|
|
||||||
onClick={() => gotoPage(0)}
|
|
||||||
size="sm"
|
|
||||||
isDisabled={!canPreviousPage}
|
|
||||||
/>
|
|
||||||
<IconButton
|
|
||||||
aria-label="Previous page"
|
|
||||||
onClick={previousPage}
|
|
||||||
isDisabled={!canPreviousPage}
|
|
||||||
icon={<ChevronLeftIcon h={6} w={6} color="black" />}
|
|
||||||
size="sm"
|
|
||||||
ml={4}
|
|
||||||
/>
|
|
||||||
</Flex>
|
|
||||||
<Text align="center" pl={4} pr={4}>
|
|
||||||
Page {pageIndex + 1} of {pageOptions.length}
|
|
||||||
</Text>
|
|
||||||
<Flex>
|
|
||||||
<IconButton
|
|
||||||
aria-label="Next page"
|
|
||||||
onClick={nextPage}
|
|
||||||
size="sm"
|
|
||||||
isDisabled={!canNextPage}
|
|
||||||
icon={<ChevronRightIcon h={6} w={6} color="black" />}
|
|
||||||
/>
|
|
||||||
<IconButton
|
|
||||||
aria-label="Last page"
|
|
||||||
onClick={() => gotoPage(pageCount - 1)}
|
|
||||||
isDisabled={!canNextPage}
|
|
||||||
icon={<ArrowRightIcon h={3} w={3} color="black" />}
|
|
||||||
size="sm"
|
|
||||||
ml={4}
|
|
||||||
/>
|
|
||||||
</Flex>
|
|
||||||
</Flex>
|
|
||||||
</Flex>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default Resource;
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
import {MutableRefObject, useEffect, useRef} from "react";
|
|
||||||
import {noop} from "../utils/misc";
|
|
||||||
|
|
||||||
interface NuiMessageData<T = unknown> {
|
|
||||||
action: string;
|
|
||||||
data: T;
|
|
||||||
}
|
|
||||||
|
|
||||||
type NuiHandlerSignature<T> = (data: T) => void;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A hook that manage events listeners for receiving data from the client scripts
|
|
||||||
* @param action The specific `action` that should be listened for.
|
|
||||||
* @param handler The callback function that will handle data relayed by this hook
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* useNuiEvent<{visibility: true, wasVisible: 'something'}>('setVisible', (data) => {
|
|
||||||
* // whatever logic you want
|
|
||||||
* })
|
|
||||||
*
|
|
||||||
**/
|
|
||||||
|
|
||||||
export const useNuiEvent = <T = any>(
|
|
||||||
action: string,
|
|
||||||
handler: (data: T) => void
|
|
||||||
) => {
|
|
||||||
const savedHandler: MutableRefObject<NuiHandlerSignature<T>> = useRef(noop);
|
|
||||||
|
|
||||||
// Make sure we handle for a reactive handler
|
|
||||||
useEffect(() => {
|
|
||||||
savedHandler.current = handler;
|
|
||||||
}, [handler]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const eventListener = (event: MessageEvent<NuiMessageData<T>>) => {
|
|
||||||
const { action: eventAction, data } = event.data;
|
|
||||||
|
|
||||||
if (savedHandler.current) {
|
|
||||||
if (eventAction === action) {
|
|
||||||
savedHandler.current(data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
window.addEventListener("message", eventListener);
|
|
||||||
// Remove Event Listener on component cleanup
|
|
||||||
return () => window.removeEventListener("message", eventListener);
|
|
||||||
}, [action]);
|
|
||||||
};
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
|
|
||||||
|
|
||||||
body {
|
|
||||||
margin: 0;
|
|
||||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans',
|
|
||||||
'Droid Sans', 'Helvetica Neue', sans-serif;
|
|
||||||
-webkit-font-smoothing: antialiased;
|
|
||||||
-moz-osx-font-smoothing: grayscale;
|
|
||||||
height: 100vh;
|
|
||||||
background: none !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
#root {
|
|
||||||
height: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
code {
|
|
||||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
|
|
||||||
}
|
|
||||||
|
|
||||||
::-webkit-scrollbar {
|
|
||||||
width: 2px;
|
|
||||||
border-radius: 1vh;
|
|
||||||
background-color: transparent;
|
|
||||||
padding: 0;
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
::-webkit-scrollbar-thumb {
|
|
||||||
background: grey;
|
|
||||||
border-radius: 1vh;
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
import React from 'react';
|
|
||||||
import ReactDOM from 'react-dom';
|
|
||||||
import { BrowserRouter } from 'react-router-dom';
|
|
||||||
import './index.css';
|
|
||||||
import App from './components/App';
|
|
||||||
import { VisibilityProvider } from './providers/VisibilityProvider';
|
|
||||||
import { ChakraProvider } from '@chakra-ui/react';
|
|
||||||
|
|
||||||
ReactDOM.render(
|
|
||||||
<React.StrictMode>
|
|
||||||
<VisibilityProvider>
|
|
||||||
<ChakraProvider>
|
|
||||||
<BrowserRouter>
|
|
||||||
<App />
|
|
||||||
</BrowserRouter>
|
|
||||||
</ChakraProvider>
|
|
||||||
</VisibilityProvider>
|
|
||||||
</React.StrictMode>,
|
|
||||||
document.getElementById('root')
|
|
||||||
);
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
import React, { Context, createContext, useContext, useEffect, useState } from 'react';
|
|
||||||
import { useNuiEvent } from '../hooks/useNuiEvent';
|
|
||||||
import { fetchNui } from '../utils/fetchNui';
|
|
||||||
|
|
||||||
const VisibilityCtx = createContext<VisibilityProviderValue | null>(null);
|
|
||||||
|
|
||||||
interface VisibilityProviderValue {
|
|
||||||
setVisible: (visible: boolean) => void;
|
|
||||||
visible: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
// This should be mounted at the top level of your application, it is currently set to
|
|
||||||
// apply a CSS visibility value. If this is non-performant, this should be customized.
|
|
||||||
export const VisibilityProvider: React.FC = ({ children }) => {
|
|
||||||
const [visible, setVisible] = useState(false);
|
|
||||||
|
|
||||||
useNuiEvent<boolean>('openUI', setVisible);
|
|
||||||
|
|
||||||
// Handle pressing escape/backspace
|
|
||||||
useEffect(() => {
|
|
||||||
// Only attach listener when we are visible
|
|
||||||
if (!visible) return;
|
|
||||||
|
|
||||||
const keyHandler = (e: KeyboardEvent) => {
|
|
||||||
if (['Escape'].includes(e.code)) {
|
|
||||||
fetchNui('exit');
|
|
||||||
setVisible(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
window.addEventListener('keydown', keyHandler);
|
|
||||||
|
|
||||||
return () => window.removeEventListener('keydown', keyHandler);
|
|
||||||
}, [visible]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<VisibilityCtx.Provider
|
|
||||||
value={{
|
|
||||||
visible,
|
|
||||||
setVisible,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div style={{ visibility: visible ? 'visible' : 'hidden', height: '100%' }}>{children}</div>
|
|
||||||
</VisibilityCtx.Provider>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useVisibility = () =>
|
|
||||||
useContext<VisibilityProviderValue>(VisibilityCtx as Context<VisibilityProviderValue>);
|
|
||||||
Vendored
-1
@@ -1 +0,0 @@
|
|||||||
/// <reference types="react-scripts" />
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
interface ChartData {
|
|
||||||
x: number;
|
|
||||||
y: number;
|
|
||||||
z: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type InitData = {
|
|
||||||
resources: string[];
|
|
||||||
totalQueries: number;
|
|
||||||
totalTime: number;
|
|
||||||
slowQueries: number;
|
|
||||||
chartData: ChartData[];
|
|
||||||
};
|
|
||||||
Vendored
-122
@@ -1,122 +0,0 @@
|
|||||||
import {
|
|
||||||
UseColumnOrderInstanceProps,
|
|
||||||
UseColumnOrderState,
|
|
||||||
UseExpandedHooks,
|
|
||||||
UseExpandedInstanceProps,
|
|
||||||
UseExpandedOptions,
|
|
||||||
UseExpandedRowProps,
|
|
||||||
UseExpandedState,
|
|
||||||
UseFiltersColumnOptions,
|
|
||||||
UseFiltersColumnProps,
|
|
||||||
UseFiltersInstanceProps,
|
|
||||||
UseFiltersOptions,
|
|
||||||
UseFiltersState,
|
|
||||||
UseGlobalFiltersColumnOptions,
|
|
||||||
UseGlobalFiltersInstanceProps,
|
|
||||||
UseGlobalFiltersOptions,
|
|
||||||
UseGlobalFiltersState,
|
|
||||||
UseGroupByCellProps,
|
|
||||||
UseGroupByColumnOptions,
|
|
||||||
UseGroupByColumnProps,
|
|
||||||
UseGroupByHooks,
|
|
||||||
UseGroupByInstanceProps,
|
|
||||||
UseGroupByOptions,
|
|
||||||
UseGroupByRowProps,
|
|
||||||
UseGroupByState,
|
|
||||||
UsePaginationInstanceProps,
|
|
||||||
UsePaginationOptions,
|
|
||||||
UsePaginationState,
|
|
||||||
UseResizeColumnsColumnOptions,
|
|
||||||
UseResizeColumnsColumnProps,
|
|
||||||
UseResizeColumnsOptions,
|
|
||||||
UseResizeColumnsState,
|
|
||||||
UseRowSelectHooks,
|
|
||||||
UseRowSelectInstanceProps,
|
|
||||||
UseRowSelectOptions,
|
|
||||||
UseRowSelectRowProps,
|
|
||||||
UseRowSelectState,
|
|
||||||
UseRowStateCellProps,
|
|
||||||
UseRowStateInstanceProps,
|
|
||||||
UseRowStateOptions,
|
|
||||||
UseRowStateRowProps,
|
|
||||||
UseRowStateState,
|
|
||||||
UseSortByColumnOptions,
|
|
||||||
UseSortByColumnProps,
|
|
||||||
UseSortByHooks,
|
|
||||||
UseSortByInstanceProps,
|
|
||||||
UseSortByOptions,
|
|
||||||
UseSortByState
|
|
||||||
} from 'react-table'
|
|
||||||
|
|
||||||
declare module 'react-table' {
|
|
||||||
// take this file as-is, or comment out the sections that don't apply to your plugin configuration
|
|
||||||
|
|
||||||
export interface TableOptions<D extends Record<string, unknown>>
|
|
||||||
extends UseExpandedOptions<D>,
|
|
||||||
UseFiltersOptions<D>,
|
|
||||||
UseGlobalFiltersOptions<D>,
|
|
||||||
UseGroupByOptions<D>,
|
|
||||||
UsePaginationOptions<D>,
|
|
||||||
UseResizeColumnsOptions<D>,
|
|
||||||
UseRowSelectOptions<D>,
|
|
||||||
UseRowStateOptions<D>,
|
|
||||||
UseSortByOptions<D>,
|
|
||||||
// note that having Record here allows you to add anything to the options, this matches the spirit of the
|
|
||||||
// underlying js library, but might be cleaner if it's replaced by a more specific type that matches your
|
|
||||||
// feature set, this is a safe default.
|
|
||||||
Record<string, any> {}
|
|
||||||
|
|
||||||
export interface Hooks<D extends Record<string, unknown> = Record<string, unknown>>
|
|
||||||
extends UseExpandedHooks<D>,
|
|
||||||
UseGroupByHooks<D>,
|
|
||||||
UseRowSelectHooks<D>,
|
|
||||||
UseSortByHooks<D> {}
|
|
||||||
|
|
||||||
export interface TableInstance<D extends Record<string, unknown> = Record<string, unknown>>
|
|
||||||
extends UseColumnOrderInstanceProps<D>,
|
|
||||||
UseExpandedInstanceProps<D>,
|
|
||||||
UseFiltersInstanceProps<D>,
|
|
||||||
UseGlobalFiltersInstanceProps<D>,
|
|
||||||
UseGroupByInstanceProps<D>,
|
|
||||||
UsePaginationInstanceProps<D>,
|
|
||||||
UseRowSelectInstanceProps<D>,
|
|
||||||
UseRowStateInstanceProps<D>,
|
|
||||||
UseSortByInstanceProps<D> {}
|
|
||||||
|
|
||||||
export interface TableState<D extends Record<string, unknown> = Record<string, unknown>>
|
|
||||||
extends UseColumnOrderState<D>,
|
|
||||||
UseExpandedState<D>,
|
|
||||||
UseFiltersState<D>,
|
|
||||||
UseGlobalFiltersState<D>,
|
|
||||||
UseGroupByState<D>,
|
|
||||||
UsePaginationState<D>,
|
|
||||||
UseResizeColumnsState<D>,
|
|
||||||
UseRowSelectState<D>,
|
|
||||||
UseRowStateState<D>,
|
|
||||||
UseSortByState<D> {}
|
|
||||||
|
|
||||||
export interface ColumnInterface<D extends Record<string, unknown> = Record<string, unknown>>
|
|
||||||
extends UseFiltersColumnOptions<D>,
|
|
||||||
UseGlobalFiltersColumnOptions<D>,
|
|
||||||
UseGroupByColumnOptions<D>,
|
|
||||||
UseResizeColumnsColumnOptions<D>,
|
|
||||||
UseSortByColumnOptions<D> {}
|
|
||||||
|
|
||||||
export interface ColumnInstance<D extends Record<string, unknown> = Record<string, unknown>>
|
|
||||||
extends UseFiltersColumnProps<D>,
|
|
||||||
UseGroupByColumnProps<D>,
|
|
||||||
UseResizeColumnsColumnProps<D>,
|
|
||||||
UseSortByColumnProps<D> {
|
|
||||||
getSortByToggleProps: (props?: Partial<TableSortByToggleProps> | undefined) => TableSortByToggleProps
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Cell<D extends Record<string, unknown> = Record<string, unknown>, V = any>
|
|
||||||
extends UseGroupByCellProps<D>,
|
|
||||||
UseRowStateCellProps<D> {}
|
|
||||||
|
|
||||||
export interface Row<D extends Record<string, unknown> = Record<string, unknown>>
|
|
||||||
extends UseExpandedRowProps<D>,
|
|
||||||
UseGroupByRowProps<D>,
|
|
||||||
UseRowSelectRowProps<D>,
|
|
||||||
UseRowStateRowProps<D> {}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
import {isEnvBrowser} from "./misc";
|
|
||||||
|
|
||||||
interface DebugEvent<T = any> {
|
|
||||||
action: string;
|
|
||||||
data: T;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Emulates dispatching an event using SendNuiMessage in the lua scripts.
|
|
||||||
* This is used when developing in browser
|
|
||||||
*
|
|
||||||
* @param events - The event you want to cover
|
|
||||||
* @param timer - How long until it should trigger (ms)
|
|
||||||
*/
|
|
||||||
export const debugData = <P>(events: DebugEvent<P>[], timer = 1000): void => {
|
|
||||||
if (process.env.NODE_ENV === "development" && isEnvBrowser()) {
|
|
||||||
for (const event of events) {
|
|
||||||
setTimeout(() => {
|
|
||||||
window.dispatchEvent(
|
|
||||||
new MessageEvent("message", {
|
|
||||||
data: {
|
|
||||||
action: event.action,
|
|
||||||
data: event.data,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}, timer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
/**
|
|
||||||
* Simple wrapper around fetch API tailored for CEF/NUI use. This abstraction
|
|
||||||
* can be extended to include AbortController if needed or if the response isn't
|
|
||||||
* JSON. Tailor it to your needs.
|
|
||||||
*
|
|
||||||
* @param eventName - The endpoint eventname to target
|
|
||||||
* @param data - Data you wish to send in the NUI Callback
|
|
||||||
*
|
|
||||||
* @return returnData - A promise for the data sent back by the NuiCallbacks CB argument
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { isEnvBrowser } from "./misc";
|
|
||||||
|
|
||||||
export async function fetchNui<T = any>(eventName: string, data?: any): Promise<T> {
|
|
||||||
const options = {
|
|
||||||
method: 'post',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json; charset=UTF-8',
|
|
||||||
},
|
|
||||||
body: JSON.stringify(data),
|
|
||||||
};
|
|
||||||
|
|
||||||
if (isEnvBrowser()) return undefined as any;
|
|
||||||
|
|
||||||
const resourceName = (window as any).GetParentResourceName ? (window as any).GetParentResourceName() : 'nui-frame-app';
|
|
||||||
|
|
||||||
const resp = await fetch(`https://${resourceName}/${eventName}`, options);
|
|
||||||
|
|
||||||
const respFormatted = await resp.json()
|
|
||||||
|
|
||||||
return respFormatted
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
// Will return whether the current environment is in a regular browser
|
|
||||||
// and not CEF
|
|
||||||
export const isEnvBrowser = (): boolean => !(window as any).invokeNative
|
|
||||||
|
|
||||||
// Basic no operation function
|
|
||||||
export const noop = () => {}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "es5",
|
|
||||||
"lib": [
|
|
||||||
"dom",
|
|
||||||
"dom.iterable",
|
|
||||||
"esnext"
|
|
||||||
],
|
|
||||||
"allowJs": true,
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"allowSyntheticDefaultImports": true,
|
|
||||||
"strict": true,
|
|
||||||
"forceConsistentCasingInFileNames": true,
|
|
||||||
"noFallthroughCasesInSwitch": true,
|
|
||||||
"module": "esnext",
|
|
||||||
"moduleResolution": "node",
|
|
||||||
"resolveJsonModule": true,
|
|
||||||
"isolatedModules": true,
|
|
||||||
"noEmit": true,
|
|
||||||
"jsx": "react-jsx"
|
|
||||||
},
|
|
||||||
"include": [
|
|
||||||
"src"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
-10919
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user