Skip to content

Database

The DB global is the framework-owned boundary over shiva-db. All database access in modules goes through DB — never import shiva-db exports directly. DB provides raw SQL methods and a fluent query builder via DB.table().

Server-only

DB is a server-side global. It is not available in client scripts.

The primary way to interact with the database. Returns a chainable QueryBuilder instance.

lua
local rows = DB.table('players')
    :where('online', true)
    :orderBy('name')
    :get()

See the Query Builder reference → for the full API.

Raw SELECT

lua
local rows = DB.raw(sql, params?)

Execute a raw SELECT and return all matching rows.

lua
local rows = DB.raw(
    'SELECT * FROM players WHERE job = ? AND grade >= ?',
    { 'police', 2 }
)

Execute (INSERT / UPDATE / DELETE / DDL)

lua
local result = DB.execute(sql, params?)

For INSERT, returns the new row's insert ID. For UPDATE/DELETE, returns affected row count.

lua
DB.execute('DELETE FROM logs WHERE created_at < ?', { cutoff })

Scalar

lua
local value = DB.scalar(sql, params?)

Returns a single value from the first column of the first row.

lua
local count = DB.scalar('SELECT COUNT(*) FROM players WHERE online = 1')

Transaction

lua
DB.transaction(function)

Runs all queries inside the function in a single transaction. Automatically rolls back on error.

lua
DB.transaction(function()
    DB.execute('UPDATE accounts SET balance = balance - ? WHERE id = ?', { amount, fromId })
    DB.execute('UPDATE accounts SET balance = balance + ? WHERE id = ?', { amount, toId })
end)

Ping

lua
local ok = DB.ping()  -- boolean

Tests the database connection. Returns true on success.

Configuration

Convar / Config KeyTypeDefaultDescription
database.logQueriesbooleanfalseLog every query via Log.debug
database.slowQueryThresholdinteger500Emit a Log.warn for queries exceeding this many milliseconds

API Reference

MethodReturnsDescription
DB.table(tableName)QueryBuilderCreate a fluent query builder for the table
DB.raw(sql, params?)table[]Execute a raw SELECT, return all rows
DB.execute(sql, params?)integerExecute any SQL statement
DB.scalar(sql, params?)anyReturn a single scalar value
DB.transaction(fn)anyRun queries in a transaction, auto-rollback on error
DB.ping()booleanTest the database connection

See Also

Released under the MIT License.