Skip to content

nss_libs - Database ​

This is a library for executing database queries.

Example ​

server.lua ​

lua
-- Getting the API
---@type NssLibsDatabase
DB = exports.nss_libs:getDatabase()

local query = 'SELECT * FROM users WHERE id = @id' -- @id is the placeholder for the parameter id.

local params = {
  id = 1
}

local on_result = function(result) 
  print('Async Result', table.unpack(result))
end

DB:asyncQuery(query, params, on_result) 
lua
-- Getting the API
---@type NssLibsDatabase
DB = exports.nss_libs:getDatabase()

local query = 'SELECT * FROM users WHERE id = @id' -- @id is the placeholder for the parameter id.

local params = {
  id = 1
}

local result = DB:query(query, params) 

print('Sync result', table.unpack(result))
lua
-- Getting the API
---@type NssLibsDatabase
DB = exports.nss_libs:getDatabase()

local query = 'SELECT * FROM users'

local result = DB:query(query) 

print('Sync result without parameters', table.unpack(result))

Methods ​

exports.nss_libs:getDatabase() ​

Returns NssLibsDatabase — the database API.


NssLibsDatabase ​

query(query, params) ​

Executes a synchronous SQL query. Blocks the thread until the result is received.

ParamTypeDefaultDescription
querystring—The SQL query string. Use @param_name as placeholders
paramstable?—The parameters for the query

Returns any | NssLibsDatabaseInsertResult — the query result.


asyncQuery(query, params, on_result) ​

Executes an asynchronous SQL query. Does not block the thread.

ParamTypeDefaultDescription
querystring—The SQL query string. Use @param_name as placeholders
paramstable?—The parameters for the query
on_resultfunction—The callback function that receives the result

Returns void — nothing.


isStarted() ​

Checks if the database resource is started. The result is cached after the first true.

Returns boolean — true if the database resource is started, otherwise false.

lua
if DB:isStarted() then
    print('Database is ready')
end

onConnected(cb) ​

Registers a callback that is called once the database is available. If the database is already started, the callback is called immediately.

WARNING

Always use this method for queries that run at resource startup to ensure the database is ready.

ParamTypeDefaultDescription
cbfunction—The callback function

Returns self — for chaining.

lua
DB:onConnected(function()
    local result = DB:query('SELECT * FROM users')
    print('Users loaded', #result)
end)

Things to know ​

Supported database wrappers

Wrappers are auto-detected by priority: oxmysql > ghmattimysql

No wrapper found

If no database wrapper is found, a mock wrapper is used that returns empty results and throws an error.

Query error handling

Query errors trigger the internal OnQueryError event which prints a stack trace.

NIGHTSHIFT STUDIO Documentation