Howdy

Typed SQL with Squirrel and Marmot

Gloo's query builder covers the everyday finds, inserts and updates. For the queries you would rather write in SQL, two code generators turn .sql files into typed Gleam functions, with the parameter and row types read from your database:

SquirrelMarmot
DatabasePostgreSQL 16 or laterSQLite
Generated code callspogsqlight
Generate withgleam run -m squirrelgleam run -m marmot
Writessql.gleam beside each sql directoryone module per sql directory, in a folder you choose
Parameters$1, $2@name

Both are dev dependencies: they run on your machine, and the code they write is ordinary Gleam that you commit. Gloo and pog, and Gloo and sqlight, are the same drivers underneath, so the generated functions can share the Repo's connections, and its transactions, once the app hands them out. This guide does that in a project made by howdy new, then builds a notes API at /api/notes on each database.

A table to query

Both generators read the schema from a running database, so the table has to exist in the development database before they can type a query against it. Make the migration and apply it:

howdy create migration notes title:string body:string
gleam run -m tasks/migrate

Run tasks/migrate again after each migration that a query depends on, before generating.

The JSON shape of a note is the same on both databases. Put the record in src/my_app/features/notes/note.gleam:

import gleam/dynamic/decode
import gleam/json

pub type Note {
  Note(id: Int, title: String, body: String)
}

pub type NoteInput {
  NoteInput(title: String, body: String)
}

pub fn input_decoder() -> decode.Decoder(NoteInput) {
  use title <- decode.field("title", decode.string)
  use body <- decode.field("body", decode.string)
  decode.success(NoteInput(title:, body:))
}

pub fn decoder() -> decode.Decoder(Note) {
  use id <- decode.field("id", decode.int)
  use title <- decode.field("title", decode.string)
  use body <- decode.field("body", decode.string)
  decode.success(Note(id:, title:, body:))
}

pub fn to_json(note: Note) -> json.Json {
  json.object([
    #("id", json.int(note.id)),
    #("title", json.string(note.title)),
    #("body", json.string(note.body)),
  ])
}

PostgreSQL with Squirrel

Install Squirrel

gleam add squirrel --dev

Write the queries

Squirrel looks for every directory called sql under src. Each file in one holds a single query, and its name becomes the function's name. Keep them with the feature, in src/my_app/features/notes/sql/:

list_notes.sql:

-- Every note, newest first.
select id, title, body
from notes
order by id desc

find_note.sql:

select id, title, body
from notes
where id = $1

create_note.sql:

insert into notes (title, body)
values ($1, $2)
returning id, title, body

delete_note.sql:

delete from notes
where id = $1

A comment at the top of a file, such as the one in list_notes.sql, becomes the function's doc comment.

Generate

Squirrel connects with DATABASE_URL, but it does not read .env. Export the file's values for the one command:

(set -a; . ./.env; set +a; gleam run -m squirrel)

Or keep them exported in your shell with a tool such as direnv. Without DATABASE_URL, Squirrel tries a database named after the project on localhost, which a Howdy project does not have.

It writes src/my_app/features/notes/sql.gleam, with a row type and a function for each query:

pub type FindNoteRow {
  FindNoteRow(id: Int, title: String, body: String)
}

pub fn find_note(
  db: pog.Connection,
  id: Int,
) -> Result(pog.Returned(FindNoteRow), pog.QueryError)

Squirrel names a parameter after the column it is compared with, so where id = $1 gives id. Where it cannot tell, as with the values of an insert, they are arg_1, arg_2 and so on.

Share the pool

The generated functions take a pog.Connection. howdy/database/postgres from Howdy Database starts one pool that answers both as a Gloo Repo and as a pog connection. Replace connect in src/my_app/platform/database.gleam with one that starts it:

import howdy/database/postgres

/// Start a connection pool for a `postgres://user:password@host:port/name`
/// URL. It answers as a Gloo Repo, for Gloo queries and Howdy modules, and as
/// a pog connection, for the queries Squirrel generates.
pub fn connect(url: String) -> Result(postgres.Pool, String) {
  postgres.from_url(url)
  |> result.try(postgres.start_pool)
  |> result.map_error(postgres.error_to_string)
}

wait_until_ready and the imports it used can go: start_pool waits for the server itself. It also brings Howdy's connection defaults: TLS for any host that is not local, timeouts on every statement, and no server older than PostgreSQL 14.

Keep the pool in the services, beside the Repo, in src/my_app.gleam:

import howdy/database/postgres

pub type Services {
  Services(db: Repo, pool: postgres.Pool)
}

pub fn database() -> postgres.Pool {
  let url = env.get_string_or("DATABASE_URL", database.default_url)
  case database.connect(url) {
    Ok(pool) -> pool
    Error(message) -> panic as { "DATABASE_URL: " <> message }
  }
}

pub fn main() -> Nil {
  load_environment()
  let pool = database()
  let db = postgres.repo(pool)
  // ... migrate with `db` as before
  let services = Services(db:, pool:)
  // ...
}

database() has three other callers. In dev/my_app_dev.gleam, do as main does:

let pool = my_app.database()
let db = postgres.repo(pool)
let assert Ok(_) = database.migrate(db)
let services = my_app.Services(db:, pool:)

and in src/tasks/migrate.gleam, migrate the pool's Repo:

let assert Ok(applied) = database.migrate(postgres.repo(my_app.database()))

The third is the test support, below.

Write the operations

Database access goes through the feature's operations module. Have its functions take a pog.Connection, not the pool, so they work on the pool and inside a transaction alike. postgres.error turns a pog error into a service.Error: a constraint violation becomes a Conflict, anything else an Internal, without the driver's message. src/my_app/features/notes/notes.gleam:

import gleam/list
import gleam/result
import howdy/database/postgres
import howdy/service
import my_app/features/notes/note.{type Note, type NoteInput, Note}
import my_app/features/notes/sql
import pog

pub fn all(conn: pog.Connection) -> service.Result(List(Note)) {
  use returned <- result.map(
    sql.list_notes(conn) |> result.map_error(postgres.error),
  )
  list.map(returned.rows, fn(row) { Note(row.id, row.title, row.body) })
}

pub fn find(conn: pog.Connection, id: Int) -> service.Result(Note) {
  use returned <- result.try(
    sql.find_note(conn, id) |> result.map_error(postgres.error),
  )
  case returned.rows {
    [row] -> Ok(Note(row.id, row.title, row.body))
    _ -> Error(service.NotFound("note not found"))
  }
}

pub fn create(conn: pog.Connection, input: NoteInput) -> service.Result(Note) {
  use returned <- result.try(
    sql.create_note(conn, input.title, input.body)
    |> result.map_error(postgres.error),
  )
  case returned.rows {
    [row] -> Ok(Note(row.id, row.title, row.body))
    _ -> Error(service.Internal("insert returned no row"))
  }
}

pub fn delete(conn: pog.Connection, id: Int) -> service.Result(Nil) {
  use returned <- result.try(
    sql.delete_note(conn, id) |> result.map_error(postgres.error),
  )
  case returned.count {
    0 -> Error(service.NotFound("note not found"))
    _ -> Ok(Nil)
  }
}

Each query has its own row type, even where the columns are the same, so each function builds the Note itself.

Route it

The controller takes the pool and hands its connection to the operations. src/my_app/features/notes/notes_controller.gleam:

import gleam/json
import howdy/body
import howdy/controller
import howdy/database/postgres
import howdy/param
import howdy/service
import my_app/features/notes/note
import my_app/features/notes/notes

pub fn controller(pool: postgres.Pool) {
  let conn = postgres.connection(pool)
  controller.new("api/notes")
  |> controller.get("/", fn(ctx) {
    notes.all(conn) |> service.respond(ctx, json.array(_, note.to_json))
  })
  |> controller.get("/:id", fn(ctx) {
    use id <- param.int(ctx, "id")
    notes.find(conn, id) |> service.respond(ctx, note.to_json)
  })
  |> controller.post("/", fn(ctx) {
    use input <- body.json(ctx, note.input_decoder())
    notes.create(conn, input) |> service.created(ctx, note.to_json)
  })
  |> controller.delete("/:id", fn(ctx) {
    use id <- param.int(ctx, "id")
    notes.delete(conn, id) |> service.no_content(ctx)
  })
}

Register it in app, ahead of the static catch-all:

|> howdy.controller(notes.controller(services.pool))

Transactions

postgres.transaction opens one transaction and gives you both handles to it: a pog connection for Squirrel's functions, and a Repo for Gloo queries and Howdy modules. Everything commits or rolls back together:

use conn, db <- postgres.transaction(pool)
use note <- result.try(notes.create(conn, input))
use _ <- result.try(todos.create(db, follow_up))
Ok(note)

Open it this way round, not with database.transaction: a Repo cannot hand its transaction to pog, so a Squirrel query inside one would run on another connection, outside it. postgres.transaction refuses to open inside a Repo transaction rather than let that happen.

Test it

support.with_db gives each test a freshly migrated database. Have it hand the tests the pool, which support.app needs for the services. In test/my_app/support.gleam:

import howdy/database/postgres

pub fn with_db(run_test: fn(postgres.Pool) -> a) -> a {
  let pool = connect()
  let db = postgres.repo(pool)
  use <- testing.cleanup(fn() { repo.close(db) })
  let assert Ok(_) = reset(db)
  let assert Ok(_) = database.migrate(db)
  run_test(pool)
}

pub fn check_database() -> Nil {
  let _ = repo.close(postgres.repo(connect()))
  Nil
}

fn connect() -> postgres.Pool {
  case database.connect(env.get_string_or("TEST_DATABASE_URL", default_url)) {
    Ok(pool) -> pool
    Error(message) -> panic as { "TEST_DATABASE_URL: " <> message }
  }
}

pub fn app(pool: postgres.Pool) {
  let services = my_app.Services(db: postgres.repo(pool), pool:)
  my_app.app(services)
}

Tests that only pass the value on to support.app keep working as they are. One that calls Gloo operations itself takes the Repo from the pool:

pub fn create_list_toggle_delete_test() {
  use pool <- support.with_db()
  let db = postgres.repo(pool)
  let assert Ok(first) = todos.create(db, support.new_todo("Write docs"))
  // ...
}

A test of the transaction above checks that both writes roll back:

pub fn transaction_rolls_back_both_test() {
  use pool <- support.with_db()
  let result = {
    use conn, db <- postgres.transaction(pool)
    use _ <- result.try(notes.create(conn, note.NoteInput("Plan", "Write it")))
    use _ <- result.try(todos.create(db, support.new_todo("Write it")))
    Error(service.Conflict("changed my mind"))
  }
  assert result == Error(service.Conflict("changed my mind"))
  assert notes.all(postgres.connection(pool)) == Ok([])
  assert todos.all(postgres.repo(pool)) == Ok([])
}

Keep it in step

gleam run -m squirrel check fails when the generated code is out of date with the .sql files. It connects to the database as generating does, so run it in CI against one that has been migrated: a forgotten gleam run -m squirrel then fails the build rather than the deploy.

Queries sent straight to pog do not go through the Repo, so they are not recorded as query spans in traces. The request and any transaction around them still are.

SQLite with Marmot

Install Marmot

Marmot is a dev dependency. The code it writes calls sqlight, the SQLite driver Gloo uses, so the app needs that directly:

gleam add marmot --dev
gleam add sqlight

Point it at the database

Marmot finds the database from its --database flag, then DATABASE_URL, then gleam.toml. A Howdy project names its file with DATABASE_PATH instead, so give Marmot the development database in gleam.toml, and keep the generated modules inside the app:

[tools.marmot]
database = "my_app.sqlite3"
output = "src/my_app/generated"

If DATABASE_URL is set in your shell for some other project, Marmot uses that instead.

Marmot also has migrate, seed and reset commands. Leave them alone: Howdy's migrations own the schema, and reset deletes the database file.

Write the queries

Marmot looks for every directory called sql under src, one query to a file, named for the function it becomes. Keep them with the feature, in src/my_app/features/notes/sql/:

list_notes.sql:

-- returns: NoteRow
select id, title, body
from notes
order by id desc

find_note.sql:

-- returns: NoteRow
select id, title, body
from notes
where id = @id

create_note.sql:

-- returns: NoteRow
insert into notes (title, body)
values (@title, @body)
returning id, title, body

delete_note.sql:

delete from notes
where id = @id
returning id

Name parameters with @name: they become labelled arguments, and a name used twice is one argument. -- returns: NoteRow makes queries in the same directory that select the same columns share one row type. The delete returns the id, as Marmot reports the rows a statement returned rather than the rows it changed: an empty list means there was no such note.

Generate

gleam run -m marmot

Each sql directory becomes one module, at the same path under output: src/my_app/generated/features/notes_sql.gleam.

pub type NoteRow {
  NoteRow(id: Int, title: String, body: String)
}

pub fn find_note(
  db db: sqlight.Connection,
  id id: Int,
) -> Result(List(NoteRow), sqlight.Error)

Marmot has no check command. To catch a forgotten run in CI, generate and fail if anything changed:

gleam run -m tasks/migrate
gleam run -m marmot
git diff --exit-code src/my_app/generated

Share the connection

The generated functions take a sqlight.Connection, and Gloo's SQLite Repo holds exactly one. Open the connection yourself and build the Repo around it, so Marmot's queries and the Repo's use the same one:

  • they see the same data, including in the tests, where ":memory:" gives each connection a database of its own
  • they share transactions
  • they can take turns. Everything that goes through howdy/database takes turns on a SQLite Repo, so that a request never runs a query inside another request's transaction. Marmot's queries need to take the same turns.

Add a Database to src/my_app/platform/database.gleam:

import gloo/adapter.{Adapter, SqConnection}
import gloo/telemetry
import sqlight

/// One SQLite connection, reachable two ways: as the Gloo Repo that Gloo
/// queries and Howdy modules take, and as the `sqlight.Connection` that the
/// functions Marmot generates take.
pub opaque type Database {
  Database(repo: Repo, connection: sqlight.Connection)
}

/// Open the SQLite file at `path`, or `":memory:"` for a database that
/// lasts as long as the connection, and apply `configure`.
pub fn open(path: String) -> Result(Database, String) {
  use connection <- result.try(
    sqlight.open(path) |> result.map_error(fn(e) { e.message }),
  )
  let db =
    repo.from_adapter(Adapter(
      name: "sqlite",
      connection: SqConnection(connection),
      quote_identifier: adapter.sqlite_quote,
      placeholder: adapter.sqlite_placeholder,
      savepoint_depth: 0,
      telemetry: telemetry.disabled(),
    ))
    // Report every query made through the Repo as a span.
    |> howdy_database.traced
  use _ <- result.try(configure(db))
  Ok(Database(repo: db, connection:))
}

/// The Repo, for Gloo queries, migrations and Howdy modules.
pub fn repo(database: Database) -> Repo {
  database.repo
}

/// Run queries on the connection, taking turns with everything else that
/// uses the database through `howdy/database`. A sqlight error becomes a
/// `service.Error` with `error`.
pub fn run(
  database: Database,
  queries: fn(sqlight.Connection) -> Result(a, sqlight.Error),
) -> service.Result(a) {
  use _ <- howdy_database.connect(database.repo)
  queries(database.connection) |> result.map_error(error)
}

/// Commit when `run` returns `Ok`; roll back otherwise. Pass the Repo
/// `run` gets to Gloo queries and Howdy modules. Functions that use `run`
/// on the same Database join the transaction too: there is one connection,
/// and the turn on it is already this process's.
pub fn transaction(
  database: Database,
  run: fn(Repo) -> service.Result(a),
) -> service.Result(a) {
  howdy_database.transaction(database.repo, run)
}

/// The error for a failed sqlight query, matching `howdy/database`: a
/// constraint violation is a `Conflict`, anything else is `Internal`.
/// Driver messages may contain personal data, so neither repeats them.
pub fn error(error: sqlight.Error) -> service.Error {
  case error.code {
    sqlight.Constraint
    | sqlight.ConstraintCheck
    | sqlight.ConstraintForeignkey
    | sqlight.ConstraintNotnull
    | sqlight.ConstraintPrimarykey
    | sqlight.ConstraintUnique ->
      service.Conflict("the record conflicts with existing data")
    _ -> service.Internal("database operation failed")
  }
}

howdy_database.connect takes the turn, and it is the same turn whichever Repo-based code asks for it, as long as everything is given the one Repo that open built. Asking again while holding it, as run does inside transaction, carries straight on.

Open it in src/my_app.gleam, and keep it in the services beside the Repo. The gloo/adapter/sqlite import, and the howdy/database one that traced the Repo, can go:

pub type Services {
  Services(db: Repo, sqlite: database.Database)
}

pub fn database() -> database.Database {
  let path = env.get_string_or("DATABASE_PATH", "my_app.sqlite3")
  case database.open(path) {
    Ok(sqlite) -> sqlite
    Error(message) -> panic as { "DATABASE_PATH: " <> message }
  }
}

pub fn main() -> Nil {
  load_environment()
  let sqlite = database()
  let db = database.repo(sqlite)
  // ... migrate with `db` as before
  let services = Services(db:, sqlite:)
  // ...
}

Do the same in dev/my_app_dev.gleam:

let sqlite = my_app.database()
let db = database.repo(sqlite)
let assert Ok(_) = database.migrate(db)
let services = my_app.Services(db:, sqlite:)

and migrate the Repo in src/tasks/migrate.gleam:

let assert Ok(applied) = database.migrate(database.repo(my_app.database()))

Write the operations

The operations take the Database, and run each query through database.run. src/my_app/features/notes/notes.gleam:

import gleam/list
import gleam/result
import howdy/service
import my_app/features/notes/note.{type Note, type NoteInput, Note}
import my_app/generated/features/notes_sql.{type NoteRow}
import my_app/platform/database.{type Database}

pub fn all(db: Database) -> service.Result(List(Note)) {
  use rows <- result.map(database.run(db, notes_sql.list_notes))
  list.map(rows, to_note)
}

pub fn find(db: Database, id: Int) -> service.Result(Note) {
  use rows <- result.try(
    database.run(db, fn(conn) { notes_sql.find_note(db: conn, id:) }),
  )
  case rows {
    [row] -> Ok(to_note(row))
    _ -> Error(service.NotFound("note not found"))
  }
}

pub fn create(db: Database, input: NoteInput) -> service.Result(Note) {
  use rows <- result.try(
    database.run(db, fn(conn) {
      notes_sql.create_note(db: conn, title: input.title, body: input.body)
    }),
  )
  case rows {
    [row] -> Ok(to_note(row))
    _ -> Error(service.Internal("insert returned no row"))
  }
}

pub fn delete(db: Database, id: Int) -> service.Result(Nil) {
  use rows <- result.try(
    database.run(db, fn(conn) { notes_sql.delete_note(db: conn, id:) }),
  )
  case rows {
    [] -> Error(service.NotFound("note not found"))
    _ -> Ok(Nil)
  }
}

fn to_note(row: NoteRow) -> Note {
  Note(id: row.id, title: row.title, body: row.body)
}

Several queries can share one turn: database.run takes a function, which can call as many of Marmot's functions as it likes.

Route it

The controller is the Postgres one with the Database in place of the pool, and no connection to take from it:

import my_app/platform/database.{type Database}

pub fn controller(db: Database) {
  controller.new("api/notes")
  |> controller.get("/", fn(ctx) {
    notes.all(db) |> service.respond(ctx, json.array(_, note.to_json))
  })
  // ... and the same for /:id, POST / and DELETE /:id
}

Register it in app, ahead of the static catch-all:

|> howdy.controller(notes.controller(services.sqlite))

Transactions

database.transaction gives run the Repo for Gloo queries and Howdy modules. The operations keep taking the Database, and join the transaction because they share its connection:

use tx <- database.transaction(sqlite)
use note <- result.try(notes.create(sqlite, input))
use _ <- result.try(todos.create(tx, follow_up))
Ok(note)

Give Gloo code the tx Repo rather than the one from database.repo, so a transaction of its own becomes a savepoint inside this one.

Marmot also writes src/my_app/generated/transaction.gleam, with a savepoint function for grouping its queries. database.transaction does that job and takes the turn too, so you do not need it.

Test it

Open each test's in-memory database through database.open, so the Repo the migrations run on is the connection the tests query. In test/my_app/support.gleam:

pub fn with_db(run_test: fn(database.Database) -> a) -> a {
  let assert Ok(sqlite) = database.open(":memory:")
  let db = database.repo(sqlite)
  use <- testing.cleanup(fn() { repo.close(db) })
  let assert Ok(_) = database.migrate(db)
  run_test(sqlite)
}

pub fn app(sqlite: database.Database) {
  let services = my_app.Services(db: database.repo(sqlite), sqlite:)
  my_app.app(services)
}

A test that calls Gloo operations itself takes database.repo(sqlite). And the transaction above:

pub fn transaction_rolls_back_both_test() {
  use sqlite <- support.with_db()
  let result = {
    use tx <- database.transaction(sqlite)
    use _ <- result.try(notes.create(sqlite, note.NoteInput("Plan", "Do")))
    use _ <- result.try(todos.create(tx, support.new_todo("Do")))
    Error(service.Conflict("changed my mind"))
  }
  assert result == Error(service.Conflict("changed my mind"))
  assert notes.all(sqlite) == Ok([])
  assert todos.all(database.repo(sqlite)) == Ok([])
}

Queries made through sqlight are not recorded as query spans in traces; the request and any transaction around them still are.

Check your work

howdy check

formats, builds and tests the project, generated code included. After changing a .sql file or a migration it depends on, migrate the development database and generate again before you check.