This commit is contained in:
Luke committed 2023-06-04 15:15:21 +02:00
1 parent 3cebaf7fa5
commit b5eba8423f
229 files changed
+6238 -10690

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
---
keywords: ['execute', 'insert']
title: Insert
---
import { Tab, Tabs } from 'nextra-theme-docs';
Inserts a new entry into the database and returns the insert id for the row, if valid.
## Promise
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
local id = MySQL.insert.await('INSERT INTO `users` (identifier, firstname, lastname) VALUES (?, ?, ?)', {
identifier, firstName, lastName
})
print(id)
```
</Tab>
<Tab>
```js
const id = await MySQL.insert('INSERT INTO `users` (identifier, firstname, lastname) VALUES (?, ?, ?)', [
identifier, firstName, lastName
])
console.log(id)
```
</Tab>
</Tabs>
**Aliases**
- `MySQL.Sync.insert`
- `exports.ghmattimysql.executeSync`
- `exports.oxmysql.insert_async`
## Callback
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
MySQL.insert('INSERT INTO `users` (identifier, firstname, lastname) VALUES (?, ?, ?)', {
identifier, firstName, lastName
}, function(id)
print(id)
end)
```
</Tab>
<Tab>
```js
MySQL.insert('INSERT INTO `users` (identifier, firstname, lastname) VALUES (?, ?, ?)', [
identifier, firstName, lastName
], (id) => {
console.log(id)
})
```
</Tab>
</Tabs>
**Aliases**
- `MySQL.Async.insert`
- `exports.ghmattimysql.execute`
- `exports.oxmysql.insert`
+77
View File
@@ -0,0 +1,77 @@
---
title: Prepare
---
import { Tab, Tabs } from 'nextra-theme-docs';
The only function that provides true 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 `query`, `single`, or `scalar` depending on the number of columns and rows selected.
## Promise
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
local response = MySQL.prepare.await('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', {
identifier
})
print(json.encode(response, { indent = true, sort_keys = true }))
```
</Tab>
<Tab>
```js
const response = await MySQL.prepare('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', [
identifier
])
console.log(JSON.stringify(response))
```
</Tab>
</Tabs>
**Aliases**
- `exports.oxmysql.prepare_async`
## Callback
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
MySQL.prepare('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', {
identifier
}, function(response)
print(json.encode(response, { indent = true, sort_keys = true }))
end)
```
</Tab>
<Tab>
```js
MySQL.prepare('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', [
identifier
], (response) => {
console.log(JSON.stringify(response))
})
```
</Tab>
</Tabs>
**Aliases**
- `exports.oxmysql.prepare`
+92
View File
@@ -0,0 +1,92 @@
---
keywords: ['fetchAll', 'execute']
title: Query
---
import { Tab, Tabs } from 'nextra-theme-docs';
When selecting data, returns all matching rows and columns; otherwise, returns data like insertId, affectedRows, etc.
## Promise
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
local response = MySQL.query.await('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', {
identifier
})
if response then
for i = 1, #response do
local row = response[i]
print(row.firstname, row.lastname)
end
end
```
</Tab>
<Tab>
```js
const response = await MySQL.query('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', [
identifier
])
if (response) {
response.forEach((row) => {
console.log(row.identifier, row.firstname, row.lastname)
})
}
```
</Tab>
</Tabs>
**Aliases**
- `MySQL.Sync.fetchAll`
- `exports.ghmattimysql.execute`
- `exports.oxmysql.query_async`
## Callback
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
MySQL.query('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', {
identifier
}, function(response)
if response then
for i = 1, #response do
local row = response[i]
print(row.firstname, row.lastname)
end
end
end)
```
</Tab>
<Tab>
```js
MySQL.query('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', [
identifier
], (response) => {
if (response) {
response.forEach((row) => {
console.log(row.firstname, row.lastname)
})
}
})
```
</Tab>
</Tabs>
**Aliases**
- `MySQL.Async.fetchAll`
- `exports.ghmattimysql.execute`
- `exports.oxmysql.query`
+74
View File
@@ -0,0 +1,74 @@
---
keywords: ['scalar', 'fetchScalar']
title: Scalar
---
import { Tab, Tabs } from 'nextra-theme-docs';
Returns the first column for a single row.
## Promise
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
local firstName = MySQL.scalar.await('SELECT `firstname` FROM `users` WHERE `identifier` = ? LIMIT 1', {
identifier
})
print(firstName)
```
</Tab>
<Tab>
```js
const firstName = await MySQL.scalar('SELECT `firstname` FROM `users` WHERE `identifier` = ? LIMIT 1', [
identifier
])
console.log(firstName)
```
</Tab>
</Tabs>
**Aliases**
- `MySQL.Sync.fetchScalar`
- `exports.ghmattimysql.scalar`
- `exports.oxmysql.scalar_async`
## Callback
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
MySQL.scalar('SELECT `firstname` FROM `users` WHERE `identifier` = ? LIMIT 1', {
identifier
}, function(firstName)
print(firstName)
end)
```
</Tab>
<Tab>
```js
MySQL.scalar('SELECT `firstname` FROM `users` WHERE `identifier` = ? LIMIT 1', [
identifier
], (firstName) => {
console.log(firstName)
})
```
</Tab>
</Tabs>
**Aliases**
- `MySQL.Async.fetchScalar`
- `exports.ghmattimysql.scalar`
- `exports.oxmysql.scalar`
+77
View File
@@ -0,0 +1,77 @@
---
title: Single
---
import { Tab, Tabs } from 'nextra-theme-docs';
Returns all selected columns for a single row.
## Promise
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
local row = MySQL.single.await('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ? LIMIT 1', {
identifier
})
if not row then return end
print(row.firstname, row.lastname)
```
</Tab>
<Tab>
```js
const row = await MySQL.single('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ? LIMIT 1', [
identifier
])
if (!row) return;
console.log(row.firstname, row.lastname)
```
</Tab>
</Tabs>
**Aliases**
- `exports.oxmysql.single_async`
## Callback
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
MySQL.single('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ? LIMIT 1', {
identifier
}, function(row)
if not row then return end
print(row.firstname, row.lastname)
end)
```
</Tab>
<Tab>
```js
MySQL.single('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ? LIMIT 1', [
identifier
], (row) => {
if (!row) return;
console.log(row.firstname, row.lastname)
})
```
</Tab>
</Tabs>
**Aliases**
- `exports.oxmysql.single`
+128
View File
@@ -0,0 +1,128 @@
---
title: Transaction
---
import { Tab, Tabs } from 'nextra-theme-docs';
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 this format, you must pass an array containing sets of queries and parameters to the transaction method.
In this case, your queries do not necessarily match and the values are unique to each query.
```lua
-- You might rename "values" as "parameters" for mysql-async compatibility.
local queries = {
{ query = 'INSERT INTO `test` (id) VALUES (?)', values = { 1 }},
{ query = 'INSERT INTO `test` (id, name) VALUES (?, ?)', values = { 2, 'bob' }},
}
-- You can also pass an array of arrays.
local queries = {
{ 'INSERT INTO `test` (id) VALUES (?)', { 1 } },
{ 'INSERT INTO `test` (id, name) VALUES (?, ?)', { 2, 'bob' } },
}
```
## Shared format
When using this format, you must pass an array containing queries and a set containing shared parameters to the transaction method.
In this case, your queries do not necessarily match and the values are unique to each query.
```lua
-- You might rename "values" as "parameters" for mysql-async compatibility.
local queries = {
'INSERT INTO `test` (id, name) VALUES (@someid, @somename)',
'SET `name` = @newname IN `test` WHERE `id` = @someid'
}
local values = {
someid = 2,
somename = 'John Doe',
newname = 'John Notdoe'
}
```
## Promise
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
local success = MySQL.transaction.await(queries, values --[[leave nil for specific format]])
print(success)
```
</Tab>
<Tab>
```js
const success = await MySQL.transaction(queries, values /*leave nil for specific format*/)
console.log(success)
```
</Tab>
</Tabs>
**Aliases**
- `MySQL.Sync.transaction`
- `exports.ghmattimysql.transaction`
- `exports.oxmysql.transaction_async`
## Callback
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
-- specific
MySQL.transaction(queries, values, function(success)
print(success)
end)
-- shared
MySQL.transaction(queries, function(success)
print(success)
end)
```
</Tab>
<Tab>
```js
// specific
MySQL.transaction(queries, (success) => {
console.log(success)
})
// shared
MySQL.transaction(queries, values, (success) => {
console.log(success)
})
```
</Tab>
</Tabs>
**Aliases**
- `MySQL.Async.transaction`
- `exports.ghmattimysql.transaction`
- `exports.oxmysql.transaction`
## Transaction Isolation Level
This can be set through the convar `mysql_transaction_isolation_level`, and is an integer ranging from `1-4`.
The default value is 2.
| Convar Value | Result |
| ------------ | ---------------- |
| 1 | Repeatable Read |
| 2 | Read Committed |
| 3 | Read Uncommitted |
| 4 | Serializable |
+74
View File
@@ -0,0 +1,74 @@
---
keywords: ['execute']
title: Update
---
import { Tab, Tabs } from 'nextra-theme-docs';
Returns the number of rows affected by the query.
## Promise
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
local affectedRows = MySQL.update.await('UPDATE users SET firstname = ? WHERE identifier = ?', {
newName, identifier
})
print(affectedRows)
```
</Tab>
<Tab>
```js
const affectedRows = await MySQL.update('UPDATE users SET firstname = ? WHERE identifier = ?', [
newName, identifier
])
console.log(affectedRows)
```
</Tab>
</Tabs>
**Aliases**
- `MySQL.Sync.execute`
- `exports.ghmattimysql.executeSync`
- `exports.oxmysql.update_async`
## Callback
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
MySQL.update('UPDATE users SET firstname = ? WHERE identifier = ?', {
newName, identifier
}, function(affectedRows)
print(affectedRows)
end)
```
</Tab>
<Tab>
```js
MySQL.update('UPDATE users SET firstname = ? WHERE identifier = ?', [
newName, identifier
], (affectedRows) => {
console.log(affectedRows)
})
```
</Tab>
</Tabs>
**Aliases**
- `MySQL.Async.execute`
- `exports.ghmattimysql.execute`
- `exports.oxmysql.update`
+71
View File
@@ -0,0 +1,71 @@
```lua
-- Internal benchmark
Low: 0.1222ms | Avg: 0.14188357ms | Total: 1418.8357ms (10000 queries)
-- Round-trip-time for exports
Low: 0.1997ms | Avg: 0.25898800ms | Total: 2589.8800ms (10000 queries)
```
## Lua (5.4)
```lua
local val = 10000
RegisterCommand('luasync', function()
local queryTimesLocal = {}
local result
MySQL.prepare.await('SELECT identifier from users WHERE lastname = ?', {'Linden'})
for i=1, val do
local time = os.nanotime()
local r = MySQL.prepare.await('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;
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;
}
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)'
);
});
```
+29
View File
@@ -0,0 +1,29 @@
---
title: Common issues
---
import { Callout } from 'nextra/components';
## Unable to establish a connection
This is usually the result of incorrect database settings or your password containing reserved characters.
`; , / ? : @ & = + $ #` are reserved.
<Callout type="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.
</Callout>
## No such export ... in resource oxmysql
- 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`.
<Callout type="warning">
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.
</Callout>
+18
View File
@@ -0,0 +1,18 @@
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
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
})
```
These are distinct from prepared statements which are handled by the MySQL server; you can use `MySQL.prepare` for more optimised and secure queries.
+45
View File
@@ -0,0 +1,45 @@
---
title: Using the debug UI
---
import { Callout } from 'nextra/components';
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:
```bash
set mysql_ui true
```
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.
<Callout type="info">
You _do not_ need to have the `mysql_debug` enabled to use the debug ui.
</Callout>
## Main page
The main page shows you the resources that ran queries where you can filter them through a search bar, your general data
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, and hovering over a query will display the full query inside a tooltip.
<Callout type="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.
</Callout>
![oxmysql_ui_queries](https://i.imgur.com/gZpJoIg.png)