Learn Actix Web · 8/13

Database Integration (using SQLx)

7 min read

Welcome back, Rustacean! 🦀

If building a web server is like building a house, the database is the basement where you store all your holiday decorations, old yearbooks, and that treadmill you swore you'd use. Without it, your application has the memory of a goldfish—restart the server, and poof, everything is gone.

In this module, we are connecting Actix Web to a database using SQLx.

Why SQLx?
Unlike traditional ORMs (Object-Relational Mappers) that hide SQL behind complex abstractions, SQLx embraces SQL. It provides compile-time checked queries. This means if you make a typo in your SQL command or try to select a column that doesn't exist, your code won't even compile. It's like having a strict librarian looking over your shoulder while you type. 📚


1. Setting up an Async Connection Pool

What is a Connection Pool?

Imagine a popular nightclub (your database). If every visitor (request) had to knock, wait for the bouncer to open the door, check their ID, and let them in one by one, the line would be miles long.

A Connection Pool is like having 10 pre-approved VIP doors always open. When a request comes in, it grabs an open door, does its business, and leaves, freeing the door for the next person.

In technical terms, establishing a TCP connection to a database is expensive (slow). A pool keeps a set of connections open and reuses them.

📜 The Setup

First, ensure your Cargo.toml has the necessary dependencies. We will use PostgreSQL for these examples, but SQLx supports MySQL and SQLite too.

toml
[dependencies]
actix-web = "4"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
# "runtime-tokio-rustls" tells SQLx to use the Tokio runtime (same as Actix)
# "postgres" enables Postgres support
# "macros" enables the compile-time checks
sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "macros", "uuid", "chrono"] }
dotenv = "0.15" # For managing environment variables

💻 The Code

We typically configure the pool in main.rs before starting the HTTP server.

rust
use actix_web::{web, App, HttpServer};
use sqlx::postgres::PgPoolOptions;
use std::env;
use dotenv::dotenv;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // 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
    // Interesting Fact: A "pool" isn't just a bag of connections. 
    // It's a smart manager that handles timeouts, health checks, and lazy loading! 🏊
    let pool = PgPoolOptions::new()
        .max_connections(5) // Don't overwhelm your DB!
        .connect(&database_url)
        .await
        .expect("Failed to connect to Postgres.");

    println!("✅ Connection to the database is successful!");

    HttpServer::new(move || {
        App::new()
            // We'll inject the pool here in the next step!
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

2. Injecting the DB Pool into Actix App State

The Problem: Sharing is Hard

Rust ownership rules are strict. You created the pool in main, but your route handlers (functions that respond to web requests) live in different threads and need access to that pool.

The Solution: web::Data

Actix Web provides a wrapper called web::Data<T>. It's essentially an Arc (Atomic Reference Counted) smart pointer designed specifically for the framework. It allows multiple threads to share ownership of the pool safely.

💻 The Code

Modify the HttpServer block from the previous step:

rust
    // ... inside main()

    HttpServer::new(move || {
        App::new()
            // 4. Register the pool as "App Data"
            // clone() here is cheap; it just increments a reference counter.
            .app_data(web::Data::new(pool.clone())) 
            .service(get_all_users) // We will create this handler soon
    })
    // ...

Now, any handler can ask for web::Data<PgPool>, and Actix will magically hand it over.


3. Performing CRUD Operations in Handlers

CRUD stands for Create, Read, Update, Delete. These are the bread and butter of any web app.

Industry Standard Tip: In large production apps, we often separate database logic into a "Repository" or "Service" layer. However, for learning, putting query logic inside handlers is perfectly fine and much clearer.

First, let's define a Model (Struct) that represents our data.

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

// FromRow allows SQLx to automatically map a database row to this struct
#[derive(Debug, Serialize, Deserialize, FromRow)]
struct User {
    id: i32,
    username: String,
    email: String,
}

3.1 READ (Select)

We use the sqlx::query_as! macro. This macro checks your SQL syntax at compile time.

rust
use actix_web::{get, web, HttpResponse, Responder};
use sqlx::PgPool;

#[get("/users")]
async fn get_all_users(pool: web::Data<PgPool>) -> impl Responder {
    // "pool" is a wrapper. pool.get_ref() gives us the actual PgPool.
    
    // query_as! asks for the Struct (User) and the SQL query.
    let result = sqlx::query_as!(
        User,
        "SELECT id, username, email FROM users"
    )
    .fetch_all(pool.get_ref()) // fetch_all returns a Vec<User>
    .await;

    match result {
        Ok(users) => HttpResponse::Ok().json(users),
        Err(_) => HttpResponse::InternalServerError().body("Error fetching users"),
    }
}

3.2 CREATE (Insert)

When inserting, we often want to return the ID of the newly created item.

rust
#[derive(Deserialize)]
struct CreateUserRequest {
    username: String,
    email: String,
}

#[post("/users")]
async fn create_user(
    pool: web::Data<PgPool>, 
    payload: web::Json<CreateUserRequest>
) -> impl Responder {
    
    let result = sqlx::query!(
        "INSERT INTO users (username, email) VALUES ($1, $2) RETURNING id, username, email",
        payload.username,
        payload.email
    )
    .fetch_one(pool.get_ref())
    .await;

    match result {
        Ok(record) => {
            // We can manually map the anonymous record to our User struct
            let new_user = User {
                id: record.id,
                username: record.username,
                email: record.email,
            };
            HttpResponse::Created().json(new_user)
        },
        Err(e) => {
            eprintln!("Database error: {:?}", e);
            HttpResponse::InternalServerError().body("Failed to create user")
        }
    }
}

3.3 UPDATE & DELETE

These follow the same pattern.

rust
#[delete("/users/{id}")]
async fn delete_user(
    pool: web::Data<PgPool>, 
    path: web::Path<i32>
) -> impl Responder {
    let user_id = path.into_inner();

    let result = sqlx::query!("DELETE FROM users WHERE id = $1", user_id)
        .execute(pool.get_ref())
        .await;

    match result {
        Ok(rows) => {
            if rows.rows_affected() == 0 {
                HttpResponse::NotFound().body("User not found")
            } else {
                HttpResponse::Ok().body("User deleted")
            }
        },
        Err(_) => HttpResponse::InternalServerError().body("Error deleting user")
    }
}

4. Handling and Translating Database Errors

The Problem: unwrap() is Evil 😈

In the examples above, we manually matched Ok and Err. If we had 50 routes, that would be a lot of repetitive match blocks.

The Solution: The ResponseError Trait

Actix Web allows you to define your own Error type. If your handler returns Result<T, MyError>, Actix will automatically convert MyError into an HTTP Response.

Step 1: Define a Custom Error

rust
use actix_web::{error, http::StatusCode, HttpResponse};
use derive_more::{Display, Error}; // Optional crate to save boilerplate

#[derive(Debug, Display, Error)]
enum MyApiError {
    #[display(fmt = "Internal Server Error")]
    InternalError,

    #[display(fmt = "Bad Request: {}", _0)]
    BadRequest(String),

    #[display(fmt = "Resource not found")]
    NotFound,
}

// Step 2: Implement ResponseError
impl error::ResponseError for MyApiError {
    fn error_response(&self) -> HttpResponse {
        HttpResponse::build(self.status_code())
            .body(self.to_string())
    }

    fn status_code(&self) -> StatusCode {
        match *self {
            MyApiError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
            MyApiError::BadRequest(_) => StatusCode::BAD_REQUEST,
            MyApiError::NotFound => StatusCode::NOT_FOUND,
        }
    }
}

Step 3: Map SQLx Errors to Custom Error
Now we can implement From<sqlx::Error> for MyApiError to handle the conversion automatically.

rust
impl From<sqlx::Error> for MyApiError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => MyApiError::NotFound,
            _ => {
                // Log the actual error for the developer
                eprintln!("Database error: {:?}", error);
                // Return a generic error to the user for security
                MyApiError::InternalError
            }
        }
    }
}

Step 4: Clean Handlers! ✨
Look how clean the handler becomes using the ? operator:

rust
#[get("/users/{id}")]
async fn get_user_by_id(
    pool: web::Data<PgPool>, 
    path: web::Path<i32>
) -> Result<HttpResponse, MyApiError> { // Return Result
    
    let user = sqlx::query_as!(
        User,
        "SELECT * FROM users WHERE id = $1",
        path.into_inner()
    )
    .fetch_one(pool.get_ref())
    .await?; // The '?' automatically converts sqlx::Error -> MyApiError!

    Ok(HttpResponse::Ok().json(user))
}

If the user isn't found, fetch_one returns RowNotFound, which our From impl converts to MyApiError::NotFound, which Actix converts to a 404 HTTP response. Magic! 🎩


📚 Further Reading & References

Happy Coding! May your queries be fast and your connections never leak. 🚀

Challenge

You are tasked with building the backend logic for a product management system using Actix Web and SQLx. Your goal is to implement the complete CRUD (Create, Read, Update, Delete) functionality for a Product entity and create a robust custom error handling mechanism.

Assume the database has a products table with the following schema:
id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, price NUMERIC(10, 2) NOT NULL, stock INT NOT NULL

Your tasks are:

  1. Implement CRUD Handlers: Complete the four handler functions (create_product, get_product, update_product, delete_product) using the appropriate sqlx macros.
    • create_product: Should insert a new product and return the newly created product object with a 201 Created status.
    • get_product: Should retrieve a product by its ID. If found, return the product object with a 200 OK status. If not found, it should trigger a NotFound error.
    • update_product: Should update an existing product's details by its ID and return the updated product object with a 200 OK status. If the product ID does not exist, it should trigger a NotFound error.
    • delete_product: Should delete a product by its ID. If successful, return a 204 No Content status. If the product ID does not exist, it should trigger a NotFound error.
  2. Implement Custom Error Handling:
    • Define a custom error enum ApiError with two variants: DatabaseError(sqlx::Error) and NotFound.
    • Implement the std::fmt::Display and std::error::Error traits for ApiError.
    • Implement the actix_web::ResponseError trait for ApiError. This implementation should map ApiError::NotFound to an HTTP 404 Not Found status and ApiError::DatabaseError to an HTTP 500 Internal Server Error.
    • Implement From<sqlx::Error> for ApiError to allow for the automatic conversion of SQLx errors using the ? operator.

Fill in the todo!() sections in the provided initial code to complete the challenge.

Expected result

Your completed code should correctly implement all the todo!() sections.

  1. ApiError Implementations:

    • The Display implementation should provide a descriptive error message for each variant.
    • The ResponseError implementation should return StatusCode::NOT_FOUND for the NotFound variant and StatusCode::INTERNAL_SERVER_ERROR for the DatabaseError variant.
    • The From<sqlx::Error> implementation should wrap the incoming sqlx::Error in the ApiError::DatabaseError variant.
  2. create_product Handler:

    • Should use sqlx::query_as! with an INSERT INTO products ... RETURNING * statement.
    • The query should be parameterized to prevent SQL injection.
    • It must call .fetch_one() on the query and await the result, using the ? operator for error propagation.
    • On success, it should return an HttpResponse::Created() with the new product serialized as JSON in the body.
  3. get_product Handler:

    • Should use sqlx::query_as! with a SELECT * FROM products WHERE id = $1 statement.
    • It must call .fetch_optional() on the query and await the result, using ?.
    • It must handle the resulting Option<Product>. If Some(product), return HttpResponse::Ok().json(product). If None, return Err(ApiError::NotFound).
  4. update_product Handler:

    • Should use sqlx::query_as! with an UPDATE products SET ... WHERE id = $1 RETURNING * statement.
    • It must call .fetch_optional() on the query and await the result, using ?.
    • It should handle the Option<Product> result similarly to get_product, returning the updated product on Some and an ApiError::NotFound on None.
  5. delete_product Handler:

    • Should use sqlx::query! with a DELETE FROM products WHERE id = $1 statement.
    • It must call .execute() on the query and await the result, using ?.
    • It must check the rows_affected() on the result. If 0, return Err(ApiError::NotFound). Otherwise, return a successful HttpResponse::NoContent().
rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.