Merge pull request #1 from N-fire/oxmysql

This commit is contained in:
Linden authored and GitHub committed 2022-03-04 10:08:59 +11:00
commit b982a68337
12 files changed
+521 -3

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
# Benchmark
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)')
})
```
+36
View File
@@ -0,0 +1,36 @@
# 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.
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).
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
```
### Using the UI
:::info
Before using the UI first you have to make sure you have the `mysql_ui` convar set to true:
```
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.
:::
+14
View File
@@ -0,0 +1,14 @@
# Common Issues
### 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.
:::
### 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.
:::
-3
View File
@@ -1,3 +0,0 @@
---
title: Installation
---
+5
View File
@@ -0,0 +1,5 @@
---
title: Usage
---
todo - include some information about proper formatting, placeholders, bad practices, etc.
+42
View File
@@ -0,0 +1,42 @@
# Insert
Inserts a new entry into the database and returns the insert id for the row, if valid.
## 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)
})()
```
+66
View File
@@ -0,0 +1,66 @@
# 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 `query, single, or scalar` depending on the number of columns and rows selected.
## 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)
})
}
})()
```
+57
View File
@@ -0,0 +1,57 @@
# 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.
## 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)
})
}
})()
```
+42
View File
@@ -0,0 +1,42 @@
# Scalar
Returns the first column for a single row.
## 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)
})()
```
+48
View File
@@ -0,0 +1,48 @@
# Single
Returns the columns for a single row.
## 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)
})
```
+100
View File
@@ -0,0 +1,100 @@
# 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 |
+48
View File
@@ -0,0 +1,48 @@
# Update
Returns the number of affected rows by the query.
## 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)
})
```