Compare commits

..
99 Commits
Author SHA1 Message Date
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
Linden 4913d6e50a chore: Version bump 2021-10-24 02:15:10 +11:00
Linden ca8cef4e26 refactor(prepare): Rename prepared export to prepare 2021-10-24 02:13:55 +11:00
Linden 2a8f4b1ea9 feat: Add an export to call prepared statements (#54)
* feat: Add an export to call prepared queries

- Utilises pool.execute (rather than query) to actually prepare parameters through mysql.

This is intended for appropriately built queries utilising  placeholders and parameters, and should only be used on frequently repeated queries.

* refactor(prepare): Clean up results and add total execution time

* feat(prepare): Send scalar response for a single value

* fix(prepare): Check if result exists before getting keys
2021-10-23 09:05:01 +11:00
Linden 1d0a5bcfd9 Update issue templates 2021-10-23 08:55:54 +11:00
Linden 5965442e48 refactor(lib): Update formatting for improved LDoc usage
- This makes it easier to see which function is being defined, but also allows LDocs / Emmy Annotations / whatever to display the full function name.
2021-10-19 08:50:42 +11:00
Linden f7ed2d5b60 chore: Bump version 2021-10-19 04:41:55 +11:00
Linden ec9d787be4 fix: Resolve null length on some queries
- Ensure parameters when checking length, and update dependencies for mysql2 patch
2021-10-19 04:26:08 +11:00
Linden abf259543d chore: Update version and dependencies 2021-10-18 02:19:09 +11:00
Linden 9d8a29388c fix(parser): Only assign null values if placeholders were found 2021-10-18 01:52:22 +11:00
Linden 00f9d0449c fix(regex): Prevent converting JSON in queries into placeholders
- When a JSON string is entered as part of a query, rather than a parameter, it is assumed to define a named placeholder - this will check for quotations and ignore it
2021-10-18 01:51:37 +11:00
Linden a46b586832 Merge pull request #51 from darksaid98/main
fix(parse): Resolve nil parameters when using `['@key'] = val`
2021-10-17 04:16:04 +11:00
darksaid98 dc50fe6dbb style: rename paramName variable 2021-10-16 19:11:09 +02:00
darksaid98 a6d483ca48 fix: nil parameters with named placeholders
- Fixes the remaining edge-case bug with passing nil parameters
2021-10-16 19:05:57 +02:00
Linden b1babdbc09 chore: Update version 2021-10-17 02:04:09 +11:00
Linden f8f97344fd Merge pull request #50 from darksaid98/varatstart
fix: Parameter keys beginning with ':' & '@'
2021-10-17 01:58:24 +11:00
darksaid98 48ee030372 fix: parameter keys beginning with : & @ 2021-10-16 16:02:43 +02:00
Linden fe1d6e6b05 fix(config): Reset colour after version check message 2021-10-16 10:46:29 +11:00
Linden c1f5bb3375 chore: Version bump 2021-10-16 10:43:27 +11:00
Linden d4e367baaf fix(lib): Allow transactions to utilise safeArgs function
- Also updates luadocs
2021-10-16 10:24:00 +11:00
Linden ce87bc488c fix(parser): Allow queries with multiple placeholders and no parameters
- '...?, ?, ?', {nil, nil, nil} will set all placeholders to null
2021-10-16 10:20:35 +11:00
Linden dc55401b78 fix: Return boolean for TINYINT 2021-10-16 10:20:35 +11:00
Linden 3b55e890a8 fix: Display correct query execution time 2021-10-16 10:20:35 +11:00
Linden bacd9c171d chore: Point mysql2 dependency to fork
I'd like some control over incoming changes to fit our use-case, and patch-package doesn't quite fulfil our needs.
2021-10-16 10:20:35 +11:00
Linden 29d28197bb chore: Version bump dependencies 2021-10-16 10:20:35 +11:00
Linden 4646c6f027 fix: Assign object entries to array
Assigning the entries to an array first permits comparing the lengths and setting undefined entries as null
2021-10-16 10:20:35 +11:00
Linden 30a391031b fix: Resolve error when parameter length does not match
- Throws a more specific error when receiving mismatch for column and value counts

- Resolves error when final parameter is nil
2021-10-16 10:20:35 +11:00
Linden 22de50c081 Apply mysql2 patch
- Remove extra _resolveNamedPlaceholders call from query

- Apply several patches by github/testn (pending merge); refer to pull requests #1408, #1402, #1401, #1400

- Optimise query.row call
- Cache lazy-evaluated field
- Optimise string decoding
- Avoid leaking TextRow/BinaryRow
2021-10-16 10:20:35 +11:00
Linden d0730c5e9b feat: Add support for nil parameters
- Throws an error if no params are defined when using named parameters, otherwise seems okay
2021-10-16 10:20:35 +11:00
Linden b781f0ca45 feat(lib): Setup support for lua docs 2021-10-15 18:41:17 +11:00
Linden 31959beb85 fix(manifest): Disable server_only
- Until dependencies can be used for server only resources, disable this to prevent clients failing to load.
2021-10-11 03:22:55 +11:00
Linden de2c731295 chore: Update comments for function return values 2021-10-08 15:58:11 +11:00
H@merandLinden 93ff6bae45 fix: Incorrect exports used in sync functions for transaction, single, and insert
* Fix insert return worng value.

* fix: Use the correct functions for execute/fetchAll

Co-authored-by: Linden <[email protected]>
2021-10-08 14:00:47 +11:00
Linden 1266f4a7b6 chore: Update dependencies and version bump 2021-10-08 11:17:50 +11:00
Linden a06cf65d10 feat(lib): safeArguments function to assert types
- Ensures each argument has the expected type
- Refactor each function for reduced code duplication
- Correctly check Store for number queries (Async functions did not retrieve string)
2021-10-08 05:51:07 +11:00
Linden 5b55c81046 chore: Update readme 2021-10-08 05:47:34 +11:00
dunak-debug 6acd0ac352 chore: Bump to 1.5.0 2021-10-06 23:52:38 +02:00
Dunak 55d8d46334 feat(ci): Include mysql-async compat library 2021-10-06 22:59:46 +02:00
Linden 4b179191d4 feat: Imports file for "mysql-async" like usage
- Include `server_script '@oxmysql/lib/MySQL.lua'` in the resource manifest

Mostly untested
2021-10-07 07:42:03 +11:00
Linden 1ec52903ca feat: Add support for semicolon connection strings 2021-10-07 06:26:07 +11:00
Linden 7e5d4cce06 chore: Version bump and set to production 2021-09-27 10:13:36 +10:00
Linden 681b39692a fix(pool): Increase default connection timeout
- Servers taking a while to start may experience a timeout; this should alleviate the issue
2021-09-27 10:13:11 +10:00
1A3 39c485644d fix: Regex fix for queries with commas (#31)
Fixes #24
2021-09-24 20:13:01 +02:00
darksaid98 634bbffd46 feat: version check on startup (#28) 2021-09-23 20:55:08 +02:00
Linden 273a4a8a89 Merge pull request #27 from gixels/main
Implemented the ability to change the port.
2021-09-23 05:03:27 +10:00
gixels b8249d5457 Implemented the ability to change the port. 2021-09-22 12:12:50 -04:00
dunak-debug 372a95632c refactor: Transaction tweaks and version bump 1.4.0 2021-09-20 17:32:58 +02:00
darksaid98 faae020dd4 feat: Added transactions support (#20)
* feat: transactions

* Adds transactions function
* Adds query & param parser with ghmattimysql compatability

* feat: transaction exports

* Adds exports for using transactions

* feat: set transaction isolation level on start

* feat: accept mysql-async syntax

* fix: acquire connection from pool

* refactor: syntactic sugar in transaction.js

* feat: optional error logging

* It ain't pretty but it gets the job done.

* Revert "feat: optional error logging"

This reverts commit fdff479f34b7575c240334cff0f4f12d03e0d48f.

* feat: transaction isolation level convar

* fix: requested changes
2021-09-20 16:48:24 +02:00
dunak-debug 5e89d62688 chore: Bump version to 1.3.5
- Removed unused ts-loader
2021-09-20 13:45:55 +02:00
dunak-debug 51ac8d1e8c refactor: Use logical OR operator when checking callback parameter 2021-09-20 13:39:46 +02:00
dunak-debug 466f230dc4 fix: Allow passing callback as second parameter 2021-09-20 13:36:07 +02:00
dunak-debug 06b106151f fix: Return null if query failed, show callback warning only in debug 2021-09-20 13:35:43 +02:00
Dunak a0573c8623 Merge pull request #22 from BerkieBb/main
Multi-game support
2021-09-19 21:38:22 +02:00
BerkieBb 076e327c9a feat: Change game to common to enable support for other game like rdr3 2021-09-19 20:41:30 +02:00
Linden c5f150e003 improvement: Only display warnings if callback is defined
- Non-function callbacks will display a warning.
- This makes the third argument optional for async queries.
2021-09-19 04:25:42 +10:00
dunak-debug 4b2b564591 chore: Bump version to 1.3.2 2021-09-18 12:45:37 +02:00
dunak-debug 3f57c566df feat: Show error trace if debug is enabled 2021-09-18 12:45:15 +02:00
Linden 5e6547611b refactor: safeCallback provides a warning, rather than an error
- The query does in fact proceed, but does not send a result
2021-09-18 11:08:21 +10:00
Linden be221b70d3 feat: Enable JS sync exports if wrapper.lua is not loaded 2021-09-18 10:28:40 +10:00
Linden f7dea332de improvement: Provide information when callback fails 2021-09-18 10:27:16 +10:00
Linden d2758de972 tweak: Query execution times are less precise unless using debug mode 2021-09-18 10:24:06 +10:00
dunak-debug c9acb09d08 refactor: Execute now return whole result object 2021-09-17 22:19:49 +02:00
dunak-debug 73ad12ed02 refactor: Show error type of nil params 2021-09-17 22:19:26 +02:00
dunak-debug 4654460e22 fix: Don´t throw error if parameter is zero or false, check for undefined 2021-09-17 20:01:47 +02:00
dunak-debug e23ba224aa fix: Execute export result checking 2021-09-17 18:09:11 +02:00
dunak-debug 878a2eb6c0 fix: **Use query instead of execute always**
- mysql2 typeCast doesn´t work on prepared statements
2021-09-17 18:06:03 +02:00
dunak-debug 290e23c190 refactor: Split files into src folder, fix parser 2021-09-17 17:20:17 +02:00
dunak-debug 546eebe1cf fix: Typo in wrapper 2021-09-17 17:19:30 +02:00
dunak-debug fd4fa877ec fix: Patch named placeholders, throw errors on nil values 2021-09-17 17:19:18 +02:00
dunak-debug 0a2f1ae856 chore: add prettier config 2021-09-17 17:18:42 +02:00
Dunak 72aafb8a16 Update pre-release.yml 2021-09-17 01:11:07 +02:00
Dunak 492aa947e6 Create pre-release.yml 2021-09-17 01:09:38 +02:00
Linden 20f35143db Revert "v2.0.0"
This reverts commit 49a5087d70.
2021-09-17 01:00:20 +02:00
dunak-debug cc74fac733 fix: Parameter parsing, new update export, null parameter warning
- fix https://github.com/overextended/oxmysql/issues/14
- fix ? https://github.com/overextended/oxmysql/issues/16
- fix https://github.com/overextended/oxmysql/issues/15
2021-09-17 00:54:13 +02:00
Linden b01e30d7b1 feat: New js sync exports (disabled by default)
New exports are faster than the lua wrapper and should be used to replace them

- Require a recent non-recommended server artifact
- If enabled, wrapper.lua should be removed

Lua 5.4 is enabled for improved memory and garbage collection when using the old wrapper
2021-09-17 06:30:58 +10:00
Linden 98a85faa1c tweaks: Improve logging data, adjust exports
- Display name of the resource displaying an error
- Correct query resolve time is displayed during heavy loads
- Removed local functions for sync exports
2021-09-17 04:50:16 +10:00
Linden 49a5087d70 v2.0.0 2021-09-17 01:09:04 +10:00
22 changed files with 943 additions and 1689 deletions

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
## Issue checklist
> Please put `x` inside of the box that matches your issue.
- [ ] I am using the latest release
- [ ] I have referenced previously reported issues
- [ ] I have referenced available documentation and cannot resolve the issue
- [ ] I'm certain this is an issue with oxymysql, and not with my resource
**Describe the bug**
A clear and concise description of what the bug is.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Code**
```lua
If applicable, include the query and relevant code
```
**Expected behavior**
A clear and concise description of what you expected to happen.
**Additional context**
Add any other context about the problem here.
**Server details**
- FX Server artifact
- Operating system
- Framework
+48
View File
@@ -0,0 +1,48 @@
name: Pre-Release
on:
workflow_dispatch:
inputs:
tag:
description: 'Version tag'
required: true
jobs:
create-release:
name: Build and Create Tagged Pre release
runs-on: ubuntu-latest
steps:
- name: Install archive tools
run: sudo apt install zip
- name: Checkout source code
uses: actions/checkout@v2
with:
fetch-depth: 0
ref: ${{ github.ref }}
- name: Install dependencies
run: yarn
- name: Run build
run: yarn build
- name: Bundle files
run: |
mv dist oxmysql
zip -r oxmysql-${{ github.event.inputs.tag }}.zip oxmysql
- name: Create Release
uses: "marvinpinto/[email protected]"
id: auto_release
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
title: "Experimental - ${{ github.event.inputs.tag }} (FOR TESTING PURPOSE)"
prerelease: true
automatic_release_tag: "${{ github.event.inputs.tag }}"
files: oxmysql-${{ github.event.inputs.tag }}.zip
env:
CI: false
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+1
View File
@@ -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
+9
View File
@@ -0,0 +1,9 @@
{
"printWidth": 120,
"singleQuote": true,
"useTabs": false,
"tabWidth": 2,
"semi": true,
"bracketSpacing": true,
"trailingComma": "es5"
}
+39 -5
View File
@@ -1,7 +1,41 @@
<h2 align='center'>oxmysql<p><a href='https://overextended.github.io/oxmysql/'>Documentation</a></p></h2> <h1 align='center'><a href='https://overextended.github.io/oxmysql/'>Documentation</a></h2>
### Introduction
Oxmysql is an alternative to the unmaintained mysql-async/ghmattimysql resources, utilising [node-mysql2](https://github.com/sidorares/node-mysql2) rather than [mysqljs](https://github.com/mysqljs/mysql).
There are several incompatibilities in the provided API, meaning we cannot guarantee 100% success when using a "drag-and-drop" mentality. For convenience we have included `@oxmysql/lib/MySQL.lua` to replace mysql-async in your resource manifests.
For more information regarding the use of queries, refer to the documentation linked above.
### Features
- Support for URI connection strings and semicolon separated values
- Asynchronous queries utilising mysql2/promises connection pool
- Lua promises in the `wrapper.lua` and `lib/MySQL.lua` files for improved performance when using sync functions
- Javascript async_retval exports when using recent FX Server builds (requires wrapper.lua to be removed)
- Support for placeholder values (named and unnamed) to improve query speed and increase security against SQL injection
- Improved error checking when placeholders and parameters do not match
### Placeholders
This allows queries to be properly prepared and escaped, as well as improve query times for frequently accessed queries.
The following lines are equivalent.
```
"SELECT group FROM users WHERE identifier = ?", {identifier}
"SELECT group FROM users WHERE identifier = :identifier", {identifier = identifier}
"SELECT group FROM users WHERE identifier = @identifier", {['@identifier'] = identifier}
```
You can also use the following syntax when you are uncertain about the column to select.
```
"SELECT ?? FROM users WHERE identifier = ?", {column, identifier}
instead of using
"SELECT "..column.." FROM users WHERE identifier = ?", {identifier}
```
<br><br><br><br><br>
<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>
oxmysql is a middleware for FXServer which utilises [node-mysql2](https://github.com/sidorares/node-mysql2) to communicate with a database and respond with the query results.
Calling the JS exports will result in async behaviour, or you can use the Lua exports to return a promise and await the response.
+10 -4
View File
@@ -1,11 +1,17 @@
fx_version 'cerulean' fx_version 'cerulean'
game 'gta5' 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.2.0' version '1.8.3'
url 'https://github.com/overextended/oxmysql' url 'https://github.com/overextended/oxmysql'
author 'overextended' author 'overextended'
use_fxv2_oal 'yes'
lua54 'yes'
server_scripts {'oxmysql.js', 'wrapper.lua'} server_scripts {
server_only 'true' 'oxmysql.js',
'wrapper.lua'
}
provide 'mysql-async'
+187
View File
@@ -0,0 +1,187 @@
-- This file allows simple conversion from MySQL-Async to Oxmysql
-- Replace any references to '@mysql-async' in your resource manifests to use '@oxmysql' instead
-- Store is used for compatibility only
local Ox = exports.oxmysql
local Store = {}
local function safeArgs(query, parameters, cb, transaction)
if type(query) == 'number' then query = Store[query] end
if transaction then
assert(type(query) == 'table', ('A table was expected for the transaction, but instead received %s'):format(query))
else
assert(type(query) == 'string', ('A string was expected for the query, but instead received %s'):format(query))
end
if cb then
assert(type(cb) == 'function', ('A callback function was expected, but instead received %s'):format(cb))
end
local type = parameters and type(parameters)
if type and type ~= 'table' and type ~= 'function' then
assert(nil, ('A %s was expected, but instead received %s'):format(cb and 'table' or 'function', parameters))
end
return query, parameters, cb
end
MySQL = { Async = {}, Sync = {} }
---@param query string
---@param parameters? table|function
---@param cb? function
---@return integer result
---returns number of rows updated by the executed query
MySQL.Async.execute = function(query, parameters, cb)
Ox:update(safeArgs(query, parameters, cb))
end
---@param query string
---@param parameters? table|function
---@param cb? function
---@return table result
---returns array of matching rows or result data
MySQL.Async.fetchAll = function(query, parameters, cb)
Ox:execute(safeArgs(query, parameters, cb))
end
---@param query string
---@param parameters? table|function
---@param cb? function
---@return integer|string
---returns value of the first column of a single row
MySQL.Async.fetchScalar = function(query, parameters, cb)
Ox:scalar(safeArgs(query, parameters, cb))
end
---@param query string
---@param parameters? table|function
---@param cb? function
---@return table result
---returns table containing key value pairs
MySQL.Async.fetchSingle = function(query, parameters, cb)
Ox:single(safeArgs(query, parameters, cb))
end
---@param query string
---@param parameters? table|function
---@param cb? function
---@return table result
---returns the last inserted id
MySQL.Async.insert = function(query, parameters, cb)
Ox:insert(safeArgs(query, parameters, cb))
end
---@param queries table
---@param parameters? table|function
---@param cb? function
---@return boolean result
---returns true when the transaction has succeeded
MySQL.Async.transaction = function(queries, parameters, cb)
Ox:transaction(safeArgs(queries, parameters, cb, true))
end
---@param query string
---@param cb? function
---@return integer result
---returns the id used to reference a stored query string
MySQL.Async.store = function(query, cb)
assert(type(query) == 'string', 'The SQL Query must be a string')
local store = #Store+1
Store[store] = query
cb(store)
end
---@param query string
---@param parameters? table|function
---@return integer result
---returns number of rows updated by the executed query
MySQL.Sync.execute = function(query, parameters)
query, parameters = safeArgs(query, parameters)
local promise = promise.new()
Ox:update(query, parameters, function(result)
promise:resolve(result)
end)
return Citizen.Await(promise)
end
---@param query string
---@param parameters? table|function
---@return table result
---returns array of matching rows or result data
MySQL.Sync.fetchAll = function(query, parameters)
query, parameters = safeArgs(query, parameters)
local promise = promise.new()
Ox:execute(query, parameters, function(result)
promise:resolve(result)
end)
return Citizen.Await(promise)
end
---@param query string
---@param parameters? table|function
---@return integer|string
---returns value of the first column of a single row
MySQL.Sync.fetchScalar = function(query, parameters)
query, parameters = safeArgs(query, parameters)
local promise = promise.new()
Ox:scalar(query, parameters, function(result)
promise:resolve(result)
end)
return Citizen.Await(promise)
end
---@param query string
---@param parameters? table|function
---@return table result
---returns table containing key value pairs
MySQL.Sync.fetchSingle = function(query, parameters)
query, parameters = safeArgs(query, parameters)
local promise = promise.new()
Ox:single(query, parameters, function(result)
promise:resolve(result)
end)
return Citizen.Await(promise)
end
---@param query string
---@param parameters? table|function
---@return table result
---returns the last inserted id
MySQL.Sync.insert = function(query, parameters)
query, parameters = safeArgs(query, parameters)
local promise = promise.new()
Ox:insert(query, parameters, function(result)
promise:resolve(result)
end)
return Citizen.Await(promise)
end
---@param queries table
---@param parameters? table|function
---@return boolean result
---returns true when the transaction has succeeded
MySQL.Sync.transaction = function(queries, parameters)
queries, parameters = safeArgs(queries, parameters, false, true)
local promise = promise.new()
Ox:transaction(queries, parameters, function(result)
promise:resolve(result)
end)
return Citizen.Await(promise)
end
---@param query string
---@return integer result
---returns the id used to reference a stored query string
MySQL.Sync.store = function(query)
assert(type(query) == 'string', 'The SQL Query must be a string')
local store = #Store+1
Store[store] = query
return store
end
MySQL.ready = function(cb)
CreateThread(function()
repeat
Wait(50)
until GetResourceState('oxmysql') == 'started'
cb()
end)
end
+131
View File
@@ -0,0 +1,131 @@
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)
-- Check for a recent native since the recommended artifact doesn't support JS async_retval or dependency constraints
if not GetEntityAttachedTo then
---@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()
oxmysql:execute(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
end)
---@param query string
---@param parameters? table
---@return table result
---returns array of matching rows or result data
exports('fetchSync', function(query, parameters)
local p = promise.new()
oxmysql:fetch(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
end)
---@param query string
---@param parameters? table
---@return table result
---returns table containing key value pairs
exports('singleSync', function(query, parameters)
local p = promise.new()
oxmysql:single(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
end)
---@param query string
---@param parameters? table
---@return integer|string
---returns value of the first column of a single row
exports('scalarSync', function(query, parameters)
local p = promise.new()
oxmysql:scalar(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
end)
---@param query string
---@param parameters? table
---@return table result
---returns the last inserted id
exports('insertSync', function(query, parameters)
local p = promise.new()
oxmysql:insert(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
end)
---@param query string
---@param parameters? table
---@return integer result
---returns number of rows updated by the executed query
exports('updateSync', function(query, parameters)
local p = promise.new()
oxmysql:update(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
end)
---@param queries table
---@param parameters? table
---@return boolean result
---returns true when the transaction has succeeded
exports('transactionSync', function(queries, parameters)
local p = promise.new()
oxmysql:transaction(queries, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
end)
---@param query string
---@param parameters table
---@return any result
---supports SELECT, INSERT, UPDATE, and DELETE
---
---return value is based on the number of results and the type of query used
exports('prepareSync', function(query, parameters)
local p = promise.new()
oxmysql:prepare(query, parameters, function(result)
p:resolve(result)
end, GetInvokingResource())
return Citizen.Await(p)
end)
end
-111
View File
@@ -1,111 +0,0 @@
/// <reference path="node_modules\@citizenfx\server\index.d.ts" />
const { createPool } = require("mysql2/promise");
const { ConnectionStringParser } = require("connection-string-parser");
const connectionString = GetConvar("mysql_connection_string", "");
if (connectionString === "") throw new Error(`Set up mysql_connection_string in server.cfg`);
const config = new ConnectionStringParser({
scheme: "mysql",
hosts: [],
}).parse(connectionString);
if (Object.keys(config).length === 0)
throw new Error(
`Set up mysql_connection_string in correct format - 'mysql://user:password@host/database'`
);
const slowQueryWarning = GetConvarInt("mysql_slow_query_warning", 100);
const debug = GetConvar("mysql_debug", "false") === "true";
const resourceName = GetCurrentResourceName() || "oxmysql";
const pool = createPool({
host: config.hosts[0].host,
user: config.username,
password: config.password,
database: config.endpoint,
charset: "utf8mb4_unicode_ci",
...config.options,
namedPlaceholders: true,
typeCast: (field, next) => {
if (field.type === "TINY" && field.length === 1) {
return field.string() === "1";
} else if (field.type === "BIT") {
return field.buffer()[0] === 1;
} else if (field.type === "TIMESTAMP" || field.type === "DATETIME") {
return new Date(field.string()).getTime() / 1000;
} else {
return next();
}
},
});
pool
.getConnection()
.then(() => {
console.info("Database server connection established.");
})
.catch((error) => {
console.error(error.message);
});
const execute = async (query, parameters, prepare = true) => {
ScheduleResourceTick(resourceName);
try {
const startTime = process.hrtime.bigint();
// FIX WHEN SENDING LUA {nil, something, nil} => [null, something, null] based on count of ? in query
// Named placeholders handles this in patch {var1 = nil, var2 = something} => { var1: null, var2: something }
if (Array.isArray(parameters) && query.includes("?")) {
const requiredParameters = query.match(/\?/g);
if (requiredParameters.length !== parameters.length)
requiredParameters.forEach((_, index) => (parameters[index] = parameters[index] || null));
}
const [result] = prepare
? await pool.execute(query, parameters)
: await pool.query(query, parameters);
const executionTime = Number(process.hrtime.bigint() - startTime) / 1e6;
if (executionTime >= slowQueryWarning || debug)
console.warn(`${query} took ${executionTime}ms!`, parameters);
return result;
} catch (error) {
console.error(error.message, query, parameters);
}
};
global.exports("execute", (query, parameters, callback = () => {}) => {
execute(query, parameters, false).then(
(result) => typeof callback === "function" && callback(result || false)
);
});
global.exports("insert", (query, parameters, callback = () => {}) => {
execute(query, parameters, false).then(
(result) => typeof callback === "function" && callback((result && result.insertId) || false)
);
});
global.exports("fetch", (query, parameters, callback = () => {}) => {
execute(query, parameters).then(
(result) => typeof callback === "function" && callback(result || false)
);
});
global.exports("single", (query, parameters, callback = () => {}) => {
execute(query, parameters).then(
(result) => typeof callback === "function" && callback((result && result[0]) || false)
);
});
global.exports("scalar", (query, parameters, callback = () => {}) => {
execute(query, parameters).then(
(result) =>
typeof callback === "function" &&
callback((result && result[0] && Object.values(result[0])[0]) || false)
);
});
+8 -10
View File
@@ -1,8 +1,8 @@
{ {
"name": "oxmysql", "name": "oxmysql",
"version": "1.2.0", "version": "1.0.0",
"main": "oxmysql.js", "main": "oxmysql.js",
"description": "FiveM MySQL wrapper using faster mysql2", "description": "node-mysql2 resource for Cfx",
"repository": "[email protected]:overextended/oxmysql.git", "repository": "[email protected]:overextended/oxmysql.git",
"author": "dunak-debug <[email protected]>", "author": "dunak-debug <[email protected]>",
"license": "GPL-3.0-or-later", "license": "GPL-3.0-or-later",
@@ -12,17 +12,15 @@
"postinstall": "patch-package" "postinstall": "patch-package"
}, },
"dependencies": { "dependencies": {
"@citizenfx/server": "^2.0.4376-1", "@citizenfx/server": "latest",
"connection-string-parser": "^1.0.4", "mysql2": "^2.3.3",
"mysql2": "^2.3.0",
"postinstall-postinstall": "^2.1.0" "postinstall-postinstall": "^2.1.0"
}, },
"devDependencies": { "devDependencies": {
"copy-webpack-plugin": "^9.0.1", "copy-webpack-plugin": "^10.0.0",
"patch-package": "^6.4.7", "patch-package": "^6.4.7",
"ts-loader": "^9.2.5", "typescript": "^4.5.2",
"typescript": "^4.4.3", "webpack": "^5.64.4",
"webpack": "^5.52.1", "webpack-cli": "^4.9.1"
"webpack-cli": "^4.8.0"
} }
} }
+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;
+11 -16
View File
@@ -1,5 +1,5 @@
diff --git a/node_modules/named-placeholders/index.js b/node_modules/named-placeholders/index.js diff --git a/node_modules/named-placeholders/index.js b/node_modules/named-placeholders/index.js
index 527d723..1a955b4 100644 index 527d723..f63ce28 100644
--- a/node_modules/named-placeholders/index.js --- a/node_modules/named-placeholders/index.js
+++ b/node_modules/named-placeholders/index.js +++ b/node_modules/named-placeholders/index.js
@@ -3,7 +3,7 @@ @@ -3,7 +3,7 @@
@@ -7,31 +7,26 @@ index 527d723..1a955b4 100644
// License: https://github.com/mscdex/node-mariasql/blob/master/LICENSE // License: https://github.com/mscdex/node-mariasql/blob/master/LICENSE
-const RE_PARAM = /(?:\?)|(?::(\d+|(?:[a-zA-Z][a-zA-Z0-9_]*)))/g, -const RE_PARAM = /(?:\?)|(?::(\d+|(?:[a-zA-Z][a-zA-Z0-9_]*)))/g,
+const RE_PARAM = /(?:\?)|(?:[:,@](\d+|(?:[a-zA-Z][a-zA-Z0-9_]*)))/g, +const RE_PARAM = /(?:\?)|(?:(?<!["'])[:@](\d+|(?:[a-zA-Z][a-zA-Z0-9_]*)))/g,
DQUOTE = 34, DQUOTE = 34,
SQUOTE = 39, SQUOTE = 39,
BSLASH = 92; BSLASH = 92;
@@ -94,15 +94,27 @@ function createCompiler(config) { @@ -94,15 +94,22 @@ function createCompiler(config) {
if (typeof params == 'undefined') if (typeof params == 'undefined')
throw new Error('Named query contains placeholders, but parameters object is undefined'); throw new Error('Named query contains placeholders, but parameters object is undefined');
+ let parsedParams = {}
+
+ for(const key in params) { + for(const key in params) {
+ parsedParams[key.charAt(0) == '@' ? key.substring(1) : key] = params[key] + if(key.charAt(0) === '@' || key.charAt(0) === ':') {
+ params[key.substring(1)] = params[key];
+ delete params[key];
+ }
+ } + }
+ +
const tokens = tree[1]; const tokens = tree[1];
for (let i=0; i < tokens.length; ++i) { for (let i=0; i < tokens.length; ++i) {
- arr.push(params[tokens[i]]); - arr.push(params[tokens[i]]);
+ if(typeof tokens[i] === 'number') { + arr.push(params[tokens[i]] === undefined ? null : params[tokens[i]]);
+ const param = parsedParams[(tokens[i] + 1).toString()];
+ arr.push(param !== undefined ? param : null);
+ } else {
+ arr.push(parsedParams[tokens[i]] !== undefined ? parsedParams[tokens[i]] : null);
+ }
} }
+
return [tree[0], arr]; return [tree[0], arr];
} }
@@ -41,7 +36,7 @@ index 527d723..1a955b4 100644
return s.slice(0, -1); return s.slice(0, -1);
} }
return s; return s;
@@ -115,7 +127,7 @@ function createCompiler(config) { @@ -115,7 +122,7 @@ function createCompiler(config) {
let unnamed = noTailingSemicolon(tree[0][0]); let unnamed = noTailingSemicolon(tree[0][0]);
for (let i=1; i < tree[0].length; ++i) { for (let i=1; i < tree[0].length; ++i) {
@@ -50,7 +45,7 @@ index 527d723..1a955b4 100644
unnamed += config.placeholder; unnamed += config.placeholder;
} }
unnamed += config.placeholder; unnamed += config.placeholder;
@@ -124,7 +136,7 @@ function createCompiler(config) { @@ -124,7 +131,7 @@ function createCompiler(config) {
const last = tree[0][tree[0].length -1]; const last = tree[0][tree[0].length -1];
if (tree[0].length == tree[1].length) { if (tree[0].length == tree[1].length) {
+21
View File
@@ -0,0 +1,21 @@
const slowQueryWarning = GetConvarInt('mysql_slow_query_warning', 150);
const debug = GetConvar('mysql_debug', 'false') === 'true';
const isolationLevel = (() => {
switch (GetConvarInt('mysql_transaction_isolation_level', 2)) {
case 1:
return 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ';
case 2:
return 'SET TRANSACTION ISOLATION LEVEL READ COMMITTED';
case 3:
return 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED';
case 4:
return 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE';
default:
return 'SET TRANSACTION ISOLATION LEVEL READ COMMITTED';
}
})();
const resourceName = GetCurrentResourceName();
export { slowQueryWarning, debug, isolationLevel, resourceName };
+9
View File
@@ -0,0 +1,9 @@
class FormatError extends Error {
constructor(message, query, parameters) {
super(message);
if (parameters) this.sql = `${query} ${JSON.stringify(parameters)}`;
else this.sql = query;
}
}
export { FormatError };
+102
View File
@@ -0,0 +1,102 @@
import { pool } from './pool';
import { parseParameters } from './parser';
import { slowQueryWarning, debug, resourceName } from './config';
import { FormatError } from './errors';
const execute = async (query, parameters, resource) => {
try {
[query, parameters] = parseParameters(query, parameters);
const connection = await pool.getConnection();
ScheduleResourceTick(resourceName);
const startTime = process.hrtime();
const [rows] = await connection.query(query, parameters);
const executionTime = process.hrtime(startTime)[1] / 1000000; // nanosecond to millisecond
if (executionTime >= slowQueryWarning || debug)
console.log(
`^3[${debug ? 'DEBUG' : 'WARNING'}] ${resource} took ${executionTime}ms to execute a query!
${query} ${JSON.stringify(parameters)}^0`
);
connection.release();
return rows;
} catch (error) {
console.log(
`^1[ERROR] ${resource} was unable to execute a query!
${error.message}
${error.sql || `${query} ${JSON.stringify(parameters)}`}^0`
);
debug && console.trace(error);
}
};
const queryType = (query) => {
switch (query.replace(/\s.*/, '')) {
case 'SELECT':
return 1;
case 'INSERT':
return 2;
case 'UPDATE':
return 3;
case 'DELETE':
return 3;
default:
return false;
}
};
const preparedStatement = async (query, parameters, resource) => {
try {
if (!Array.isArray(parameters))
throw new FormatError(`Placeholders were defined, but query received no parameters!`, query);
if (typeof query !== 'string') throw new FormatError(`Prepared statements must utilise a single query`);
const type = queryType(query);
if (!type) throw new FormatError(`Prepared statements only accept SELECT, INSERT, UPDATE, and DELETE methods!`);
const connection = await pool.getConnection();
ScheduleResourceTick(resourceName);
const results = [];
let queryCount = parameters.length;
const startTime = process.hrtime();
for (let i = 0; i < queryCount; i++) {
const [rows] = await connection.execute(query, parameters[i]);
results[i] = rows && (type === 3 ? rows.affectedRows : type === 2 ? rows.insertId : rows);
}
const executionTime = process.hrtime(startTime)[1] / 1000000; // nanosecond to millisecond
if (executionTime >= slowQueryWarning || debug)
console.log(
`^3[${debug ? 'DEBUG' : 'WARNING'}] ${resource} took ${executionTime}ms to execute ${
queryCount > 1 ? queryCount + ' queries' : 'a query'
}!
${query} ${JSON.stringify(parameters)}^0`
);
connection.release();
if (results.length === 1) {
if (type === 1) {
if (results[0][0] && Object.keys(results[0][0]).length === 1) {
return Object.values(results[0][0])[0];
}
return results[0][0];
}
return results[0];
}
return results;
} catch (error) {
console.log(
`^1[ERROR] ${resource} was unable to execute a query!
${error.message}
${error.sql || `${query} ${JSON.stringify(parameters)}`}^0`
);
debug && console.trace(error);
}
};
export { execute, preparedStatement };
+96
View File
@@ -0,0 +1,96 @@
import { pool } from './pool';
import { execute, preparedStatement } from './execute';
import { transaction } from './transaction';
import { debug, isolationLevel } 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) => {
if (typeof callback === 'function') callback(result);
};
global.exports('execute', (query, parameters, cb, resource = GetInvokingResource()) => {
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));
});
global.exports('update', (query, parameters, cb, resource = GetInvokingResource()) => {
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));
});
global.exports('single', (query, parameters, cb, resource = GetInvokingResource()) => {
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])
);
});
global.exports('transaction', (queries, parameters, cb, resource = GetInvokingResource()) => {
transaction(queries, parameters, resource).then((result) => {
safeCallback(cb || parameters, result || false, resource, debug && JSON.stringify(queries));
});
});
global.exports('prepare', (query, parameters, cb, resource = GetInvokingResource()) => {
preparedStatement(query, parameters, resource).then((result) => safeCallback(cb || parameters, result));
});
// Check for a recent native (~server artifact 4700) to enable JS exports
if (GetEntityAttachedTo !== undefined || !GetResourceMetadata(GetCurrentResourceName(), 'server_script', 1)) {
global.exports('prepareSync', async (query, parameters) => {
const result = await preparedStatement(query, parameters, GetInvokingResource());
return result;
});
global.exports('executeSync', async (query, parameters) => {
const result = await execute(query, parameters, GetInvokingResource());
return result;
});
global.exports('insertSync', async (query, parameters) => {
const result = await execute(query, parameters, GetInvokingResource());
return result && result.insertId;
});
global.exports('updateSync', async (query, parameters) => {
const result = await execute(query, parameters, GetInvokingResource());
return result && result.affectedRows;
});
global.exports('fetchSync', async (query, parameters) => {
const result = await execute(query, parameters, GetInvokingResource());
return result;
});
global.exports('singleSync', async (query, parameters) => {
const result = await execute(query, parameters, GetInvokingResource());
return result && result[0];
});
global.exports('scalarSync', async (query, parameters) => {
const result = await execute(query, parameters, GetInvokingResource());
return result && result[0] && Object.values(result[0])[0];
});
global.exports('transactionSync', async (queries, parameters) => {
const result = await transaction(queries, parameters, GetInvokingResource());
return result;
});
}
+97
View File
@@ -0,0 +1,97 @@
import { FormatError } from './errors';
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) => {
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();
}
};
const parseParameters = (query, parameters) => {
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;
})();
return [query, obj];
}
const queryParams = query.match(/\?(?!\?)/g);
if (queryParams === null) return [query, []];
if (parameters === undefined)
throw new FormatError(`Placeholders were defined, but query received no parameters!`, query);
if (!Array.isArray(parameters)) {
let arr = [];
Object.entries(parameters).forEach((entry) => {
const [key, value] = entry;
arr[key - 1] = value;
});
parameters = arr;
}
if (Array.isArray(parameters)) {
if (parameters.length === 0) {
for (let i = 0; i < queryParams.length; i++) parameters[i] = null;
return [query, parameters];
}
const diff = queryParams.length - parameters.length;
if (diff > 0) {
for (let i = 0; i < diff; i++) parameters[queryParams.length + i] = null;
}
}
return [query, parameters];
};
const parseTransaction = (queries, parameters) => {
//https://github.com/GHMatti/ghmattimysql/blob/37f1d2ae5c53f91782d168fe81fba80512d3c46d/packages/ghmattimysql/src/server/utility/sanitizeTransactionInput.ts#L5
if (!Array.isArray(queries)) throw new Error(`Transaction queries must be array type`);
const parsedTransaction = queries.map((query) => {
const [parsedQuery, parsedParameters] = parseParameters(
typeof query === 'object' ? query.query : query,
(typeof query === 'object' && (query.parameters || query.values)) || parameters || []
);
return { query: parsedQuery, params: parsedParameters };
});
return parsedTransaction;
};
export { parseTypes, parseParameters, parseTransaction };
+31
View File
@@ -0,0 +1,31 @@
import { createPool } from 'mysql2/promise';
import { parseTypes } from './parser';
const connectionString = GetConvar('mysql_connection_string', '');
if (connectionString === '') {
throw new Error(`Set up mysql_connection_string in server.cfg`);
}
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;
}, {});
options.namedPlaceholders = true;
options.typeCast = parseTypes;
return options;
})();
export const pool = createPool(dbOptions);
+52
View File
@@ -0,0 +1,52 @@
import { pool } from './pool';
import { parseTransaction } from './parser';
import { slowQueryWarning, debug, resourceName } from './config';
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)}`;
const transaction = async (queries, parameters, resource) => {
ScheduleResourceTick(resourceName);
const connection = await pool.getConnection();
try {
const startTime = process.hrtime();
const fullQuery = parseTransaction(queries, parameters);
const transactionAmount = fullQuery.length;
await connection.beginTransaction();
for (let i = 0; i < transactionAmount; i++) {
await connection.query(fullQuery[i].query, fullQuery[i].params);
}
await connection.commit();
const executionTime = process.hrtime(startTime)[1] / 1000000;
if (executionTime >= slowQueryWarning * transactionAmount || debug)
console.log(
`^3[${
debug ? 'DEBUG' : 'WARNING'
}] ${resource} took ${executionTime}ms to execute a transaction!\n${transactionError(queries, parameters)}^0`
);
return true;
} catch (error) {
await connection.rollback();
console.log(
`^1[ERROR] ${resource} was unable to execute a transaction!
${error.message}
${error.sql || `${transactionError(queries, parameters)}`}^0`
);
debug && console.trace(error);
} finally {
connection.release();
}
};
export { transaction };
+6 -6
View File
@@ -2,12 +2,9 @@ const path = require("path");
const { DefinePlugin, IgnorePlugin } = require("webpack"); const { DefinePlugin, IgnorePlugin } = require("webpack");
const CopyPlugin = require("copy-webpack-plugin"); const CopyPlugin = require("copy-webpack-plugin");
const filesToCopy = ["fxmanifest.lua", "wrapper.lua", "README.md", "LICENSE.md"];
module.exports = { module.exports = {
mode: "development", mode: "production",
devtool: "source-map", entry: "./src/index.js",
entry: "./oxmysql.js",
resolve: { resolve: {
extensions: [".js"], extensions: [".js"],
}, },
@@ -18,12 +15,15 @@ module.exports = {
contextRegExp: /./, contextRegExp: /./,
}), }),
new CopyPlugin({ new CopyPlugin({
patterns: filesToCopy, patterns: ["./lua", "./lua", "README.md", "LICENSE.md"],
}), }),
], ],
output: { output: {
filename: "oxmysql.js", filename: "oxmysql.js",
path: path.resolve(__dirname, "dist"), path: path.resolve(__dirname, "dist"),
}, },
optimization: {
minimize: false,
},
target: "node", target: "node",
}; };
-84
View File
@@ -1,84 +0,0 @@
---
-- Execute query and fetch affected rows
--
-- @param query tring
-- @param parameters table
--
-- @return table with result
--
local function executeSync(query, parameters)
local p = promise.new()
exports['oxmysql']:execute(query, parameters, function(result)
p:resolve(result)
end)
return Citizen.Await(p)
end
exports('executeSync', executeSync)
---
-- Execute query and fetch all result
--
-- @param query tring
-- @param parameters table
--
-- @return table with result
--
local function fetchSync(query, parameters)
local p = promise.new()
exports['oxmysql']:fetch(query, parameters, function(result)
p:resolve(result)
end)
return Citizen.Await(p)
end
exports('fetchSync', fetchSync)
---
-- Execute query and fetch first row
--
-- @param query tring
-- @param parameters table
--
-- @return table with result row
--
local function singleSync(query, parameters)
local p = promise.new()
exports['oxmysql']:single(query, parameters, function(result)
p:resolve(result)
end)
return Citizen.Await(p)
end
exports('singleSync', singleSync)
---
-- Execute query and fetch first column of first row
--
-- @param query tring
-- @param parameters table
--
-- @return result
--
local function scalarSync(query, parameters)
local p = promise.new()
exports['oxmysql']:scalar(query, parameters, function(result)
p:resolve(result)
end)
return Citizen.Await(p)
end
exports('scalarSync', scalarSync)
---
-- Insert data and return inserted id
--
-- @param query tring
-- @param parameters table
--
-- @return insert data result
--
local function insertSync(query, parameters)
local p = promise.new()
exports['oxmysql']:insert(query, parameters, function(result)
p:resolve(result)
end)
return Citizen.Await(p)
end
exports('insertSync', insertSync)
-1453
View File
File diff suppressed because it is too large. Load diff