The platform · the database
One database, and the types you say
An app has one database: Postgres, or SQLite inside the server's own process. Db runs statements and decodes rows into the record type you annotate. Transactions keep one connection for a call; migrations run once each as the server starts. Actors' state and the jobs queue live there too.
Postgres or SQLite#
The program picks the database, and the app's SQL is written for it: nothing is translated.
Sqlite(path), the default (data/app.dbwhen the program names none), is a file inside the server's process, atpathfrom where the server starts, made with its directory when missing. There is nothing to set up. It suits an app on one server, which is what the platform runs; every example app with a database uses it.Postgresis found at--database-url(orDATABASE_URL). Without one there is no database, and an app with tables doesn't start (below). Choose it for data other programs share, or more than one server's disk holds.Turso(path)is SQLite's SQL on another engine, whose transactions can write at the same time (below).
program = App.program({
init!: |_started| Ok({}),
database: Sqlite("data/plate.db"),
})--database-url sqlite:/var/lib/plate.db moves a SQLite app's file (onto a volume, or to a test's own). A URL for the other kind of database stops the server at start, naming the one the app wants.
A package names the databases it works with in its plugin's needs: Database (either), Postgres or Sqlite; a mismatch stops the app at start. A package with SQL for both asks Db.backend! which to run, and lists a migration for each ({ name: "0001_jobs", sql: lite, on: Sqlite }), as the jobs plugin does.
A query#
Db.all! runs a statement with its parameters and returns its rows, of the type the annotation says. From the platform's test app:
("GET", "/notes") => {
found : Try(List({ id : I64, body : Str, note : Db.Nullable(Str) }), [DbErr(Str), BadRow(Str)])
found = Db.all!("select id, body, note from notes order by id", [])
match found {
Ok(notes) => text(200, Str.join_with(notes.map(|each| "${each.id.to_str()} ${each.body} ${noted(each.note)}"), "\n"))
Err(DbErr(why)) => text(500, why)
Err(BadRow(why)) => text(500, why)
}
}Db.one! reads one row. It is NotFound when there is none (an endpoint answers 404), and the first in the statement's order when there are several, so say which you mean (order by … limit 1). From the tasks example:
## The list `id` (as its URL has it): its name.
list! : Str => Try({ id : Str, name : Str }, Problem)
list! = |id| {
key = number(id)?
row : { name : Str }
row = Db.one!("select name from lists where id = $1", [Int(key)])?
Ok({ id, name: row.name })
}Parameters are $1, $2… on both databases, each a Db.Value: Null, Text, Int or Bool. Postgres receives text and reads it as the type its place wants ($1 in where id = $1 becomes a bigint). SQLite receives each as it is (a Bool as 1 or 0), and a number column accepts numeric text. Never build a statement from strings: pass values as parameters.
On Postgres, Db.array passes a list as one parameter, in Postgres's text form for arrays ({"work","to do",NULL}), read as the array of text or numbers its place wants: = any($1), @> $1, $1::bigint[], unnest($1::text[]) (alone, unnest($1) needs the cast). Each text is quoted, so a comma, a brace or the word NULL inside stays text. SQLite has no arrays: pass JSON text and read it with json_each (where tag in (select value from json_each($1))).
tagged : Try(List({ id : I64 }), [DbErr(Str), BadRow(Str)])
tagged = Db.all!("select id from notes where tags @> $1", [Db.array(tags.map(|tag| Text(tag)))])
Db.run!("delete from notes where id = any($1)", [Db.array(ids.map(|id| Int(id)))])Rows, as records#
The host hands Roc the rows as JSON, each column as the database typed it. Db.all! and Db.one! decode each row into the record you annotated, matching fields to columns by name. A row that doesn't fit is BadRow, saying why.
- Nulls are typed. Read a column that may be null as
Db.Nullable(a):NullorSome(a). A null where the record reads a plain value isBadRow, naming the column. - From Postgres: booleans, integers, floats, text,
jsonandjsonb,uuid, and timestamps and dates (as text). Other types need a cast (::text). - From SQLite: values as they are (an integer or a real as a number, text as a string), a column declared
booleanas aBool, one declaredjsonas its JSON. A boolean computed in a statement (exists (…)) is 0 or 1, anI64. SQLite has no time type: store milliseconds in an integer (Time.now_millis!).
Writing#
Db.run! runs a statement and returns how many rows it changed. Db.script! runs several statements without parameters (separated by ;) as one transaction: if one fails, none stays.
("POST", "/notes") =>
match Db.run!("insert into notes (body, note) values ($1, $2)", [Text(Server.text_of(request)), if (request.query == "noted") Text("a note") else Null]) {
Ok(count) => text(201, "added ${count.to_str()}")
Err(DbErr(why)) => text(500, why)
}Transactions#
Db.transaction! runs a function on one connection. Its writes, and the jobs it queues, stay only if it returns Ok. An Err, a failing statement, a crash, or the call ending with the transaction open rolls all of it back.
("POST", "/jobs/commit") => {
# One body `?`s Db and Job, with nothing mapped: the transaction's error is both (and
# any error of the app's own), and the caller matches each.
done = Db.transaction!(
|{}| {
_ = Db.run!("insert into notes (body) values ($1)", [Text("with a job ${run}")])?
Job.enqueue!(note_job, { run, said: "committed" }, {})?
Ok("queued")
},
)
match done {
Ok(said) => text(202, said)
Err(DbErr(why)) => text(500, why)
Err(JobErr(why)) => text(500, why)
}
}Inside, ? works on what Db, Job and your own code return, with no error mapping. Their errors are open tag unions (Db.run!'s is [DbErr(Str), ..others], Job.enqueue!'s [JobErr(Str), ..others]), so the transaction's error is their union: with an app's own Err(Refused), [DbErr(Str), JobErr(Str), Refused], which the caller matches.
A job queued in a transaction is a row in it: it runs only if the transaction commits, and the workers wake when it does (jobs).
A transaction inside another#
A helper can open its own transaction and still be called inside another: the inner Db.transaction! is then a level of the outer one (a savepoint). On Ok, its writes stay in the outer transaction, which commits them or not. On Err, or a failing statement, only its own writes are undone, with what it notified and the jobs it queued, and the error comes back to the outer body, which can handle it and go on:
## Gives a customer points, in a transaction of its own: more than 100 at once are refused, and
## none stay. Called inside another transaction, its transaction is a level of that one.
award! : Str, I64 => Try({}, [DbErr(Str), TooMany])
award! = |customer, points|
Db.transaction!(
|{}| {
_ = Db.run!("insert into points (customer, points) values ($1, $2)", [Text(customer), Int(points)])?
if (points > 100) Err(TooMany) else Ok({})
},
)
## An order, and a point for every 10 spent. Points refused leave the order without them: their
## level is rolled back, and this transaction goes on and commits.
place_order! : Str, I64 => Try(Str, [DbErr(Str)])
place_order! = |customer, total|
Db.transaction!(
|{}| {
_ = Db.run!("insert into orders (customer, total) values ($1, $2)", [Text(customer), Int(total)])?
match award!(customer, total // 10) {
Ok({}) => Ok("ordered, with points")
Err(TooMany) => Ok("ordered, without points")
Err(DbErr(why)) => Err(DbErr(why))
}
},
)- An outer
Errstill undoes everything, inner levels included, and a crash rolls back the whole transaction. - Levels nest as deep as you like; a level's writes stay only if every level around it commits.
- It works the same on Postgres, SQLite, and Turso in both modes. On Postgres a failing statement aborts the transaction until its level rolls back, so an inner body that ignores the error and returns
Okstill gets it fromDb.transaction!, and its level is undone. - On Turso's MVCC, a level that loses to another transaction's write isn't run again alone: the whole transaction has lost. Its statements fail from then on, and the outermost
Db.transaction!runs its body again when the error reaches it.
Migrations#
An app's schema is a list of migrations built into its executable. With rocx build, put each in a .sql file in migrations/ (0001_tables.sql, 0002_seed.sql…): the build embeds them in name order. A hand-written program lists them in program.migrations, each a name and its SQL, imported from a file:
import "migrations/0001_tables.sql" as tables : Str
import "migrations/0002_note_index.sql" as note_index : Str
…
program = {
…
# The app's schema, in the executable: applied once each, in order, when the server starts.
migrations: [{ name: "0001_tables.sql", sql: tables }, { name: "0002_note_index.sql", sql: note_index }, { name: "0003_admin.sql", sql: admin_tables }, { name: "0004_nested.sql", sql: nested_tables }],-- The test app's tables: applied once, at the server's start (the program's migrations, embedded in it).
create table if not exists notes (id bigserial primary key, body text not null, note text);
create table if not exists job_log (id bigserial primary key, kind text not null, said text not null, at timestamptz not null default now());
create table if not exists flaky (name text primary key, tries int not null default 0);At start, the server applies each migration it hasn't yet, in order, each in its own transaction, and records it by name in rocx_migrations: the platform's tables (rocx_actors, rocx_actor_timers) first, then the plugins' (the jobs plugin's rocx_jobs, as jobs/0001_jobs), then the app's. A failing migration stops the server, saying why. Two servers starting at once (a deploy's old and new) take turns, by an advisory lock on Postgres or the write lock on SQLite.
Where it can be used#
Anywhere only the server runs: an endpoint, a middleware, a job, an actor, a stream. A component also compiles for the browser, so it can't query; it reads through a GET endpoint (.read!()), which the server answers in-process while rendering. Only the server runs the handler, so it may query; the browser's copy has just the endpoint's method and URL (who is asking).
- Connections. A statement borrows a connection from a pool (16 for Postgres, 8 for a SQLite or Turso file); a transaction keeps one until it ends. Statements are prepared once per connection, and kept. SQLite's and Turso's calls run on threads of their own, so a call waiting on one holds none of Roc's.
- Postgres connections use TLS when the database offers it (or the URL's
sslmodeasks), checked against the web's certificate authorities. In this repository,just dbruns a Postgres in Docker and prints its URL. - No database? A Postgres app with no URL and no tables still runs: each query answers that there is no database, and
Db.connected!says so up front. One whose app or plugins have tables (the jobs plugin's, auth's) doesn't start, saying which have them; under--devor--debugit starts and logs a line. - SQLite's file is in WAL mode, with
-waland-shmfiles beside it. Back it up withsqlite3 data/plate.db ".backup copy.db", or copy it while the server is stopped (a Turso file only that way: the server holds it while it runs).
Notifications#
Db.notify!(channel, payload) tells whoever listens on channel, when the call's transaction commits (never if it, or the level that notified, rolls back), or at once outside a transaction. A call listens with Db.listen!(channel), then gets each notification from Live.next! as a message on the topic db:<channel> (topics). On Postgres it is pg_notify, so other processes can notify too; on SQLite it stays within the server. Job workers sleep on it until a job is queued.
Checking queries: rocx check --sql#
rocx check --sql checks an app's SQL with the engine it runs on, and its row types with the compiler, without running anything. Each string-literal statement at a Db.all!, Db.one! or Db.run! is prepared (never run) on a scratch database that the app's own server builds from its migrations: a file for SQLite and Turso, or a database on the Postgres server DATABASE_URL names, either removed afterwards. It never migrates a database nobody named for it: without the CREATEDB privilege, it says to grant it, or to name a database it may migrate (--sql-database URL). rocx dev runs the check after each build.
$ rocx check --sql app
app/Store.roc:29:15: SQLite refuses it: no such column: bodyy in select bodyy as body from notes at offset 7
app/Store.roc:33:16: parameter $2 is given, and the statement doesn't use it
app/Store.roc:50:10: `body` is read as an integer, and notes.body is a TEXT (text)
app/Store.roc:58:10: `note` is read as a plain value, and notes.note may be null (it has no `not null`): read it as Db.Nullable(…)
app/Store.roc:66:10: `title` isn't a column the statement returns (it returns id)
rocx check --sql: 7 statements checked on SQLite (the rows of 5 against their records): 5 problems- The SQL. The engine judges the statement: its syntax, tables, columns and functions, Postgres's types, and what Turso doesn't support yet. A call's parameter list must be exactly the statement's
$1to$n, each used. - The rows. For a
Db.all!orDb.one!whose rows are annotated (rows : List(T),row : T, or the result of the function the call is in), it compares the record with the statement's columns: a field the statement doesn't return, a type the column's values can't decode into, and a plain field over a column that may be null (nonot null), whichDb.Nullableshould read. rocx reads the type with the compiler's parser, in a small app beside a copy of yours (packages/dbcheck), so aliases, nominal types and packages' types read as the compiler has them. - What it can't check: SQL built from strings (
"select ${columns} from notes") or passed in a variable, which--verbosecounts and lists; and statements on a table the app creates at run time, not in a migration, which you mark withDb.unchecked(sql). - Where to run it: by hand, in CI, and in
just examplesfor each example.--engine tursoasks Turso about a SQLite app (or SQLite about a Turso app). Describing a statement takes milliseconds; most of a check is the server starting and migrating.
Turso: SQLite's SQL on another engine#
Turso(path) is Sqlite(path) on Turso, SQLite rewritten in Rust, also inside the server's process. Its SQL and file format are SQLite's, so what this page says of SQLite holds for it, including packages' and plugins' SQLite migrations and needs. Db.backend! answers Sqlite for both; Db.engine! tells them apart.
program = App.program({
init!: |_started| Ok({}),
database: Turso("data/plate.db"),
})The URL picks the engine: --database-url turso:data/plate.db runs a SQLite app on Turso, and sqlite: a Turso app on SQLite, to compare them under rocx dev. A release (rocx build, --image) has only the engine its program names, to stay small, and refuses another at start.
What Turso adds: writes at the same time. Its file is in MVCC mode. A transaction (Db.transaction!) begins concurrent, on its own snapshot, and writes beside the others. When two write the same row, the second to commit rolls back and its body runs again (up to a hundred times; the outermost body when transactions are nested), so keep what isn't the database's (a fetch, an email) out of a transaction. A write outside a transaction is its own concurrent transaction, retried the same way; a schema change (a migration) takes the file to itself. Two transactions that read rows and write different ones both commit, where on SQLite the second would wait.
What differs:
- In MVCC mode the file is Turso's alone; SQLite refuses to open it.
--database-url turso:data/plate.db?mvcc=off, run once, gives it back (in that mode Turso's writes take turns, as SQLite's do). - The server locks a Turso file while it runs (an OS lock), so
sqlite3or a test'snode:sqliteopens it only after the server stops. - Turso has no FTS5, so the full-text search in
examples/notesandexamples/plateneeds SQLite, and noorder byinside an aggregate (json_group_array(value order by key), whichexamples/boarduses). - Turso is younger than SQLite (0.8, before its 1.0). Once it has checkpointed rows, deleting many of them badly slows what follows until its next checkpoint;
pragma wal_checkpoint(truncate)after such a delete avoids it, and?mvcc=offdoesn't have the problem.
examples/sqlite-vs-turso times the same work on both, in Roc in the server (writes, reads, scans, JSON, eight callers at once); its page has the numbers.
roc-pg: queries checked at build#
For Postgres, roc-pg is a client written in Roc. It speaks Postgres's protocol over the platform's Tcp, signs in with its Random, and checks each query against a schema at compile time: a missing column, a parameter of the wrong type, or a nullable column read as non-null fails the build. The platform's example (server/examples/roc-pg) uses the same schema.sql as its migration, so roc-pg checks against what the server applied.
planets! = |url| {
db : Client.Client(Tcp, Schema)
db = Client.connect_url!(url, { connect!: |host, port| Tcp.connect!(host, port), random_u64!: Random.seed_u64!, statement_timeout: Client.millis(30_000) })?
_ = db.execute!("INSERT INTO rocpg_planets (id, name, gravity) VALUES ($id, $name, $gravity) ON CONFLICT (id) DO NOTHING", { id: 3.I32, name: "Earth", gravity: 9.80665.F64 })?
found : List({ id : I32, name : Str, gravity : F64, moons : Try(I32, [Null]) })
found = db.query!("SELECT id, name, gravity, moons FROM rocpg_planets WHERE gravity > $least ORDER BY id", { least: 1.0.F64 })?
db.close!()
Ok(Str.join_with(found.map(|planet| "${planet.id.to_str()} ${planet.name}"), "\n"))
}Use either, or both. Db has a pool, transactions that take jobs with them, and rows decoded into the record you annotate, checked by rocx check --sql. roc-pg has queries the compiler checks, and a connection per use (no pool). Checking the example takes under a second from cold, an optimized build about six; the platform's tests build it and run it against Postgres.
Not yet#
- The check's blind spots, besides SQL it can't read (above): a row whose type isn't annotated where rocx can read it, a column from the outer side of a
left join(taken as its table says), and, on SQLite, an expression's type and nullability. Those still show when the query runs (BadRow). - Parameters are four kinds (null, text, integer, boolean) and arrays of them: no floats (pass a number as
Text, which Postgres reads as the type its place wants) and no bytes yet. A row reads an array column through a cast (array_to_json(tags)). - No cursors or streaming: a query's rows come back whole.
- SQLite is a file: no in-memory database (the server's connections couldn't share it), and a blob is read through
hex(…). - Turso's sync to Turso's cloud and its own full-text search aren't used yet; in MVCC mode it has no
WITHOUT ROWIDtables and noREINDEX.