Learn Axum · 8/13

Database Integration (Practical Data)

7 min read

Welcome back, brave Rustacean! 🦀

Up until now, our Axum applications have been suffering from a condition known as "Short-term Memory Loss." We store data in a Vec or a HashMap, we feel good about ourselves, and then... the server restarts. Poof! 💨 All that data vanishes into the digital void.

Imagine building a banking app where the account balance resets to zero every time you deploy an update. Your users would likely form an angry mob with pitchforks.

To avoid the mob, we need Persistence. We need a Database.

In this guide, we aren't just going to "connect" to a database. We are going to do it the Industry Standard way using SQLx and PostgreSQL.


1. Choosing an Async DB Driver: Introduction to SQLx

The Problem: Blocking the Thread

In the old days (and in synchronous languages), when your code asked the database for data, the entire program would stop and wait (block) until the database replied.

In Axum, which runs on the tokio runtime, blocking is a crime. If you block an async thread while waiting for a slow SQL query, your server stops handling other requests. It’s like a waiter refusing to seat new customers because one table hasn't decided what they want to order yet.

The Solution: SQLx

SQLx is the superhero we need. It is:

  1. Fully Async: It plays perfectly with Tokio. It sends a query and lets the thread do other work while waiting for the result.
  2. Pure Rust: No messy C-bindings to configure.
  3. Compile-time Checked Queries: (This is the "killer feature"). If you write a SQL query with a typo, or ask for a column that doesn't exist, your code will not compile. It's like having a DBA (Database Administrator) inside your compiler. 🧙‍♂️

Setting Up

Let's get our Cargo.toml ready. We need axum, tokio, serde, and sqlx.

toml
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# We use the "postgres" feature. 
# "runtime-tokio-native-tls" sets up the async runtime integration.
sqlx = { version = "0.7", features = ["runtime-tokio-native-tls", "postgres", "macros"] }
dotenvy = "0.15" # To manage .env files

Fun Fact: SQLx supports PostgreSQL, MySQL, SQLite, and MSSQL. But in the Rust world, PostgreSQL is the cool kid everyone hangs out with.


2. Connection Pools: Setting Up and Injecting State

The Problem: The Cost of Connection

Imagine if every time you wanted to check a book out of the library, the library had to build a new front door, verify your ID with the government, and hire a new librarian. That’s what opening a new database connection for every single request looks like. It is incredibly slow and resource-heavy.

The Solution: Connection Pools

A Connection Pool is like a taxi rank. A bunch of connections are created upfront and sit there idling. When a request comes in:

  1. Borrow a connection from the pool.
  2. Run the query.
  3. Return the connection to the pool.

This makes your app blazing fast. 🔥

Implementation: Axum State

In Axum, we don't use global variables (globals are the root of all evil). We use State. We create the pool once in main and pass it to every handler that needs it.

Step 1: The Setup (main.rs)

rust
use axum::{routing::{get, post}, Router};
use sqlx::postgres::PgPoolOptions;
use std::net::SocketAddr;
use dotenvy::dotenv;
use std::env;

#[tokio::main]
async fn main() {
    // 1. Load environment variables from .env file
    dotenv().ok();
    
    // 2. Get the database URL
    let database_url = env::var("DATABASE_URL")
        .expect("DATABASE_URL must be set in .env file");

    // 3. Create the Connection Pool
    // We configure it to hold up to 5 connections.
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect(&database_url)
        .await
        .expect("Failed to connect to DB");

    // 4. Create the App and inject the pool as State
    let app = Router::new()
        .route("/", get(|| async { "Hello, World!" }))
        // We will add more routes here later
        .with_state(pool); // <--- THIS IS THE MAGIC

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    println!("Listening on port 3000...");
    axum::serve(listener, app).await.unwrap();
}

Note: PgPool is internally wrapped in an Arc (Atomic Reference Count). You can clone it cheaply. You don't need to wrap it in Arc yourself!


3. CRUD Operations: Executing Queries Inside Handlers

Now that we have a pool, let's do something useful. Let's manage a list of Tasks.

The Setup: Structs and Tables

First, ensure you have a database running. In your .env file:

env
DATABASE_URL=postgres://username:password@localhost:5432/my_database

Let's assume we have a table:

sql
CREATE TABLE tasks (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    priority INT NOT NULL
);

In Rust, we need a matching struct:

rust
use serde::{Deserialize, Serialize};
use sqlx::FromRow;

// FromRow allows sqlx to automatically map database rows to this struct
#[derive(Serialize, FromRow)] 
struct Task {
    id: i32,
    name: String,
    priority: i32,
}

// A separate struct for incoming data (we don't create the ID, the DB does)
#[derive(Deserialize)]
struct CreateTask {
    name: String,
    priority: i32,
}

The Handler: Extracting State

To use the DB in a handler, we use axum::extract::State.

A. Create (INSERT)

Notice the usage of sqlx::query_as!. This is the macro that checks your SQL at compile time.

rust
use axum::{extract::State, http::StatusCode, Json};
use sqlx::PgPool;

async fn create_task(
    State(pool): State<PgPool>, // <--- Extract the pool
    Json(payload): Json<CreateTask>,
) -> Result<(StatusCode, Json<Task>), StatusCode> {
    
    // The query! macro checks the SQL syntax against your DB schema!
    // We return the created record to the user.
    let task = sqlx::query_as!(
        Task, // Map the result to the Task struct
        "INSERT INTO tasks (name, priority) VALUES ($1, $2) RETURNING id, name, priority",
        payload.name,
        payload.priority
    )
    .fetch_one(&pool) // Execute using the pool
    .await
    .map_err(|e| {
        eprintln!("Error creating task: {}", e);
        StatusCode::INTERNAL_SERVER_ERROR
    })?;

    Ok((StatusCode::CREATED, Json(task)))
}

B. Read (SELECT)

rust
async fn get_tasks(
    State(pool): State<PgPool>
) -> Result<Json<Vec<Task>>, StatusCode> {
    
    let tasks = sqlx::query_as!(
        Task,
        "SELECT id, name, priority FROM tasks ORDER BY id"
    )
    .fetch_all(&pool)
    .await
    .map_err(|e| {
        eprintln!("Error fetching tasks: {}", e);
        StatusCode::INTERNAL_SERVER_ERROR
    })?;

    Ok(Json(tasks))
}

Industry Tip: Always select specific columns (SELECT id, name...) rather than SELECT *. It makes your application robust against database schema changes in the future.

C. Update (UPDATE)

rust
use axum::extract::Path;

async fn update_task(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
    Json(payload): Json<CreateTask>,
) -> StatusCode {
    
    let result = sqlx::query!(
        "UPDATE tasks SET name = $1, priority = $2 WHERE id = $3",
        payload.name,
        payload.priority,
        id
    )
    .execute(&pool)
    .await;

    match result {
        Ok(res) => {
            if res.rows_affected() == 0 {
                StatusCode::NOT_FOUND // ID didn't exist
            } else {
                StatusCode::OK
            }
        }
        Err(e) => {
            eprintln!("Update error: {}", e);
            StatusCode::INTERNAL_SERVER_ERROR
        }
    }
}

4. Migrations: Managing Database Schema Changes

The Problem: Schema Drift

You write code expecting a priority column. You deploy it. But the production database doesn't have that column yet because you created the table manually on your laptop. Crash. 💥

Or worse, you work on a team. Your colleague changes the DB, but your local DB is old. Your code breaks.

The Solution: Migrations

Migrations are version control for your database. They are files that describe changes (up) and how to undo them (down).

Using sqlx-cli

We don't write SQL CREATE TABLE scripts inside our Rust code. We use the CLI.

1. Install the CLI:

bash
cargo install sqlx-cli --no-default-features --features native-tls,postgres

2. Initialize the project:

bash
# Creates a _sqlx_migrations table in your DB to track version history
sqlx database create

3. Create a migration:

bash
sqlx migrate add create_tasks_table

This generates a folder migrations with a timestamped file, e.g., 20231025120000_create_tasks_table.sql.

4. Edit the Migration file:
Open the generated .sql file and add your SQL:

sql
-- Add migration script here
CREATE TABLE tasks (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    priority INT NOT NULL
);

5. Run the Migration:

bash
sqlx migrate run

Now your database is in sync!

Auto-Migration on Startup

In a real production app (especially in containers/Docker), you want the app to update the DB when it starts. Add this to your main function before starting the server:

rust
// Inside main()
// This runs any pending migrations in the /migrations folder
sqlx::migrate!()
    .run(&pool)
    .await
    .expect("Failed to migrate database");

Summary Checklist 📝

  1. Dependencies: Added sqlx (postgres + runtime-tokio) and dotenvy.
  2. State: Used PgPool wrapped in Axum State to share connections.
  3. Handlers: Used sqlx::query_as! for type-safe interaction.
  4. Migrations: Used sqlx-cli to manage schema changes and run them on startup.

You now have a production-ready data layer. Your data will survive restarts, your queries are checked by the compiler, and your database schema is versioned. You have successfully avoided the pitchfork mob! 🛡️

References & Further Reading 📚

Challenge

Challenge Instructions

Write an async function named processUserProfiles that takes an array of URL strings as its only argument. Each URL is supposed to point to a JSON object representing a user profile.

Your task is to implement the function to perform the following actions:

  1. Concurrently fetch data from all the URLs provided in the input array.
  2. Some URLs may result in network errors or point to non-existent resources. Your function must handle these errors gracefully and not terminate execution.
  3. For each successful response, parse the JSON body. A valid user profile is an object containing three specific properties: id (a number), name (a string), and isActive (a boolean).
  4. Filter out any results that were errors, did not contain valid JSON, or represented user profiles that are not active (i.e., where isActive is false). Also, discard profiles that do not strictly contain the required properties.
  5. From the remaining valid and active user profiles, extract only the name of each user.
  6. Return a single array of these names, sorted alphabetically.

Expected result

Your solution should consist of a complete implementation of the processUserProfiles function.

The function must:

  • Be async and accept a single array argument urls.
  • Utilize a promise-based mechanism like Promise.allSettled to manage concurrent requests to the provided URLs using the mockFetch function.
  • Correctly process the results, filtering for fulfilled promises that contain valid and active user profiles.
  • A valid profile must be an object with id (number), name (string), and isActive (boolean set to true).
  • The function must return a promise that resolves to an array of strings.
  • The final array must contain only the names of the active users, sorted in alphabetical order.

For example, if the function is called with:

javascript
[
  "https://api.example.com/users/1", // Alice, active
  "https://api.example.com/users/2", // Bob, inactive
  "https://api.example.com/users/3", // Charlie, active
  "https://api.example.com/users/4", // Not Found
  "https://api.example.com/users/5", // Eve, active
  "https://api.example.com/users/6", // Invalid data (missing isActive)
  "https://api.example.com/error/7"  // Network error
]

The promise returned by your function should resolve to:

javascript
["Alice", "Charlie", "Eve"]
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.