santoku
santoku

santoku

A Lua framework for building applications end to end

Lua 5.1 from the build system to the server to the browser. Every example on this site runs in your browser. Edit one and run it.


santoku targets Lua 5.1, because 5.1 is the version its platforms actually share. LuaJIT implements 5.1 and OpenResty embeds LuaJIT, so server code, client code and the build harness all run the same language. Compiled to WebAssembly, the 5.1 core is smaller to embed, and its single number type sidesteps the integer and float split introduced in 5.3, which keeps numeric values crossing the JavaScript boundary simple. Support for newer versions is meant to come from compatibility shims layered over the 5.1 core rather than version branches in the tree; contributions and design ideas for that layer are welcome.

santoku-mysql

View on LuaRocks

MySQL and MariaDB client with santoku-sqlite's API: server-side prepared statements, verified TLS, and native and OpenResty cosocket transports

santoku-mysql is a MySQL and MariaDB client with santoku-sqlite's API. The core takes a transport backend: require("santoku.mysql")(backend). Every bound query is a server-side prepared statement, cached per connection. TLS is required and verified by default.

Details
  • santoku-socket's santoku.socket.tcp is the native transport.
  • santoku-resty's santoku.resty.tcp runs over nginx cosockets, so a query never blocks a worker.
  • Lua drives the socket, and a C codec frames packets, decodes binary rows and encodes parameters.
  • Plain TCP without TLS is an explicit opt-out.
  • santoku-mysql doesn't depend on either transport. List santoku-socket, or santoku-resty 2.8.0 or newer, beside it in your dependencies.
  • The examples write password = "secret" inline. A server reads the password from the environment once, in init_by_lua, as the Secrets cards on https://santoku.dev/start-server show.

Open a handle and query

open(opts) logs in and returns a handle. getter(sql, prop) returns a function that runs the statement and returns the first row. all(sql, prop) returns every row.

local mysql = require("santoku.mysql")(require("santoku.socket.tcp"))
local db = mysql.open({
  host = "db.internal", port = 3306,
  user = "app", password = "secret", database = "app",
  tls = { cafile = "/etc/ssl/db-ca.pem" },
})
db.exec("CREATE TABLE IF NOT EXISTS notes (id INT PRIMARY KEY AUTO_INCREMENT, body TEXT)")
local add = db.inserter("INSERT INTO notes (body) VALUES (?)")
local one = db.getter("SELECT id, body FROM notes WHERE id = ?", true)
local bodies = db.all("SELECT body FROM notes ORDER BY id")
local id = add("first")
print(one(id).body, #bodies())
print(one(id + 1000))
db.close()
Illustrative: runs outside the browser.
Details
  • A failed login raises the server's message, code and sqlstate.
  • getter's prop true gives a table keyed by column name, false gives nothing, and anything else gives the columns as values.
  • When no row matches, the getter's function returns nothing, so the result tests as nil.
  • all returns each row as a named table with prop true, or as its first column otherwise.
  • runner returns the affected row count, and inserter returns the insert id.
  • exec runs SQL with no parameters through the text protocol.
  • Each getter, all, runner and inserter prepares its statement once, when you create it.
  • A connection keeps at most max_statements prepared statements, 64 by default. When it needs room, it closes the least recently used statement with COM_STMT_CLOSE.
  • So SQL built at runtime can't exhaust the server's max_prepared_stmt_count.
  • A statement the server no longer knows, error 1243, is prepared again once. That happens after a proxy switches backends, for example.
  • USE drops the cached statements, because a statement keeps the database it was prepared under.
  • A call that binds a different Lua type in a position than the last call prepares the statement again. The types are string, integer, float and boolean.
  • MySQL 8 casts a string to the type of the statement's first execution. Without the new prepare, SELECT ? run with 0.1 and then 'a' would return 0.
  • nil matches any type and prepares nothing new.
  • close() sends COM_QUIT and closes the connection.
  • A call on a closed handle raises mysql: handle closed, and a second close does nothing.

Binding parameters

Values travel in COM_STMT_EXECUTE and never enter the SQL text. ?NNN names a parameter by position, and :name takes the next position. A table as the only argument binds :name parameters by key.

local get = db.getter("SELECT ?2, ?1, ?2")
print(get("a", "b"))
local find = db.getter("SELECT id FROM users WHERE email = :email OR alias = :email")
print(find({ email = "a@example.com" }))
print(find("a@example.com"))
Illustrative: runs outside the browser.
Details
  • Repeats of ?NNN reuse its position.
  • :name reuses its position on repeats, so positional arguments fill names in order of first use.
  • Question marks and colons inside quotes, backticks and comments are left alone. := and :: aren't parameters.
  • The scanner reads the body of /*! and /*M! comments as SQL, as the server does.
  • The scanner treats a backslash as a plain character when the session runs NO_BACKSLASH_ESCAPES.
  • A value the client can't bind, such as a function, raises before anything is sent. The connection and any open transaction stay as they were.
Lua valueBinds as
integral number below 2^63BIGINT
other numberDOUBLE
boolean1 or 0
stringbinary-safe string
nilNULL

Types

Rows decode from the binary protocol straight into Lua values. NULL is nil everywhere, so a named row omits the key.

local id, total, at, body = db.getter("SELECT CAST(18446744073709551615 AS UNSIGNED), "
  .. "CAST(1.5 AS DECIMAL(10,2)), TIMESTAMP('2024-01-02 03:04:05.25'), NULL")()
print(id, total, at, body)
Illustrative: runs outside the browser.
Details
  • Integers past 2^53 lose precision. Read large ids as strings with CAST(x AS CHAR) when every digit matters.
  • Zero and invalid dates that the server allows come back as written, such as 0000-00-00.
Column typeLua value
integers of every width, signed or unsignednumber
FLOAT, DOUBLEnumber
DECIMALstring, so no digits are lost
DATEYYYY-MM-DD
DATETIME, TIMESTAMPYYYY-MM-DD hh:mm:ss plus the column's fractional digits
TIME[-]hhh:mm:ss, hours past 24 included
strings, BLOB, BIT, ENUM, SET, JSONstring with every byte kept
NULLnil

Transactions

transaction(fn, ...) runs fn between START TRANSACTION and COMMIT and returns what fn returns. If fn raises, it rolls back and raises the same error.

local move = db.runner("UPDATE accounts SET balance = balance + ? WHERE id = ?")
db.transaction(function ()
  move(-10, 1)
  move(10, 2)
end)
Illustrative: runs outside the browser.
Details
  • Inside a transaction, transaction(fn) just calls fn.
  • A string first argument passes options, as in transaction("READ ONLY", fn).
  • begin, commit and rollback give manual control.
  • begin raises mysql: a transaction is already open when one is.
  • commit and rollback raise mysql: no transaction is open when none is.
  • begin(tag) and the options string go into the SQL text as written. Pass only fixed text such as READ ONLY or WITH CONSISTENT SNAPSHOT. Never pass user input there.

TLS and unix sockets

Over TCP the client asks for TLS on every connection and verifies the server's certificate and host name. path connects through a unix socket on the same machine, where TLS is off by default.

local local_db = mysql.open({ path = "/run/mysqld/mysqld.sock", user = "app", password = "secret" })
local by_ip = mysql.open({ host = "10.0.0.5", user = "app", password = "secret",
  tls = { cafile = "/etc/ssl/db-ca.pem" } })
local legacy = mysql.open({ host = "10.0.0.6", user = "app", password = "secret", tls = false })
Illustrative: runs outside the browser.
Details
  • tls = true uses the system trust store.
  • A tls table sets cafile, capath, sslname and verify.
  • A DNS host matches the certificate's DNS names. An IP host such as 127.0.0.1 matches only its IP addresses, IP:127.0.0.1 in subjectAltName.
  • A server that offers no TLS is refused unless you pass tls = false, which sends queries in the clear.
  • caching_sha2_password works over TLS or a unix socket.
  • Over plain TCP, the full caching_sha2_password login needs opts.rsa and opts.rsa_key.
  • opts.rsa is a function that encrypts with a public key. opts.rsa_key is the server's public key, pinned by you.
  • The client never fetches the key from the server, because anyone on the path could swap it and read the password.
  • mysql_native_password works everywhere.

Under OpenResty

With santoku.resty.tcp every query yields to nginx while it waits on the network. open is lazy there and checks nothing until the first call. Each call borrows a connection from nginx's keepalive pool.

http {
  lua_ssl_trusted_certificate /etc/ssl/db-ca.pem;
  lua_ssl_verify_depth 2;
  server {
    location = /user {
      content_by_lua_block {
        local mysql = require("santoku.mysql")(require("santoku.resty.tcp"))
        local db = mysql.open({ host = "db.internal", user = "app", password = "secret",
          database = "app", tls = { sslname = "db.internal" } })
        local name = db.getter("SELECT name FROM users WHERE id = ?")(tonumber(ngx.var.arg_id))
        ngx.say(name or "")
      }
    }
  }
}
Illustrative: runs outside the browser.
Details
  • santoku-mysql pools whenever the transport exports semaphore(n), as santoku.resty.tcp does. Since santoku-mysql 0.4.0 no other flag turns pooling on.
  • Since santoku-socket 6.0.0, santoku.socket.tcp pools the same way on the native loop: its connect honours the pool name, keepalive parks the connection, and semaphore(n) comes from santoku.system.async. A transaction keeps one connection for its task.
  • Each call returns its connection to the pool afterwards.
  • A reused connection runs COM_RESET_CONNECTION, SET NAMES and init_sql first. So no call sees another call's user variables, temporary tables, locks or prepared statements.
  • Statements prepare again on each call.
WorkloadExtra time per call from the reset
one call on loopbackabout 0.13 ms
  • A connection whose call ran USE closes instead of going back to the pool, since the reset keeps the database.
  • Leave autocommit on. A call that leaves a transaction open outside begin is rolled back and raises.
  • pool_size: up to this many connections open per worker for each set of options. The default is 16.
  • timeout_ms: a call past pool_size waits this long for a connection to come free, then raises "no pooled connection came free". The default is 30000.
  • pool_idle_ms: the keepalive timeout. The default is 60000.
  • A transaction keeps one connection for its light thread until it ends.
  • A network error, or a Lua error raised while a result is still arriving, closes the connection it hit.
  • iter reads its whole result before it returns, because a pooled connection can't stay mid-result.
  • Certificates verify against lua_ssl_trusted_certificate in nginx.conf, and a cafile option raises.

Errors and lost connections

A server error raises the message, the MySQL error code and the sqlstate, and the connection stays usable. A network error, a packet out of sequence or a reply past 1 GiB drops the connection.

local err = require("santoku.error")
local ok, msg, code, state = err.pcall(db.exec, "SELEC 1")
print(ok, code, state)
Illustrative: runs outside the browser.
Details
  • Those connection errors raise a message that starts with mysql:.
  • Natively the next call reconnects. It also reconnects when the server closed an idle connection, as after KILL or wait_timeout.
  • Inside a transaction the client never reconnects. The failing call raises, and so do commit and rollback, with mysql: connection lost inside a transaction.

Differences from santoku-sqlite

open takes connection settings in place of santoku-sqlite's file path. Every connection runs SET NAMES utf8mb4 and then init_sql, so text arrives as UTF-8 whatever the server or column charset.

local rows, names = db.query("SHOW SESSION STATUS LIKE 'Com_stmt_prepare'")
print(names[1], rows[1][2], db.info().version, db.ping())
Illustrative: runs outside the browser.
Details
  • latin1 columns convert on the server.
  • The client asks for session tracking, CLIENT_SESSION_TRACK, so it sees USE and sql_mode changes as they happen.
  • Natively, getter, all, iter, runner and inserter prepare when you create them, as in santoku-sqlite. Under OpenResty they prepare on their first call.
  • query(sql, ...) prepares, runs and closes a statement once. It returns the rows as arrays plus the column names, as santoku-sqlite's query does.
  • changes() returns the row count of the last write and keeps it across reads, as in santoku-sqlite.
  • info() and ping() are extra. info() returns the connection id, server version, current database and whether TLS is on. ping() checks the connection.
  • santoku-sqlite's db, authorizer and progress have no MySQL counterpart and don't exist here.