Writing a database driver
A driver connects Luma’s database layer to one database engine: it speaks the engine’s protocol, and db does the rest. Drivers are not part of Luma; they are .luma files that anyone can write and share. This page is for the people who write them.
The contract: db.driver
A driver is an obj that is a db.driver, a built-in trait:
trait db.driver {
fn query(sql: str, params: [json]): [json]
fn exec(sql: str, params: [json]): db.result
fn mark(n: int): str
fn close()
}And it gives programs a function that connects, by convention connect:
import "mysql"
conn: db = db.open(mysql.connect("user:password@localhost:3306/shop"))db.open wraps the driver’s obj; programs then only use db’s methods. The driver never sees :name, transactions or conn.sql(): the layer handles those.
| Method | Gets | Gives |
|---|---|---|
query | SQL with the driver’s placeholders, and the values in order | the rows: one json object per row, with the columns by name |
exec | the same | a db.result { changed: ..., id: ... }: the rows changed, and the id an insert made (0 if none) |
mark(n) | the number of a placeholder, from 1 | how the engine writes it: "?" (MySQL, SQLite) or "$${n}" (PostgreSQL), … |
close | ends the connection |
exec also gets BEGIN, COMMIT and ROLLBACK for transactions, with no values.
Values
params holds one json for each placeholder, in order: a string, a number, true/false or null. A list a program gives for IN (:ids) arrives as separate values, one per placeholder.
A driver either sends them as the engine’s own parameters (prepared statements in MySQL, the extended protocol of PostgreSQL), which is the safest, or writes them into the SQL itself, with the engine’s quoting rules. db.quote(text) quotes the standard SQL way: 'it''s'. Engines that also treat \ specially, like MySQL, need their own quoting.
Rows
Each row is a json object. Give values their types: numbers as numbers, NULL as null, so that programs can convert the rows into their objs:
fn row(id: int, name: str, nickname: str): json {
if nickname == "" {
return {"id": id, "name": name, "nickname": null}
}
return {"id": id, "name": name, "nickname": nickname}
}
print(row(1, "Ann", ""))Output:
{"id":1,"name":"Ann","nickname":null}Errors
When the database says no (a syntax error, a missing table, a wrong password), raise it with db.fail(message): it is error 15, the database error, which programs catch with try. Start the message with the driver’s name, so that people know where it comes from: db.fail("mysql: Unknown column 'nmae'"). (Programs can’t make errors below 100 with error(...); db.fail is how a driver can.)
Errors of the connection itself, from tcp, are error 14; let them through.
A complete driver
Drivers don’t have to speak to a server. This one wraps another driver and keeps the SQL it sends, for tests or for a log; it shows each part of the contract:
// canned answers every query with the same rows
obj canned: db.driver {
rows: [json] = []
fn query(sql: str, params: [json]): [json] {
if sql.contains("nope") {
db.fail("canned: no table nope")
}
return self.rows
}
fn exec(sql: str, params: [json]): db.result {
return db.result { changed: len(params), id: 7 }
}
fn mark(n: int): str {
return "$${n}"
}
fn close() {
}
}
// logged passes everything on to another driver, and keeps the SQL
obj logged: db.driver {
inner: db.driver
lines: [str] = []
fn init(inner: db.driver) {
self.inner = inner
}
fn query(sql: str, params: [json]): [json] {
self.lines[] = "${sql} ${params}"
return self.inner.query(sql, params)
}
fn exec(sql: str, params: [json]): db.result {
self.lines[] = "${sql} ${params}"
return self.inner.exec(sql, params)
}
fn mark(n: int): str {
return self.inner.mark(n)
}
fn close() {
self.lines[] = "closed"
self.inner.close()
}
}
log: logged = logged(canned { rows: [{"id": 1}] })
conn: db = db.open(log)
conn.query("SELECT * FROM t WHERE id IN (:ids) AND name = :name", {"ids": [1, 2], "name": "Ann"})
conn.begin()
conn.exec("DELETE FROM t WHERE id = :id", {"id": 1})
conn.commit()
err: error = nil
try err {
conn.query("SELECT * FROM nope")
}
print("${err.code}: ${err.message}")
conn.close()
log.lines.walk(line) {
print(line)
}Output:
15: canned: no table nope
SELECT * FROM t WHERE id IN ($1, $2) AND name = $3 [1, 2, "Ann"]
BEGIN []
DELETE FROM t WHERE id = $1 [1]
COMMIT []
SELECT * FROM nope []
closedA driver for a server
A driver for a database server opens a tcp connection in connect, sends each statement the way the engine wants, and reads the answer. This one speaks a made-up protocol, one line of JSON each way, to show the shape:
// linedb: a driver for a made-up database that speaks JSON lines
pub obj conn: db.driver {
sock: tcp
fn query(sql: str, params: [json]): [json] {
answer: json = ask(self.sock, sql, params)
rows: [json] = []
answer["rows"].walk(row) {
rows[] = row
}
return rows
}
fn exec(sql: str, params: [json]): db.result {
answer: json = ask(self.sock, sql, params)
changed: int = convert(answer["changed"])
id: int = convert(answer["id"])
return db.result { changed: changed, id: id }
}
fn mark(n: int): str {
return "?"
}
fn close() {
self.sock.close()
}
}
// connect takes "host:port"
pub fn connect(address: str): conn {
parts: [str] = address.split(":")
port: int = convert(parts[1])
sock: tcp = tcp.connect(parts[0], port, 5)
sock.timeout(30)
return conn { sock: sock }
}
fn ask(sock: tcp, sql: str, params: [json]): json {
request: json = {"sql": sql, "params": params}
sock.write("${request}\n")
answer: json = convert(sock.line())
if has(answer, "error") {
message: str = convert(answer["error"])
db.fail("linedb: ${message}")
}
return answer
}Real protocols are binary: build and read their packets with a buffer, use crypto for the login (SHA-1, SHA-256, HMAC, PBKDF2), bitwise operators for flags, and while to read until the end of the rows.
Sharing a driver
- Name the file after the engine (
mysql.luma,postgres.luma), so thatimport "mysql"reads well. - Write down what
connecttakes (the address, user, password, database) and which types become whichjsonvalues. - Programs copy the file next to their own, or into a folder:
import "drivers/mysql". - Luma’s official drivers are in its
modsfolder;mods/mysql.lumaandmods/postgres.lumaare complete ones to learn from, with their tests beside them.mods/sqlite.lumais a database engine of its own, in the foldermods/sqlite/.