Compare commits

..
168 Commits
Author SHA1 Message Date
Linden d54bcae363 fix(db): incorrect error reporting failed queries
When using callback functions and throwing an error (i.e. attempt to index a nil value), it would respond about an error in a nested ref call.

Don't catch callback errors.
2021-12-28 18:41:19 +11:00
Linden 75eedcbb09 fix(lib): accept cb.__cfx_functionReference during safeArgs 2021-12-28 01:36:03 +11:00
Linden 893b802029 fix(lib): set correct alias for execute
MySQL-async syntax was calling the execute export rather than update.
2021-12-25 04:10:09 +11:00
Linden 9b8d6d6c56 update release workflows 2021-12-25 01:58:04 +11:00
Linden 00bfcd35cc Relicense from GPL to LGPL
Since lib/MySQL is loaded into a resource as a module, it would technically require any resources linking to oxmysql to be licensed under GPLv3.
LGPL exists to provide this exception when dynamically linking modules.
2021-12-24 19:31:46 +11:00
Linden a12e6d8a94 fix(lib): safeArgs requires transaction for await 2021-12-24 17:37:21 +11:00
Linden 03b94c749f refactor(lib): MySQL.Sync and MySQL.Async shared __index method
Apply the same metatable and create both cb and promise variants when one is called.
Improve assertion error messages.
2021-12-24 17:35:27 +11:00
Dunak a047e21f51 fix(lib): Pass transaction to safeArgs 2021-12-23 22:37:50 +01:00
Linden e86bf26221 fix(lib): ensure safeArgs when using __call method
This asserts types and checks stored queries when sending a number.
2021-12-24 03:59:39 +11:00
Linden fc06cab6eb fix(lib): don't clear alias table
I'll fix that up later.
2021-12-24 03:51:18 +11:00
Linden 3fc3cfeecf feat(lib): setup new export wrappers with mysql-async aliases
i.e.
MySQL.Async.fetchAll = MySQL.query
MySQL.Sync.fetchAll = MySQL.query.await
MySQL.Async.fetchScalar = MySQL.scalar
MySQL.Sync.fetchScalar = MySQL.scalar.await

More information in issue #77
2021-12-24 03:31:36 +11:00
Linden f9c33be0fe refactor: rename exports
Removes _callback suffix from exports and bring some exports out of deprecation (single, scalar, etc).

"Sync" exports still use _async.
2021-12-24 03:08:06 +11:00
Linden 452d1ad5ee fix(execute): incorrect queryCount when sending single array
An array containing parameters, rather than arrays, is always a single query.
2021-12-23 19:50:21 +11:00
Linden 0537519c8a chore: update readme info and include some sample queries 2021-12-23 15:21:14 +11:00
Linden 36dd8ddd14 refactor: utilise new exports and deprecate old ones
Exports now utilise more accurate names to reflect their behaviour, with less confusion for JS users (await executeSync is no more).

Exports return promises or callback results directly to reduce promise chaining.

Promise exports now fully utilise JS, with Lua being removed from the resource - version checking runs through JS instead.

Various improvements to lib/MySQL as well as introduction of a prepare wrapper.
2021-12-23 14:15:17 +11:00
Linden e5c5fc3b1b refactor(execute): split into execute and query
query refers to the old execute function.
preparedStatement renamed to execute.

Parse arguments before establishing connection.
Utilise response function to determine and return correct values to the export.

execute now accepts an array of values when performing a single query, rather than requiring an array within an array.
2021-12-23 13:56:31 +11:00
Linden 860af3ff14 refactor(transaction): parse arguments prior to establishing connection
Rather then acquiring a connection, throwing an error, then closing the connection.
2021-12-23 13:51:20 +11:00
Linden 0afb32858d refactor(utils): rename parser and add additional functions
Create a handler for ScheduleResourceTick.
Handle serverReady function and isReady state.

Rewrite parameter parser to wrap all export arguments, ensure parameter and callbacks, and improve placeholder resolution.

Setup a response function to handle export return values.
2021-12-23 13:47:25 +11:00
Linden f5e25e3574 refactor(config): moved typeCast function into config 2021-12-23 13:42:12 +11:00
Linden 35f198f2b5 refactor(pool): cleanup connection options and createPool defaults
Additionally perform initial database connection as part of this module, rather than index.
2021-12-23 13:40:54 +11:00
Linden 17c4916010 refactor: replace webpack with esbuild 2021-12-23 13:35:43 +11:00
Linden b7a17d9566 refactor(patches): remove redundant code
mysql2 calls some code, namely _resolveNamedPlaceholders, that is handled by oxmysql before the query is executed.

Other changes:
Calculate query execution time as part of the Query command.
Check for undefined parameters during placeholder resolution.
2021-12-23 13:29:29 +11:00
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
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
Dunak 1e31cc0ace fix: typo in workflow 2021-09-12 18:11:56 +02:00
dunak-debug e09b3482ba chore: bump version to 1.2.0 2021-09-12 18:09:37 +02:00
Dunak a31df20979 Create release.yml 2021-09-12 18:07:44 +02:00
dunak-debug f6fb7cc017 fix: remove mysql2 patch, format lua parameters 2021-09-12 17:56:36 +02:00
dunak-debug 04e03e4fef fix: Type casting, removed old query format, dont prepare execute/insert
- fixed https://github.com/overextended/oxmysql/issues/6
- fixed https://github.com/overextended/oxmysql/issues/7
- fixed https://github.com/overextended/oxmysql/issues/8
- fixed https://github.com/overextended/oxmysql/issues/9
- closes https://github.com/overextended/oxmysql/issues/12
- support for modified named-placeholders package patch
2021-09-12 16:46:38 +02:00
dunak-debug 94bd814186 fix: patch mysql2, named-placeholders 2021-09-12 16:28:02 +02:00
dunak-debug 93d86f849a chore: bump version to 1.1.0 2021-09-11 03:40:23 +02:00
dunak-debug d6886bdd3f fix: leftover console.log, typeCast 2021-09-11 03:26:58 +02:00
dunak-debug 8c6c6119f1 feat: mysql-async/ghmatti '@' compatibility, debug, error handling
- Implemented mysql-async/ghmatti '@' syntax for queries and parameters
- Better error handling on database connection error
- Check callback type
- Added `mysql_debug` convar
- Resolves https://github.com/overextended/oxmysql/pull/4
Co-authored-by: pitermcflebor
2021-09-11 03:21:30 +02:00
Dunak 2af99e35a7 Update README.md 2021-09-09 22:23:03 +02:00
Dunak 03e6e534f5 Update README.md 2021-09-09 22:22:36 +02:00
Dunak 45f9f72daa Create FUNDING.yml 2021-09-09 22:20:31 +02:00
Dunak c4a9db0a79 Merge pull request #1 from darksaid98/main
feat(fxmanifest): set server_only
2021-09-09 16:01:36 +02:00
darksaid98 8be251382d feat(fxmanifest): set server_only
- Since the script only runs on the server there is no need for clients to be aware of it's existance
2021-09-09 15:28:34 +02:00
Dunak 6bfda0c64d Revert "Assets"
This reverts commit cf8eb3e590.
2021-09-09 12:41:12 +02:00
Dunak cf8eb3e590 Assets 2021-09-09 12:36:35 +02:00
Dunak 44c4ea5fba Update README.md 2021-09-08 23:55:32 +02:00
dunak-debug 6517951c83 feat: Parse URI-like connection string, support for slow query warning 2021-09-08 01:07:27 +02:00
Linden f252c94413 Refactor functions; change pool options 2021-08-29 09:16:39 +10:00
Linden 43c8ffd694 chore: Set default values for createPool 2021-08-20 06:58:22 +10:00
dunak-debug 5d50e098d8 fix(mysql): Use ScheduleResourceTick() instead of raw node.js api
- https://forum.cfx.re/t/node-mysql2-question-about-performance-process-nexttick/4550064/2?u=dunak
2021-08-19 02:49:26 +02:00
Linden dd85e2bf99 Update README.md 2021-08-18 13:31:47 +10:00
dunak-debug ce0d35fcf2 chore(version): setup first release 0.1.0 2021-08-17 16:50:25 +02:00
Dunak 36221e192f Create codeql-analysis.yml 2021-08-17 16:36:12 +02:00
Dunak 13bfd2c5b3 Update README.md 2021-08-17 16:33:21 +02:00
Linden 381578786f fix(js/exports): Set exports as global 2021-08-17 15:07:44 +10:00
dunak-debug 1f1cc61928 fix(scalar/single): fixed nested array access 2021-08-17 03:09:43 +02:00
dunak-debug 8df05c748b refactor: remove typescript and refactor 2021-08-17 02:58:31 +02:00
dunak-debug d2a9a433bb fix(callback): use process._tickCallback() fix (process.nextTick())
- this fixes whole issue with slow queries
- https://github.com/alcoholiclobster/fivem-mongodb/blob/400ac6615a334d43531a7a1824f2e8b540246fe2/index.js#L105
- setImmediate will just make performance worse
- now it also works in coroutine if yielded
- also i´m not sure why tickCallback helps, if somebody know i would be glad to know :D
- process.nextTick() is issue maybe, it works only for natives and not node functions
- process.nextTick isn't firing until the socket timeout callback fires
- discord conversation about it https://discord.com/channels/192358910387159041/433008322732490778/479523175869317130
2021-08-16 21:42:18 +02:00
dunak-debug f4dc666a98 Revert "fix(callback): forgot to wrap setImmediate on execute export"
This reverts commit ea98463224.
2021-08-16 21:36:04 +02:00
dunak-debug baa91dab4e Revert "fix(callback): use setImmediate to callback on main thread"
This reverts commit e9a18b5a46.
2021-08-16 21:35:55 +02:00
dunak-debug ea98463224 fix(callback): forgot to wrap setImmediate on execute export 2021-08-16 20:09:37 +02:00
dunak-debug e9a18b5a46 fix(callback): use setImmediate to callback on main thread
- maybe fix of random query times inside coroutines
2021-08-16 19:43:47 +02:00
Dunak ccf71fab83 Update README.md 2021-08-16 15:32:12 +02:00
dunak-debug c242e03baf feat(mysql): setup insert, single, scalar exports
- renamed test.lua to wrapper.lua
- use local function for documentation (maybe?)
- setup sync wrappers
2021-08-16 15:29:00 +02:00
dunak-debug b2ade77589 feat(mysql): setup execute export
- also setup test.lua for testing
2021-08-16 00:12:28 +02:00
dunak-debug 7afd440931 fix(webpack): fixed resolving .js extension when building
- also removed eslint
2021-08-15 16:48:29 +02:00
dunak-debug 1f675b44c4 Setup node package 2021-08-15 16:13:48 +02:00
dunak-debug 91e3af5a4c Initial commit 2021-08-15 15:39:27 +02:00
40 changed files with 1660 additions and 759 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
ko_fi: dunak
+41
View File
@@ -0,0 +1,41 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
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**
- FXServer artifact
- Operating system
**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.
+71
View File
@@ -0,0 +1,71 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ main ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ main ]
schedule:
- cron: '32 5 * * 2'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'javascript' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
-32
View File
@@ -1,32 +0,0 @@
name: build docs
on:
push:
branches:
- docs
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: "recursive"
fetch-depth: 0 # Fetch all history for .GitInfo and .Lastmod
- name: Setup Python
uses: actions/setup-python@v1
with:
python-version: '3.7'
architecture: 'x64'
- name: Install dependencies
run: |
python3 -m pip install --upgrade pip # install pip
python3 -m pip install mkdocs # install mkdocs
python3 -m pip install mkdocs-material # install material theme
python3 -m pip install -r ./requirements.txt
- name: Build site
run: mkdocs build
- name: Deploy
uses: JamesIves/[email protected]
with:
branch: gh-pages
folder: site
+50
View File
@@ -0,0 +1,50 @@
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: |
mkdir -p ./temp/oxmysql
cp ./{LICENSE,README.md,fxmanifest.lua} ./temp/oxmysql
cp -r ./{lib,dist} ./temp/oxmysql
cd ./temp && 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 }}
+50
View File
@@ -0,0 +1,50 @@
name: Release
on:
push:
tags:
- "v*"
jobs:
create-release:
name: Build and Create Tagged 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: Set env
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
- name: Install dependencies
run: yarn
- name: Run build
run: yarn build
- name: Bundle files
run: |
mkdir -p ./temp/oxmysql
cp ./{LICENSE,README.md,fxmanifest.lua} ./temp/oxmysql
cp -r ./{lib,dist} ./temp/oxmysql
cd ./temp && zip -r ../oxmysql-${{ env.RELEASE_VERSION }}.zip ./oxmysql
- name: Create Release
uses: "marvinpinto/[email protected]"
id: auto_release
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
title: ${{ env.RELEASE_VERSION }}
prerelease: false
files: oxmysql-${{ env.RELEASE_VERSION }}.zip
env:
CI: false
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+121 -2
View File
@@ -1,3 +1,122 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
.env.production
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist dist
node_modules
.yarn* # Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
yarn.lock
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# FiveM
.yarn.installed
+9
View File
@@ -0,0 +1,9 @@
{
"printWidth": 120,
"singleQuote": true,
"useTabs": false,
"tabWidth": 2,
"semi": true,
"bracketSpacing": true,
"trailingComma": "es5"
}
+165
View File
@@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
+65
View File
@@ -0,0 +1,65 @@
<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).
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.
### Features
- Support for URI connection strings and semicolon separated values
- Asynchronous queries utilising mysql2/promises connection pool
- Javascript async_retval exports supports promises across resources and runtimes
- 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
- Lua promises in `lib/MySQL.lua` files for improved performance when awaiting a response
- Support mysql-async syntax while providing newer (more accurate) names
### Usage
```lua
-- Lua
MySQL.query('SELECT * from users WHERE identifier = ?', {identifier}), function(result)
-- callback response
-- same as MySQL.Async.fetchAll
end)
CreateThread(function()
local result = MySQL.query.await('SELECT * from users WHERE identifier = ?', {identifier})
-- await a promise to resolve
-- same as MySQL.Sync.fetchAll
end)
```
```js
// JS
exports.oxmysql.query('SELECT * from users WHERE identifier = ?', [identifier], (result) => {
// callback response
})
(async() => {
const result = await exports.oxmysql.query_async('SELECT * from users WHERE identifier = ?', [identifier])
// await a promise to resolve
})()
exports.oxmysql.query_async('SELECT * from users WHERE identifier = ?', [identifier]).then((result) => {
// utilise .then to resolve a promise like a callback
})
```
For more information regarding the use of queries, refer to the documentation linked above.
### Placeholders
This allows queries to be properly prepared and escaped; 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>
<hr>
-1
View File
@@ -1 +0,0 @@
theme: jekyll-theme-minimal
-4
View File
@@ -1,4 +0,0 @@
nav:
- index.md
- issues.md
- usage
-82
View File
@@ -1,82 +0,0 @@
---
title: Getting Started
---
## Installation
- Download the [latest build](https://github.com/overextended/oxmysql/releases/latest) of oxmysql (not the source code).
- Extract the contents of the archive to your resources folder.
- Start the resource near the top of your resources in your `server.cfg`.
- If you have a lot of streamed assets, load them first to prevent timing out the connection.
## Configuration
You can change the configuration settings by using convars inside your `server.cfg`.
Reference the following for an idea of how to set your connection options.
You must include one of the following lines, adjusted for your connection and database settings.
```
set mysql_connection_string "mysql://root:12345@localhost/es_extended?charset=utf8mb4"
set mysql_connection_string "user=root;database=es_extended;password=12345;charset=utf8mb4"
```
Certain special characters are reserved or blocked and may cause issues when used in your password.
You can also add the following convars if you require extra information when testing queries.
```
set mysql_slow_query_warning 150
set mysql_debug true
```
For more optional settings (such as multiple statements) you can reference [pool.d.ts](https://github.com/sidorares/node-mysql2/blob/master/typings/mysql/lib/Pool.d.ts#L10) and [connection.d.ts](https://github.com/sidorares/node-mysql2/blob/master/typings/mysql/lib/Connection.d.ts#L8).
## Benchmark
```
Lua: Low: 0.2167ms | Avg: 0.28788843ms | Total: 2878.8843ms (10000 queries)
JS: Low: 0.2098ms | Avg: 0.29384436ms | Total: 2938.4436ms (10000 queries)
```
These benchmarks await the previous response rather than occuring asynchronously, and measure the total time spent executing the export.
The `MySQL.Sync.prepare` function calls `exports.oxmysql:execute_async`, as used in the JS sample.
#### Lua (5.4)
```lua
local val = 10000
RegisterCommand('luasync', function()
local queryTimesLocal = {}
local result
local r = MySQL.Sync.prepare('SELECT identifier from users WHERE lastname = ?', {'Linden'})
for i=1, val do
local time = os.nanotime()
local r = MySQL.Sync.prepare('SELECT identifier from users WHERE lastname = ?', {'Linden'})
queryTimesLocal[#queryTimesLocal+1] = (os.nanotime() - time) / 1000000
if i==1 then result = r end
end
local queryMsLow, queryMsSum = 1000, 0
for _, v in pairs(queryTimesLocal) do
queryMsSum = queryMsSum + v
end
for _, v in pairs(queryTimesLocal) do
if v < queryMsLow then queryMsLow = v end
end
local averageQueryTime = queryMsSum / #queryTimesLocal
print(json.encode(result))
print('Low: '.. queryMsLow ..'ms | Avg: '..averageQueryTime..'ms | Total: '..queryMsSum..'ms ('..#queryTimesLocal..' queries)')
end)
```
#### JavaScript
```js
const val = 10000
RegisterCommand('jssync', async() => {
const queryTimesLocal = [];
let result
for(let i=0; i < val; i++) {
const startTime = process.hrtime()
const r = await exports.oxmysql.execute_async('SELECT identifier from users WHERE lastname = ?', ['Linden'])
queryTimesLocal.push(process.hrtime(startTime)[1] / 1000000)
if (i === 0) result = r
}
const queryMsSum = queryTimesLocal.reduce((a, b) => a + b, 0)
const queryMsLow = queryTimesLocal.sort((a, b) => a - b)[0]
const averageQueryTime = queryMsSum / queryTimesLocal.length
console.log(result)
console.log('Low: '+ queryMsLow +'ms | Avg: '+averageQueryTime+'ms | Total: '+queryMsSum+'ms ('+queryTimesLocal.length+' queries)')
})
```
-12
View File
@@ -1,12 +0,0 @@
---
title: Common issues
---
### Unable to establish a connection
This is usually the result of incorrect database settings or your password containing reserved characters (typically `; , / ? : @ & = + $ #`).
!!! check "Solution"
Ensure you have entered the correct database settings in the mysql_connection_string convar. You can try using the semicolon-separated format if your password contains reserved characters.
### No such export ... in resource oxmysql
Typically the result of failing to follow instructions.
!!! check "Solution"
Download the latest release _build_ (not source) of oxmysql, and ensure it is starting before any resources that require it.
-22
View File
@@ -1,22 +0,0 @@
.md-content {
--md-typeset-a-color: rgb(83, 108, 238);
}
.md-typeset {
color-adjust: exact;
font-size: .71rem;
line-height: 1.3;
}
[data-md-color-scheme="slate"] {
--md-hue: 215;
--md-default-bg-color: rgb(40, 43, 57);
}
[data-md-color-primary="indigo"] {
--md-primary-fg-color: rgb(55, 70, 149);
--md-primary-fg-color--light: rgb(93, 108, 192);
--md-primary-fg-color--dark: rgb(48, 63, 161);
--md-primary-bg-color: rgb(255, 255, 255);
--md-primary-bg-color--light: rgba(255, 255, 255, 0.7);
}
-5
View File
@@ -1,5 +0,0 @@
---
title: Index
---
todo - include some information about proper formatting, placeholders, bad practices, etc.
-43
View File
@@ -1,43 +0,0 @@
---
title: insert
---
Inserts a new entry into the database and returns the insert id for the row, if valid.
!!! info "Example"
=== "Lua"
**Callback**
```lua
-- Alias: exports.oxmysql:insert
-- Alias: MySQL.Async.insert
MySQL.insert('INSERT INTO users (identifier, firstname, lastname) VALUES (?, ?, ?) ', {playerIdentifier, firstName, lastName}, function(id)
print(id)
end)
```
**Promise**
```lua
-- Alias: exports.oxmysql:insert_async
-- Alias: MySQL.Sync.insert
CreateThread(function()
local id = MySQL.insert.await('INSERT INTO users (identifier, firstname, lastname) VALUES (?, ?, ?) ', {playerIdentifier, firstName, lastName})
print(id)
end)
```
=== "JavaScript"
**Callback**
```js
exports.oxmysql.insert('INSERT INTO users (identifier, firstname, lastname) VALUES (?, ?, ?) ', [playerIdentifier, firstName, lastName], function(id) {
console.log(id)
})
```
**Promise**
```js
(async () => {
const id = exports.oxmysql.insert_async('INSERT INTO users (identifier, firstname, lastname) VALUES (?, ?, ?) ', [playerIdentifier, firstName, lastName]) {
console.log(id)
})()
```
-114
View File
@@ -1,114 +0,0 @@
---
title: prepare
---
The only function that provides true [prepared statements](https://github.com/sidorares/node-mysql2#using-prepared-statements), granting native protection and query planning by MySQL.
Prepare can be used to execute frequently called queries faster and accepts multiple sets of parameters to be used with a single query.
- Date will not return the datestring commonly used in FiveM
- TINYINT 1 and BIT will not return a boolean
- You can only use `?` value placeholders, `??` column placeholders and named placeholders will throw an error
When using SELECT, the return value will match `fetchAll, fetchSingle, or fetchScalar` depending on the number of columns and rows selected.
!!! info "Example"
=== "Lua"
**Callback**
```lua
-- Alias: exports.oxmysql:prepare
-- Alias: MySQL.Async.prepare
MySQL.prepare('SELECT * FROM users WHERE identifier = ?', {playerIdentifier}, function(result)
if result then
for _, v in pairs(result) do
print(v.identifier, v.firstname, v.lastname)
end
end
end)
```
**Promise**
```lua
-- Alias: exports.oxmysql:prepare_async
-- Alias: MySQL.Sync.prepare
CreateThread(function()
local result = MySQL.prepare.await('SELECT * FROM users WHERE identifier = ?', {playerIdentifier})
if result then
for _, v in pairs(result) do
print(v.identifier, v.firstname, v.lastname)
end
end
end)
```
=== "JavaScript"
**Callback**
```js
exports.oxmysql.prepare('SELECT * FROM users WHERE identifier = ?', [playerIdentifier], function(result) {
if (result) {
result.forEach((v) => {
console.log(v.identifier, v.firstname, v.lastname)
})
}
})
```
**Promise**
```js
(async () => {
const result = await exports.oxmysql.prepare_async('SELECT * FROM users WHERE identifier = ?', [playerIdentifier]) {
if (result) {
result.forEach((v) => {
console.log(v.identifier, v.firstname, v.lastname)
})
}
})()
```
As mentioned above, you can utilise an array of parameters for a transaction-like query without the rollback; reducing the number of exports being performed reduces strain on the server. Included below is some examples of using prepare in ESX Legacy.
```lua
ESX.SavePlayer = function(xPlayer, cb)
MySQL.Async.prepare("UPDATE `users` SET `accounts` = ?, `job` = ?, `job_grade` = ?, `group` = ?, `position` = ?, `inventory` = ? WHERE `identifier` = ?", {{
json.encode(xPlayer.getAccounts(true)),
xPlayer.job.name,
xPlayer.job.grade,
xPlayer.group,
json.encode(xPlayer.getCoords()),
json.encode(xPlayer.getInventory(true)),
xPlayer.identifier
}}, function(affectedRows)
if affectedRows == 1 then
print(('[^2INFO^7] Saved player ^5"%s^7"'):format(xPlayer.name))
end
if cb then cb() end
end)
end
ESX.SavePlayers = function(cb)
local xPlayers = ESX.GetExtendedPlayers()
local count = #xPlayers
if count > 0 then
local parameters = {}
for i=1, count do
local xPlayer = xPlayers[i]
parameters[#parameters+1] = {
json.encode(xPlayer.getAccounts(true)),
xPlayer.job.name,
xPlayer.job.grade,
xPlayer.group,
json.encode(xPlayer.getCoords()),
json.encode(xPlayer.getInventory(true)),
xPlayer.identifier
}
end
MySQL.Async.prepare("UPDATE `users` SET `accounts` = ?, `job` = ?, `job_grade` = ?, `group` = ?, `position` = ?, `inventory` = ? WHERE `identifier` = ?", parameters,
function(results)
if results then
if type(cb) == 'function' then cb() else print(('[^2INFO^7] Saved %s %s'):format(count, count > 1 and 'players' or 'player') end
end
end)
end
end
```
-60
View File
@@ -1,60 +0,0 @@
---
title: query
---
Generic function that can be utilised for any query.
When selecting data it will return all matching rows and columns, otherwise it will return field data such as insertid, affectedRows, etc.
!!! info "Example"
=== "Lua"
**Callback**
```lua
-- Alias: exports.oxmysql:query
-- Alias: MySQL.Async.query
MySQL.query('SELECT * FROM users WHERE identifier = ?', {playerIdentifier}, function(result)
if result then
for _, v in pairs(result) do
print(v.identifier, v.firstname, v.lastname)
end
end
end)
```
**Promise**
```lua
-- Alias: exports.oxmysql:query
-- Alias: MySQL.Sync.query
CreateThread(function()
local result = MySQL.query.await('SELECT * FROM users WHERE identifier = ?', {playerIdentifier})
if result then
for _, v in pairs(result) do
print(v.identifier, v.firstname, v.lastname)
end
end
end)
```
=== "JavaScript"
**Callback**
```js
exports.oxmysql.query('SELECT * FROM users WHERE identifier = ?', [playerIdentifier], function(result) {
if (result) {
result.forEach((v) => {
console.log(v.identifier, v.firstname, v.lastname)
})
}
})
```
**Promise**
```js
(async () => {
const result = await exports.oxmysql.query_async('SELECT * FROM users WHERE identifier = ?', [playerIdentifier]) {
if (result) {
result.forEach((v) => {
console.log(v.identifier, v.firstname, v.lastname)
})
}
})()
```
-43
View File
@@ -1,43 +0,0 @@
---
title: scalar
---
Returns the first column for a single row.
!!! info "Example"
=== "Lua"
**Callback**
```lua
-- Alias: exports.oxmysql:scalar
-- Alias: MySQL.Async.fetchScalar
MySQL.scalar('SELECT firstname FROM users WHERE identifier = ?', {playerIdentifier}, function(firstname)
print(firstname)
end)
```
**Promise**
```lua
-- Alias: exports.oxmysql:scalar_async
-- Alias: MySQL.Sync.fetchScalar
CreateThread(function()
local firstname = MySQL.scalar.await('SELECT firstname FROM users WHERE identifier = ?', {playerIdentifier})
print(firstname)
end)
```
=== "JavaScript"
**Callback**
```js
exports.oxmysql.scalar('SELECT firstname FROM users WHERE identifier = ?', [playerIdentifier], function(firstname) {
console.log(firstname)
})
```
**Promise**
```js
(async () => {
const firstname = await exports.oxmysql.scalar_async('SELECT firstname FROM users WHERE identifier = ?', [playerIdentifier]) {
console.log(firstname)
})()
```
-49
View File
@@ -1,49 +0,0 @@
---
title: single
---
Returns the columns for a single row.
!!! info "Example"
=== "Lua"
**Callback**
```lua
-- Alias: exports.oxmysql:single
-- Alias: MySQL.Async.fetchSingle
MySQL.single('SELECT * FROM users WHERE identifier = ?', {playerIdentifier}, function(result)
if result then
print(result.identifier, result.firstname, result.lastname)
end
end)
```
**Promise**
```lua
-- Alias: exports.oxmysql:single_async
-- Alias: MySQL.Sync.fetchSingle
CreateThread(function()
local result = MySQL.single.await('SELECT * FROM users WHERE identifier = ?', {playerIdentifier})
if result then
print(result.identifier, result.firstname, result.lastname)
end
end)
```
=== "JavaScript"
**Callback**
```js
exports.oxmysql.single('SELECT * FROM users WHERE identifier = ?', [playerIdentifier], function(result) {
if (result)
console.log(result.identifier, result.firstname, result.lastname)
})
```
**Promise**
```js
setImmediate(async () => {
const result = await exports.oxmysql.single_async('SELECT * FROM users WHERE identifier = ?', [playerIdentifier]) {
if (result)
console.log(result.identifier, result.firstname, result.lastname)
})
```
-102
View File
@@ -1,102 +0,0 @@
---
title: transaction
---
todo - update formatting and information
# Transactions
A transaction executes multiple queries and commits them only if all succeed. If one fails, none of the queries are committed. The return value is a `boolean`, which is the result of the transaction.
## Specific Format
When using the `Specific` format you must pass one parameter to the oxmysql export. In this case, the `queries` parameter contains your queries and the SQL variables unique to each query.
This is useful for transactions where the queries do not share many SQL variables.
### Usage
Lua
```lua
local queries = {
{ query = 'INSERT INTO `test` (id) VALUES (:someid)', values = { ['someid'] = 1 } },
{ query = 'INSERT INTO `test` (id) VALUES (:someid)', values = { ['someid'] = 2 } }
} -- NOTE, the 'values' tables can be named 'parameters' here for MySQL-Async compatibility.
-- Async
exports.oxmysql:transaction(queries, function(result)
print(result)
end)
-- Sync
local result = exports.oxmysql:transactionSync(queries)
print(result)
```
JavaScript
```js
const queries = [
{ query = 'INSERT INTO `test` (id) VALUES (:someid)', values = { someid = 1 } },
{ query = 'INSERT INTO `test` (id) VALUES (:someid)', values = { someid = 2 } }
] // NOTE, the 'values' objects can be named 'parameters' here for MySQL-Async compatibility.
// Async
exports.oxmysql.transaction(queries, (result) => {
console.log(result)
})
// Sync
const result = await exports.oxmysql.transactionSync(queries)
console.log(result)
```
### Shared Format
When using the `Shared` format you must pass two parameters to the oxmysql export. The `queries` and the `parameters` those queries will use.
This is useful if your queries use the same SQL variables.
Lua
```lua
local queries = {
'INSERT INTO `test` (id, name) VALUES (:someid, :somename)',
'SET `name` = :newname IN `test` WHERE `id` = :someid'
}
local parameters = { ['someid'] = 2, ['somename'] = 'John Doe', ['newname'] = 'John Notdoe' }
-- Async
exports.oxmysql:transaction(queries, parameters, function(result)
print(result)
end)
-- Sync
local result = exports.oxmysql:transactionSync(queries, parameters)
print(result)
```
JavaScript
```js
const queries = [
'INSERT INTO `test` (id, name) VALUES (:someid, :somename)',
'SET `name` = :newname IN `test` WHERE `id` = :someid'
]
const parameters = { someid = 2, somename = 'John Doe', newname = 'John Notdoe' }
// Async
exports.oxmysql.transaction(queries, parameters, (result) => {
console.log(result)
})
// Sync
const result = await exports.oxmysql.transactionSync(queries, parameters)
console.log(result)
```
## Transaction Isolation Level
This can be set through the convar `mysql_transaction_isolation_level` which should be an integer ranging from `1-4`. The default convar value set by oxmysql is `2`.
| Convar Value | Result |
| -------------- | ------------------ |
| 1 | Repeatable Read |
| 2 | Read Committed |
| 3 | Read Uncommitted |
| 4 | Serializable |
-49
View File
@@ -1,49 +0,0 @@
---
title: update
---
Returns the number of affected rows by the query.
!!! info "Example"
=== "Lua"
**Callback**
```lua
-- Alias: exports.oxmysql:update
-- Alias: MySQL.Async.update
MySQL.Async.update('UPDATE users SET firstname = ? WHERE identifier = ? ', {newName, playerIdentifier}, function(affectedRows)
if affectedRows then
print(affectedRows)
end
end)
```
**Promise**
```lua
-- Alias: exports.oxmysql:update_async
-- Alias: MySQL.update
CreateThread(function()
local affectedRows = MySQL.update.await('UPDATE users SET firstname = ? WHERE identifier = ? ', {newName, playerIdentifier})
if affectedRows then
print(affectedRows)
end
end)
```
=== "JavaScript"
**Callback**
```js
exports.oxmysql.update('UPDATE users SET firstname = ? WHERE identifier = ? ', [newName, playerIdentifier], function(affectedRows) {
if (affectedRows)
console.log(affectedRows)
})
```
**Promise**
```js
setImmediate(async () => {
const id = exports.oxmysql.update_async('UPDATE users SET firstname = ? WHERE identifier = ? ', [newName, playerIdentifier]) {
if (affectedRows)
console.log(affectedRows)
})
```
+18
View File
@@ -0,0 +1,18 @@
fx_version 'cerulean'
game 'common'
name 'oxmysql'
description 'Database wrapper for FiveM utilising node-mysql2 offering improved performance and security.'
version '1.9.1'
url 'https://github.com/overextended/oxmysql'
author 'overextended'
dependencies {
'/server:5104',
}
server_scripts {
'dist/server/build.js',
}
provide 'mysql-async'
+159
View File
@@ -0,0 +1,159 @@
-- lib/MySQL.lua provides complete compatibility for resources designed for mysql-async
-- As of v2.0.0 this is the preferred method of interacting with oxmysql
-- * You can use mysql-async syntax or oxmysql syntax (refer to issue #77 or line 118)
-- * Using this lib provides minor improvements to performance and helps debug poor queries
-- * If using mysql-async syntax, a resource is not explicity bound to using oxmysql
-- todo: new annotations; need to see if I can get it working with metatables, otherwise it'll need stubs
local Store = {}
local function addStore(query, cb)
assert(type(query) == 'string', 'The SQL Query must be a string')
local store = #Store+1
Store[store] = query
if cb then cb(store) else return store end
end
local MySQL = {
Sync = { store = addStore },
Async = { store = addStore },
ready = function(cb)
CreateThread(function()
repeat
Wait(50)
until GetResourceState('oxmysql') == 'started'
cb()
end)
end
}
local type = type
local function safeArgs(query, parameters, cb, transaction)
if type(query) == 'number' then query = Store[query] end
if transaction then
assert(type(query) == 'table', ('Transaction query expects a table, received %s'):format(query))
else
assert(type(query) == 'string', ('Query expects a string, received %s'):format(query))
end
if parameters then
local type = type(parameters)
if type ~= 'table' and type ~= 'function' then
error(('Parameters expected table or function, received %s'):format(parameters))
end
end
if cb then
local type = type(cb)
if type ~= 'function' and (type == 'table' and not cb.__cfx_functionReference) then
error(('Callback expects a function, received %s'):format(cb))
end
end
return query, parameters, cb
end
local promise = promise
local oxmysql = exports.oxmysql
local Await = Citizen.Await
local GetCurrentResourceName = GetCurrentResourceName()
local function await(fn, query, parameters)
local p = promise.new()
fn(nil, query, parameters, function(result)
p:resolve(result)
end, GetCurrentResourceName)
return Await(p)
end
setmetatable(MySQL, {
__index = function(self, method)
local state = GetResourceState('oxmysql')
if state == 'started' or state == 'starting' then
self[method] = setmetatable({}, {
__call = function(_, query, parameters, cb)
return oxmysql[method](nil, safeArgs(query, parameters, cb, method == 'transaction'))
end,
__index = function(_, index)
assert(index == 'await', ('unable to index MySQL.%s.%s, expected .await'):format(method, index))
self[method].await = function(query, parameters)
return await(oxmysql[method], safeArgs(query, parameters, nil, method == 'transaction'))
end
return self[method].await
end
})
return self[method]
else
error(('^1oxmysql resource state is %s - unable to trigger exports.oxmysql:%s^0'):format(state, method), 0)
end
end
})
local alias = {
fetchAll = 'query',
fetchScalar = 'scalar',
fetchSingle = 'single',
insert = 'insert',
execute = 'update',
transaction = 'transaction',
prepare = 'prepare'
}
local alias_mt = {
__index = function(self, key)
if alias[key] then
MySQL.Async[key] = MySQL[alias[key]]
MySQL.Sync[key] = MySQL[alias[key]].await
alias[key] = nil
return self[key]
end
end
}
setmetatable(MySQL.Async, alias_mt)
setmetatable(MySQL.Sync, alias_mt)
_ENV.MySQL = MySQL
--[[
exports.oxmysql:query (previously exports.oxmysql:execute)
MySQL.Async.fetchAll = MySQL.query
MySQL.Sync.fetchAll = MySQL.query.await
exports.oxmysql:scalar
MySQL.Async.fetchScalar = MySQL.scalar
MySQL.Sync.fetchScalar = MySQL.scalar.await
exports.oxmysql:single
MySQL.Async.fetchSingle = MySQL.single
MySQL.Sync.fetchSingle = MySQL.single.await
exports.oxmysql:insert
MySQL.Async.insert = MySQL.insert
MySQL.Sync.insert = MySQL.insert.await
exports.oxmysql:update
MySQL.Async.execute = MySQL.update
MySQL.Sync.execute = MySQL.update.await
exports.oxmysql:transaction
MySQL.Async.transaction = MySQL.transaction
MySQL.Sync.transaction = MySQL.transaction.await
exports.oxmysql:prepare
MySQL.Async.prepare = MySQL.prepare
MySQL.Sync.prepare = MySQL.prepare.await
--]]
-132
View File
@@ -1,132 +0,0 @@
site_name: OxMySQL
site_description: Documentation
site_author: Overextended
# Repository
repo_name: OxMySQL
repo_url: https://github.com/overextended/oxmysql
edit_uri: ""
# Copyright
copyright: Copyright &copy; 2021 Overextended
# Configuration
docs_dir: docs
site_dir: site
strict: true
# nav:
# - Getting Started: "index.md"
# - Functions:
# - "functions/index.md"
# - Client:
# - "functions/client/progress.md"
# - "functions/client/playanim.md"
# - "functions/client/playanimadvanced.md"
# - "functions/client/inventorysearch.md"
# - Shared:
# - "functions/shared/checktable.md"
# - "functions/shared/copytable.md"
# - "functions/shared/matchtables.md"
# - "functions/shared/tablecontains.md"
# - Items:
# - items/index.md
# - items/client.md
# - items/server.md
# Theme
theme:
name: material
# 404 Page
static_templates:
- 404.html
# Don't include MKDoc's JavaScript
include_search_page: false
search_index_only: true
# Default values, taken from mkdocs_theme.yml
language: en
features:
- tabs
- navigation.instant
- navigation.tabs
- navigation.tabs.sticky
- toc.integrate
- navigation.top
palette:
scheme: slate
primary: indigo
accent: indigo
font:
text: Roboto
code: Roboto Code
icon:
logo: material/school
repo: fontawesome/brands/github
favicon: assets/images/favicon.png
# Plugins
plugins:
- search
- awesome-pages
extra_css:
- stylesheets/extra.css
# Social
extra:
social:
- icon: fontawesome/brands/github
link: https://github.com/overextended/ox_inventory
- icon: fontawesome/brands/discord
link: https://discord.io/overextended
# Extensions
markdown_extensions:
- toc:
toc_depth: 2
- markdown.extensions.admonition
- markdown.extensions.attr_list
- markdown.extensions.codehilite:
guess_lang: false
linenums: true
- markdown.extensions.def_list
- markdown.extensions.footnotes
- markdown.extensions.meta
- markdown.extensions.toc:
permalink: true
- pymdownx.betterem:
smart_enable: all
- pymdownx.caret
- pymdownx.critic
- pymdownx.details
- pymdownx.emoji:
emoji_index: !!python/name:materialx.emoji.twemoji
emoji_generator: !!python/name:materialx.emoji.to_svg
- pymdownx.inlinehilite
- pymdownx.keys
- pymdownx.magiclink:
provider: "github"
repo_url_shortener: true
repo_url_shorthand: true
social_url_shorthand: true
labels:
{
"commit": "Commit",
"compare": "Compare",
"issue": "Issue",
"pr": "Pull Request",
"mention": "User",
"repo": "Repository",
}
- pymdownx.mark
- pymdownx.smartsymbols
- pymdownx.snippets:
check_paths: true
- pymdownx.superfences
- pymdownx.tabbed
- pymdownx.tasklist:
custom_checkbox: true
- pymdownx.tilde
+23
View File
@@ -0,0 +1,23 @@
{
"name": "oxmysql",
"version": "1.0.0",
"description": "FXServer to MySQL communication via node-mysql2",
"repository": "[email protected]:overextended/oxmysql.git",
"author": "dunak-debug <[email protected]>",
"license": "GPL-3.0-or-later",
"type": "module",
"private": true,
"scripts": {
"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/server/index.js --outfile=dist/server/build.js",
"postinstall": "patch-package"
},
"dependencies": {
"@citizenfx/server": "latest",
"esbuild": "^0.14.7",
"mysql2": "^2.3.3",
"patch-package": "^6.4.7",
"postinstall-postinstall": "^2.1.0"
},
"devDependencies": {}
}
+311
View File
@@ -0,0 +1,311 @@
diff --git a/node_modules/mysql2/index.d.ts b/node_modules/mysql2/index.d.ts
index a465b43..183dc97 100644
--- a/node_modules/mysql2/index.d.ts
+++ b/node_modules/mysql2/index.d.ts
@@ -166,7 +166,6 @@ export interface ConnectionOptions extends mysql.ConnectionOptions {
decimalNumbers?: boolean;
isServer?: boolean;
maxPreparedStatements?: number;
- namedPlaceholders?: boolean;
nestTables?: boolean | string;
passwordSha1?: string;
pool?: any;
diff --git a/node_modules/mysql2/lib/commands/query.js b/node_modules/mysql2/lib/commands/query.js
index e51da3c..a60811a 100644
--- a/node_modules/mysql2/lib/commands/query.js
+++ b/node_modules/mysql2/lib/commands/query.js
@@ -1,6 +1,5 @@
'use strict';
-const process = require('process');
const Timers = require('timers');
const Readable = require('stream').Readable;
@@ -19,7 +18,6 @@ class Query extends Command {
this.sql = options.sql;
this.values = options.values;
this._queryOptions = options;
- this.namedPlaceholders = options.namedPlaceholders || false;
this.onResult = callback;
this.timeout = options.timeout;
this.queryTimeout = null;
@@ -52,6 +50,7 @@ class Query extends Command {
this._connection = connection;
this.options = Object.assign({}, connection.config, this._queryOptions);
this._setTimeout();
+ this._time = process.hrtime()
const cmdPacket = new Packets.Query(
this.sql,
@@ -73,7 +72,7 @@ class Query extends Command {
this.queryTimeout = null;
}
if (this.onResult) {
- let rows, fields;
+ let rows, fields, time;
if (this._resultIndex === 0) {
rows = this._rows[0];
fields = this._fields[0];
@@ -81,13 +80,14 @@ class Query extends Command {
rows = this._rows;
fields = this._fields;
}
+ if (this._time) time = process.hrtime(this._time)[1] / 1000000
if (fields) {
process.nextTick(() => {
- this.onResult(null, rows, fields);
+ this.onResult(null, rows, fields, time);
});
} else {
process.nextTick(() => {
- this.onResult(null, rows);
+ this.onResult(null, rows, undefined, time);
});
}
}
diff --git a/node_modules/mysql2/lib/connection.js b/node_modules/mysql2/lib/connection.js
index 47970e9..a0fec80 100644
--- a/node_modules/mysql2/lib/connection.js
+++ b/node_modules/mysql2/lib/connection.js
@@ -27,8 +27,6 @@ const CharsetToEncoding = require('./constants/charset_encodings.js');
let _connectionId = 0;
-let convertNamedPlaceholders = null;
-
class Connection extends EventEmitter {
constructor(opts) {
super();
@@ -495,7 +493,6 @@ class Connection extends EventEmitter {
sql: sql,
values: values
};
- this._resolveNamedPlaceholders(opts);
return SqlString.format(
opts.sql,
opts.values,
@@ -516,23 +513,6 @@ class Connection extends EventEmitter {
return SqlString.raw(sql);
}
- _resolveNamedPlaceholders(options) {
- let unnamed;
- if (this.config.namedPlaceholders || options.namedPlaceholders) {
- if (Array.isArray(options.values)) {
- // if an array is provided as the values, assume the conversion is not necessary.
- // this allows the usage of unnamed placeholders even if the namedPlaceholders flag is enabled.
- return
- }
- if (convertNamedPlaceholders === null) {
- convertNamedPlaceholders = require('named-placeholders')();
- }
- unnamed = convertNamedPlaceholders(options.sql, options.values);
- options.sql = unnamed[0];
- options.values = unnamed[1];
- }
- }
-
query(sql, values, cb) {
let cmdQuery;
if (sql.constructor === Commands.Query) {
@@ -540,7 +520,6 @@ class Connection extends EventEmitter {
} else {
cmdQuery = Connection.createQuery(sql, values, cb, this.config);
}
- this._resolveNamedPlaceholders(cmdQuery);
const rawSql = this.format(cmdQuery.sql, cmdQuery.values !== undefined ? cmdQuery.values : []);
cmdQuery.sql = rawSql;
return this.addCommand(cmdQuery);
@@ -608,26 +587,11 @@ class Connection extends EventEmitter {
options.sql = sql;
options.values = values;
}
- this._resolveNamedPlaceholders(options);
// check for values containing undefined
if (options.values) {
- //If namedPlaceholder is not enabled and object is passed as bind parameters
- if (!Array.isArray(options.values)) {
- throw new TypeError(
- 'Bind parameters must be array if namedPlaceholders parameter is not enabled'
- );
- }
options.values.forEach(val => {
- //If namedPlaceholder is not enabled and object is passed as bind parameters
- if (!Array.isArray(options.values)) {
- throw new TypeError(
- 'Bind parameters must be array if namedPlaceholders parameter is not enabled'
- );
- }
if (val === undefined) {
- throw new TypeError(
- 'Bind parameters must not contain undefined. To pass SQL NULL specify JS null'
- );
+ val = null
}
if (typeof val === 'function') {
throw new TypeError(
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;
diff --git a/node_modules/mysql2/promise.d.ts b/node_modules/mysql2/promise.d.ts
index 6ab3d6f..68bc9cb 100644
--- a/node_modules/mysql2/promise.d.ts
+++ b/node_modules/mysql2/promise.d.ts
@@ -25,41 +25,15 @@ export interface Connection extends EventEmitter {
changeUser(options: ConnectionOptions): Promise<void>;
query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader>(
- sql: string
- ): Promise<[T, FieldPacket[]]>;
- query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader>(
- sql: string,
- values: any | any[] | { [param: string]: any }
- ): Promise<[T, FieldPacket[]]>;
- query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader>(
- options: QueryOptions
- ): Promise<[T, FieldPacket[]]>;
- query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader>(
- options: QueryOptions,
- values: any | any[] | { [param: string]: any }
+ sql_or_options: string | QueryOptions,
+ values?: any | any[] | { [param: string]: any },
): Promise<[T, FieldPacket[]]>;
execute<
T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader
>(
- sql: string
- ): Promise<[T, FieldPacket[]]>;
- execute<
- T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader
- >(
- sql: string,
- values: any | any[] | { [param: string]: any }
- ): Promise<[T, FieldPacket[]]>;
- execute<
- T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader
- >(
- options: QueryOptions
- ): Promise<[T, FieldPacket[]]>;
- execute<
- T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader
- >(
- options: QueryOptions,
- values: any | any[] | { [param: string]: any }
+ sql_or_options: string | QueryOptions,
+ values?: any | any[] | { [param: string]: any },
): Promise<[T, FieldPacket[]]>;
unprepare(sql: string): void;
@@ -86,41 +60,15 @@ export interface PoolConnection extends Connection {
export interface Pool extends EventEmitter {
query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader>(
- sql: string
- ): Promise<[T, FieldPacket[]]>;
- query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader>(
- sql: string,
- values: any | any[] | { [param: string]: any }
- ): Promise<[T, FieldPacket[]]>;
- query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader>(
- options: QueryOptions
- ): Promise<[T, FieldPacket[]]>;
- query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader>(
- options: QueryOptions,
- values: any | any[] | { [param: string]: any }
+ sql_or_options: string | QueryOptions,
+ values?: any | any[] | { [param: string]: any },
): Promise<[T, FieldPacket[]]>;
execute<
T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader
>(
- sql: string
- ): Promise<[T, FieldPacket[]]>;
- execute<
- T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader
- >(
- sql: string,
- values: any | any[] | { [param: string]: any }
- ): Promise<[T, FieldPacket[]]>;
- execute<
- T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader
- >(
- options: QueryOptions
- ): Promise<[T, FieldPacket[]]>;
- execute<
- T extends RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[] | ResultSetHeader
- >(
- options: QueryOptions,
- values: any | any[] | { [param: string]: any }
+ sql_or_options: string | QueryOptions,
+ values?: any | any[] | { [param: string]: any },
): Promise<[T, FieldPacket[]]>;
getConnection(): Promise<PoolConnection>;
diff --git a/node_modules/mysql2/promise.js b/node_modules/mysql2/promise.js
index fc74cc0..fea1ccf 100644
--- a/node_modules/mysql2/promise.js
+++ b/node_modules/mysql2/promise.js
@@ -4,7 +4,7 @@ const core = require('./index.js');
const EventEmitter = require('events').EventEmitter;
function makeDoneCb(resolve, reject, localErr) {
- return function (err, rows, fields) {
+ return function (err, rows, fields, time) {
if (err) {
localErr.message = err.message;
localErr.code = err.code;
@@ -14,7 +14,7 @@ function makeDoneCb(resolve, reject, localErr) {
localErr.sqlMessage = err.sqlMessage;
reject(localErr);
} else {
- resolve([rows, fields]);
+ resolve([rows, fields, time]);
}
};
}
+60
View File
@@ -0,0 +1,60 @@
diff --git a/node_modules/named-placeholders/index.js b/node_modules/named-placeholders/index.js
index 527d723..53ef4cf 100644
--- a/node_modules/named-placeholders/index.js
+++ b/node_modules/named-placeholders/index.js
@@ -3,7 +3,7 @@
// based on code from Brian White @mscdex mariasql library - https://github.com/mscdex/node-mariasql/blob/master/lib/Client.js#L272-L332
// 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,
DQUOTE = 34,
SQUOTE = 39,
BSLASH = 92;
@@ -94,15 +94,24 @@ function createCompiler(config) {
if (typeof params == 'undefined')
throw new Error('Named query contains placeholders, but parameters object is undefined');
+ for(const key in params) {
+ 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];
}
function noTailingSemicolon(s) {
- if (s.slice(-1) == ':') {
+ const char = s.slice(-1)
+ if (char == ':' || char == '@') {
return s.slice(0, -1);
}
return s;
@@ -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) == ':') {
+ const char = tree[0][i-1].slice(-1)
+ if (char == ':' || char == '@') {
unnamed += config.placeholder;
}
unnamed += config.placeholder;
@@ -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) == ':') {
+ const char = last.slice(-1)
+ if (char == ':' || char == '@') {
unnamed += config.placeholder;
}
unnamed += config.placeholder;
-7
View File
@@ -1,7 +0,0 @@
# Direct dependencies
mkdocs>=1.1
Pygments>=2.4
markdown>=3.2
pymdown-extensions>=7.0
mkdocs-material-extensions>=1.0
mkdocs-awesome-pages-plugin>=2.2.1
+39
View File
@@ -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();
}
};
+58
View File
@@ -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;
};
+37
View File
@@ -0,0 +1,37 @@
import { createPool } from 'mysql2/promise';
import { mysql_connection_string, mysql_transaction_isolation_level, typeCast } from '../config.js';
const connectionString = (() => {
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;
+28
View File
@@ -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();
[query, parameters, cb] = parseArguments(invokingResource, query, parameters, cb);
scheduleTick();
let result, executionTime;
try {
[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);
};
+59
View File
@@ -0,0 +1,59 @@
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();
const parsedQuery = parseTransaction(invokingResource, queries, parameters);
scheduleTick();
const connection = await pool.getConnection();
let result;
try {
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;
};
+54
View File
@@ -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);
});
+61
View File
@@ -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);
});
+126
View File
@@ -0,0 +1,126 @@
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`);
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;
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 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;
}
};
+34
View File
@@ -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);