The built-in db module talks to SQLite, PostgreSQL and MySQL /
MariaDB through one API. Values are always sent as bound parameters, never
pasted into the SQL text, so SQL injection through values cannot happen.
// no-check
let local = db.open("sqlite:app.db") // file (created if missing)
let memory = db.open("sqlite::memory:") // in-memory, gone when closed
let pg = db.open("postgres://user:secret@localhost:5432/shop")
let my = db.open("mysql://user:secret@127.0.0.1:3306/shop")
let maria = db.open("mariadb://root@localhost/shop?socket=/run/mysqld/mysqld.sock")
print(local.driver, db.drivers) // "sqlite" ["sqlite", "postgres", "mysql"]
| URL | Driver |
|---|---|
sqlite:path/to/file.db, sqlite:///abs/path.db, sqlite::memory: |
SQLite (built into Korr, nothing to install) |
postgres://user:pass@host:port/db or postgresql://... |
PostgreSQL |
mysql://user:pass@host:port/db or mariadb://... (?socket=/path for a Unix socket) |
MySQL / MariaDB |
Keep credentials out of source code: db.open(os.env("DATABASE_URL")) together
with os.load_env().
SQLite connections enable foreign keys and wait up to 5 seconds when the file is locked.
let conn = db.open("sqlite::memory:")
conn.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL, age INT)")
// exec: INSERT / UPDATE / DELETE / DDL: returns { affected, last_id }
let r = conn.exec("INSERT INTO users (email, age) VALUES (?, ?)", ["ana@example.com", 20])
print(r.affected, r.last_id) // 1 1
// named parameters with a map
conn.exec("INSERT INTO users (email, age) VALUES (:email, :age)", { email: "budi@example.com", age: 31 })
let all = conn.query("SELECT id, email FROM users ORDER BY id") // array of maps
let adult = conn.one("SELECT * FROM users WHERE age >= ?", [21]) // first row or null
let count = conn.value("SELECT COUNT(*) FROM users") // first column of first row
print(all, adult.email, count)
| Method | Returns |
|---|---|
conn.exec(sql, params?) |
{ affected, last_id } (last_id is null on PostgreSQL; use RETURNING id with query) |
conn.query(sql, params?) |
array of maps (column to value) |
conn.one(sql, params?) |
first row as a map, or null |
conn.value(sql, params?) |
first column of the first row, or null |
conn.transaction(fn(tx)) |
the function’s result; commits on success, rolls back if it throws |
conn.close() |
closes the connection (later calls raise DatabaseError) |
conn.driver |
"sqlite", "postgres" or "mysql" |
Parameters: pass an array for ? placeholders or a map for :name
placeholders. The same placeholders work on every driver (Korr rewrites them to
$1, $2 for PostgreSQL). Placeholders inside quoted strings and comments are left
alone. Giving too many or too few values is a DatabaseError.
exec without parameters may contain several statements separated by ;
(handy for migrations).
let conn = db.open("sqlite::memory:")
conn.exec("CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INT NOT NULL)")
conn.exec("INSERT INTO accounts (balance) VALUES (100), (0)")
fn transfer(conn, from, to, amount)
return conn.transaction(fn(tx)
let balance = tx.value("SELECT balance FROM accounts WHERE id = ?", [from])
if balance < amount
throw error("insufficient funds", "PaymentError")
tx.exec("UPDATE accounts SET balance = balance - ? WHERE id = ?", [amount, from])
tx.exec("UPDATE accounts SET balance = balance + ? WHERE id = ?", [amount, to])
return true
)
transfer(conn, 1, 2, 30)
try
transfer(conn, 1, 2, 500) // rolled back, nothing changes
catch err
print(err.kind, err.message)
print(conn.query("SELECT * FROM accounts"))
Keep schema changes as numbered SQL files next to your code:
migrations/
001_users.sql
002_posts.sql
003_posts_add_published.sql
and apply them when the app starts:
// no-check
let conn = db.open(os.env("DATABASE_URL", "sqlite:{__dir__}/app.db"))
let applied = conn.migrate("{__dir__}/migrations")
if len(applied) > 0
log.info("migrations applied", { files: applied.join(", ") })
korr_migrations table (name, applied_at).migrate raises a
DatabaseError that names the file. Fix the file and start again.CREATE, ALTER and DROP immediately, so a failed
MySQL migration can be half applied; keep MySQL migrations to one schema change
per file. SQLite and PostgreSQL roll the whole file back.| Korr to database | |
|---|---|
null, bool, int, float, str |
the matching SQL value (bool is 1/0 on SQLite and MySQL) |
array, map, struct instance |
JSON text; store it in a TEXT/JSON/JSONB column |
| Database to Korr | |
|---|---|
| integers | int |
| floating point | float |
DECIMAL / NUMERIC |
str (exact; convert with float() if you accept rounding) |
BOOLEAN |
bool on PostgreSQL; int (0/1) on SQLite and MySQL, which have no real boolean type |
DATE, TIME, TIMESTAMP, DATETIME |
str such as "2026-11-28 14:30:00"; TIMESTAMPTZ becomes "2026-11-28T07:30:00Z" (use time.parse() to get milliseconds) |
JSON / JSONB |
decoded into maps/arrays |
UUID |
str |
BLOB / BYTEA |
hex str |
| everything else | str |
Every database failure raises an error of kind DatabaseError with the server’s
message:
let conn = db.open("sqlite::memory:")
try
conn.query("SELEC broken")
catch err
print(err.kind, err.message) // DatabaseError near "SELEC": syntax error ...
// no-check
const conn = db.open(os.env("DATABASE_URL", "sqlite:app.db"))
conn.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)")
let app = http.app()
app.get("/notes", fn(req) => conn.query("SELECT * FROM notes ORDER BY id DESC"))
app.post("/notes", fn(req)
let body = str(req.json?.body ?? "").trim()
if body == ""
return http.json({ error: "body is required" }, 422)
let r = conn.exec("INSERT INTO notes (body) VALUES (?)", [body])
return http.json({ id: r.last_id, body }, 201)
)
app.listen(8080)
db.open() is one connection. With server workers
every worker runs your program, so every worker opens its own connection: there
is one connection per worker and no pool is needed. SQLite waits up to 5 seconds
for a write lock held by another worker; for many concurrent writes, run
conn.exec("PRAGMA journal_mode=WAL") once after opening.--no-default-features has no database drivers
(db.drivers is []); see Compiling.postgres crate; Korr’s own tests cover
SQLite and MariaDB end-to-end. Run the PostgreSQL tests against your server with
KORR_TEST_POSTGRES=postgres://... korr test tests.| Previous: Full-stack web with Korr | Docs index | Next: CLI apps and the korr command |