ServersYour serverFor creatorsForumFAQDocumentationSecurity
Download the launcher
  1. Documentation
  2. Server functions
  3. dbTransaction

Function

dbTransaction

ServerDatabaseTrilogy Hub only

Runs several queries as one transaction. The function receives a tx object with the tx:query, tx:queryOne and tx:exec methods. An SQL error, error() or return false inside the function rolls back every change.

Syntax

bool, mixed dbTransaction(element connection, function fn)

Arguments

connectionelement
A connection from dbConnect.
fnfunction
The fn(tx) function with the transaction queries.

Returns

true and the values returned by the function; false and a message after a rollback.

Example

async(function()
    local ok, err = dbTransaction(db, function(tx)
        local row = tx:queryOne("SELECT money FROM players WHERE id = ?", 1)
        if not row or row.money < 500 then return false end
        tx:exec("UPDATE players SET money = money - 500 WHERE id = ?", 1)
        tx:exec("UPDATE players SET money = money + 500 WHERE id = ?", 2)
    end)
    print(ok, err)
end)

Notes

Inside an async task the server keeps running meanwhile; outside one it waits like dbPoll(..., -1). Other queries on the same connection wait until the transaction ends. With SQLite the function cannot wait (await, sleep).

See also