Skip to Content

The database

Use the project's Postgres from handlers, write SQL and Rust migrations, and check queries at build time.

Each project can have its own Postgres database on Floor. A backend reaches it through cx.db(), keeps its schema in db/migrations/, and can have its SQL checked against that schema when it builds. This page covers all three.

The project's database

An operator makes it once per project (and once per environment, which is a project of its own):

floor db create gate
floor db create gate --ext postgis --ext pg_trgm    # with extensions

For a project gate, Floor makes:

  • a database named gate, on Floor's Postgres 17 server;
  • a login role gate_app that owns it. The role isn't a superuser and can't create databases or roles, bypass row security or replicate. It has 20 connections by default.

Every database Floor makes refuses connections from other projects' roles, so gate_app can do anything inside gate and nothing outside it. Extensions are added on request and never removed: timescaledb, postgis, vector, pg_trgm, pgcrypto, citext and btree_gist. Add one later with floor db update gate --ext citext.

A deployed backend gets DATABASE_URL for its project's database, as gate_app. A project without a database gets none, and cx.db() panics with this backend has no database (set DATABASE_URL).

To look at the real data:

psql "$(floor db url gate)"

Using it from a handler

cx.db() is a sqlx PgPool, four connections by default (FLOOR_DB_POOL changes it). Use sqlx as you would anywhere:

let visit: Visit = sqlx::query_as("select id, plate, status from visits where id = $1 and organization = $2")
    .bind(id)
    .bind(cx.org()?)
    .fetch_optional(cx.db())
    .await?
    .or_not_found()?;

A transaction is cx.db().begin():

let mut tx = cx.db().begin().await?;
sqlx::query("select pg_advisory_xact_lock($1)").bind(lane).execute(&mut *tx).await?;
// … read, then write, one event per lane at a time
tx.commit().await?;

sqlx errors turn into statuses through ?: no row is a 404, a unique or foreign key violation is a 409, anything else a 500. sqlx is the crate's own dependency; floor new writes it with the features the framework needs.

Migrations

db/migrations/ holds the schema's history. SQL files and Rust files sit side by side and run in version order:

db/migrations/0001_gate.sql          SQL
db/migrations/0002_plate_loose.rs    Rust, for what SQL can't do
db/migrations/0003_drop_plate.sql

A SQL migration is plain SQL:

-- db/migrations/0001_gate.sql
create table vehicles (
    id bigserial primary key,
    organization text not null,
    plate text not null,
    plate_loose text not null,
    allowed boolean not null default true,
    unique (organization, plate_loose)
);

A Rust migration is <version>_<name>.rs with a pub async fn up. It can call the backend's own code, which SQL can't:

// db/migrations/0002_plate_loose.rs: every plate_loose as model::loose computes it now.
use floor::Result;
use sqlx::PgConnection;

use crate::model::loose;

pub async fn up(db: &mut PgConnection) -> Result<()> {
    let rows: Vec<(i64, String)> = sqlx::query_as("select id, plate from vehicles")
        .fetch_all(&mut *db)
        .await?;
    for (id, plate) in rows {
        sqlx::query("update vehicles set plate_loose = $2 where id = $1")
            .bind(id)
            .bind(loose(&plate))
            .execute(&mut *db)
            .await?;
    }
    Ok(())
}

How they run:

  • Each runs once, in its own transaction, under a lock, so two processes never migrate at the same time. A SQL file whose first line is -- no-transaction runs outside one.
  • They're recorded in sqlx's _sqlx_migrations table. A database sqlx already migrated carries on from where it is.
  • Two files with the same version are an error.
  • A file that ran is never edited. Its checksum is kept, and a changed file fails the migration with changed after it ran: add a new migration instead. This includes your dev database: once floor dev ran a file, add a new one.

On Floor

A deploy migrates before the new version starts. floord runs <backend> --migrate in the new release's sandbox, with its variables, and the deployment's log shows each migration it applied. One that fails stops the deploy, and the old version keeps serving.

Rollbacks run on the newer schema. Rolling back serves an older release, but the database keeps the newer migrations; the older version doesn't know them, and that's not an error. So keep each release working on the next one's schema:

  1. Add the new column in one release, and write both.
  2. Stop reading the old column in the next.
  3. Drop it in a later one.

By hand

The backend binary migrates on its own:

DATABASE_URL=postgres://… gate --migrate    # applies db/migrations, prints each one, exits
gate --describe                             # the manifest, with the migrations it has

floor dev and floor test apply the migrations too: floor dev to <backend>_dev on your local Postgres, floor test to each test's fresh database.

Checked queries

sqlx's macros check SQL against the schema when the backend builds. A wrong column or type is a build error, and the row comes back typed:

let device = sqlx::query_scalar!(
    "select device from lanes where id = $1 and organization = $2",
    lane,
    cx.org()?
)
.fetch_optional(cx.db())
.await?
.or_not_found()?;

The macros need the schema at build time, from a database or from .sqlx/:

  • While you edit, floor dev builds against its dev database, with the SQL migrations applied.
  • For deploys and CI, run floor prepare. It applies the SQL migrations to the dev database, checks every query in the crate (the library, the binary and each test), and writes what builds need to .sqlx/. Commit it. Builds then check offline (SQLX_OFFLINE=true), with no database. floor deploy sets that when .sqlx/ is there.
  • After a migration or a query changes, run floor prepare again. A build whose .sqlx/ is out of date fails and names the query.
floor prepare
applied 1 migrations to the dev database
3 queries checked; .sqlx/ has what builds need without a database: commit it

floor prepare --database-url <url> checks against another database.

Two limits:

  • Rust migrations don't run before the check. floor dev and floor prepare apply only the SQL files before building. A query can't check against a table only a Rust migration makes, so make tables in SQL.
  • floor dev applies SQL migrations when it starts. On later saves, the restarted backend applies new ones after the build. If a query! names a table from a migration added since floor dev started, run floor prepare (or restart floor dev) so the dev database has it first.

Unchecked queries (sqlx::query, query_as, query_scalar without !) need neither and work everywhere. The gate uses both.

See also Testing for the test database and floor.toml for deploy settings.

On this page