rewrite oxmysql docs

This commit is contained in:
Linden committed 2023-05-31 21:23:24 +10:00
1 parent 864a1b3858
commit 3298244c9a
17 files changed
+630 -520

No files matched your search

+28 -22
View File
@@ -1,14 +1,10 @@
# Benchmark
Internal benchmark
```md
```lua
-- Internal benchmark
Low: 0.1222ms | Avg: 0.14188357ms | Total: 1418.8357ms (10000 queries)
```
Round-trip-time for exports
```md
-- Round-trip-time for exports
Low: 0.1997ms | Avg: 0.25898800ms | Total: 2589.8800ms (10000 queries)
```
@@ -44,24 +40,34 @@ end)
## JavaScript
```js
const val = 10000
RegisterCommand('jssync', async() => {
const val = 10000;
RegisterCommand('jssync', async () => {
const queryTimesLocal = [];
let result
await exports.oxmysql.prepare_async('SELECT identifier from users WHERE lastname = ?', ['Linden'])
let result;
await exports.oxmysql.prepare_async('SELECT identifier from users WHERE lastname = ?', ['Linden']);
for(let i=0; i < val; i++) {
const startTime = process.hrtime()
const r = await exports.oxmysql.prepare_async('SELECT identifier from users WHERE lastname = ?', ['Linden'])
queryTimesLocal.push(process.hrtime(startTime)[1] / 1000000)
if (i === 0) result = r
for (let i = 0; i < val; i++) {
const startTime = process.hrtime();
const r = await exports.oxmysql.prepare_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
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)')
})
console.log(result);
console.log(
'Low: ' +
queryMsLow +
'ms | Avg: ' +
averageQueryTime +
'ms | Total: ' +
queryMsSum +
'ms (' +
queryTimesLocal.length +
' queries)'
);
});
```
+94 -40
View File
@@ -10,79 +10,133 @@ Most resources for FiveM were designed to be used with MySQL 5.7 and may hit com
- More reserved keywords, like 'stored' and 'group'.
- Longtext / JSON fields do not support default values.
[MariaDB](https://mariadb.org/) is strongly recommended for compatibility, and improved performance (over all versions of MySQL).
[MariaDB](https://mariadb.com/downloads/community/) is highly recommended for compatibility, and improved performance (over all versions of MySQL).
## XAMPP
## Should I use XAMPP?
XAMPP is not a database, and should not be used solely to start your MySQL/MariaDB service. Please _do not_ use XAMPP.
**No.** XAMPP is a webserver stack intended to be used for development, allowing easy local development and testing.
Do not setup XAMPP just to run your database, and install [MariaDB](https://mariadb.com/downloads/community/) directly instead.
## 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.
### Download the [latest release](https://github.com/overextended/oxmysql/releases/latest)
## 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.
### Configure your server
:::caution
When using convars do not replicate sensitive information to the client.
**set** will only be set on the server, while **setr** is replicated.
When using convars do not replicate sensitive information to the client. **set** will only be set on the server, while **setr** is replicated.
:::
```yaml
set mysql_connection_string "mysql://root:12345@localhost:3306/es_extended?charset=utf8mb4"
set mysql_connection_string "user=root;password=12345;host=localhost;port=3306;database=es_extended;charset=utf8mb4"
- Start by opening your server configuration (i.e. server.cfg) and adding `start oxmysql` before any of its dependents (usually it's the first resource you start).
- Set a mysql connection string using either of the following formats, using your server authentication details and target database.
```bash
set mysql_connection_string "mysql://root:12345@localhost:3306/es_extended"
set mysql_connection_string "user=root;password=12345;host=localhost;port=3306;database=es_extended"
```
Certain special characters are reserved or blocked and may cause issues when used in your password.
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).
:::info
Certain special characters are reserved or unsupported depending on your connection string.
Avoid using these characters `; , / ? : @ & = + $ #`, and try swapping connection string format.
:::
You can also add the following convars if you require extra information when testing queries.
### Slow query warnings
```yaml
By default you will receive warnings if a query took ~150ms to complete, however
1. Query time is calculated on fxserver based on response time, and may not be entirely accurate.
2. Server hitches may delay the query response, and may not indicate a database issue.
3. Excessive queries in a short timeframe may report with higher response times.
You can adjust the minimum response time with a convar.
```bash
set mysql_slow_query_warning 150
set mysql_debug true
```
### Debug options
### Debug
When using the `mysql_debug` convar, rather than setting the value as true, you can send an array and enable debug prints for a set list of resources instead.
Enabling the debug option will print all queries in the server console; you can also use an array to only print from a list of resources instead.
```yaml
```bash
set mysql_debug true
set mysql_debug [
"ox_core",
"ox_inventory"
"ox_core",
"ox_inventory"
]
```
This list can be adjusted during runtime with commands, temporarily adding or removing resources until the resource is restarted.
This value can be changed without restarting oxmysql, and you can temporarily modify the list with commands.
```yaml
```bash
oxmysql_debug remove ox_core
oxmysql_debug add ox_core
```
### Debug UI
### mysql-async compatibility
Debug UI is used to see your total query number, speeds, per resource queries and their speeds, etc...
The `mysql-async` directory must be deleted to properly provide support.
You can read more about using the debug UI on the [Using the Debug UI](/docs/oxmysql/Getting%20Started/ui) page
- 🗹 Supports server_script '@mysql-async/lib/MySQL.lua'.
- 🗹 Supports MySQL.Sync and MySQL.Async methods.
- ☐ Raw exports are not supported (i.e. exports['mysql-async].mysql_execute).
- ☐ Multi-statements are disabled for security reasons (see [#102](https://github.com/overextended/oxmysql/issues/102)).
## Compatibility
### ghmattimysql compatibility
You shouldn't run multiple mysql resources to ensure the best experience.
The resources listed below can be deleted to allow oxmysql to handle the events, without any changes.
The `ghmattimysql` resource must be stopped to properly provide support.
### mysql-async
- 🗹 Supports exports.ghmattimysql.execute and other similar exports.
- 🗹 Supports exports.ghmattimysql.executeSync and other similar exports.
Standard API for mysql-async uses `server_script '@mysql-async/lib/MySQL.lua'`.
Raw exports, mostly used in resources written in JavaScript or C#, are _not supported_.
## Usage
### ghmattimysql
Resources can import oxmysql methods by including our library, granting some type-checking and minor performance improvements over raw export calls.
As of v2.4.0, oxmysql can be utilised with ghmattimysql's exports, such as `exports.ghmattimysql:execute`.
### Lua
Modify `fxmanifest.lua` for your resource, and add the following above any other script files.
```lua
server_script '@oxmysql/lib/MySQL.lua'
```
If you're using [Lua Language Server](https://marketplace.visualstudio.com/items?itemName=sumneko.lua) you can get access to basic types and intellisense.
```json
"Lua.workspace.library": [
"C:/pathtoserver/resources/oxmysql/lib/define.lua",
]
```
### JavaScript
You can use raw exports, or install [our npm package](https://www.npmjs.com/package/@overextended/oxmysql) for intellisense and similar usage as Lua.
```bash
# With pnpm
pnpm add @overextended/oxmysql
# With Yarn
yarn add @overextended/oxmysql
# With npm
npm install @overextended/oxmysql
```
Import the oxmysql object into your resource.
```js
import { oxmysql as MySQL } from '@overextended/oxmysql';
```
## Upserting
When uncertain if a row should be inserted into the database, or an existing row should be updated, queries should check for duplicate keys.
```lua
MySQL.prepare('INSERT INTO ox_inventory (owner, name, data) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data)', { owner, dbId, inventory })
```
This is preferred over checking the existence of a row, then inserting or updating depending on the result.
Furthermore, unlike using 'REPLACE INTO', the row is not deleted and re-inserted.
+21 -18
View File
@@ -1,24 +1,27 @@
# Common Issues
---
title: Common issues
---
### Unable to establish a connection
## Unable to establish a connection
This is usually the result of incorrect database settings or your password containing reserved characters (`; , / ? : @ & = + $ #`).
:::tip 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.
This is usually the result of incorrect database settings or your password containing reserved characters.
`; , / ? : @ & = + $ #` are reserved.
:::info
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
## No such export ... in resource oxmysql
Typically the result of failing to follow instructions.
:::tip Solution
Download the latest release _build_ (not source) of oxmysql, and ensure it is starting before any resources that require it.
- Download the latest release _build_ (not the source code) of oxmysql.
- Ensure it is starting before any resources that require it.
## Numbers treated as string
To resolve this issue simply enable `decimalNumbers` in your connection string, ie. `mysql://root@localhost/essentialmode?decimalNumbers=true`.
:::caution
JavaScript treats all numbers as floats, so a double or decimal value will be cast as a float with this setting.
Numbers will have less precision when this setting is enabled.
:::
### Numbers treated as string
This is an incompatibility between mysqljs (used by mysql-async) and mysql2 (used by oxmysql) (See [Known incompatibilities with node-mysql](https://github.com/sidorares/node-mysql2/tree/master/documentation#known-incompatibilities-with-node-mysql))
To resolve this issue simply add `&decimalNumbers=true` to the connection string, ie. `mysql://root@localhost/essentialmode?charset=utf8mb4_general_ci&decimalNumbers=true` to revert to the behavior of mysqljs.
Do note with this that precision will be less with this, as Javascript treats all numbers as floats, so a double or decimal will be cast to a float this way.
+14 -5
View File
@@ -1,11 +1,20 @@
# Placeholders
This allows queries to be properly prepared and escaped; the following lines are equivalent.
Placeholders allow for query parameters to be safely executed, preventing [common SQL injection methods](https://bobby-tables.com/).
Parameters can be passed an an array or map (referred to as named named parameters).
```lua
"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}
local identifier = 'license:abc123'
local group = 'admin'
MySQL.scalar('SELECT `username` FROM `users` WHERE `identifier` = ? AND `group` = ?', { identifier, group })
-- Named placeholders (deprecated)
MySQL.scalar('SELECT `username` FROM `users` WHERE `identifier` = @identifier AND `group` = @group', {
group = group
identifier = identifier
})
```
Named placeholders are deprecated and should be avoided as much as possible.
These are distinct from prepared statements which are handled by the MySQL server; you can use `MySQL.prepare` for more optimised and secure queries.
+12 -21
View File
@@ -1,25 +1,22 @@
---
title: Using the Debug UI
title: Using the debug UI
---
Debug UI can show you useful information about your queries such as the total query time, count and total number of slow queries.
You can also see which resources take up the most query time, the number of queries they ran and how many were slow.
## Requirements
The debug UI lets you easily see all the queries that have been executed by resources, query response times, and per-resource statistics.
You should only enable this during production, or with a small player count - for larger servers, look into builtin MySQL logging.
Before using the UI first you have to make sure you have the `mysql_ui` convar set to true:
```yaml
```bash
set mysql_ui true
```
Also make sure that you have `command` ace permission access, then you should be able to use the `mysql` command in game to open up the UI and see your query data.
Also make sure that you have `command` or `command.mysql` ace permission access, then you should be able to use the `mysql` command in game.
:::info
:::tip
You _do not_ need to have the `mysql_debug` enabled to use the debug ui.
You *do not* need to have the `mysql_debug` convar set to `true` in order to use the debug ui.
:::
## Main page
@@ -29,24 +26,18 @@ along side a pie chart which shows what resources took the most query time.
![oxmysql_ui_main](https://i.imgur.com/iQqWELJ.png)
## Resource page
The resource page shows you all the queries and their execution time inside a table that the resource previously ran,
alongside the total amount of the queries, execution time and slow queries for the selected resource.
Columns can be sorted by ascending and descending order.
Columns can be sorted by ascending and descending order, and hovering over a query will display the full query inside a tooltip.
Hovering over a query will display the full query inside a tooltip.
:::info
Queries that exceed `mysql_slow_query_warning` (default 150ms) are displayed in orange.
For demonstation purposes the `mysql_slow_query_warning` convar was set to 5 here.
![oxmysql_ui_queries](https://i.imgur.com/gZpJoIg.png)
:::tip
Queries that exceed the value set in the `mysql_slow_query_warning` convar (defualt is 150) are going to show up as orange
and will be added to the slow queries count.
:::
*Note: For demonstation purposes the `mysql_slow_query_warning` convar was set to 5 here.*
![oxmysql_ui_queries](https://i.imgur.com/gZpJoIg.png)