Compare commits

..
31 Commits
Author SHA1 Message Date
Linden 4e29905179 fix(execute): check resourcestate is 'started' to resolve promise 2021-12-10 10:55:27 +00:00
Linden 78ce45f1de refactor(patch/named-placeholders): performance tweaks
Little bit of micro-optimisation to increase speed of placeholder resolution by 2x
2021-12-10 11:19:27 +11:00
Linden 193da3e6c7 refactor(execute): execute queries after first tick
Force queries to wait until the server has ticked before sending anything.
2021-12-10 11:18:15 +11:00
Linden cd2e73953f test: re-enable slow query warnings 2021-12-10 11:17:02 +11:00
Linden 3928415930 test: revert recent changes
People are experiencing errors that I've been unable to reproduce, but 1.8.3 apparently works fine.
Revert changes that were made.

This disables slow query warnings for now.
2021-12-08 07:43:25 +11:00
Linden b27662d138 Update issue templates 2021-12-07 10:58:27 +11:00
Linden 45b90c4ad3 fix: performance tweaks
Moved getConnection and ScheduleResourceTick above the try block.
Moved connection.release into the finally block
Increased default connection timeout to 1 minute.
2021-12-06 17:55:50 +11:00
Linden 87a5123117 fix: JS sync exports check
Since JS is such a bad language it throws an error when doing `variable !== undefined`, so wrap the whole thing in a try block and catch the error.
2021-12-04 03:22:53 +11:00
Linden 94fe76340e fix: undefined values
Various mistakes from 1.8.1
2021-12-02 19:32:38 +11:00
Linden b7763141b7 fix(transactions): resolve error when executing transaction 2021-12-02 08:19:22 +11:00
Linden bf2d729a39 feat: mysql2 patch-package 2021-12-01 03:46:05 +11:00
Linden a352273b08 refactor(execute): await connection to send query
Waiting for the connection to become available lets us move executiontime back into the resource.
2021-12-01 03:42:44 +11:00
Linden e685ff5f4c refactor: minor cleanup and formatting 2021-12-01 02:52:48 +11:00
Linden dbe107e669 refactor: enable JS exports for more recent artifacts
We still don't have a bump in recommended artifact, so for now check for the existence of new(ish) native.
2021-12-01 02:51:05 +11:00
Linden 3e266ec952 chore: update dependencies 2021-12-01 00:41:29 +11:00
Linden cd2b5db342 Update fxmanifest.lua 2021-11-30 04:05:22 +11:00
Linden f3fc016f31 refactor(pool): new createConnection function
Remove the connection string parsing and send the URI directly, if it exists. For semicolon connection strings, check for and replace aliases.
2021-11-25 20:29:02 +11:00
Linden 381627266f chore: update version 2021-11-15 09:10:57 +11:00
Linden f779ba4228 chore: update packages 2021-11-15 09:10:37 +11:00
Linden b004ec943d refactor(pool): permit extra user and password aliases 2021-11-15 09:09:52 +11:00
Linden 647243f1cf fix(lib): incorrect safeArgs for Sync.transaction (callback)
Additionally no longer sending Resource argument since oxmysql can handle that already.
2021-11-11 18:06:36 +11:00
Linden 12e9ccbc8a feat(lua): update http link and version checking 2021-10-31 08:32:27 +11:00
Linden 2a9b14ce54 chore(lua): update fxmanifest version 2021-10-31 07:18:55 +11:00
Linden f7949db0d3 chore(workflow): update run tasks 2021-10-31 07:17:45 +11:00
Linden 2a14ab1e21 refactor(webpack): update patterns and do not minify 2021-10-31 06:48:30 +11:00
Linden 9de50f684f refactor(lua): remove file check and move to subdirectory 2021-10-31 06:48:00 +11:00
Linden 2c90290c84 fix(wrapper): check if oxmysql.js exists via io function 2021-10-29 09:26:01 +11:00
Linden 9fc06c2132 refactor(versioncheck): remove module and perform check with Lua
Unnecessary dependency with functionality that can be easily handled via PerformHttpRequest.

Since the check references fxmanifest instead, we will no longer maintain the version in package.json.
2021-10-29 08:14:39 +11:00
Linden def891268b feat(wrapper): throw an error when no build exists
Many people refuse to download releases, instead opting for the source code. Throw an error and include a link to the direct download.
2021-10-29 07:08:36 +11:00
Dunak 8a3fa20408 fix(pool): Remove default database value from config 2021-10-25 10:55:42 +02:00
Dunak 5d6ca06f49 fix(parser): Check if query is string type not undefined
- Should fix issues when exports is wrong called with `.` instead of `:`
2021-10-24 14:56:38 +02:00
19 changed files with 248 additions and 1604 deletions

No files matched your search

+7 -4
View File
@@ -2,7 +2,7 @@
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
labels: bug
assignees: ''
---
@@ -23,7 +23,7 @@ If applicable, add screenshots to help explain your problem.
**Code**
```lua
If applicable, include the query and relevant code
-- If applicable, include the query and relevant code
```
**Expected behavior**
@@ -33,6 +33,9 @@ A clear and concise description of what you expected to happen.
Add any other context about the problem here.
**Server details**
- FX Server artifact
- FXServer artifact
- Operating system
- Framework
**Database details**
- MariaDB or MySQL
- Version
+20
View File
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
-2
View File
@@ -32,8 +32,6 @@ jobs:
- name: Bundle files
run: |
mv dist oxmysql
mkdir oxmysql/lib
mv lib/MySQL.lua oxmysql/lib/MySQL.lua
zip -r oxmysql-${{ env.RELEASE_VERSION }}.zip oxmysql
- name: Create Release
+1
View File
@@ -111,6 +111,7 @@ dist
.vscode-test
# yarn v2
yarn.lock
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
+6 -2
View File
@@ -3,15 +3,19 @@ game 'common'
name 'oxmysql'
description 'Database wrapper for FiveM utilising node-mysql2 offering improved performance and security.'
version '1.7.0'
version '1.8.7'
url 'https://github.com/overextended/oxmysql'
author 'overextended'
use_fxv2_oal 'yes'
lua54 'yes'
--dependencies {
-- '/server:4837', Disabled until the heat death of the universe (or recommended artifact updates)
--}
server_scripts {
'oxmysql.js',
'wrapper.lua'
}
provide 'mysql-async'
provide 'mysql-async'
+8 -9
View File
@@ -3,7 +3,6 @@
-- Store is used for compatibility only
local Ox = exports.oxmysql
local Resource = GetCurrentResourceName()
local Store = {}
local function safeArgs(query, parameters, cb, transaction)
@@ -99,7 +98,7 @@ MySQL.Sync.execute = function(query, parameters)
local promise = promise.new()
Ox:update(query, parameters, function(result)
promise:resolve(result)
end, Resource)
end)
return Citizen.Await(promise)
end
@@ -112,7 +111,7 @@ MySQL.Sync.fetchAll = function(query, parameters)
local promise = promise.new()
Ox:execute(query, parameters, function(result)
promise:resolve(result)
end, Resource)
end)
return Citizen.Await(promise)
end
@@ -125,7 +124,7 @@ MySQL.Sync.fetchScalar = function(query, parameters)
local promise = promise.new()
Ox:scalar(query, parameters, function(result)
promise:resolve(result)
end, Resource)
end)
return Citizen.Await(promise)
end
@@ -138,7 +137,7 @@ MySQL.Sync.fetchSingle = function(query, parameters)
local promise = promise.new()
Ox:single(query, parameters, function(result)
promise:resolve(result)
end, Resource)
end)
return Citizen.Await(promise)
end
@@ -151,7 +150,7 @@ MySQL.Sync.insert = function(query, parameters)
local promise = promise.new()
Ox:insert(query, parameters, function(result)
promise:resolve(result)
end, Resource)
end)
return Citizen.Await(promise)
end
@@ -160,11 +159,11 @@ end
---@return boolean result
---returns true when the transaction has succeeded
MySQL.Sync.transaction = function(queries, parameters)
queries, parameters = safeArgs(queries, parameters, true)
queries, parameters = safeArgs(queries, parameters, false, true)
local promise = promise.new()
Ox:transaction(queries, parameters, function(result)
promise:resolve(result)
end, Resource)
end)
return Citizen.Await(promise)
end
@@ -185,4 +184,4 @@ MySQL.ready = function(cb)
until GetResourceState('oxmysql') == 'started'
cb()
end)
end
end
+38 -8
View File
@@ -1,10 +1,40 @@
local oxmysql = exports.oxmysql
CreateThread(function()
Wait(1000)
local resource = GetCurrentResourceName()
local url = GetResourceMetadata(resource, 'url', 0)
local version = GetResourceMetadata(resource, 'version', 0)
PerformHttpRequest(('%s/main/lua/fxmanifest.lua'):format(url:gsub('github.com', 'raw.githubusercontent.com')), function(error, response)
if error == 200 then
local latest = response:match('%d%.%d+%.%d+')
if version ~= latest then
local curMajor, curMinor = string.strsplit('.', version)
local newMajor, newMinor = string.strsplit('.', response:match('%d%.%d+%.%d+'))
local link = ('%s/releases/download/v%s/oxmysql-v%s.zip'):format(url, latest, latest)
if tonumber(curMajor) < tonumber(newMajor) then
latest = 'A major update'
elseif tonumber(curMinor) < tonumber(newMinor) then
latest = 'An update'
else
latest = 'A patch'
end
print(('^3%s is available for oxmysql - please update to the latest release (current version: %s)\n ^3- %s^0'):format(latest, version, link))
end
end
end, 'GET')
end)
---@param query string
---@param parameters? table
---@return integer result
---returns array of matching rows or result data
exports('executeSync', function(query, parameters)
local p = promise.new()
exports['oxmysql']:execute(query, parameters, function(result)
oxmysql:execute(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
@@ -16,7 +46,7 @@ end)
---returns array of matching rows or result data
exports('fetchSync', function(query, parameters)
local p = promise.new()
exports['oxmysql']:fetch(query, parameters, function(result)
oxmysql:fetch(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
@@ -28,7 +58,7 @@ end)
---returns table containing key value pairs
exports('singleSync', function(query, parameters)
local p = promise.new()
exports['oxmysql']:single(query, parameters, function(result)
oxmysql:single(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
@@ -40,7 +70,7 @@ end)
---returns value of the first column of a single row
exports('scalarSync', function(query, parameters)
local p = promise.new()
exports['oxmysql']:scalar(query, parameters, function(result)
oxmysql:scalar(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
@@ -52,7 +82,7 @@ end)
---returns the last inserted id
exports('insertSync', function(query, parameters)
local p = promise.new()
exports['oxmysql']:insert(query, parameters, function(result)
oxmysql:insert(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
@@ -64,7 +94,7 @@ end)
---returns number of rows updated by the executed query
exports('updateSync', function(query, parameters)
local p = promise.new()
exports['oxmysql']:update(query, parameters, function(result)
oxmysql:update(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
@@ -76,7 +106,7 @@ end)
---returns true when the transaction has succeeded
exports('transactionSync', function(queries, parameters)
local p = promise.new()
exports['oxmysql']:transaction(queries, parameters, function(result)
oxmysql:transaction(queries, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
@@ -90,7 +120,7 @@ end)
---return value is based on the number of results and the type of query used
exports('prepareSync', function(query, parameters)
local p = promise.new()
exports['oxmysql']:prepare(query, parameters, function(result)
oxmysql:prepare(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
+7 -9
View File
@@ -1,6 +1,6 @@
{
"name": "oxmysql",
"version": "1.7.0",
"version": "1.0.0",
"main": "oxmysql.js",
"description": "node-mysql2 resource for Cfx",
"repository": "[email protected]:overextended/oxmysql.git",
@@ -12,17 +12,15 @@
"postinstall": "patch-package"
},
"dependencies": {
"@citizenfx/server": "^2.0.4793-1",
"connection-string-parser": "^1.0.4",
"github-version-checker": "^2.2.0",
"mysql2": "https://github.com/overextended/node-mysql2.git",
"@citizenfx/server": "latest",
"mysql2": "^2.3.3",
"postinstall-postinstall": "^2.1.0"
},
"devDependencies": {
"copy-webpack-plugin": "^9.0.1",
"copy-webpack-plugin": "^10.0.0",
"patch-package": "^6.4.7",
"typescript": "^4.4.3",
"webpack": "^5.52.1",
"webpack-cli": "^4.8.0"
"typescript": "^4.5.2",
"webpack": "^5.64.4",
"webpack-cli": "^4.9.1"
}
}
@@ -1,12 +0,0 @@
diff --git a/node_modules/github-version-checker/lib/check.js b/node_modules/github-version-checker/lib/check.js
index 7f00060..cf0e231 100644
--- a/node_modules/github-version-checker/lib/check.js
+++ b/node_modules/github-version-checker/lib/check.js
@@ -88,7 +88,6 @@ const rest = (options, callback) => {
if (found) {
const mapped = schemeMapper[options.fetchTags ? 'tag' : 'release'](version);
- console.log(mapped);
callback(null, mapped);
} else {
callback(null, null);
+47
View File
@@ -0,0 +1,47 @@
diff --git a/node_modules/mysql2/lib/connection_config.js b/node_modules/mysql2/lib/connection_config.js
index 11ad01b..6fab74e 100644
--- a/node_modules/mysql2/lib/connection_config.js
+++ b/node_modules/mysql2/lib/connection_config.js
@@ -187,7 +187,6 @@ class ConnectionConfig {
'LONG_PASSWORD',
'FOUND_ROWS',
'LONG_FLAG',
- 'CONNECT_WITH_DB',
'ODBC',
'LOCAL_FILES',
'IGNORE_SPACE',
@@ -200,15 +199,14 @@ class ConnectionConfig {
'TRANSACTIONS',
'SESSION_TRACK'
];
- if (options && options.multipleStatements) {
- defaultFlags.push('MULTI_STATEMENTS');
+ if (options) {
+ if (options.multipleStatements) defaultFlags.push('MULTI_STATEMENTS');
+ if (options.database) defaultFlags.push('CONNECT_WITH_DB');
+ if (options.connectAttributes) defaultFlags.push('CONNECT_ATTRS')
}
defaultFlags.push('PLUGIN_AUTH');
defaultFlags.push('PLUGIN_AUTH_LENENC_CLIENT_DATA');
- if (options && options.connectAttributes) {
- defaultFlags.push('CONNECT_ATTRS');
- }
return defaultFlags;
}
diff --git a/node_modules/mysql2/lib/packets/execute.js b/node_modules/mysql2/lib/packets/execute.js
index c612f66..02dbe22 100644
--- a/node_modules/mysql2/lib/packets/execute.js
+++ b/node_modules/mysql2/lib/packets/execute.js
@@ -28,7 +28,9 @@ function toParameter(value, encoding, timezone) {
if (value !== null) {
switch (typeof value) {
case 'undefined':
- throw new TypeError('Bind parameters must not contain undefined');
+ value = '';
+ type = Types.NULL;
+ break
case 'number':
type = Types.DOUBLE;
+15 -13
View File
@@ -1,5 +1,5 @@
diff --git a/node_modules/named-placeholders/index.js b/node_modules/named-placeholders/index.js
index 527d723..f63ce28 100644
index 527d723..728188b 100644
--- a/node_modules/named-placeholders/index.js
+++ b/node_modules/named-placeholders/index.js
@@ -3,7 +3,7 @@
@@ -11,46 +11,48 @@ index 527d723..f63ce28 100644
DQUOTE = 34,
SQUOTE = 39,
BSLASH = 92;
@@ -94,15 +94,22 @@ function createCompiler(config) {
@@ -94,6 +94,14 @@ function createCompiler(config) {
if (typeof params == 'undefined')
throw new Error('Named query contains placeholders, but parameters object is undefined');
+ for(const key in params) {
+ if(key.charAt(0) === '@' || key.charAt(0) === ':') {
+ const char = key[0]
+ if(char == '@' || char == ':') {
+ params[key.substring(1)] = params[key];
+ delete params[key];
+ }
+ }
+
+
const tokens = tree[1];
for (let i=0; i < tokens.length; ++i) {
- arr.push(params[tokens[i]]);
+ arr.push(params[tokens[i]] === undefined ? null : params[tokens[i]]);
}
return [tree[0], arr];
arr.push(params[tokens[i]]);
@@ -102,7 +110,8 @@ function createCompiler(config) {
}
function noTailingSemicolon(s) {
- if (s.slice(-1) == ':') {
+ if (s.slice(-1) == ':' || s.slice(-1) == '@') {
+ const char = s.slice(-1)
+ if (char == ':' || char == '@') {
return s.slice(0, -1);
}
return s;
@@ -115,7 +122,7 @@ function createCompiler(config) {
@@ -115,7 +124,8 @@ function createCompiler(config) {
let unnamed = noTailingSemicolon(tree[0][0]);
for (let i=1; i < tree[0].length; ++i) {
- if (tree[0][i-1].slice(-1) == ':') {
+ if (tree[0][i-1].slice(-1) == ':' || tree[0][i-1].slice(-1) == '@') {
+ const char = tree[0][i-1].slice(-1)
+ if (char == ':' || char == '@') {
unnamed += config.placeholder;
}
unnamed += config.placeholder;
@@ -124,7 +131,7 @@ function createCompiler(config) {
@@ -124,7 +134,8 @@ function createCompiler(config) {
const last = tree[0][tree[0].length -1];
if (tree[0].length == tree[1].length) {
- if (last.slice(-1) == ':') {
+ if (last.slice(-1) == ':' || last.slice(-1) == '@') {
+ const char = last.slice(-1)
+ if (char == ':' || char == '@') {
unnamed += config.placeholder;
}
unnamed += config.placeholder;
+1 -24
View File
@@ -1,6 +1,3 @@
import versionCheck from 'github-version-checker';
import currentVersion from '../package.json';
const slowQueryWarning = GetConvarInt('mysql_slow_query_warning', 150);
const debug = GetConvar('mysql_debug', 'false') === 'true';
@@ -19,26 +16,6 @@ const isolationLevel = (() => {
}
})();
const resourceName = GetCurrentResourceName() || 'oxmysql';
const resourceName = GetCurrentResourceName();
export { slowQueryWarning, debug, isolationLevel, resourceName };
setImmediate(async () => {
const versionCheckConfig = {
repo: 'oxmysql',
owner: 'overextended',
currentVersion: currentVersion.version,
latest: true,
};
try {
const update = await versionCheck(versionCheckConfig);
if (update) {
console.log(
`^3Your version of oxmysql is outdated (v${versionCheckConfig.currentVersion})! Please update to the latest version (${update.name}) here: \nhttps://github.com/overextended/oxmysql/releases/latest^0`
);
}
} catch (e) {
console.log(`^3Could not fetch updates for oxmysql!^0\n${e}`);
}
});
+38 -9
View File
@@ -1,13 +1,39 @@
import { pool } from './pool';
import { parseParameters } from './parser';
import { slowQueryWarning, debug, resourceName } from './config';
import { slowQueryWarning, debug, resourceName, isolationLevel } from './config';
import { FormatError } from './errors';
let isReady = false;
const serverReady = async () => {
return new Promise((resolve) => {
const id = setInterval(() => {
if (GetResourceState(resourceName) == 'started') resolve(id);
}, 50);
}).then((id) => {
clearInterval(id);
isReady = true;
});
};
setImmediate(async () => {
try {
await pool.query(isolationLevel);
console.log(`^2Database server connection established!^0`);
} catch (error) {
console.log(`^3Unable to establish a connection to the database! [${error.code}]\n${error.message}^0`);
}
});
const execute = async (query, parameters, resource) => {
if (!isReady) await serverReady();
try {
[query, parameters] = parseParameters(query, parameters);
ScheduleResourceTick(resourceName);
const [executionTime, rows] = await pool.query(query, parameters);
const startTime = process.hrtime();
const [rows] = await pool.query(query, parameters);
const executionTime = process.hrtime(startTime)[1] / 1000000; // nanosecond to millisecond
if (executionTime >= slowQueryWarning || debug)
console.log(
@@ -42,6 +68,9 @@ const queryType = (query) => {
};
const preparedStatement = async (query, parameters, resource) => {
if (!isReady) await serverReady();
ScheduleResourceTick(resourceName);
const connection = await pool.getConnection();
try {
if (!Array.isArray(parameters))
throw new FormatError(`Placeholders were defined, but query received no parameters!`, query);
@@ -51,21 +80,19 @@ const preparedStatement = async (query, parameters, resource) => {
const type = queryType(query);
if (!type) throw new FormatError(`Prepared statements only accept SELECT, INSERT, UPDATE, and DELETE methods!`);
ScheduleResourceTick(resourceName);
const results = [];
let totalTime = 0;
let queryCount = parameters.length;
const startTime = process.hrtime();
for (let i = 0; i < queryCount; i++) {
const [executionTime, rows] = await pool.execute(query, parameters[i]);
totalTime + executionTime;
const [rows] = await connection.execute(query, parameters[i]);
results[i] = rows && (type === 3 ? rows.affectedRows : type === 2 ? rows.insertId : rows);
}
totalTime = totalTime / queryCount;
if (totalTime >= slowQueryWarning || debug)
const executionTime = process.hrtime(startTime)[1] / 1000000; // nanosecond to millisecond
if (executionTime >= slowQueryWarning || debug)
console.log(
`^3[${debug ? 'DEBUG' : 'WARNING'}] ${resource} took ${totalTime}ms to execute ${
`^3[${debug ? 'DEBUG' : 'WARNING'}] ${resource} took ${executionTime}ms to execute ${
queryCount > 1 ? queryCount + ' queries' : 'a query'
}!
${query} ${JSON.stringify(parameters)}^0`
@@ -88,6 +115,8 @@ const preparedStatement = async (query, parameters, resource) => {
${error.sql || `${query} ${JSON.stringify(parameters)}`}^0`
);
debug && console.trace(error);
} finally {
connection.release();
}
};
+11 -29
View File
@@ -1,52 +1,35 @@
import { pool } from './pool';
import { execute, preparedStatement } from './execute';
import { transaction } from './transaction';
import { debug, isolationLevel } from './config';
import { debug } from './config';
setImmediate(async () => {
try {
await pool.query(isolationLevel);
console.log(`^2Database server connection established!^0`);
} catch (error) {
console.log(`^3Unable to establish a connection to the database! [${error.code}]\n${error.message}^0`);
}
});
const safeCallback = (callback, result, resource, query) => {
if (typeof callback === 'function')
return callback(result);
else if (debug)
return console.log(`^3[WARNING] ${resource} executed a query, but no callback function was defined!\n ^3 ${query}^0`);
const safeCallback = (callback, result) => {
if (typeof callback === 'function') callback(result);
};
global.exports('execute', (query, parameters, cb, resource = GetInvokingResource()) => {
execute(query, parameters, resource).then((result) =>
safeCallback(cb || parameters, result, resource, query));
execute(query, parameters, resource).then((result) => safeCallback(cb || parameters, result));
});
global.exports('insert', (query, parameters, cb, resource = GetInvokingResource()) => {
execute(query, parameters, resource).then((result) =>
safeCallback(cb || parameters, result && result.insertId, resource, query));
execute(query, parameters, resource).then((result) => safeCallback(cb || parameters, result && result.insertId));
});
global.exports('update', (query, parameters, cb, resource = GetInvokingResource()) => {
execute(query, parameters, resource).then((result) =>
safeCallback(cb || parameters, result && result.affectedRows, resource, query));
execute(query, parameters, resource).then((result) => safeCallback(cb || parameters, result && result.affectedRows));
});
global.exports('fetch', (query, parameters, cb, resource = GetInvokingResource()) => {
execute(query, parameters, resource).then((result) =>
safeCallback(cb || parameters, result, resource, query));
execute(query, parameters, resource).then((result) => safeCallback(cb || parameters, result));
});
global.exports('single', (query, parameters, cb, resource = GetInvokingResource()) => {
execute(query, parameters, resource).then((result) =>
safeCallback(cb || parameters, result && result[0], resource, query));
execute(query, parameters, resource).then((result) => safeCallback(cb || parameters, result && result[0]));
});
global.exports('scalar', (query, parameters, cb, resource = GetInvokingResource()) => {
execute(query, parameters, resource).then((result) =>
safeCallback(cb || parameters, result && result[0] && Object.values(result[0])[0], resource, query));
safeCallback(cb || parameters, result && result[0] && Object.values(result[0])[0])
);
});
global.exports('transaction', (queries, parameters, cb, resource = GetInvokingResource()) => {
@@ -56,8 +39,7 @@ global.exports('transaction', (queries, parameters, cb, resource = GetInvokingRe
});
global.exports('prepare', (query, parameters, cb, resource = GetInvokingResource()) => {
preparedStatement(query, parameters, resource).then((result) =>
safeCallback(cb || parameters, result, resource, query))
preparedStatement(query, parameters, resource).then((result) => safeCallback(cb || parameters, result));
});
if (!GetResourceMetadata(GetCurrentResourceName(), 'server_script', 1)) {
+20 -15
View File
@@ -3,8 +3,9 @@ import * as createCompiler from 'named-placeholders';
const convertNamedPlaceholders = createCompiler();
// DATE compatibility with mysql-async
// https://github.com/brouznouf/fivem-mysql-async/blob/master/mysql-async.js#L15499-L15536
const parseTypes = (field, next) => {
//https://github.com/GHMatti/ghmattimysql/blob/37f1d2ae5c53f91782d168fe81fba80512d3c46d/packages/ghmattimysql/src/server/utility/typeCast.ts#L3
switch (field.type) {
case 'DATETIME':
case 'DATETIME2':
@@ -16,8 +17,7 @@ const parseTypes = (field, next) => {
? new Date(field.string() + ' 00:00:00').getTime()
: new Date(field.string()).getTime();
case 'TINY':
if (field.length == 1) return field.string() === '1';
else return next();
return field.length === 1 ? field.string() === '1' : next();
case 'BIT':
return field.buffer()[0] === 1;
default:
@@ -26,23 +26,28 @@ const parseTypes = (field, next) => {
};
const parseParameters = (query, parameters) => {
if (query === undefined) throw new FormatError(`Undefined query passed`);
if (typeof query !== 'string')
throw new Error(
`Non-string query passed. Make sure you use "oxmysql:execute" instead of "oxmysql.execute" when calling exports.`
);
if (!parameters || typeof parameters === 'function') return [query, []];
if (query.includes('@') || query.includes(':')) {
const obj = parameters.length !== 0 ? parameters : (() => {
let obj = {};
const [_, paramNames] = convertNamedPlaceholders.parse(query);
if (paramNames) {
for (let i = 0; i < paramNames.length; i++)
obj[paramNames[i]] = null;
}
return obj;
})();
const obj =
parameters.length !== 0
? parameters
: (() => {
let obj = {};
const [_, paramNames] = convertNamedPlaceholders.parse(query);
if (paramNames) {
for (let i = 0; i < paramNames.length; i++) obj[paramNames[i]] = null;
}
return obj;
})();
return [query, obj]
};
return [query, obj];
}
const queryParams = query.match(/\?(?!\?)/g);
+23 -52
View File
@@ -1,6 +1,5 @@
import { createPool } from 'mysql2/promise';
import { parseTypes } from './parser';
import { ConnectionStringParser } from 'connection-string-parser';
const connectionString = GetConvar('mysql_connection_string', '');
@@ -8,59 +7,31 @@ if (connectionString === '') {
throw new Error(`Set up mysql_connection_string in server.cfg`);
}
const parseSemiColons = () => {
const parts = connectionString.split(';');
if (parseTypes.length === 1) {
throw new Error(
`Set up mysql_connection_string in correct format - 'username=root;password=password;database=db;host=127.0.0.1'`
);
}
return parts.reduce((connectionInfo, parameter) => {
const [key, value] = parameter.split('=');
connectionInfo[key] = value;
return connectionInfo;
}, {});
};
const dbOptions = (() => {
const options = connectionString.includes('mysql://')
? { uri: connectionString }
: connectionString
.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;
}, {});
const createConnection = () => {
if (connectionString.includes('database=')) {
const options = parseSemiColons();
options.typeCast = parseTypes;
options.namedPlaceholders = true;
return createPool({
host: options.host || 'localhost',
port: options.port || 3306,
user: options.username || options.user || options.userid || 'root',
password: options.password || options.pass || '',
database: options.endpoint || options.database || 'es_extended',
charset: 'utf8mb4_unicode_ci',
connectTimeout: 30000,
...options.options,
namedPlaceholders: true,
typeCast: parseTypes,
});
} else {
const options = new ConnectionStringParser({
scheme: 'mysql',
hosts: [],
}).parse(connectionString);
// increase the default timeout for slow servers
options.connectTimeout = options.connectTimeout || 60000;
if (Object.keys(options).length === 0) {
throw new Error(`Set up mysql_connection_string in correct format - 'mysql://user:password@host/database'`);
}
// disabled to prevent SQL injection
options.multipleStatements = options.multipleStatements || false;
return createPool({
host: options.hosts[0].host || 'localhost',
port: options.hosts[0].port || 3306,
user: options.username || 'root',
password: options.password || '',
database: options.endpoint || 'es_extended',
charset: 'utf8mb4_unicode_ci',
connectTimeout: 30000,
...options.options,
namedPlaceholders: true,
typeCast: parseTypes,
});
}
};
return options;
})();
export const pool = createConnection();
export const pool = createPool(dbOptions);
+2 -2
View File
@@ -13,10 +13,10 @@ const transaction = async (queries, parameters, resource) => {
ScheduleResourceTick(resourceName);
const connection = await pool.getConnection();
try {
const time = debug ? process.hrtime.bigint() : Date.now();
const fullQuery = parseTransaction(queries, parameters);
const transactionAmount = fullQuery.length;
const startTime = process.hrtime();
await connection.beginTransaction();
@@ -26,7 +26,7 @@ const transaction = async (queries, parameters, resource) => {
await connection.commit();
const executionTime = debug ? Number(process.hrtime.bigint() - time) / 1e6 : Date.now() - time;
const executionTime = process.hrtime(startTime)[1] / 1000000;
if (executionTime >= slowQueryWarning * transactionAmount || debug)
console.log(
+4 -1
View File
@@ -15,12 +15,15 @@ module.exports = {
contextRegExp: /./,
}),
new CopyPlugin({
patterns: ["fxmanifest.lua", "wrapper.lua", "README.md", "LICENSE.md"],
patterns: ["./lua", "./lua", "README.md", "LICENSE.md"],
}),
],
output: {
filename: "oxmysql.js",
path: path.resolve(__dirname, "dist"),
},
optimization: {
minimize: false,
},
target: "node",
};
-1413
View File
File diff suppressed because it is too large. Load diff