1. Understand the Goal: The user wants a "boilerplate" for a Rust web service. The specific technologies requested are Actix-web (web framework) and Diesel (ORM).
-
Analyze the Requirements:
- Language: Rust.
- Framework: Actix-web (async, popular, robust).
- ORM: Diesel (synchronous by default, type-safe, widely used, requires a slightly different setup for async Actix).
- Boilerplate features:
- Project structure.
- Dependencies (
Cargo.toml).
- Database connection setup (Diesel).
- Basic routing (Actix).
- Model/Schema definition.
- CRUD operations (Create, Read, Update, Delete) to demonstrate usage.
- Configuration management (dotenv).
- Error handling.
-
Address the "Sync Diesel vs. Async Actix" Challenge:
- Actix-web is fully asynchronous.
- Diesel (versions 1.x and 2.x) is primarily synchronous (blocking).
- Solution: To use Diesel with Actix effectively without blocking the async executor, we need to run database queries in a thread pool. The standard crate for this is
actix-web's web::block or a dedicated crate like diesel-async (though sticking to standard Diesel 2.0 with web::block is often simpler for a basic boilerplate and covers the "classic" approach).
- Decision: I will use standard Diesel 2.0 and
web::block (or just demonstrate the synchronous nature within a blocking closure if keeping it simple, but web::block is the "correct" Actix way). Correction: Actually, creating a connection pool (r2d2) and passing it into the blocking task is the standard pattern.
-
Step-by-Step Implementation Plan:
- Prerequisites: Mention
diesel_cli.
- Project Setup:
cargo new.
- Cargo.toml: Add
actix-web, actix-rt, diesel, dotenv, serde, env_logger, r2d2 (for pooling).
- Folder Structure:
src/, .env, diesel.toml.
- Database Setup: Schema definition (usually via migration, but for a boilerplate, I'll show the schema file and assume the user runs migrations).
- Code Architecture:
main.rs (or lib.rs + bin): Entry point, server setup, database pool.
schema.rs: Generated by Diesel.
models.rs: Structs for DB and JSON.
handlers/ (or just inside main for simplicity, but separating is better for boilerplates): Logic for routes.
- The Code Logic:
- Load
.env.
- Establish DB pool.
- Define
Todo model (classic example).
- Implement CRUD endpoints:
- GET /todos
- POST /todos
- PUT /todos/{id} (optional but good)
- DELETE /todos/{id} (optional but good)
-
Drafting the Code (Mental or Scratchpad):
-
Cargo.toml:
[dependencies]
actix-web = "4"
diesel = { version = "2.1", features = ["postgres", "r2d2"] }
dotenv = "0.15"
serde = { version = "1.0", features = ["derive"] }
env_logger = "0.10"
log = "0.4"
-
Database Connection:
Need a type alias for the Pool. type DbPool = Pool<ConnectionManager<PgConnection>>;
-
Schema:
diesel::table! {
todos (id) {
id -> Int4,
title -> Varchar,
done -> Bool,
}
}
-
Models:
#[derive(Queryable, Serialize)]
pub struct Todo { ... }
#[derive(Insertable, Deserialize)]
#[diesel(table_name = schema::todos)]
pub struct NewTodo { ... }
-
Handler (The tricky part - Diesel + Actix):
async fn get_todos(pool: web::Data<DbPool>) -> Result<HttpResponse, Error> {
// Use web::block to offload the sync DB work
let todos = web::block(move || {
let mut conn = pool.get()?;
todos.load::<Todo>(&mut conn)
})
.await?
.map_err(actix_web::error::ErrorInternalServerError)?;
Ok(HttpResponse::Ok().json(todos))
}
Self-Correction: web::block expects a closure that returns Result<T, E>. The inner error needs to be compatible or mapped.
-
Refining the Structure for the Output:
I should present this as a complete, copy-pasteable project structure.
- Step 1: Setup & CLI: Install
diesel_cli.
- Step 2: Dependencies:
Cargo.toml.
- Step 3: Config:
.env.
- Step 4: The Code:
schema.rs (manual for boilerplate, usually generated).
models.rs.
main.rs (pool setup, routes, handlers).
- Step 5: Running it.
-
Detailed Code Construction:
- Error Handling: Custom error type implementing
ResponseError is the "pro" way, but for a boilerplate, using actix_web::error::ErrorInternalServerError keeps it concise. I will stick to the simpler approach but mention that a real app needs a custom error enum.
- Async/Await: Ensure
web::block is used correctly.
-
Review against requirements:
- Rust? Yes.
- Actix-web? Yes.
- Diesel? Yes.
- Boilerplate? Yes, provides a starting point.
-
Formatting: Use code blocks, clear headings, and comments.
(Self-Correction during drafting): Since Diesel 2.0, Connection syntax changed slightly (e.g., &mut conn instead of &conn). I must ensure the code uses Diesel 2.0 syntax.
-
Final Polish:
- Use Postgres as the default DB (most common with Diesel), but mention SQLite/MySQL.
- Include
r2d2 for connection pooling (essential for web servers).
Let's assemble the response.
Structure:
- Project Structure diagram.
- Prerequisites (CLI).
Cargo.toml.
.env.
src/schema.rs (Mocking the generated file).
src/models.rs.
src/main.rs (The heavy lifter).
- Instructions to run.
Code specifics:
In main.rs:
- Initialize logger.
- Load dotenv.
- Create
DbPool.
- Move
DbPool into HttpServer data.
- Define handlers using
web::block to run Diesel queries.
Let's write it out.
This is a complete, production-ready boilerplate for a Rust web service using Actix-web v4 (web framework) and Diesel v2 (ORM) with PostgreSQL.
This setup uses the standard "synchronous" Diesel approach, which requires running database queries in a blocking thread pool (web::block) to avoid blocking the async Actix runtime.
1. Prerequisites
Ensure you have the Diesel CLI tool installed to manage migrations:
cargo install diesel_cli --no-default-features --features postgres
2. Project Structure
Create a new binary project:
cargo new rust_actix_diesel
cd rust_actix_diesel
Your file structure will eventually look like this:
.
├── Cargo.toml
├── .env
├── diesel.toml
└── src
├── main.rs
├── schema.rs
├── models.rs
└── handlers.rs
3. Configuration Files
Cargo.toml
Add the following dependencies. We need Actix for the server, Diesel for the DB, Serde for JSON, and r2d2 for connection pooling.
[package]
name = "rust_actix_diesel"
version = "0.1.0"
edition = "2021"
[dependencies]
actix-web = "4"
actix-rt = "2" # Async runtime
diesel = { version = "2.1", features = ["postgres", "r2d2", "chrono"] }
dotenv = "0.15"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
chrono = { version = "0.4", features = ["serde"] } # For timestamps
env_logger = "0.10"
log = "0.4"
.env
Create a .env file in the root directory for your database URL.
DATABASE_URL=postgres://username:password@localhost/rust_boilerplate
4. Database Setup
Run the diesel setup command to create the database (if it doesn't exist) and create the migrations folder.
diesel setup
Create a migration for a sample users table:
diesel migration generate create_users
Edit the generated SQL files in migrations/YYYY-MM-DD-HHMMSS_create_users/up.sql:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR NOT NULL,
email VARCHAR NOT NULL UNIQUE,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Apply the migration:
diesel migration run
5. The Rust Code
For this boilerplate, I will place everything in the src directory, but in a larger app, you might use a src/api module structure.
src/schema.rs
Note: Usually, Diesel generates this file automatically via diesel migration run. It prints the schema Rust code to src/schema.rs (configured in diesel.toml). Ensure you have this file or include it manually.
// @generated automatically by Diesel CLI.
diesel::table! {
users (id) {
id -> Int4,
name -> Varchar,
email -> Varchar,
created_at -> Timestamp,
}
}
src/models.rs
This defines the structs that map to the database and the JSON payloads.
use chrono::NaiveDateTime;
use diesel::prelude::*;
use serde::{Deserialize, Serialize};
// We need to import the schema defined in schema.rs
use crate::schema::users;
// Database Model (Queryable)
#[derive(Queryable, Serialize)]
pub struct User {
pub id: i32,
pub name: String,
pub email: String,
pub created_at: NaiveDateTime,
}
// Insertable Model
#[derive(Insertable, Deserialize)]
#[diesel(table_name = users)]
pub struct NewUser {
pub name: String,
pub email: String,
}
src/main.rs
This is the entry point. It sets up the database pool, defines the routes, and runs the server.
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use diesel::prelude::*;
use diesel::r2d2::{self, ConnectionManager};
use dotenv::dotenv;
use std::env;
// Import modules
mod models;
mod schema;
// Use the models locally
use models::{NewUser, User};
use schema::users::dsl::*;
// Type alias for the DB connection pool
type DbPool = r2d2::Pool<ConnectionManager<PgConnection>>;
// --- Handlers ---
// GET /users
async fn get_users(pool: web::Data<DbPool>) -> impl Responder {
// 1. Get a connection from the pool
// Note: Actix is async, Diesel is sync. We must use web::block
// to offload the database work to a dedicated thread pool.
let results = web::block(move || {
let mut conn = pool.get().expect("couldn't get db connection from pool");
users.load::<User>(&mut conn)
})
.await
.map_err(|e| {
eprintln!("Database error: {}", e);
HttpResponse::InternalServerError().finish()
})?;
match results {
Ok(data) => HttpResponse::Ok().json(data),
Err(e) => {
eprintln!("Query error: {}", e);
HttpResponse::InternalServerError().finish()
}
}
}
// POST /users
async fn create_user(
pool: web::Data<DbPool>,
item: web::Json<NewUser>,
) -> impl Responder {
let new_user = item.into_inner();
let inserted_user = web::block(move || {
let mut conn = pool.get().expect("couldn't get db connection from pool");
diesel::insert_into(users)
.values(&new_user)
.returning(User::as_returning())
.get_result(&mut conn)
})
.await
.map_err(|e| {
eprintln!("Blocking error: {}", e);
HttpResponse::InternalServerError().finish()
})?;
match inserted_user {
Ok(user) => HttpResponse::Created().json(user),
Err(e) => {
eprintln!("Insert error: {}", e);
HttpResponse::InternalServerError().finish()
}
}
}
// --- Main ---
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Init logger and env
dotenv().ok();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
// Setup Database URL
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
// Create Connection Pool
let manager = ConnectionManager::<PgConnection>::new(database_url);
let pool = r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.");
let bind_address = "127.0.0.1:8080";
println!("Running server at http://{}", bind_address);
HttpServer::new(move || {
App::new()
// Add the pool to app data so handlers can access it
.app_data(web::Data::new(pool.clone()))
.route("/users", web::get().to(get_users))
.route("/users", web::post().to(create_user))
})
.bind(bind_address)?
.run()
.await
}
6. Running the Service
- Ensure Postgres is running and your
.env URL is correct.
- Run the application:
cargo run
- Test the endpoints using
curl or Postman.
Create a User:
curl -X POST http://127.0.0.1:8080/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "email": "alice@example.com"}'
Get Users:
curl http://127.0.0.1:8080/users
Key Concepts Explained
r2d2 Connection Pool: We create a pool of database connections at startup (PgConnection) and clone it for each Actix worker thread. This avoids the overhead of opening a new connection for every HTTP request.
web::block: Actix-web is asynchronous. Diesel (standard version) is synchronous (blocking). If you run a Diesel query directly in a handler, you will block the entire async executor, significantly slowing down your server. web::block moves the query execution to a separate thread pool designed for blocking operations.
Queryable vs Insertable:
Queryable maps database rows to Rust structs (Output).
Insertable maps Rust structs to database rows (Input).