Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

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.

main.roc
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:

server/test/app/main.roc, in part
("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:

examples/tasks/Store.roc, in part
## 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))).

An array as a parameter
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.

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.

server/test/app/main.roc, in part
("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.

server/test/app/main.roc, in part
("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:

server/test/app/Samples.roc, in part
## 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))
			}
		},
	)

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:

server/test/app/main.roc, in part
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 }],
server/test/app/migrations/0001_tables.sql
-- 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).

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

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.

main.roc
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:

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.

server/examples/roc-pg/main.roc, in part
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#