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

+1 -1
View File
@@ -5,4 +5,4 @@ Git is a version control system, allowing changes to be effectively tracked, mer
As our resources are hosted on GitHub, it can be incredibly useful to learn how to create your own repository to track changes and keep up-to-date. If you plan on making your own changes to our resources, this will allow you to keep your own changes and prevent loss of data.
- Refer to [GitHub's guide to setting up Git](https://docs.github.com/en/get-started/quickstart/set-up-git#setting-up-git).
- You can also download a Git GUI client, such as [GitKraken](https://www.gitkraken.com/), to improve your workflow and more easily maintain changes.
- You can use a Git GUI client like [GitKraken](https://www.gitkraken.com/) to improve your workflow and more easily maintain changes.
+2 -2
View File
@@ -9,8 +9,8 @@ If you feel like the documentation is lacking in some department then feel free
## Support our team
Our projects will always remain free and open-source, with our core developers working voluntarily.
If you love what we do and want to help us continue, why not show your appreciation with a donation?
Providing and maintaining free open-source resources to the community takes a lot of time and hard work.
If you appreciate what we do, consider supporting us so we can continue our work.
<div style={{paddingLeft:"50px", lineHeight:"20px", background:"url('https://avatars.githubusercontent.com/u/65407488?s=70&v=4') no-repeat left", backgroundSize:"40px"}}>
Linden
+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)
-63
View File
@@ -1,63 +0,0 @@
# Usage
## lib/MySQL
Resources can import oxmysql methods by including our library, granting some type-checking and minor performance improvements over raw export calls.
### 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 are using VSCode with [sumneko Lua](https://marketplace.visualstudio.com/items?itemName=sumneko.lua) you can get access to some basic types and intellisense.
```json
"Lua.workspace.library": [
"C:\\pathtoserver\\resources\\oxmysql\\lib\\define.lua",
]
```
### JavaScript
Use your favourite package manager to install our [node package](https://www.npmjs.com/package/@overextended/oxmysql).
```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';
```
## Placeholders
Safely format queries by using placeholders in the query, and sending arguments in an array or object.
Named placeholders are not recommended, and unsupported when using MySQL.prepare.
```lua
MySQL.query('SELECT * FROM users WHERE identifier = ?', { 'license:abcdefg' })
MySQL.query('SELECT * FROM users WHERE identifier = :identifier', { identifier = 'license:abcdefg' })
```
## Upsert
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.
+53 -31
View File
@@ -1,53 +1,75 @@
---
keywords: ['execute', 'insert']
keywords: ['execute', 'insert']
title: Insert
---
# Insert
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
Inserts a new entry into the database and returns the insert id for the row, if valid.
## Lua
## Promise
### Callback
<Tabs>
<TabItem value="1" label="Lua">
```lua
-- alias: exports.oxmysql:insert
-- alias: MySQL.Async.insert
-- alias: exports.ghmattimysql:execute
local id = MySQL.insert.await('INSERT INTO `users` (identifier, firstname, lastname) VALUES (?, ?, ?)', {
identifier, firstName, lastName
})
MySQL.insert('INSERT INTO users (identifier, firstname, lastname) VALUES (?, ?, ?)', {playerIdentifier, firstName, lastName}, function(id)
print(id)
```
</TabItem>
<TabItem value="2" label="JS">
```js
const id = await MySQL.insert('INSERT INTO `users` (identifier, firstname, lastname) VALUES (?, ?, ?)', [
identifier, firstName, lastName
])
console.log(id)
```
</TabItem>
</Tabs>
**Aliases**
- `MySQL.Sync.insert`
- `exports.ghmattimysql.executeSync`
- `exports.oxmysql.insert_async`
## Callback
<Tabs>
<TabItem value="1" label="Lua">
```lua
MySQL.insert('INSERT INTO `users` (identifier, firstname, lastname) VALUES (?, ?, ?)', {
identifier, firstName, lastName
}, function(id)
print(id)
end)
```
### Promise
```lua
-- alias: exports.oxmysql:insert_async
-- alias: MySQL.Sync.insert
-- alias: exports.ghmattimysql:executeSync
local id = MySQL.insert.await('INSERT INTO users (identifier, firstname, lastname) VALUES (?, ?, ?)', {playerIdentifier, firstName, lastName})
print(id)
```
## JavaScript
### Callback
</TabItem>
<TabItem value="2" label="JS">
```js
// alias: exports.oxmysql.insert
MySQL.insert('INSERT INTO users (identifier, firstname, lastname) VALUES (?, ?, ?)', [playerIdentifier, firstName, lastName], (id) => {
MySQL.insert('INSERT INTO `users` (identifier, firstname, lastname) VALUES (?, ?, ?)', [
identifier, firstName, lastName
], (id) => {
console.log(id)
})
```
### Promise
</TabItem>
</Tabs>
```js
// alias: exports.oxmysql.insert_async
**Aliases**
const id = await MySQL.insert('INSERT INTO users (identifier, firstname, lastname) VALUES (?, ?, ?)', [playerIdentifier, firstName, lastName])
console.log(id)
```
- `MySQL.Async.insert`
- `exports.ghmattimysql.execute`
- `exports.oxmysql.insert`
+57 -39
View File
@@ -1,60 +1,78 @@
# Prepare
---
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.
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
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
- 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.
When using SELECT, the return value will match `query`, `single`, or `scalar` depending on the number of columns and rows selected.
## Lua
## Promise
### Callback
<Tabs>
<TabItem value="1" label="Lua">
```lua
-- alias: exports.oxmysql:prepare
local response = MySQL.prepare.await('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', {
identifier
})
MySQL.prepare('SELECT * FROM users WHERE identifier = ?', {playerIdentifier}, function(result)
if result then
print(json.encode(result, {indent=true}))
end
print(json.encode(response, { indent = true, sort_keys = true }))
```
</TabItem>
<TabItem value="2" label="JS">
```js
const response = await MySQL.prepare('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', [
identifier
])
console.log(JSON.stringify(response))
```
</TabItem>
</Tabs>
**Aliases**
- `exports.oxmysql.prepare_async`
## Callback
<Tabs>
<TabItem value="1" label="Lua">
```lua
MySQL.prepare('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', {
identifier
}, function(response)
print(json.encode(response, { indent = true, sort_keys = true }))
end)
```
### Promise
```lua
-- alias: exports.oxmysql:prepare_async
local result = MySQL.prepare.await('SELECT * FROM users WHERE identifier = ?', {playerIdentifier})
if result then
print(json.encode(result, {indent=true}))
end
```
## JavaScript
### Callback
</TabItem>
<TabItem value="2" label="JS">
```js
// alias: exports.oxmysql.prepare
MySQL.prepare('SELECT * FROM users WHERE identifier = ?', [playerIdentifier], (result) => {
if (result) {
console.log(result.identifier, result.firstname, result.lastname)
}
MySQL.prepare('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', [
identifier
], (response) => {
console.log(JSON.stringify(response))
})
```
### Promise
</TabItem>
</Tabs>
```js
// alias: exports.oxmysql.prepare_async
**Aliases**
const result = await MySQL.prepare_async('SELECT * FROM users WHERE identifier = ?', [playerIdentifier])
if (result) {
console.log(result.identifier, result.firstname, result.lastname)
}
```
- `exports.oxmysql.prepare`
+73 -52
View File
@@ -1,72 +1,93 @@
---
keywords: ['execute', 'fetchall']
keywords: ['fetchAll', 'execute']
title: Query
---
# Query
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
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.
When selecting data, returns all matching rows and columns; otherwise, returns data like insertId, affectedRows, etc.
## Lua
## Promise
### Callback
<Tabs>
<TabItem value="1" label="Lua">
```lua
-- alias: exports.oxmysql:query
-- alias: MySQL.Async.fetchAll
-- alias: exports.ghmattimysql:execute
local response = MySQL.query.await('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', {
identifier
})
MySQL.query('SELECT * FROM users WHERE identifier = ?', {playerIdentifier}, function(result)
if result then
for i = 1, #result do
local row = result[i]
print(row.identifier, row.firstname, row.lastname)
end
end
end)
```
### Promise
```lua
-- alias: exports.oxmysql:query_async
-- alias: MySQL.Sync.fetchAll
-- alias: exports.ghmattimysql:executeSync
local result = MySQL.query.await('SELECT * FROM users WHERE identifier = ?', {playerIdentifier})
if result then
for i = 1, #result do
local row = result[i]
print(row.identifier, row.firstname, row.lastname)
if response then
for i = 1, #response do
local row = response[i]
print(row.firstname, row.lastname)
end
end
```
## JavaScript
### Callback
</TabItem>
<TabItem value="2" label="JS">
```js
// alias: exports.oxmysql.query
const response = await MySQL.query('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', [
identifier
])
MySQL.query('SELECT * FROM users WHERE identifier = ?', [playerIdentifier], (result) => {
if (result) {
result.forEach((row) => {
console.log(row.identifier, row.firstname, row.lastname)
})
}
})
```
### Promise
```js
// alias: exports.oxmysql.query_async
const result = await MySQL.query('SELECT * FROM users WHERE identifier = ?', [playerIdentifier])
if (result) {
result.forEach((row) => {
if (response) {
response.forEach((row) => {
console.log(row.identifier, row.firstname, row.lastname)
})
}
```
</TabItem>
</Tabs>
**Aliases**
- `MySQL.Sync.fetchAll`
- `exports.ghmattimysql.execute`
- `exports.oxmysql.query_async`
## Callback
<Tabs>
<TabItem value="1" label="Lua">
```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)
```
</TabItem>
<TabItem value="2" label="JS">
```js
MySQL.query('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ?', [
identifier
], (response) => {
if (response) {
response.forEach((row) => {
console.log(row.firstname, row.lastname)
})
}
})
```
</TabItem>
</Tabs>
**Aliases**
- `MySQL.Async.fetchAll`
- `exports.ghmattimysql.execute`
- `exports.oxmysql.query`
+55 -33
View File
@@ -1,53 +1,75 @@
---
keywords: ['scalar', 'fetchscalar']
keywords: ['scalar', 'fetchScalar']
title: Scalar
---
# Scalar
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
Returns the first column for a single row.
## Lua
## Promise
### Callback
<Tabs>
<TabItem value="1" label="Lua">
```lua
-- alias: exports.oxmysql:scalar
-- alias: MySQL.Async.fetchScalar
-- alias: exports.ghmattimysql:scalar
local firstName = MySQL.scalar.await('SELECT `firstname` FROM `users` WHERE `identifier` = ? LIMIT 1', {
identifier
})
MySQL.scalar('SELECT firstname FROM users WHERE identifier = ?', {playerIdentifier}, function(firstname)
print(firstname)
print(firstName)
```
</TabItem>
<TabItem value="2" label="JS">
```js
const firstName = await MySQL.scalar('SELECT `firstname` FROM `users` WHERE `identifier` = ? LIMIT 1', [
identifier
])
console.log(firstName)
```
</TabItem>
</Tabs>
**Aliases**
- `MySQL.Sync.fetchScalar`
- `exports.ghmattimysql.scalar`
- `exports.oxmysql.scalar_async`
## Callback
<Tabs>
<TabItem value="1" label="Lua">
```lua
MySQL.scalar('SELECT `firstname` FROM `users` WHERE `identifier` = ? LIMIT 1', {
identifier
}, function(firstName)
print(firstName)
end)
```
### Promise
```lua
-- alias: exports.oxmysql:scalar_async
-- alias: MySQL.Sync.fetchScalar
-- alias: exports.ghmattimysql:scalarSync
local firstname = MySQL.scalar.await('SELECT firstname FROM users WHERE identifier = ?', {playerIdentifier})
print(firstname)
```
## JavaScript
### Callback
</TabItem>
<TabItem value="2" label="JS">
```js
// alias: exports.oxmysql.scalar
MySQL.scalar('SELECT firstname FROM users WHERE identifier = ?', [playerIdentifier], (firstname) => {
console.log(firstname)
MySQL.scalar('SELECT `firstname` FROM `users` WHERE `identifier` = ? LIMIT 1', [
identifier
], (firstName) => {
console.log(firstName)
})
```
### Promise
</TabItem>
</Tabs>
```js
// alias: exports.oxmysql.scalar_async
**Aliases**
const firstname = await MySQL.scalar('SELECT firstname FROM users WHERE identifier = ?', [playerIdentifier])
console.log(firstname)
```
- `MySQL.Async.fetchScalar`
- `exports.ghmattimysql.scalar`
- `exports.oxmysql.scalar`
+61 -36
View File
@@ -1,53 +1,78 @@
# Single
---
title: Single
---
Returns the columns for a single row.
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
## Lua
Returns all selected columns for a single row.
### Callback
## Promise
<Tabs>
<TabItem value="1" label="Lua">
```lua
-- alias: exports.oxmysql:single
local row = MySQL.scalar.await('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ? LIMIT 1', {
identifier
})
MySQL.single('SELECT * FROM users WHERE identifier = ?', {playerIdentifier}, function(row)
if row then
print(row.identifier, row.firstname, row.lastname)
end
if not row then return end
print(row.firstname, row.lastname)
```
</TabItem>
<TabItem value="2" label="JS">
```js
const row = await MySQL.scalar('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ? LIMIT 1', [
identifier
])
if (!row) return;
console.log(row.firstname, row.lastname)
```
</TabItem>
</Tabs>
**Aliases**
- `exports.oxmysql.single_async`
## Callback
<Tabs>
<TabItem value="1" label="Lua">
```lua
MySQL.scalar('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ? LIMIT 1', {
identifier
}, function(row)
if not row then return end
print(row.firstname, row.lastname)
end)
```
### Promise
```lua
-- alias: exports.oxmysql:single_async
local row = MySQL.single.await('SELECT * FROM users WHERE identifier = ?', {playerIdentifier})
if row then
print(row.identifier, row.firstname, row.lastname)
end
```
## JavaScript
### Callback
</TabItem>
<TabItem value="2" label="JS">
```js
// alias: exports.oxmysql.single
MySQL.scalar('SELECT `firstname`, `lastname` FROM `users` WHERE `identifier` = ? LIMIT 1', [
identifier
], (row) => {
if (!row) return;
MySQL.single('SELECT * FROM users WHERE identifier = ?', [playerIdentifier],(row) => {
if (row) {
console.log(row.identifier, row.firstname, row.lastname)
}
console.log(row.firstname, row.lastname)
})
```
### Promise
</TabItem>
</Tabs>
```js
// alias: exports.oxmysql.single_async
**Aliases**
const row = await MySQL.single('SELECT * FROM users WHERE identifier = ?', [playerIdentifier])
if (row) {
console.log(row.identifier, row.firstname, row.lastname)
}
```
- `exports.oxmysql.single`
+92 -114
View File
@@ -1,147 +1,125 @@
---
keywords: ['transaction']
title: Transaction
---
# Transaction
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
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.
A transaction executes multiple queries and commits them only if all succeed.
If one fails, none of the queries are committed.
## Specific Format
The return value is a boolean, which is the result of the transaction.
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.
## Specific format
This is useful for transactions where the queries do not share many SQL variables.
### Lua
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 (: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.
{ 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' } },
}
```
#### Callback
## 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
-- alias: exports.oxmysql:transaction
-- alias: MySQL.Async.transaction
-- alias: exports.ghmattimysql:transaction
-- 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>
<TabItem value="1" label="Lua">
```lua
local success = MySQL.transaction.await(queries, values --[[leave nil for specific format]])
print(success)
```
</TabItem>
<TabItem value="2" label="JS">
```js
const success = await MySQL.transaction(queries, values /*leave nil for specific format*/)
console.log(success)
```
</TabItem>
</Tabs>
**Aliases**
- `MySQL.Sync.transaction`
- `exports.ghmattimysql.transaction`
- `exports.oxmysql.transaction_async`
## Callback
<Tabs>
<TabItem value="1" label="Lua">
```lua
-- specific
MySQL.transaction(queries, values, function(success)
print(success)
end)
-- shared
MySQL.transaction(queries, function(success)
print(success)
end)
```
#### Promise
```lua
-- alias: exports.oxmysql:transaction_async
-- alias: MySQL.Sync.transaction
-- alias: exports.ghmattimysql:transactionSync
local success = MySQL.transaction.await(queries)
print(success)
```
### JavaScript
</TabItem>
<TabItem value="2" label="JS">
```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.
```
#### Callback
```js
// alias: exports.oxmysql.transaction
// specific
MySQL.transaction(queries, (success) => {
console.log(success);
});
console.log(success)
})
// shared
MySQL.transaction(queries, values, (success) => {
console.log(success)
})
```
#### Promise
</TabItem>
</Tabs>
```js
// alias: exports.oxmysql.transaction_async
**Aliases**
const success = await MySQL.transaction(queries);
console.log(success);
```
## 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' }
```
#### Callback
```lua
-- alias: exports.oxmysql:transaction
-- alias: MySQL.Async.transaction
MySQL.transaction(queries, parameters, function(success)
print(success)
end)
```
#### Promise
```lua
-- alias: exports.oxmysql:transaction_async
-- alias: MySQL.Sync.transaction
local success = MySQL.transaction.await(queries, parameters)
print(success)
```
### 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' };
```
#### Callback
```js
// alias: exports.oxmysql.transaction
MySQL.transaction(queries, parameters, (success) => {
console.log(success);
});
```
#### Promise
```js
// exports.oxmysql.transaction_async
const success = await MySQL.transaction(queries, parameters);
console.log(success);
```
- `MySQL.Async.transaction`
- `exports.ghmattimysql.transaction`
- `exports.oxmysql.transaction`
## 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`.
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 |
| ------------ | ---------------- |
+56 -42
View File
@@ -1,61 +1,75 @@
---
keywords: ['execute']
title: Update
---
# Update
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
Returns the number of affected rows by the query.
Returns the number of rows affected by the query.
## Lua
## Promise
### Callback
<Tabs>
<TabItem value="1" label="Lua">
```lua
-- alias: exports.oxmysql:update
-- alias: MySQL.Async.execute
-- alias: exports.ghmattimysql:execute
local affectedRows = MySQL.update.await('UPDATE users SET firstname = ? WHERE identifier = ?', {
newName, identifier
})
MySQL.update('UPDATE users SET firstname = ? WHERE identifier = ?', {newName, playerIdentifier}, function(affectedRows)
if affectedRows then
print(affectedRows)
end
print(affectedRows)
```
</TabItem>
<TabItem value="2" label="JS">
```js
const affectedRows = await MySQL.update('UPDATE users SET firstname = ? WHERE identifier = ?', [
newName, identifier
])
console.log(affectedRows)
```
</TabItem>
</Tabs>
**Aliases**
- `MySQL.Sync.execute`
- `exports.ghmattimysql.executeSync`
- `exports.oxmysql.update_async`
## Callback
<Tabs>
<TabItem value="1" label="Lua">
```lua
MySQL.update('UPDATE users SET firstname = ? WHERE identifier = ?', {
newName, identifier
}, function(affectedRows)
print(affectedRows)
end)
```
### Promise
```lua
-- alias: exports.oxmysql:update_async
-- alias: MySQL.Sync.execute
-- alias: exports.ghmattimysql:executeSync
local affectedRows = MySQL.update.await('UPDATE users SET firstname = ? WHERE identifier = ?', {newName, playerIdentifier})
if affectedRows then
print(affectedRows)
end
```
## JavaScript
### Callback
</TabItem>
<TabItem value="2" label="JS">
```js
// alias: exports.oxmysql.update
MySQL.update('UPDATE users SET firstname = ? WHERE identifier = ? ', [newName, playerIdentifier], (affectedRows) => {
if (affectedRows) {
console.log(affectedRows);
}
});
MySQL.update('UPDATE users SET firstname = ? WHERE identifier = ?', [
newName, identifier
], (affectedRows) => {
console.log(affectedRows)
})
```
### Promise
</TabItem>
</Tabs>
```js
// alias: exports.oxmysql.update_async
**Aliases**
const id = MySQL.update('UPDATE users SET firstname = ? WHERE identifier = ? ', [newName, playerIdentifier]);
if (affectedRows) {
console.log(affectedRows);
}
```
- `MySQL.Async.execute`
- `exports.ghmattimysql.execute`
- `exports.oxmysql.update`
+1 -1
View File
@@ -3,5 +3,5 @@ collapsible: true
collapsed: true
link:
type: generated-index
description: A drop-in replacement of mysql-async and ghmattimysql with expanded API and improved compatibility for MySQL 8.
description: A replacement of mysql-async and ghmattimysql with expanded API and improved compatibility for MySQL 8.
position: 2
+10
View File
@@ -108,3 +108,13 @@ ul.theme-doc-sidebar-menu {
border-left: none;
margin-left: 0.2rem;
}
code {
background-color: var(--ifm-code-background);
border: 0.1rem solid rgba(255, 255, 255, 0.1);
border-radius: var(--ifm-code-border-radius);
font-family: var(--ifm-font-family-monospace);
font-size: var(--ifm-code-font-size);
padding: var(--ifm-code-padding-vertical) var(--ifm-code-padding-horizontal);
vertical-align: middle;
}