### CMake Build - Linux Source: https://github.com/fredyh/mysqloo/blob/master/README.md Compile the project on Linux using CMake and a C++ compiler. Prerequisites include installing `build-essential`, `gcc-multilib`, and `cmake`. Compilation involves running `cmake .` followed by `make` in the project directory. ```bash sudo apt install build-essential gcc-multilib cmake cd /path/to/project cmake . make // The resulting binary should be placed directly in the project directory. ``` -------------------------------- ### Query Object Functions Source: https://github.com/fredyh/mysqloo/blob/master/README.md Details on the methods available for interacting with Query objects, including starting, checking status, retrieving data, and managing errors. ```APIDOC ## Query Object Functions ### Description Methods for executing and managing standard SQL queries. ### Functions #### Query:start() * **Description**: Starts the query execution. * **Returns**: Nothing. #### Query:isRunning() * **Description**: Checks if the query is currently running or waiting. * **Returns**: [Boolean] - `true` if the query is running or waiting, `false` otherwise. #### Query:getData() * **Description**: Retrieves the data returned by the query. * **Returns**: [Table] - The query results in a table format. Rows can be indexed by field name or numerically if `OPTION_NUMERIC_FIELDS` is enabled. #### Query:abort() * **Description**: Attempts to abort a query that is in the `QUERY_WAITING` state. * **Returns**: [Boolean] - `true` if at least one running instance was aborted, `false` otherwise. #### Query:lastInsert() * **Description**: Gets the autoincrement index of the last inserted row. * **Returns**: [Number] - The index of the last inserted row. #### Query:affectedRows() * **Description**: Gets the number of rows affected by the query. * **Returns**: [Number] - The number of affected rows. #### Query:setOption(option) * **Description**: Changes how the query returns data using `mysqloo.OPTION_*` enums. * **Parameters**: - `option` (Enum) - The option to set. * **Returns**: Nothing. #### Query:wait(shouldSwap) * **Description**: Forces the server to wait for the query to finish. Use only when necessary. * **Parameters**: - `shouldSwap` (Boolean) - If `true`, the query is moved to the front of the execution queue. * **Returns**: Nothing. #### Query:error() * **Description**: Retrieves any error message associated with the query. * **Returns**: [String] - The error message, or an empty string if no error occurred. #### Query:hasMoreResults() * **Description**: Checks if there are more result sets available for the query. * **Returns**: [Boolean] - `true` if more results are available, `false` otherwise. #### Query:getNextResults() * **Description**: Retrieves the next result set, updating `lastInsert`, `affectedRows`, and `getData` accordingly. * **Returns**: [Table] - The rows of the next result set. Throws an error if no more results are available. ### Callbacks #### Query.onAborted(q) * **Description**: Called when the query is aborted. * **Parameters**: - `q` (Query) - The aborted query object. #### Query.onError(q, err, sql) * **Description**: Called when the query encounters an error. * **Parameters**: - `q` (Query) - The query object that errored. - `err` (String) - The error message. - `sql` (String) - The SQL query that caused the error. #### Query.onSuccess(q, data) * **Description**: Called when the query executes successfully. * **Parameters**: - `q` (Query) - The successful query object. - `data` (Table) - The data returned by the query. #### Query.onData(q, data) * **Description**: Called each time a row of data is retrieved by the query. * **Parameters**: - `q` (Query) - The query object. - `data` (Table) - The retrieved row of data. ``` -------------------------------- ### Call Stored Procedures with Prepared Statements using Mysqloo Source: https://context7.com/fredyh/mysqloo/llms.txt Illustrates how to call stored procedures with parameter binding using prepared statements in mysqloo. This example first creates a sample stored procedure and then demonstrates executing it with input parameters and processing its multiple result sets. ```lua require("mysqloo") local db = mysqloo.connect("localhost", "username", "password", "database_name", 3306) function db:onConnected() -- First, create the stored procedure local createProc = db:query([[ CREATE PROCEDURE IF NOT EXISTS get_user_stats (IN user_id INT) BEGIN SELECT * FROM users WHERE id = user_id; SELECT COUNT(*) as post_count FROM posts WHERE user_id = user_id; END ]]) function createProc:onSuccess() print("Stored procedure created") -- Call the stored procedure with prepared statement local callProc = db:prepare("CALL get_user_stats(?)") callProc:setNumber(1, 5) -- Set user_id parameter function callProc:onSuccess(data) -- First result set: user data print("User found:", data[1].username) -- Second result set: post count if callProc:hasMoreResults() then local statsData = callProc:getNextResults() print("User has", statsData[1].post_count, "posts") end -- Stored procedures may have extra empty result sets while callProc:hasMoreResults() do callProc:getNextResults() end end function callProc:onError(err) print("Procedure call error:", err) end callProc:start() end createProc:start() end db:connect() ``` -------------------------------- ### Query Execution and Management Source: https://github.com/fredyh/mysqloo/blob/master/README.md Functions for executing and managing database queries. `start()` initiates a query. `isRunning()` checks if a query is active. `getData()` retrieves query results. `abort()` attempts to cancel a waiting query. `lastInsert()` and `affectedRows()` provide information about the last operation. `setOption()` customizes query behavior. `wait()` forces query completion. `error()` returns any query errors. `hasMoreResults()` and `getNextResults()` handle multiple result sets. ```lua Query:start() -- Returns nothing -- Starts the query. Query:isRunning() -- Returns [Boolean] -- True if the query is running or waiting, false if it isn't. Query:getData() -- Returns [Table] -- Gets the data the query returned from the server -- Format: { row1, row2, row3, ... } -- Row format: { field_name = field_value } or {first_field, second_field, ...} if OPTION_NUMERIC_FIELDS is enabled Query:abort() -- Returns [Boolean] -- Attempts to abort the query if it is still in the state QUERY_WAITING -- Returns true if at least one running instance of the query was aborted successfully, false otherwise Query:lastInsert() -- Returns [Number] -- Gets the autoincrement index of the last inserted row of the current result set Query:affectedRows() -- Returns [Number] -- Gets the number of rows the query has affected (of the current result set) Query:setOption( option ) -- Returns nothing -- Changes how the query returns data (mysqloo.OPTION_* enums). Query:wait(shouldSwap) -- Returns nothing -- Forces the server to wait for the query to finish. -- This should only ever be used if it is really necessary, since it can cause lag and -- If shouldSwap is true, the query is being swapped to the front of the queue -- making it the next query to be executed Query:error() -- Returns [String] -- Gets the error caused by the query, or "" if there was no error. Query:hasMoreResults() -- Returns [Boolean] -- Returns true if the query still has more data associated with it (which means getNextResults() can be called) -- Note: This function works unfortunately different that one would expect. -- hasMoreResults() returns true if there is currently a result that can be popped, rather than if there is an -- additional result that has data. However, this does make for a nicer code that handles multiple results. -- See Examples/multi_results.lua for an example how to use it. Query:getNextResults() -- Returns [Table] -- Pops the current result set, chaning the results of lastInsert() and affectedRows() and getData() -- to those of the next result set. Returns the rows of the next result set in the same format as getData() -- Throws an error if attempted to be called when there is no result set left to be popped ``` -------------------------------- ### Lua: Mysqloo Prepared Statements for Safe Query Execution Source: https://context7.com/fredyh/mysqloo/llms.txt Shows how to use prepared statements with the mysqloo Lua library for secure and efficient SQL query execution. Prepared statements use placeholders (?) which are then safely bound with data, preventing SQL injection and improving performance for repeated queries. This example covers both INSERT and SELECT statements. ```lua require("mysqloo") local db = mysqloo.connect("localhost", "username", "password", "database_name", 3306) function db:onConnected() -- Create prepared query with parameters (?) local prepQuery = db:prepare("INSERT INTO users (username, email, age, active, bio) VALUES (?, ?, ?, ?, ?)") -- Set parameters by index (1-based) prepQuery:setString(1, "john_doe") prepQuery:setString(2, "john@example.com") prepQuery:setNumber(3, 25) prepQuery:setBoolean(4, true) prepQuery:setNull(5) -- NULL value for bio function prepQuery:onSuccess(data) print("Insert successful") print("Last insert ID:", prepQuery:lastInsert()) print("Affected rows:", prepQuery:affectedRows()) end function prepQuery:onError(err, sql) print("Prepared query error:", err) end -- Start the prepared query prepQuery:start() -- Can reuse the same prepared query with different parameters local selectQuery = db:prepare("SELECT * FROM users WHERE age > ? AND active = ?") selectQuery:setNumber(1, 18) selectQuery:setBoolean(2, true) function selectQuery:onSuccess(data) print("Found", #data, "active adult users") for i, row in ipairs(data) do print(row.username, row.age) end end selectQuery:start() end db:connect() ``` -------------------------------- ### PreparedQuery:putNewParameters() - mysqloo Source: https://github.com/fredyh/mysqloo/blob/master/README.md Clears all currently set parameters inside the prepared statement. This method is deprecated; instead, start the same prepared statement multiple times. ```lua -- Returns nothing -- Clears all currently set parameters inside the prepared statement. PreparedQuery:putNewParameters() ``` -------------------------------- ### CMake Build - Windows Visual Studio Source: https://github.com/fredyh/mysqloo/blob/master/README.md Build instructions for Windows using Visual Studio 2017 or later. Users can open the CMakeLists.txt file directly and utilize the predefined CMakeSettings.json for 32 and 64-bit configurations. Building is done via the toolbar, with output in the `out/build/{ConfigurationName}/` subfolder. ```bash File > Open > CMake... // Select the CMakeList.txt from this directory. // Build using the toolbar. // Output files are placed in the `out/build/{ConfigurationName}/` subfolder. ``` -------------------------------- ### CMake Build - CLion Source: https://github.com/fredyh/mysqloo/blob/master/README.md Instructions for building the project using CLion. Open the project and import the CMake project. Ensure a valid toolchain is set up. Build using `Build > Build Project`. For 32-bit compilation, select a 32-bit VS toolchain. Output files are in the `cmake-build-debug/` directory. ```bash // Open the project in CLion and import the CMake project. // Build using `Build > Build Project`. // Output files are placed within the `cmake-build-debug/` directory. ``` -------------------------------- ### Database Connection and Callbacks Source: https://github.com/fredyh/mysqloo/blob/master/README.md This section details how to manage database connections and set up callback functions for connection events. ```APIDOC ## Database Connection and Callbacks ### Description Functions for managing database connections and defining callbacks for connection events like success, failure, and disconnection. ### Callbacks #### Database.onConnected(db) * **Description**: Called when the connection to the MySQL server is successful. * **Parameters**: - `db` (Database) - The database instance. #### Database.onConnectionFailed(db, err) * **Description**: Called when the connection to the MySQL server fails. * **Parameters**: - `db` (Database) - The database instance. - `err` (String) - The reason for the connection failure. #### Database.onDisconnected(db) * **Description**: Called after `Database.disconnect` has been called and all queries have finished executing. Must be set before calling `Database:connect()`. * **Parameters**: - `db` (Database) - The database instance. ``` -------------------------------- ### MySQLoo Core Functions and Constants Source: https://github.com/fredyh/mysqloo/blob/master/README.md This section covers the initialization function and global constants for the MySQLoo library. ```APIDOC ## MySQLoo Initialization and Constants ### Description Provides functions to initialize the database connection and constants for library version and status codes. ### Functions #### mysqloo.connect(host, username, password, database [, port, socket]) - **Description**: Initializes the database object. Note that this does not actually connect to the database. - **Returns**: [Database] ### Constants - **mysqloo.VERSION**: [String] Current MySQLOO version (currently "9"). - **mysqloo.MINOR_VERSION**: [String] Minor version of this library. - **Database Status Codes**: - **mysqloo.DATABASE_CONNECTED**: [Number] Database is connected. - **mysqloo.DATABASE_NOT_CONNECTED**: [Number] Database is not connected. - **mysqloo.DATABASE_INTERNAL_ERROR**: [Number] Internal error. - **Query Status Codes**: - **mysqloo.QUERY_NOT_RUNNING**: [Number] Query not running. - **mysqloo.QUERY_WAITING**: [Number] Query is queued/started. - **mysqloo.QUERY_RUNNING**: [Number] Query is being processed (on the database server). - **mysqloo.QUERY_COMPLETE**: [Number] Query is complete. - **mysqloo.QUERY_ABORTED**: [Number] Query was aborted. - **Option Flags**: - **mysqloo.OPTION_NUMERIC_FIELDS**: [Number] Instead of rows being key value pairs, this makes them just be an array of values. - **mysqloo.OPTION_NAMED_FIELDS**: [Number] Not used anymore. - **mysqloo.OPTION_INTERPRET_DATA**: [Number] Not used anymore. - **mysqloo.OPTION_CACHE**: [Number] Not used anymore. ``` -------------------------------- ### Configure Project and Library Build Settings (CMake) Source: https://github.com/fredyh/mysqloo/blob/master/CMakeLists.txt Sets up the minimum CMake version, project name, and recursively adds subdirectories. It then finds and includes source files, sets the C++ standard, and defines the build type. Finally, it adds a shared library target named 'mysqloo'. ```cmake cmake_minimum_required(VERSION 3.5) project(mysqloo) add_subdirectory(GmodLUA) file(GLOB_RECURSE MYSQLOO_SRC "src/*.h" "src/*.cpp") set(SOURCE_FILES ${MYSQLOO_SRC}) set(CMAKE_BUILD_TYPE RelWithDebInfo) set (CMAKE_CXX_STANDARD 14) add_library(mysqloo SHARED ${SOURCE_FILES}) ``` -------------------------------- ### MySQL Connection and Initialization (Lua) Source: https://github.com/fredyh/mysqloo/blob/master/README.md Establishes a database connection object using mysqloo.connect. Note that this function initializes the object but does not establish an actual connection. It returns a database object that can then be used for further operations. ```lua -- mysqloo table mysqloo.connect( host, username, password, database [, port, socket] ) -- returns [Database] -- Initializes the database object, note that this does not actually connect to the database. ``` -------------------------------- ### PreparedQuery Object Functions Source: https://github.com/fredyh/mysqloo/blob/master/README.md Documentation for PreparedQuery methods, which allow for secure and efficient execution of parameterized SQL statements. ```APIDOC ## PreparedQuery Object Functions ### Description Functions for using prepared statements to securely execute SQL queries with parameters, preventing SQL injection. ### Functions #### PreparedQuery:setNumber(index, number) * **Description**: Sets a parameter at the specified index to be a double value. * **Parameters**: - `index` (Number) - The 1-based index of the parameter. - `number` (Number) - The double value to set. * **Returns**: Nothing. #### PreparedQuery:setString(index, str) * **Description**: Sets a parameter at the specified index to be a string value. Do not escape the string. * **Parameters**: - `index` (Number) - The 1-based index of the parameter. - `str` (String) - The string value to set. * **Returns**: Nothing. #### PreparedQuery:setBoolean(index, bool) * **Description**: Sets a parameter at the specified index to be a boolean value. * **Parameters**: - `index` (Number) - The 1-based index of the parameter. - `bool` (Boolean) - The boolean value to set. * **Returns**: Nothing. #### PreparedQuery:setNull(index) * **Description**: Sets a parameter at the specified index to be NULL. * **Parameters**: - `index` (Number) - The 1-based index of the parameter. * **Returns**: Nothing. #### PreparedQuery:clearParameters() * **Description**: Clears all set parameters for the prepared query. ``` -------------------------------- ### MySQL Query Execution and Management (Lua) Source: https://github.com/fredyh/mysqloo/blob/master/README.md Provides functions for executing SQL queries, preparing statements, and managing query states within the mysqloo library. Includes methods for running arbitrary SQL, creating prepared statements, and checking query status. ```lua -- Database object -- Functions Database:query( sql ) -- Returns [Query] -- Initializes a query to the database, [String] sql is the SQL query to run. Database:prepare( sql ) -- Returns [PreparedQuery] -- Creates a prepared query associated with the database ``` -------------------------------- ### Connect to MySQL/MariaDB Database with Callbacks Source: https://context7.com/fredyh/mysqloo/llms.txt Establishes a connection to a MySQL/MariaDB database using provided credentials and handles connection success or failure events via callbacks. It also provides methods to retrieve server and connection information. ```lua require("mysqloo") -- Create database connection object local db = mysqloo.connect("localhost", "username", "password", "database_name", 3306) -- Connection success callback function db:onConnected() print("Database connected successfully") print("Server version:", db:serverVersion()) print("Server info:", db:serverInfo()) print("Host info:", db:hostInfo()) end -- Connection failure callback function db:onConnectionFailed(err) print("Database connection failed:", err) end -- Optional: Disconnect callback (must be set before connect()) function db:onDisconnected() print("Database has been disconnected") end -- Initiate the connection (non-blocking) db:connect() -- Optional: Wait for connection to complete (blocking - use with caution) -- db:wait() -- Check connection status local status = db:status() if status == mysqloo.DATABASE_CONNECTED then print("Status: Connected") elseif status == mysqloo.DATABASE_NOT_CONNECTED then print("Status: Not connected") end ``` -------------------------------- ### Connect and Manage MySQL Database with mysqloo Source: https://context7.com/fredyh/mysqloo/llms.txt Establishes a MySQL connection, retrieves server information, checks connection status, queues multiple queries, and handles graceful disconnection. It also demonstrates disabling prepared statement caching. ```lua require("mysqloo") local db = mysqloo.connect("localhost", "username", "password", "database_name", 3306) function db:onConnected() print("MySQLOO version:", mysqloo.VERSION) print("MySQLOO minor version:", mysqloo.MINOR_VERSION) -- Get server information print("Server version:", db:serverVersion()) print("Server info string:", db:serverInfo()) print("Host information:", db:hostInfo()) -- Check connection status local status = db:status() if status == mysqloo.DATABASE_CONNECTED then print("Database is connected") end -- Queue multiple queries for i = 1, 10 do local q = db:query("SELECT " .. i) q:start() end -- Check queue size print("Current queue size:", db:queueSize()) -- Ping the database (blocking operation) local isAlive = db:ping() if isAlive then print("Database connection is alive") else print("Database connection is down") end -- Disable prepared statement caching if hitting server limits db:setCachePreparedStatements(false) -- Graceful disconnection timer.Simple(5, function() -- Disconnect and wait for all queries to finish db:disconnect(true) end) end function db:onDisconnected() print("Database disconnected gracefully") end db:connect() ``` -------------------------------- ### CMake: Configure Garry's Mod Module Base Library Source: https://github.com/fredyh/mysqloo/blob/master/GmodLUA/CMakeLists.txt This CMake script configures a base library for Garry's Mod modules. It defines the source files, sets the library as an interface library, and specifies include directories. The `set_gmod_suffix_prefix` function further customizes the library's properties based on the target operating system and architecture. ```cmake set(SOURCES GarrysMod/Lua/Interface.h GarrysMod/Lua/LuaBase.h GarrysMod/Lua/SourceCompat.h GarrysMod/Lua/Types.h GarrysMod/Lua/UserData.h) add_library(gmod-module-base INTERFACE) target_include_directories(gmod-module-base INTERFACE .) function(set_gmod_suffix_prefix library) SET_TARGET_PROPERTIES(${library} PROPERTIES PREFIX "gmsv_") if(APPLE) if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "4") SET_TARGET_PROPERTIES(${library} PROPERTIES SUFFIX "_osx.dll") else() SET_TARGET_PROPERTIES(${library} PROPERTIES SUFFIX "_osx64.dll") endif() elseif(UNIX) if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "4") SET_TARGET_PROPERTIES(${library} PROPERTIES SUFFIX "_linux.dll") else() SET_TARGET_PROPERTIES(${library} PROPERTIES SUFFIX "_linux64.dll") endif() elseif(WIN32) if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "4") SET_TARGET_PROPERTIES(${library} PROPERTIES SUFFIX "_win32.dll") else() SET_TARGET_PROPERTIES(${library} PROPERTIES SUFFIX "_win64.dll") endif() endif() endfunction() ``` -------------------------------- ### mysqloo Constants and Version Information (Lua) Source: https://github.com/fredyh/mysqloo/blob/master/README.md Defines constants for tracking database and query states, as well as options for customizing query behavior. It also exposes version information for the mysqloo library itself, aiding in compatibility checks and debugging. ```lua mysqloo.VERSION -- [String] Current MySQLOO version (currently "9") mysqloo.MINOR_VERSION -- [String] minor version of this library mysqloo.DATABASE_CONNECTED -- [Number] - Database is connected mysqloo.DATABASE_NOT_CONNECTED -- [Number] - Database is not connected mysqloo.DATABASE_INTERNAL_ERROR -- [Number] - Internal error mysqloo.QUERY_NOT_RUNNING -- [Number] - Query not running mysqloo.QUERY_WAITING -- [Number] - Query is queued/started mysqloo.QUERY_RUNNING -- [Number] - Query is being processed (on the database server) mysqloo.QUERY_COMPLETE -- [Number] - Query is complete mysqloo.QUERY_ABORTED -- [Number] - Query was aborted mysqloo.OPTION_NUMERIC_FIELDS -- [Number] - Instead of rows being key value pairs, this makes them just be an array of values mysqloo.OPTION_NAMED_FIELDS -- [Number] - Not used anymore mysqloo.OPTION_INTERPRET_DATA -- [Number] - Not used anymore mysqloo.OPTION_CACHE -- [Number] - Not used anymore ``` -------------------------------- ### Find MariaDB Client Library based on Architecture and OS (CMake) Source: https://github.com/fredyh/mysqloo/blob/master/CMakeLists.txt Conditionally finds the MariaDB client library ('mariadbclient') and potentially SSL/Crypto libraries based on the system's architecture (32-bit or 64-bit) and operating system (Windows or Linux). It specifies hints for library locations. ```cmake if (CMAKE_SIZEOF_VOID_P EQUAL 8) if (WIN32) find_library(MARIADB_CLIENT_LIB mariadbclient HINTS "${PROJECT_SOURCE_DIR}/MySQL/lib64/windows") else () find_library(MARIADB_CLIENT_LIB mariadbclient HINTS "${PROJECT_SOURCE_DIR}/MySQL/lib64/linux") find_library(CRYPTO_LIB crypto HINTS "${PROJECT_SOURCE_DIR}/MySQL/lib64/linux") find_library(SSL_LIB ssl HINTS "${PROJECT_SOURCE_DIR}/MySQL/lib64/linux") endif () elseif (CMAKE_SIZEOF_VOID_P EQUAL 4) if (WIN32) find_library(MARIADB_CLIENT_LIB mariadbclient HINTS "${PROJECT_SOURCE_DIR}/MySQL/lib/windows") else () find_library(MARIADB_CLIENT_LIB mariadbclient HINTS "${PROJECT_SOURCE_DIR}/MySQL/lib/linux") find_library(CRYPTO_LIB crypto HINTS "${PROJECT_SOURCE_DIR}/MySQL/lib/linux") find_library(SSL_LIB ssl HINTS "${PROJECT_SOURCE_DIR}/MySQL/lib/linux") endif () endif () ``` -------------------------------- ### MySQL Character Set and SSL Configuration (Lua) Source: https://github.com/fredyh/mysqloo/blob/master/README.md Allows configuration of the database connection's character set and SSL settings. `setCharacterSet` attempts to change the connection's character encoding, while `setSSLSettings` enables secure connections over the internet using TLS by specifying key, certificate, and other SSL parameters. ```lua Database:setCharacterSet(charSetName) -- Returns [Boolean] -- Attempts to set the connection's character set to the one specified. -- Please note that this does block the main server thread if there is a query currently being ran -- Returns true on success, false on failure Database:setSSLSettings(key, cert, ca, capath, cipher) -- Returns nothing -- Sets the SSL configuration of the database object. This allows you to enable secure connections over the internet using TLS. -- Every parameter is optional and can be omitted (set to nil) if not required. -- See https://dev.mysql.com/doc/c-api/8.0/en/mysql-ssl-set.html for the description of each parameter. ``` -------------------------------- ### Handle Multiple Result Sets with Mysqloo Source: https://context7.com/fredyh/mysqloo/llms.txt Demonstrates how to process multiple result sets returned by multi-statements or stored procedures using the mysqloo library. It shows how to check for and retrieve subsequent result sets after the initial one. ```lua require("mysqloo") local db = mysqloo.connect("localhost", "username", "password", "database_name", 3306) function db:onConnected() -- Execute multiple SELECT statements local query = db:query("SELECT 1 as first; SELECT 2 as second; SELECT 3 as third;") function query:onSuccess(data) -- First result set print("First result:", data[1].first) -- Check for more results if query:hasMoreResults() then local secondData = query:getNextResults() print("Second result:", secondData[1].second) end if query:hasMoreResults() then local thirdData = query:getNextResults() print("Third result:", thirdData[1].third) end -- No more results if not query:hasMoreResults() then print("All results processed") end end function query:onError(err) print("Error:", err) end query:start() end db:connect() ``` -------------------------------- ### Prepared Query Parameter Setting Source: https://github.com/fredyh/mysqloo/blob/master/README.md Methods for setting parameters in prepared SQL statements. `setNumber()` sets a double parameter. `setString()` sets a string parameter (without requiring manual escaping). `setBoolean()` sets a boolean parameter. `setNull()` sets a parameter to NULL. `clearParameters()` resets all parameters for the prepared query. ```lua PreparedQuery:setNumber(index, number) -- Returns nothing -- Sets the parameter at index (1-based) to be of type double with value number PreparedQuery:setString(index, str) -- Returns nothing -- Sets the parameter at index (1-based) to be of type string with value str -- Note: str should not!! be escaped PreparedQuery:setBoolean(index, bool) -- Returns nothing -- Sets the parameter at index (1-based) to be of type boolean with value bool PreparedQuery:setNull(index) -- Returns nothing -- Sets the parameter at index (1-based) to be NULL PreparedQuery:clearParameters() ``` -------------------------------- ### Link External Libraries and Include Directories (CMake) Source: https://github.com/fredyh/mysqloo/blob/master/CMakeLists.txt Links the 'mysqloo' library against 'gmod-module-base' and specifies include directories for MySQL headers. This ensures that the project can access functionality from the base module and find the necessary MySQL header files during compilation. ```cmake target_link_libraries(mysqloo gmod-module-base) target_include_directories(mysqloo PRIVATE MySQL/include) ``` -------------------------------- ### MySQL Connection Status and Control (Lua) Source: https://github.com/fredyh/mysqloo/blob/master/README.md Offers functionalities to manage the MySQL database connection, including checking its status, aborting pending queries, and configuring automatic reconnection. It also provides methods to control statement preparation caching and force connection waits. ```lua Database:abortAllQueries() -- Returns the amount of queries aborted successfully -- Aborts all waiting (QUERY_WAITING) queries Database:status() -- Returns [Number] (mysqloo.DATABASE_* enums) -- Checks the connection to the database -- This shouldn't be used to detect timeouts to the server anymore (it's not possible anymore) Database:setAutoReconnect(shouldReconnect) -- Returns nothing -- The autoreconnect feature of mysqloo can be disabled if this function is called with shouldReconnect = false -- This may only be called before Database:connect() Database:setMultiStatements(useMultiStatemets) -- Returns nothing -- Multi statements ("SELECT 1; SELECT 2;") can be disabled if this function is called with useMultiStatemets = false -- This may only be called before Database:connect() Database:setCachePreparedStatements(cachePreparedStatements) -- Returns nothing -- This will disable all caching of prepared query handles -- which will reduce the performance of prepared queries that are being reused -- Set this to true if you run into the prepared query limit imposed by the server Database:wait() -- Returns nothing -- Forces the server to wait for the connection to finish. (might cause deadlocks) -- This may only be called after Database:connect() ``` -------------------------------- ### Execute Basic SQL Queries with Callbacks Source: https://context7.com/fredyh/mysqloo/llms.txt Executes a standard SQL query and processes the results or errors using a callback-based system. It supports retrieving query results, affected rows, last insert ID, and handling individual row data or query abortion. ```lua require("mysqloo") local db = mysqloo.connect("localhost", "username", "password", "database_name", 3306) function db:onConnected() -- Create a query object local query = db:query("SELECT * FROM users WHERE active = 1") -- Success callback with result data function query:onSuccess(data) print("Query returned", #data, "rows") -- Iterate through results for i, row in ipairs(data) do print("User ID:", row.id) print("Username:", row.username) print("Email:", row.email) end -- Alternative: Get data later local cachedData = query:getData() -- Get query metadata print("Affected rows:", query:affectedRows()) print("Last insert ID:", query:lastInsert()) end -- Error callback function query:onError(err, sql) print("Query error:", err) print("Failed SQL:", sql) print("Error details:", query:error()) end -- Optional: Data callback (called for each row) function query:onData(row) print("Received row:", row.username) end -- Optional: Abort callback function query:onAborted() print("Query was aborted") end -- Start the query (non-blocking) query:start() -- Check if query is running if query:isRunning() then print("Query is executing...") end end db:connect() ``` -------------------------------- ### Platform-Specific Library Linking (CMake) Source: https://github.com/fredyh/mysqloo/blob/master/CMakeLists.txt Links necessary libraries to the 'mysqloo' target based on the operating system. For Windows, it links against the found MariaDB client library and several Windows-specific system libraries. For other systems (like Linux), it finds the Threads library and links against MariaDB, SSL, Crypto, Threads, and the dynamic loading library, also linking the static C++ standard library. ```cmake if (WIN32) target_link_libraries(mysqloo ${MARIADB_CLIENT_LIB} crypt32 ws2_32 shlwapi bcrypt secur32) else () find_package(Threads REQUIRED) target_link_libraries(mysqloo ${MARIADB_CLIENT_LIB} ${SSL_LIB} ${CRYPTO_LIB} Threads::Threads ${CMAKE_DL_LIBS}) target_link_libraries(mysqloo -static-libstdc++) endif () ``` -------------------------------- ### Set GMod Suffix Prefix (CMake) Source: https://github.com/fredyh/mysqloo/blob/master/CMakeLists.txt Applies a suffix prefix to the 'mysqloo' target, likely for compatibility or naming conventions within the GMod environment. This is a project-specific configuration step. ```cmake set_gmod_suffix_prefix(mysqloo) ``` -------------------------------- ### MySQL Server Information Retrieval (Lua) Source: https://github.com/fredyh/mysqloo/blob/master/README.md Retrieves detailed information about the connected MySQL server, including its version, general information string, and host connection details. This is useful for logging, diagnostics, or adapting application behavior based on server capabilities. ```lua Database:serverVersion() -- Returns [Number] -- Gets the MySQL servers version Database:serverInfo() -- Returns [String] -- Fancy string of the MySQL servers version Database:hostInfo() -- Returns [String] -- Gets information about the connection. ``` -------------------------------- ### MySQL Connection Health Check and Queue Size (Lua) Source: https://github.com/fredyh/mysqloo/blob/master/README.md Provides methods to check the health of the database connection and query the number of pending queries. The `ping` function actively verifies the connection and attempts a reconnect if necessary, though it can cause server freezes if the connection is down. `queueSize` returns the count of queries awaiting execution. ```lua Database:queueSize() -- Returns [Number] -- Gets the amount of queries waiting to be processed Database:ping() -- Returns [Boolean] -- Actively checks if the database connection is still up and attempts to reconnect if it is down -- This will freeze your server for at least 2 times the pingtime to -- the database server if the connection is down -- returns true if the connection is still up, false otherwise ``` -------------------------------- ### Database Object Functions Source: https://github.com/fredyh/mysqloo/blob/master/README.md Functions available on the Database object for managing connections, queries, and transactions. ```APIDOC ## Database Object ### Description Provides methods for interacting with a connected MySQL database, including executing queries, managing transactions, and retrieving connection information. ### Functions #### Database:connect() - **Description**: Connects to the database (non-blocking). This function calls the `onConnected` or `onConnectionFailed` callback. - **Returns**: Nothing #### Database:disconnect(shouldWait) - **Description**: Disconnects from the database and waits for all queries to finish if `shouldWait` is true. This function calls the `onDisconnected` callback if it existed on the database before the database was connected. - **Parameters**: - `shouldWait` (boolean) - Optional. If true, waits for all queries to finish. - **Returns**: Nothing #### Database:query(sql) - **Description**: Initializes a query to the database. - **Parameters**: - `sql` (string) - The SQL query to run. - **Returns**: [Query] #### Database:prepare(sql) - **Description**: Creates a prepared query associated with the database. - **Parameters**: - `sql` (string) - The SQL query to prepare. - **Returns**: [PreparedQuery] #### Database:createTransaction() - **Description**: Creates a transaction that executes multiple statements atomically. Check [url]https://en.wikipedia.org/wiki/ACID[/url] for more information. - **Returns**: [Transaction] #### Database:escape(str) - **Description**: Escapes a string so that it is safe to use in a query. If the character set of the database is changed after connecting, this might not work properly anymore. - **Parameters**: - `str` (string) - The string to escape. - **Returns**: [String] #### Database:abortAllQueries() - **Description**: Aborts all waiting (`QUERY_WAITING`) queries. - **Returns**: The amount of queries aborted successfully. #### Database:status() - **Description**: Checks the connection to the database. This shouldn't be used to detect timeouts to the server anymore (it's not possible anymore). - **Returns**: [Number] (mysqloo.DATABASE_* enums) #### Database:setAutoReconnect(shouldReconnect) - **Description**: The autoreconnect feature of mysqloo can be disabled if this function is called with `shouldReconnect = false`. This may only be called before `Database:connect()`. - **Parameters**: - `shouldReconnect` (boolean) - Whether to enable auto-reconnect. - **Returns**: Nothing #### Database:setMultiStatements(useMultiStatemets) - **Description**: Multi statements ("SELECT 1; SELECT 2;") can be disabled if this function is called with `useMultiStatemets = false`. This may only be called before `Database:connect()`. - **Parameters**: - `useMultiStatemets` (boolean) - Whether to enable multi-statement support. - **Returns**: Nothing #### Database:setCachePreparedStatements(cachePreparedStatements) - **Description**: This will disable all caching of prepared query handles, which will reduce the performance of prepared queries that are being reused. Set this to true if you run into the prepared query limit imposed by the server. - **Parameters**: - `cachePreparedStatements` (boolean) - Whether to enable caching of prepared statements. - **Returns**: Nothing #### Database:wait() - **Description**: Forces the server to wait for the connection to finish. (Might cause deadlocks). This may only be called after `Database:connect()`. - **Returns**: Nothing #### Database:serverVersion() - **Description**: Gets the MySQL servers version. - **Returns**: [Number] #### Database:serverInfo() - **Description**: Fancy string of the MySQL servers version. - **Returns**: [String] #### Database:hostInfo() - **Description**: Gets information about the connection. - **Returns**: [String] #### Database:queueSize() - **Description**: Gets the amount of queries waiting to be processed. - **Returns**: [Number] #### Database:ping() - **Description**: Actively checks if the database connection is still up and attempts to reconnect if it is down. This will freeze your server for at least 2 times the ping time to the database server if the connection is down. - **Returns**: [Boolean] `true` if the connection is still up, `false` otherwise. #### Database:setCharacterSet(charSetName) - **Description**: Attempts to set the connection's character set to the one specified. Please note that this does block the main server thread if there is a query currently being ran. - **Parameters**: - `charSetName` (string) - The name of the character set to set. - **Returns**: [Boolean] `true` on success, `false` on failure. #### Database:setSSLSettings(key, cert, ca, capath, cipher) - **Description**: Sets the SSL configuration of the database object. This allows you to enable secure connections over the internet using TLS. Every parameter is optional and can be omitted (set to `nil`) if not required. See [https://dev.mysql.com/doc/c-api/8.0/en/mysql-ssl-set.html](https://dev.mysql.com/doc/c-api/8.0/en/mysql-ssl-set.html) for the description of each parameter. - **Parameters**: - `key` (string) - Path to the SSL key file. - `cert` (string) - Path to the SSL certificate file. - `ca` (string) - Path to the CA certificate file. - `capath` (string) - Path to a directory containing trusted CA certificates. - `cipher` (string) - SSL cipher to use. - **Returns**: Nothing #### Timeout Settings - **Database:setReadTimeout(timeout)**: Sets the read timeout for the connection. - **Database:setWriteTimeout(timeout)**: Sets the write timeout for the connection. - **Database:setConnectTimeout(timeout)**: Sets the connection timeout. - **Returns**: Nothing for all timeout setting functions. ``` -------------------------------- ### Database Connection Callbacks Source: https://github.com/fredyh/mysqloo/blob/master/README.md Callbacks for handling database connection events. `onConnected` is called upon successful connection. `onConnectionFailed` is invoked when the connection fails, providing an error message. `onDisconnected` is triggered after a disconnection request and query completion. Note that `onDisconnected` must be set before calling `Database:connect()`. ```lua Database.onConnected( db ) -- Called when the connection to the MySQL server is successful Database.onConnectionFailed( db, err ) -- Called when the connection to the MySQL server fails, [String] err is why. Database.onDisconnected( db ) -- Called after Database.disconnect has been called and all queries have finished executing -- Note: You have to set this callback before calling Database:connect() or it will not be called. ``` -------------------------------- ### Query Abortion in Lua with mysqloo Source: https://context7.com/fredyh/mysqloo/llms.txt Illustrates how to abort queued queries before they are executed using the `abort` method and `abortAllQueries`. This is useful for canceling operations that are no longer needed, preventing unnecessary database load. Note that queries already in execution cannot be aborted. ```lua require("mysqloo") local db = mysqloo.connect("localhost", "username", "password", "database_name", 3306) function db:onConnected() -- Start a long-running query to block the queue local slowQuery = db:query("SELECT SLEEP(5)") slowQuery:start() -- Queue more queries local query1 = db:query("SELECT * FROM users") local query2 = db:query("SELECT * FROM posts") local query3 = db:query("SELECT * FROM comments") query1:start() query2:start() query3:start() -- Set up abort callback for query2 function query2:onAborted() print("Query 2 was successfully aborted") end -- Try to abort queries (only works if still waiting) local aborted1 = query1:abort() local aborted2 = query2:abort() local aborted3 = query3:abort() print("Query 1 aborted:", aborted1) -- true if still waiting print("Query 2 aborted:", aborted2) -- true if still waiting print("Query 3 aborted:", aborted3) -- true if still waiting -- Cannot abort query that's already running local abortedSlow = slowQuery:abort() print("Slow query aborted:", abortedSlow) -- false (already running) -- Abort all waiting queries in the database local abortCount = db:abortAllQueries() print("Aborted", abortCount, "queries from database queue") end db:connect() ``` -------------------------------- ### Configure Secure SSL/TLS Database Connections and Timeouts Source: https://context7.com/fredyh/mysqloo/llms.txt Configures secure connections to a remote MySQL/MariaDB server using SSL/TLS encryption. It allows specifying paths for certificate files, setting connection timeouts, and disabling auto-reconnect. Character set configuration can also be performed after a successful connection. ```lua require("mysqloo") local db = mysqloo.connect("remote-server.example.com", "username", "password", "database_name", 3306) -- Configure SSL settings before connecting -- All parameters are optional (pass nil if not needed) db:setSSLSettings( nil, -- key: path to client private key file nil, -- cert: path to client certificate file "/path/to/ca-cert.pem", -- ca: path to CA certificate file nil, -- capath: directory containing CA certificates nil -- cipher: allowed cipher suite ) -- Set connection timeouts (in seconds) db:setConnectTimeout(10) db:setReadTimeout(30) db:setWriteTimeout(30) -- Disable auto-reconnect if needed (must be before connect()) db:setAutoReconnect(false) function db:onConnected() print("Secure connection established") -- Change character set after connection local success = db:setCharacterSet("utf8mb4") if success then print("Character set changed to utf8mb4") end end function db:onConnectionFailed(err) print("Connection failed:", err) end db:connect() ```