Skip to main content

IndexRustTutorial

Axum with SQLx and PostgreSQL: A Real Database

Part 12 of Rust for web developers: store data in PostgreSQL with SQLx. Migrations, a connection pool, compile-time checked queries and database errors.

By LearnWebCraft Team20 min readBeginner

Part 12 of 15 · Rust for web developers

linkbox has everything an API needs except memory. Restart it, and every link is gone. This part replaces the in-memory map from part 11 with PostgreSQL.

We'll use SQLx, and the reason it's worth learning is one feature: it checks your SQL against a real database while your code compiles. Misspell a column name, select a column that doesn't exist, or read a BIGINT into an i32, and cargo build fails, pointing at the query. In most stacks, including Node with a plain database driver, you find those mistakes when the query runs, often in production.

By the end of this part, linkbox will store links in Postgres, run its own migrations on startup, turn duplicate URLs into a proper 409 response, survive the database going away for a while, and build without a database when it needs to (which matters for Docker in part 15).

This ran on Rust 1.100.0 with SQLx 0.9.1 and PostgreSQL 18.7, and as always, every output shown is real.

Why SQLx

Rust has three popular choices for SQL databases. Diesel is the oldest. It's a query builder and ORM: you write queries in Rust, and it generates SQL. It's very type-safe, but it has its own way of describing your schema, and async support came later through a separate crate. SeaORM is an async ORM built on top of SQLx, closer in spirit to Prisma or TypeORM, where you work with entities and generated models. SQLx isn't an ORM at all. You write plain SQL, and SQLx runs it, maps the rows into your structs, and checks the queries at compile time.

I like SQLx for learning because there's nothing to learn between you and the database. If you know SQL, you know how to write SQLx queries, and what you write is exactly what runs. It's also what most Axum examples you'll find online use. If you'd rather work with an ORM, SeaORM is a good choice, and the Axum side of this series works the same with either.

Postgres in Docker

The easiest way to run Postgres locally is in a container:

Fig. 1bash
docker run -d --name linkbox-db -p 5432:5432 \
  -e POSTGRES_PASSWORD=postgres \
  -e POSTGRES_DB=linkbox \
  postgres:18

That starts Postgres 18 in the background, creates a database called linkbox, and makes it reachable on port 5432. (Use a real password for anything that isn't your laptop.)

SQLx finds the database through a connection URL, conventionally in the DATABASE_URL environment variable. Put it in a .env file in the project root:

Fig. 2text
DATABASE_URL=postgres://postgres:postgres@localhost:5432/linkbox

Both the SQLx command-line tool and SQLx's compile-time checks read .env automatically. Add .env to .gitignore, since it'll hold real credentials once you deploy.

Dependencies

Fig. 3bash
cargo add sqlx --no-default-features --features runtime-tokio,tls-rustls,postgres,macros,migrate,chrono
cargo add chrono --no-default-features --features serde,clock
cargo add anyhow

SQLx is split into features so you only compile what you use:

  • runtime-tokio makes it use Tokio for its networking. SQLx also supports other async runtimes, so you have to pick one.
  • tls-rustls enables encrypted connections using rustls, a TLS library written in Rust. Hosted databases usually require TLS.
  • postgres is the database driver. There are also mysql and sqlite.
  • macros gives us query! and query_as!, the compile-time checked queries.
  • migrate adds support for running migrations from the app.
  • chrono lets SQLx convert Postgres timestamps into chrono date types.

chrono is the most common date and time crate. Its serde feature lets dates serialise to JSON.

The SQLx command-line tool

SQLx has a separate CLI for creating and running migrations. Install it from crates.io with only the Postgres support:

Fig. 4bash
cargo install sqlx-cli --no-default-features --features postgres,rustls

It compiles from source, so it takes a few minutes. Check it worked:

Fig. 5bash
sqlx --version
Fig. 6text
sqlx-cli 0.9.1

Migrations

A migration is a SQL file that changes the database schema. You keep them in your repository, run them in order, and every copy of the database (yours, a teammate's, production) ends up with the same structure. If you've used Prisma Migrate, Knex migrations or Rails migrations, it's the same idea.

Create one with the CLI:

Fig. 7bash
sqlx migrate add create_links

That creates a file like migrations/20261201000000_create_links.sql. The number is a timestamp, which keeps migrations in order. (With -r, it makes a pair of files instead, .up.sql and .down.sql, if you want migrations you can undo.)

Here's the table for links:

Fig. 8sql
CREATE TABLE links (
    id          BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    url         TEXT NOT NULL UNIQUE,
    title       TEXT NOT NULL,
    tags        TEXT[] NOT NULL DEFAULT '{}',
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX links_tags_idx ON links USING GIN (tags);

A few things worth knowing, especially if you're more used to MySQL or MongoDB:

  • GENERATED ALWAYS AS IDENTITY is the modern Postgres way to make an auto-incrementing id. You'll see SERIAL in older tutorials, which does the same thing in a less standard way.
  • UNIQUE on url means Postgres itself refuses to store the same URL twice, even if two requests try at the same moment. We'll turn that refusal into a 409 response.
  • TEXT[] is an array column. Postgres can store a list of tags directly in the row, without a separate tags table. For a small app that's simpler. A big app with tag pages and renaming would probably want a proper tags table.
  • TIMESTAMPTZ is a timestamp with time zone, stored as UTC. Use it instead of TIMESTAMP almost always.
  • The GIN index makes "find links with this tag" fast, by indexing every element of every tags array.

Run it:

Fig. 9bash
sqlx migrate info
sqlx migrate run
sqlx migrate info
Fig. 10text
20261201000000/pending create links
Applied 20261201000000/migrate create links (5.45035ms)
20261201000000/installed create links

SQLx records which migrations have run in a table called _sqlx_migrations, so running migrate run again does nothing. It also stores a checksum of each file, so if someone edits a migration that has already been applied, SQLx refuses to continue. The rule is: once a migration has run anywhere that matters, don't change it. Write a new one.

The models

Link changes in two small ways:

Fig. 11rust
use chrono::{DateTime, Utc};

#[derive(Debug, Clone, Serialize)]
pub struct Link {
    pub id: i64,
    pub url: String,
    pub title: String,
    pub tags: Vec<String>,
    pub created_at: DateTime<Utc>,
}

id is now i64, because Postgres's BIGINT is a signed 64-bit integer, and Rust makes you match types exactly. And there's a new created_at, a UTC timestamp, which Postgres fills in by itself.

ListParams switches limit and offset to i64 too, since that's what Postgres expects for LIMIT and OFFSET. NewLink doesn't change at all, which is the point of keeping input and output types separate: clients still can't set id or created_at.

The connection pool

Opening a database connection takes a network round trip, authentication and some setup. You don't want to do that for every request. A connection pool keeps a set of connections open and lends them out: a handler borrows one, runs its query, and gives it back.

SQLx's pool is PgPool, and it slots into AppState in place of the map:

Fig. 12rust
use sqlx::PgPool;

/// Everything the handlers share. `PgPool` is already an `Arc` inside,
/// so cloning the state is cheap.
#[derive(Clone)]
pub struct AppState {
    pool: PgPool,
}

impl AppState {
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }
}

There's no Arc and no lock any more. PgPool is designed to be shared: it's an Arc internally, so cloning it is cheap, and it does its own synchronisation. The database handles concurrent changes to the data, which is what databases are for.

Queries

Now the AppState methods from part 11 become queries. Here's fetching one link:

Fig. 13rust
pub async fn get(&self, id: i64) -> Result<Option<Link>, sqlx::Error> {
    sqlx::query_as!(
        Link,
        "SELECT id, url, title, tags, created_at FROM links WHERE id = $1",
        id,
    )
    .fetch_optional(&self.pool)
    .await
}

query_as! takes the struct to build, the SQL, and the values for each $1, $2 placeholder. The values are sent separately from the SQL, never pasted into the string, so there's no way to cause SQL injection through them. That's the same as parameterised queries in any Node driver, but here there's no string-building API to misuse.

.fetch_optional returns Option<Link>: Some for a row, None for no rows. There are matching methods for the other cases:

Method Returns Use when
fetch_one Link Exactly one row is expected; zero is an error
fetch_optional Option<Link> Zero or one row
fetch_all Vec<Link> Any number of rows
execute Rows affected INSERT, UPDATE, DELETE without RETURNING

The method signatures changed from part 11 in two ways. They're async, because talking to the database is I/O. And they return Result, because the database can fail in ways a HashMap couldn't: the connection could drop, a constraint could be violated, the server could be down.

Listing links, with the optional tag filter:

Fig. 14rust
pub async fn list(
    &self,
    tag: Option<&str>,
    offset: i64,
    limit: i64,
) -> Result<Vec<Link>, sqlx::Error> {
    sqlx::query_as!(
        Link,
        r#"
        SELECT id, url, title, tags, created_at
        FROM links
        WHERE $1::text IS NULL OR $1 = ANY(tags)
        ORDER BY id
        LIMIT $2 OFFSET $3
        "#,
        tag,
        limit.clamp(1, 100),
        offset.max(0),
    )
    .fetch_all(&self.pool)
    .await
}

The WHERE clause is a common trick for optional filters. When tag is None, SQLx sends NULL, so $1::text IS NULL is true and every row matches. When it's Some("rust"), the first half is false and $1 = ANY(tags) keeps only links whose tags array contains rust. The ::text tells Postgres the parameter's type, since it can't work it out from IS NULL alone.

limit.clamp(1, 100) keeps the limit between 1 and 100. Without an upper bound, anyone could ask for a million rows at once. r#"..."# is a raw string, so the SQL can span lines and contain quotes without escaping.

Inserting uses RETURNING, a Postgres feature that hands back the inserted row, including the id and timestamp the database generated:

Fig. 15rust
pub async fn insert(&self, input: NewLink) -> Result<Link, sqlx::Error> {
    sqlx::query_as!(
        Link,
        r#"
        INSERT INTO links (url, title, tags)
        VALUES ($1, $2, $3)
        RETURNING id, url, title, tags, created_at
        "#,
        input.url,
        input.title,
        &input.tags,
    )
    .fetch_one(&self.pool)
    .await
}

&input.tags is a &Vec<String>, which SQLx sends as a Postgres TEXT[]. replace is the same shape with UPDATE ... RETURNING and fetch_optional, since the id might not exist.

Deleting doesn't need the row back, so it uses execute and checks how many rows were affected:

Fig. 16rust
pub async fn remove(&self, id: i64) -> Result<bool, sqlx::Error> {
    let result = sqlx::query!("DELETE FROM links WHERE id = $1", id)
        .execute(&self.pool)
        .await?;
    Ok(result.rows_affected() == 1)
}

query! (without _as) is for queries where you don't want a particular struct.

Checked at compile time

Here's what makes SQLx different. When you build, the query! and query_as! macros connect to the database in DATABASE_URL, ask Postgres to prepare each query, and check the answer against your Rust code. Postgres reports the type of every parameter and every result column, and the macro makes sure they line up with your variables and struct fields.

Without a database to ask, it won't build at all:

Fig. 17text
error: set `DATABASE_URL` to use query macros online, or run `cargo sqlx prepare` to update the query cache
  --> src/state.rs:29:9
   |
29 | /         sqlx::query_as!(
30 | |             Link,
31 | |             r#"
32 | |             SELECT id, url, title, tags, created_at
...  |
40 | |             offset.max(0),
41 | |         )
   | |_________^

(The second option in that message is offline mode, which we'll get to.)

With the database available, here's what a typo in a column name does:

Fig. 18rust
"SELECT id, url, titel, tags, created_at FROM links WHERE id = $1",
Fig. 19text
error: error returned from database: column "titel" does not exist at line 3861
  --> src/state.rs:47:9
   |
47 | /         sqlx::query_as!(
48 | |             Link,
49 | |             "SELECT id, url, titel, tags, created_at FROM links WHERE id = $1",
50 | |             id,
51 | |         )
   | |_________^

That's Postgres's own error message, delivered by the compiler. (The "line 3861" is an internal position from Postgres, not a line in your file. The arrows point at the right query.)

And a type mismatch. If I change Link::id to an i32:

Fig. 20text
error[E0277]: the trait bound `i32: From<i64>` is not satisfied
  --> src/state.rs:29:9
   |
29 | /         sqlx::query_as!(
30 | |             Link,
31 | |             r#"
32 | |             SELECT id, url, title, tags, created_at
...  |
40 | |             offset.max(0),
41 | |         )
   | |_________^ the trait `From<i64>` is not implemented for `i32`

Postgres said id is a BIGINT, which is an i64, and the struct wants an i32. A 64-bit number doesn't always fit in 32 bits, so there's no automatic conversion, and the build fails. In JavaScript, every number is a double, so a database driver might hand you a BIGINT as a string, or as a number that has quietly lost precision above 2^53. Neither problem can happen here.

The checks also cover nullability. Every column in our table is NOT NULL, so SQLx lets them map to plain String and i64. If title were nullable, the macro would insist on Option<String>, so a NULL from the database could never show up where your code doesn't expect one.

There's a cost: you need the database running while you develop, and builds that touch queries are a little slower. I think it's well worth it. The whole category of "the query was wrong" bugs moves from runtime to compile time.

Handlers

Because the queries live behind AppState's methods, the handlers change very little. Each call gains .await?:

Fig. 21rust
async fn show(
    State(state): State<AppState>,
    AppPath(id): AppPath<i64>,
) -> Result<AppJson<Link>, AppError> {
    let link = state.get(id).await?.ok_or(AppError::NotFound(id))?;
    Ok(AppJson(link))
}

Read the chain left to right: run the query, ? returns early if the database failed, ok_or turns "no such row" into a NotFound error, and the final ? returns that if needed.

remove now uses the bool from the method:

Fig. 22rust
async fn remove(
    State(state): State<AppState>,
    AppPath(id): AppPath<i64>,
) -> Result<StatusCode, AppError> {
    if state.remove(id).await? {
        Ok(StatusCode::NO_CONTENT)
    } else {
        Err(AppError::NotFound(id))
    }
}

Database errors in AppError

For ? to work on sqlx::Error, AppError needs to be able to hold one. There are two kinds of database error we care about. A duplicate URL is the client's fault and should be a 409 Conflict. Anything else, like a lost connection, is our fault and should be a 500.

Two new variants:

Fig. 23rust
#[error("a link with that url already exists")]
Conflict,

#[error("database error: {0}")]
Database(sqlx::Error),

Instead of #[from], I wrote the From conversion by hand, so it can look inside the error:

Fig. 24rust
impl From<sqlx::Error> for AppError {
    fn from(err: sqlx::Error) -> Self {
        match &err {
            sqlx::Error::Database(db) if db.is_unique_violation() => AppError::Conflict,
            _ => AppError::Database(err),
        }
    }
}

sqlx::Error::Database holds an error reported by the database itself, and is_unique_violation() checks whether it was a UNIQUE constraint failing. That's the match guard from part 4: a pattern plus an if.

Then the status codes:

Fig. 25rust
AppError::Conflict => (StatusCode::CONFLICT, "conflict"),
AppError::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal"),

One more change, and it's important for security. A database error message can include table names, column names, constraint names and sometimes data. You don't want to send that to whoever is calling your API. So into_response now logs server errors in full and sends the client a generic message:

Fig. 26rust
impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, code) = self.status_and_code();
        let message = if status.is_server_error() {
            tracing::error!(error = %self, "request failed");
            "something went wrong on our side".to_string()
        } else {
            self.to_string()
        };
        let body = Json(json!({ "error": { "code": code, "message": message } }));
        (status, body).into_response()
    }
}

Client errors (4xx) still show their message, because those messages help the client fix their request. Server errors (5xx) are logged with the details, and the client only learns that something went wrong.

Starting up

main.rs now connects to the database and runs migrations before serving requests:

Fig. 27rust
use std::time::Duration;

use anyhow::Context;
use linkbox::{AppState, app};
use sqlx::postgres::PgPoolOptions;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // ... tracing setup as before ...

    let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL must be set")?;

    let pool = PgPoolOptions::new()
        .max_connections(10)
        .acquire_timeout(Duration::from_secs(3))
        .connect(&database_url)
        .await
        .context("could not connect to the database")?;

    sqlx::migrate!()
        .run(&pool)
        .await
        .context("could not run migrations")?;
    tracing::info!("migrations are up to date");

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    tracing::info!("listening on {}", listener.local_addr()?);
    axum::serve(listener, app(AppState::new(pool))).await?;
    Ok(())
}

main returns anyhow::Result, the application error pattern from part 5, so every startup failure becomes a readable message with context instead of a panic.

max_connections(10) caps how many connections the pool opens. Postgres has its own limit (100 by default), shared between everything that connects to it, so don't set this higher than you need. acquire_timeout is how long a handler waits for a free connection before giving up. Without it, if the database disappeared, requests would wait for a long time.

sqlx::migrate!() embeds every file in migrations/ into the binary at compile time, and .run(&pool) applies any that haven't run yet. So deploying a new version that includes a new migration upgrades the database automatically when it starts. That's convenient for a small app. Bigger teams often run migrations as a separate deployment step instead, so they can control exactly when the schema changes.

One thing to notice: the SQLx macros and CLI read .env, but the app itself only reads real environment variables. Locally, export the variable or run with DATABASE_URL=... cargo run. In production, the hosting platform sets it, as we'll see in part 15. (The dotenvy crate can load .env in the app too, if you prefer.)

Trying it out

Starting the server logs:

Fig. 28text
INFO linkbox: migrations are up to date
INFO linkbox: listening on 0.0.0.0:3000

Creating links works as before, now with timestamps from Postgres:

Fig. 29bash
curl -X POST http://127.0.0.1:3000/links -H 'content-type: application/json' \
  -d '{"url":"https://www.rust-lang.org","title":"Rust","tags":["rust"]}'
Fig. 30text
{"id":1,"url":"https://www.rust-lang.org","title":"Rust","tags":["rust"],"created_at":"2026-12-01T07:05:53.016456Z"}

chrono serialises timestamps in ISO 8601 format, which JavaScript's new Date(...) parses directly.

After adding two more, trying to save a URL that's already there:

Fig. 31bash
curl -i -X POST http://127.0.0.1:3000/links -H 'content-type: application/json' \
  -d '{"url":"https://tokio.rs","title":"Tokio again"}'
Fig. 32text
HTTP/1.1 409 Conflict
content-type: application/json

{"error":{"code":"conflict","message":"a link with that url already exists"}}

That's the database's UNIQUE constraint, through is_unique_violation(), into a 409. Because the check happens in Postgres, it holds even when two requests race to insert the same URL at the same time. Checking with a SELECT first and then inserting would leave a gap between the two where a duplicate could sneak in.

Filtering by tag uses the array query:

Fig. 33text
[{"id":1,"url":"https://www.rust-lang.org","title":"Rust","tags":["rust"],"created_at":"2026-12-01T07:05:53.016456Z"},{"id":2,"url":"https://tokio.rs","title":"Tokio","tags":["rust","async"],"created_at":"2026-12-01T07:05:53.032644Z"}]

PUT and DELETE behave exactly as in part 11, including a 404 for deleting the same link twice. And ?limit=0 returns one link, since the limit was clamped to at least 1.

Now the real test. I restarted the server and listed the links again:

Fig. 34text
[{"id":1,"url":"https://www.rust-lang.org","title":"Rust","tags":["rust"],"created_at":"2026-12-01T07:05:53.016456Z"},{"id":2,"url":"https://tokio.rs/tokio/tutorial","title":"Tokio tutorial","tags":["rust","async"],"created_at":"2026-12-01T07:05:53.032644Z"}]

They survived, including the update to link 2. Looking in the database directly with psql:

Fig. 35text
 id |               url               |     title      |     tags
----+---------------------------------+----------------+--------------
  1 | https://www.rust-lang.org       | Rust           | {rust}
  2 | https://tokio.rs/tokio/tutorial | Tokio tutorial | {rust,async}
(2 rows)

When the database goes away

Databases restart, networks blip, and managed databases have maintenance windows. I stopped the Postgres container while the server was running, and called the health check, which now runs SELECT 1 to make sure the database answers:

Fig. 36text
HTTP/1.1 500 Internal Server Error
content-type: application/json
x-response-time: 3002.08ms

{"error":{"code":"internal","message":"something went wrong on our side"}}

The client got a generic message after 3 seconds, which is the acquire_timeout. The server log has the details:

Fig. 37text
ERROR request{method=GET uri=/health version=HTTP/1.1}: linkbox::error: request failed error=database error: pool timed out while waiting for an open connection

Then I started Postgres again, and without touching the server:

Fig. 38text
HTTP/1.1 200 OK
content-type: application/json

{"status":"ok","version":"0.1.0"}

The pool noticed the dead connections and opened new ones. No restart, no special code. Having the health check test the database means a hosting platform can tell that this instance can't do its job and stop sending it traffic, which we'll set up in part 15.

Building without a database

Compile-time checking needs a database, which is a problem in two places: CI, and building a Docker image, where there's no database to connect to. SQLx's answer is offline mode. Run this with the database available:

Fig. 39bash
cargo sqlx prepare
Fig. 40text
query data written to .sqlx in the current directory; please check this into version control

It creates a .sqlx folder with one JSON file per query, describing the parameter and column types that Postgres reported. Commit it. When SQLX_OFFLINE=true is set, or when there's no DATABASE_URL, the macros read these files instead of connecting:

Fig. 41bash
SQLX_OFFLINE=true cargo build

That builds with no database at all. If you change a query and forget to run prepare again, the offline build fails, because the cached data no longer matches the query. A CI job that runs cargo sqlx prepare --check catches that before merging.

Express with Prisma, and Axum with SQLx

Node Rust
pg or Prisma SQLx
prisma migrate dev sqlx migrate add and sqlx migrate run
Prisma schema file Plain SQL migrations
new Pool() from pg PgPoolOptions::new().connect(...)
pool.query("... $1", [id]) query_as!(Link, "... $1", id)
Wrong column name fails at runtime (with pg) Wrong column name fails at compile time
BIGINT may come back as a string BIGINT is an i64
err.code === "23505" for unique violations db.is_unique_violation()
prisma generate for types Types come from your structs, checked by the macros
Client needs schema generation in CI cargo sqlx prepare and the .sqlx folder

Prisma deserves credit here: it also gives you type-safe queries. The difference is where the types come from. Prisma generates them from its own schema file. SQLx checks your hand-written SQL against the actual database, so anything Postgres can do, you can write, and it's still checked.

Exercises

  1. Write a migration that adds a nullable notes TEXT column to links. Add notes: Option<String> to Link and NewLink. What does the compiler tell you about every query until you update them?
  2. Add a GET /tags route that returns every distinct tag with its count, like [{"tag":"rust","count":2}]. The SQL needs unnest(tags) and GROUP BY. What type does SQLx give the count column, and why is it an Option?
  3. Use sqlx::query_scalar! to write a count() method on AppState, and include the total in the GET /links response as {"total": 2, "links": [...]}.
  4. Try inserting a link, getting a 409 for a duplicate, then inserting a new link. What id does it get, and why? (Look up how Postgres sequences behave when an insert fails.)
  5. Add .idle_timeout(Duration::from_secs(60)) to the pool, then look at the other PgPoolOptions settings. Which would you change for a server that gets a request every few minutes, and which for one under heavy load?

Next up: authentication, validation and security

linkbox now stores data for real. But anyone who can reach it can create, change and delete every link, the validation is two if statements, and a browser on another domain can't call it at all.

Part 13 fixes all three. We'll add users with passwords hashed using Argon2 (in spawn_blocking, as part 9 promised), log them in with session tokens, protect the write routes with an extractor that only lets authenticated users through, replace check() with the validator crate, and configure CORS so a frontend on another origin can call the API safely.