- Documentation
- Server functions
- dbTransaction
Function
dbTransaction
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
See also
dbExecAwaitRuns a write query and waits for the database to confirm it. Inside anasynctask the server keeps running in the meantime. Returns the number of affected rows and the id of the new row.dbQuerySends a query that returns a result. Collect it withdbPollor in a callback that receives the query handle.