Documentation
¶
Overview ¶
Package lua exposes hex/db to Lua scripts via a gopher-lua module named "db".
The module is installed by hex/db/provider whenever a shared *hex/lua.Environment is bound in the container (i.e. hex/lua/provider is also registered). No separate bridge provider is needed — the DB provider owns both the *sql.DB binding and the Lua module registration.
Consumer scripts (including the REPL) can then:
local db = require("db")
-- Many rows:
local rows, err = db.query("SELECT id, name FROM users WHERE active = ?", true)
for _, row in ipairs(rows) do
print(row.id, row.name)
end
-- Single row (returns nil, nil when no rows match):
local u, err = db.queryOne("SELECT * FROM users WHERE id = ?", 1)
if u ~= nil then print(u.email) end
-- Writes:
local result, err = db.exec(
"UPDATE users SET name = ? WHERE id = ?", "Alice", 1)
print(result.rows_affected, result.last_insert_id)
-- Transactions — the callback receives a `tx` table with the
-- same shape (query, queryOne, exec). On error inside the
-- callback the tx rolls back; otherwise it commits.
local ok, err = db.transaction(function(tx)
tx.exec("INSERT INTO widgets (name) VALUES (?)", "sprocket")
tx.exec("UPDATE counters SET n = n + 1 WHERE k = 'widgets'")
end)
Errors always return (nil, "message") — check `err` before using the first return value.
Concurrency:
*sql.DB is safe for concurrent use, but *lua.LState is not. When multiple goroutines share an LState (event handlers, web request handlers), pass Bindings.Mutex to serialise access. For REPL / one-off scripts the default nil mutex is fine.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var TypeStub string
TypeStub is the Teal .d.tl source describing the `db` module's shape. hex/db/provider passes it to *hex/lua.Environment.SetType so Teal-mode REPL sessions and .tl scripts can require("db") without type errors.
Functions ¶
This section is empty.
Types ¶
type Bindings ¶
type Bindings struct {
// DB is the *sql.DB the module executes against. Required.
DB *sql.DB
// Mutex, when non-nil, is locked around every DB call. Use this
// when multiple goroutines call require("db") functions against
// the same *lua.LState. Nil is fine for the REPL and other
// single-threaded contexts.
Mutex *sync.Mutex
// Context, when non-nil, is used for every DB call. Defaults to
// context.Background().
Context context.Context
}
Bindings configures the 'db' module. Constructed and installed by hex/db/lua/provider; callers wiring the module manually build one directly and call Loader.