-- Lua-side of the sqlite module. -- The connection methods execute/query/queryOne/lastInsertRowid/changes/close -- are provided by Rust. This file adds the transaction helpers on top of the -- same connection so users can write con:transaction(fn), con:begin(), etc. -- -- Rust passes in `Connection`: the shared method table that every connection's -- metatable indexes into (mlua hides the metatable itself from Lua). return function(Connection) --- Begin a transaction. function Connection:begin() self:execute("BEGIN") end --- Commit the current transaction. function Connection:commit() self:execute("COMMIT") end --- Roll back the current transaction. function Connection:rollback() self:execute("ROLLBACK") end --- Run `fn` inside a transaction: commit on success, roll back and re-raise --- on error. The original error is re-raised unchanged (level 0), and fn's --- return values are passed through on success. function Connection:transaction(fn) if type(fn) ~= "function" then error("sqlite: transaction requires a function argument (got " .. type(fn) .. ")", 2) end self:begin() local results = table.pack(pcall(fn)) if results[1] then self:commit() return table.unpack(results, 2, results.n) end -- On failure, roll back but never let a rollback error mask the original -- one (the connection may already be closed, or no transaction active). pcall(self.rollback, self) error(results[2], 0) end end