Databases: db

db is Luma’s database layer: one way to send SQL and get rows back, whatever the database is. It is built in; no import is needed.

The part that speaks to a database engine, its driver, is not part of Luma: each driver is a .luma file, which you put next to your program and import. The official ones are in Luma’s mods folder (SQLite, MySQL and MariaDB, PostgreSQL), and anyone can write one (see Writing a database driver).

import "demo"     // a driver: mysql, postgres, ... (this page uses a stand-in, see the end)

conn: db = db.open(demo.connect("shop"))
rows: json = conn.query("SELECT id, name FROM users WHERE age > :min", {"min": 21})
rows.walk(row) {
    print("${row["id"]}: ${row["name"]}")
}
conn.close()

Output:

1: Ann
2: Bo

Connecting

A driver gives a connection to its database: mysql.connect("user:password@localhost:3306/shop"), postgres.connect(...), whatever that driver asks for. db.open takes it and gives a db, which has the same methods for every database:

MethodDoes
conn.query(sql, values)runs a query and gives its rows (a json array)
conn.exec(sql, values)runs a statement that changes something and gives how many rows it changed
conn.inserted()the id the last exec made, for a table with an automatic id (0 if none)
conn.begin(), conn.commit(), conn.rollback()a transaction
conn.active()true while a transaction is open
conn.sql()the last SQL, with the values written in: for reading, when something doesn’t work
conn.close()ends the connection

values can be left out when the SQL has none.

Values: :name

Don’t paste values into the SQL text. Write :name where a value goes, and give the values in a json object:

import "demo"

conn: db = db.open(demo.connect("shop"))
name: str = "O'Hara"
conn.query("SELECT * FROM users WHERE name = :name AND age >= :age", {"name": name, "age": 18})
print(conn.sql())

Output:

SELECT * FROM users WHERE name = 'O''Hara' AND age >= 18

The driver gets the SQL with its own placeholders (? or $1) and the values separately, so a value can never change what the SQL does: the quote in O'Hara is just a letter of the name. This is what keeps a program safe from SQL injection. Don’t build SQL with ${...} from what users type.

  • A value can be a str, a number, a bool, null (SQL’s NULL), or a list.
  • A list gives one value for each element, for IN: WHERE id IN (:ids) with {"ids": [1, 2, 3]} is IN (1, 2, 3). An empty list is an error, because SQL has no IN ().
  • :name inside quotes (':name') and comments (-- :name) is left as it is, and so is :: (a cast in PostgreSQL: price::int).
  • Each :name needs a value, and each value must be used: a typo is an error, not a silent NULL.
import "demo"

conn: db = db.open(demo.connect("shop"))
conn.query("SELECT name FROM users WHERE id IN (:ids) AND role <> 'guest:x'", {"ids": [3, 5, 8]})
print(conn.sql())

Output:

SELECT name FROM users WHERE id IN (3, 5, 8) AND role <> 'guest:x'

Rows

query gives the rows as a json array: each row is an object, with the columns by name. Its values have their types (numbers, strings, true/false, and null for NULL):

import "demo"

conn: db = db.open(demo.connect("shop"))
rows: json = conn.query("SELECT id, name, age FROM users")
print(len(rows))
first: json = rows[0]
age: int = convert(first["age"])
print("${first["name"]} is ${age}")
print(rows[1]["age"].kind())

Output:

2
Ann is 30
null

The easiest way to work with rows is to convert them into a list of your own obj type. Each column goes into the field of the same name. Columns the obj doesn’t have are left out, and a column that is missing or NULL keeps the field’s default, so give a column that can be NULL a default (age: int = 0):

import "demo"

obj User {
    id: int
    name: str
    age: int = 0
}

conn: db = db.open(demo.connect("shop"))
users: [User] = convert(conn.query("SELECT id, name, age FROM users"))
users.walk(u) {
    print("${u.id}: ${u.name} (${u.age})")
}

Output:

1: Ann (30)
2: Bo (0)

Changing data

exec runs INSERT, UPDATE, DELETE, CREATE TABLE and other statements that give no rows. It gives the number of rows changed, and inserted() the id an INSERT made:

import "demo"

conn: db = db.open(demo.connect("shop"))
conn.exec("INSERT INTO users (name, age) VALUES (:name, :age)", {"name": "Cid", "age": 41})
print("new user ${conn.inserted()}")
changed: int = conn.exec("UPDATE users SET age = age + 1 WHERE age < :age", {"age": 40})
print("${changed} rows changed")

Output:

new user 3
2 rows changed

Transactions

A transaction makes several changes count as one: either all of them happen (commit) or none (rollback). Use try, so that an error rolls back:

import "demo"

conn: db = db.open(demo.connect("shop"))
err: error = nil
conn.begin()
try err {
    conn.exec("UPDATE accounts SET balance = balance - :n WHERE id = :from", {"n": 50, "from": 1})
    conn.exec("UPDATE accounts SET balance = balance + :n WHERE id = :to", {"n": 50, "to": 2})
    conn.commit()
}
if err != nil {
    conn.rollback()
    print("transfer failed: ${err.message}")
}
print(conn.active())

Output:

false

db knows whether a transaction is open: commit() or rollback() without one, and begin() inside one, are errors right away, instead of a puzzling message from the database. The layer sends BEGIN, COMMIT and ROLLBACK, which almost all databases understand.

Errors

Database errors are error 15. They are raised at the line of your program that called db, and try catches them:

MessageWhen
no value for :min: give it with the SQL, e.g. {"min": ...}a :name without a value
the value "mni" isn't used: the SQL has no :mnia value no :name asks for
the list for :ids is empty, and SQL can't have IN ()an empty list
no transaction is open to commit: begin() starts onecommit or rollback without begin
a transaction is already open: commit() or rollback() it firstbegin twice
the database connection is closedusing a connection after close
the driver’s own messagethe database said no: a syntax error, a duplicate key, a wrong password, …

Network problems on the way to the database are error 14, as for every connection.

Details

  • A db is shared like an object: it can be passed to functions and kept in fields. It prints as just db, so that a driver’s password never ends up in a log.
  • query reads all the rows of a query into memory. For very large tables, ask for parts with LIMIT and OFFSET.
  • One db is one connection, used one statement at a time, like everything in Luma.

Not available yet

  • Pools of connections, and reading rows one at a time while they arrive.
  • Types for dates and binary data in values: give them as text ("2024-12-25") or numbers.
  • Official drivers for other engines than SQLite, MySQL, MariaDB and PostgreSQL.

SQLite

mods/sqlite.luma and the folder mods/sqlite/ are SQLite in Luma: the SQL and the file format of SQLite 3, read and written by Luma itself, with no other program or library. Copy both next to your program:

import "sqlite"

conn: db = db.open(sqlite.connect("app.db"))
conn.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT NOT NULL)")
conn.exec("INSERT INTO notes (text) VALUES (:t)", {"t": "Buy milk"})

connect takes a file’s path, made if it isn’t there, or ":memory:" for a database that lives only while the program runs. ?timeout=10 says how many seconds to wait while another program writes (5 if not given).

  • The files are SQLite’s: the sqlite3 program, DB Browser for SQLite and every app that uses SQLite read and write them, also at the same time as a Luma program (with SQLite’s locks), and so can several connections in one program. A commit goes through SQLite’s rollback journal, so a crash or a power cut never leaves a broken file: the next program that opens it, Luma or SQLite, rolls the unfinished commit back.
  • WAL mode: PRAGMA journal_mode = wal (once; the database stays in it) makes commits go to a log beside the database, app.db-wal, as SQLite’s do: readers don’t wait for a writer, and each reads the database as it was when its transaction began, while one connection at a time writes. Databases that other apps keep in WAL mode work the same. A checkpoint copies the log into the database: after a commit that leaves 1000 pages in the log (PRAGMA wal_autocheckpoint = N changes that, 0 turns it off), with PRAGMA wal_checkpoint (or (FULL), (RESTART), (TRUNCATE), which wait for the others as SQLite’s do), and when the last connection closes, which also deletes the log and its index (app.db-shm). After a crash, the next program reads the log again up to its last whole commit. PRAGMA journal_mode = delete goes back, when no other connection has the database open. PRAGMA synchronous is FULL (2) unless set to NORMAL (1), which syncs the log only at checkpoints, as in SQLite: faster, and a power cut may lose the last commits but never breaks the file.
  • The SQL: CREATE and DROP of tables, indexes (also on expressions, and partial indexes with WHERE), views and triggers (INTEGER PRIMARY KEY, also with AUTOINCREMENT, whose ids are never used twice, kept in SQLite’s sqlite_sequence table, PRIMARY KEY, UNIQUE, NOT NULL, CHECK, DEFAULT, COLLATE NOCASE, REFERENCES), INSERT (also OR REPLACE, OR IGNORE, from a SELECT, and upserts: ON CONFLICT (...) DO UPDATE SET ... = excluded.col or DO NOTHING), UPDATE (also UPDATE ... FROM), DELETE, RETURNING on all three, and SELECT with joins (JOIN, LEFT, RIGHT and FULL JOIN, USING, NATURAL), window functions (OVER, PARTITION BY, frames with ROWS, RANGE and GROUPS, EXCLUDE, WINDOW, FILTER), WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, OFFSET, DISTINCT, UNION, UNION ALL, INTERSECT, EXCEPT, VALUES, WITH (also WITH RECURSIVE) and subqueries, also ones that use the outer query’s columns; transactions with BEGIN, COMMIT and ROLLBACK.
  • Changing tables: ALTER TABLE with RENAME TO, RENAME COLUMN, ADD COLUMN and DROP COLUMN, which rewrite the schema as SQLite does (also the indexes and views that name the table or column), so sqlite3 reads it the same.
  • Triggers: BEFORE, AFTER and INSTEAD OF (which lets a view take INSERT, UPDATE and DELETE), on INSERT, UPDATE [OF columns] and DELETE, with WHEN, NEW and OLD, and RAISE(IGNORE), RAISE(ABORT, ...), RAISE(FAIL, ...) and RAISE(ROLLBACK, ...); they fire in SQLite’s order, and not inside themselves (unless PRAGMA recursive_triggers = ON).
  • Foreign keys, once PRAGMA foreign_keys = ON (as in SQLite, they are off until then): a child row needs its parent; deleting or changing a parent does ON DELETE and ON UPDATE’s CASCADE, SET NULL, SET DEFAULT, RESTRICT or NO ACTION; DEFERRABLE INITIALLY DEFERRED keys are checked at COMMIT.
  • JSON: json, json_extract and the operators -> and ->>, json_set, json_insert, json_replace, json_remove, json_patch, json_array, json_object, json_type, json_valid, json_quote, json_array_length, json_error_position, the aggregates json_group_array and json_group_object, and the tables json_each and json_tree (FROM orders, json_each(orders.items)). JSON5 is read too; the text written is SQLite’s, to the byte.
  • Functions: SQLite’s, among them date, time, datetime, julianday, unixepoch, strftime, timediff with all of SQLite’s modifiers ('+3 days', 'start of month', 'weekday 0', 'localtime', 'utc', …), CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP; printf and format with SQLite’s own formats (%q, %Q, %w, %!, …); concat, concat_ws, iif, coalesce, substr, replace, instr, round, hex, quote and the aggregates count, sum, total, avg, min, max, group_concat. 'now' is the same moment for all of a statement; 'localtime' and 'utc' use the computer’s time zone, as Luma’s dates do.
  • PRAGMA: table_info, index_list, index_info, foreign_key_list, foreign_key_check, user_version (also set, for migrations), foreign_keys, recursive_triggers, journal_mode (delete and wal), wal_checkpoint, wal_autocheckpoint, synchronous, integrity_check; others are ignored, as SQLite ignores the ones it doesn’t know.
  • Values and rows follow SQLite’s rules: types per value, column affinity, comparisons, NULL, integer overflow becoming a real, the text of reals. Rows give INTEGER and REAL as numbers, TEXT as a str, a BLOB as a str of its bytes, NULL as null. inserted() is the rowid of the last INSERT.
  • Indexes are used to find rows by rowid (or INTEGER PRIMARY KEY), by an index’s leading columns, and for ranges of rowids; joins look up the inner table the same way.
  • Errors say what SQLite says: sqlite: UNIQUE constraint failed: users.email, sqlite: near "SELEC": syntax error.
  • Not yet: the journal modes truncate, persist, memory and off, WAL databases on read-only files, the binary JSON of the jsonb_* functions, generated columns, WITHOUT ROWID tables, virtual tables such as full-text search, ATTACH, SAVEPOINT and VACUUM.

MySQL and MariaDB

mods/mysql.luma is the official driver for MySQL and MariaDB, written in Luma. Copy it next to your program:

import "mysql"

conn: db = db.open(mysql.connect("shop:secret@db.example.com:3306/shop?tls=true"))

connect takes user:password@host:port/database, with options after ?:

Part
host:portlocalhost and 3306 when left out: "shop:secret@/shop"
passwordcan hold @ and :
?tls=trueencrypted, the server’s certificate checked as for https
?tls=insecureencrypted, the certificate not checked
?ca=file.pemencrypted, trusting that authority too
?timeout=10seconds to connect and to wait for each answer (to connect: 10 if not given; for answers: as long as it takes)
  • Logins: mysql_native_password, caching_sha2_password (MySQL 8’s) and sha256_password. With caching_sha2_password, the server wants the password itself the first time a user logs in after it started, and with sha256_password always: that needs tls=true.
  • Values go as the server’s own (prepared statements): they never become a part of the SQL. A connection keeps up to 64 prepared statements. SQL without values goes as text.
  • Rows: integers, FLOAT and DOUBLE are numbers; NULL is null; DECIMAL is a str, so no digit is lost; DATE, DATETIME, TIMESTAMP and TIME are str like "2024-12-25 14:30:00"; text, BLOB, JSON, ENUM and SET are str; BIT is a number.
  • Errors say the server’s number: mysql: 1146 Table 'shop.nope' doesn't exist.
  • A stored procedure’s CALL gives its first result’s rows.
  • Not yet: MariaDB’s ed25519 login and LOAD DATA LOCAL.

PostgreSQL

mods/postgres.luma is the official driver for PostgreSQL, written in Luma. Copy it next to your program:

import "postgres"

conn: db = db.open(postgres.connect("shop:secret@db.example.com:5432/shop?tls=true"))

connect takes the same form as MySQL’s, user:password@host:port/database?options, with the same options (tls, ca, timeout). The host is localhost, the port 5432 and the database the user’s name when left out. A postgres://... URL works too; in it, %40 and the like are decoded.

  • Logins: SCRAM-SHA-256 (PostgreSQL’s default), md5, and the password itself (only with tls=true).
  • Statements: one at a time, its values apart from the SQL; the server reads them as the types the SQL needs, so write a cast where it can’t tell (:n::int + 1). A connection keeps up to 64 statements prepared; one whose table changed since is prepared again (in a transaction, the error ends the transaction, as PostgreSQL does).
  • Rows: integers, real and double precision are numbers (NaN and Infinity a str); boolean is true or false; json and jsonb are json, so row["data"]["name"] works; numeric is a str, so no digit is lost; dates and times are str like "2024-12-25 14:30:00"; bytea is a str of its bytes; arrays, uuid and the rest are str as PostgreSQL writes them ("{1,2,3}").
  • Ids: PostgreSQL has no “last id”; with RETURNING, inserted() gives the first column of the first row: conn.exec("INSERT INTO users (name) VALUES (:name) RETURNING id", {"name": "Ann"}).
  • Errors say PostgreSQL’s code: postgres: 42P01 relation "nope" does not exist.
  • Not yet: COPY, LISTEN/NOTIFY, cancelling a running query, SCRAM with channel binding.

The driver used on this page

The examples above use demo.luma, a stand-in that answers every query with the same two users and counts the changes. It is a complete driver, a small version of what Writing a database driver explains:

File demo.luma:

pub obj conn: db.driver {
    next_id: int = 2

    fn query(sql: str, params: [json]): [json] {
        rows: json = convert("[{\"id\": 1, \"name\": \"Ann\", \"age\": 30}, {\"id\": 2, \"name\": \"Bo\", \"age\": null}]")
        out: [json] = []
        rows.walk(row) {
            out[] = row
        }
        return out
    }

    fn exec(sql: str, params: [json]): db.result {
        if sql.starts("INSERT") {
            self.next_id = self.next_id + 1
            return db.result { changed: 1, id: self.next_id }
        }
        if sql.starts("UPDATE") {
            return db.result { changed: 2 }
        }
        return db.result {}
    }

    fn mark(n: int): str {
        return "?"
    }

    fn close() {
    }
}

pub fn connect(name: str): conn {
    return conn {}
}