Compare commits

..
14 Commits
Author SHA1 Message Date
Linden ab6e0ec92f Merge pull request #81 from dolutattoo/docs
Fixed wrong variable name
2022-01-21 18:47:21 +11:00
Dolu 937084a9a0 Fixed wrong variable name 2022-01-21 08:34:46 +01:00
Linden 90a5895882 Update common issues 2021-12-25 04:14:51 +11:00
Linden e6da9843ea update syntax and include aliases 2021-12-24 03:43:03 +11:00
Linden 6cf83ac4d1 rename update to execute 2021-12-23 22:08:26 +11:00
Linden eef4b7bdf9 fix formatting 2021-12-23 21:33:42 +11:00
Linden 40dee21923 update functions for 1.9.0, finally write prepare and common issues 2021-12-23 20:53:32 +11:00
Linden c07dfc085c gitignore 2021-12-23 19:55:28 +11:00
Linden 89e41be3c0 Call the correct function for UPDATE 2021-10-27 08:13:52 +11:00
Linden db9b1ffb7d Set correct navigation path 2021-10-25 08:41:51 +11:00
Linden 2c2f4e0661 Wrap Sync exports in CreateThread/setImmediate 2021-10-25 08:09:00 +11:00
Linden 9af6205bb7 Rename directory and fix JS Sync examples 2021-10-25 07:55:07 +11:00
Linden 2b40fafa7f Fix formatting 2021-10-25 03:48:14 +11:00
Dunak 5bcec3a0b1 New documentation 2021-10-25 03:35:33 +11:00
40 changed files with 759 additions and 1670 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
ko_fi: dunak
-41
View File
@@ -1,41 +0,0 @@
---
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
@@ -1,20 +0,0 @@
---
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
@@ -1,71 +0,0 @@
# 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
@@ -0,0 +1,32 @@
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
@@ -1,50 +0,0 @@
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
@@ -1,50 +0,0 @@
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 }}
+2 -121
View File
@@ -1,122 +1,3 @@
# 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
# 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
node_modules
.yarn*
-9
View File
@@ -1,9 +0,0 @@
{
"printWidth": 120,
"singleQuote": true,
"useTabs": false,
"tabWidth": 2,
"semi": true,
"bracketSpacing": true,
"trailingComma": "es5"
}
-165
View File
@@ -1,165 +0,0 @@
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.
-67
View File
@@ -1,67 +0,0 @@
<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.
Refer to [issue #77](https://github.com/overextended/oxmysql/issues/77) for information on replacing your queries from older versions of oxmysql or ghmattimysql.
### 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
@@ -0,0 +1 @@
theme: jekyll-theme-minimal
+4
View File
@@ -0,0 +1,4 @@
nav:
- index.md
- issues.md
- usage
+82
View File
@@ -0,0 +1,82 @@
---
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
@@ -0,0 +1,12 @@
---
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
@@ -0,0 +1,22 @@
.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
@@ -0,0 +1,5 @@
---
title: Index
---
todo - include some information about proper formatting, placeholders, bad practices, etc.
+43
View File
@@ -0,0 +1,43 @@
---
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
@@ -0,0 +1,114 @@
---
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
@@ -0,0 +1,60 @@
---
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
@@ -0,0 +1,43 @@
---
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
@@ -0,0 +1,49 @@
---
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
@@ -0,0 +1,102 @@
---
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
@@ -0,0 +1,49 @@
---
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
@@ -1,18 +0,0 @@
fx_version 'cerulean'
game 'common'
name 'oxmysql'
description 'Database wrapper for FiveM utilising node-mysql2 offering improved performance and security.'
version '1.9.2'
url 'https://github.com/overextended/oxmysql'
author 'overextended'
dependencies {
'/server:5104',
}
server_scripts {
'dist/server/build.js',
}
provide 'mysql-async'
-159
View File
@@ -1,159 +0,0 @@
-- 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
@@ -0,0 +1,132 @@
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
@@ -1,23 +0,0 @@
{
"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
@@ -1,311 +0,0 @@
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
@@ -1,60 +0,0 @@
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
@@ -0,0 +1,7 @@
# 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
@@ -1,39 +0,0 @@
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
@@ -1,58 +0,0 @@
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;
};
-39
View File
@@ -1,39 +0,0 @@
import { createPool } from 'mysql2/promise';
import { mysql_connection_string, mysql_transaction_isolation_level, typeCast } from '../config.js';
const connectionString = (() => {
if (mysql_connection_string === '') throw new Error(`^1Missing mysql_connection_string in server.cfg! Refer to the documentation^0`);
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
@@ -1,28 +0,0 @@
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();
let result, executionTime;
try {
[query, parameters, cb] = parseArguments(invokingResource, query, parameters, cb);
scheduleTick();
[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);
};
-58
View File
@@ -1,58 +0,0 @@
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();
scheduleTick();
const connection = await pool.getConnection();
let result;
try {
const parsedQuery = parseTransaction(invokingResource, queries, parameters);
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
@@ -1,54 +0,0 @@
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
@@ -1,61 +0,0 @@
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);
});
-133
View File
@@ -1,133 +0,0 @@
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`);
if (
parameters &&
typeof parameters === 'object' &&
!Array.isArray(parameters) &&
(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 {
const queryParams = query.match(/\?(?!\?)/g);
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
@@ -1,34 +0,0 @@
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);