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: BoConnecting
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:
| Method | Does |
|---|---|
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 >= 18The 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, abool,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]}isIN (1, 2, 3). An empty list is an error, because SQL has noIN (). :nameinside quotes (':name') and comments (-- :name) is left as it is, and so is::(a cast in PostgreSQL:price::int).- Each
:nameneeds a value, and each value must be used: a typo is an error, not a silentNULL.
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
nullThe 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 changedTransactions
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:
falsedb 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:
| Message | When |
|---|---|
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 :mni | a 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 one | commit or rollback without begin |
a transaction is already open: commit() or rollback() it first | begin twice |
the database connection is closed | using a connection after close |
| the driver’s own message | the 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
dbis shared like an object: it can be passed to functions and kept in fields. It prints as justdb, so that a driver’s password never ends up in a log. queryreads all the rows of a query into memory. For very large tables, ask for parts withLIMITandOFFSET.- One
dbis 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
sqlite3program, 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 = Nchanges that, 0 turns it off), withPRAGMA 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 = deletegoes back, when no other connection has the database open.PRAGMA synchronousisFULL(2) unless set toNORMAL(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:
CREATEandDROPof tables, indexes (also on expressions, and partial indexes withWHERE), views and triggers (INTEGER PRIMARY KEY, also withAUTOINCREMENT, whose ids are never used twice, kept in SQLite’ssqlite_sequencetable,PRIMARY KEY,UNIQUE,NOT NULL,CHECK,DEFAULT,COLLATE NOCASE,REFERENCES),INSERT(alsoOR REPLACE,OR IGNORE, from aSELECT, and upserts:ON CONFLICT (...) DO UPDATE SET ... = excluded.colorDO NOTHING),UPDATE(alsoUPDATE ... FROM),DELETE,RETURNINGon all three, andSELECTwith joins (JOIN,LEFT,RIGHTandFULL JOIN,USING,NATURAL), window functions (OVER,PARTITION BY, frames withROWS,RANGEandGROUPS,EXCLUDE,WINDOW,FILTER),WHERE,GROUP BY,HAVING,ORDER BY,LIMIT,OFFSET,DISTINCT,UNION,UNION ALL,INTERSECT,EXCEPT,VALUES,WITH(alsoWITH RECURSIVE) and subqueries, also ones that use the outer query’s columns; transactions withBEGIN,COMMITandROLLBACK. - Changing tables:
ALTER TABLEwithRENAME TO,RENAME COLUMN,ADD COLUMNandDROP COLUMN, which rewrite the schema as SQLite does (also the indexes and views that name the table or column), sosqlite3reads it the same. - Triggers:
BEFORE,AFTERandINSTEAD OF(which lets a view takeINSERT,UPDATEandDELETE), onINSERT,UPDATE [OF columns]andDELETE, withWHEN,NEWandOLD, andRAISE(IGNORE),RAISE(ABORT, ...),RAISE(FAIL, ...)andRAISE(ROLLBACK, ...); they fire in SQLite’s order, and not inside themselves (unlessPRAGMA 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 doesON DELETEandON UPDATE’sCASCADE,SET NULL,SET DEFAULT,RESTRICTorNO ACTION;DEFERRABLE INITIALLY DEFERREDkeys are checked atCOMMIT. - JSON:
json,json_extractand 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 aggregatesjson_group_arrayandjson_group_object, and the tablesjson_eachandjson_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,timediffwith all of SQLite’s modifiers ('+3 days','start of month','weekday 0','localtime','utc', …),CURRENT_DATE,CURRENT_TIMEandCURRENT_TIMESTAMP;printfandformatwith SQLite’s own formats (%q,%Q,%w,%!, …);concat,concat_ws,iif,coalesce,substr,replace,instr,round,hex,quoteand the aggregatescount,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(deleteandwal),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 astr, a BLOB as astrof its bytes, NULL asnull.inserted()is the rowid of the lastINSERT. - 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,memoryandoff, WAL databases on read-only files, the binary JSON of thejsonb_*functions, generated columns,WITHOUT ROWIDtables, virtual tables such as full-text search,ATTACH,SAVEPOINTandVACUUM.
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:port | localhost and 3306 when left out: "shop:secret@/shop" |
| password | can hold @ and : |
?tls=true | encrypted, the server’s certificate checked as for https |
?tls=insecure | encrypted, the certificate not checked |
?ca=file.pem | encrypted, trusting that authority too |
?timeout=10 | seconds 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) andsha256_password. Withcaching_sha2_password, the server wants the password itself the first time a user logs in after it started, and withsha256_passwordalways: that needstls=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,
FLOATandDOUBLEare numbers;NULLisnull;DECIMALis astr, so no digit is lost;DATE,DATETIME,TIMESTAMPandTIMEarestrlike"2024-12-25 14:30:00"; text,BLOB,JSON,ENUMandSETarestr;BITis a number. - Errors say the server’s number:
mysql: 1146 Table 'shop.nope' doesn't exist. - A stored procedure’s
CALLgives its first result’s rows. - Not yet: MariaDB’s
ed25519login andLOAD 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,
realanddouble precisionare numbers (NaNandInfinityastr);booleanistrueorfalse;jsonandjsonbarejson, sorow["data"]["name"]works;numericis astr, so no digit is lost; dates and times arestrlike"2024-12-25 14:30:00";byteais astrof its bytes; arrays,uuidand the rest arestras 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 {}
}