How to use SQLx with Axum

Connect Axum to SQLx by injecting a PgPool into handlers using the State extractor.

Use axum::extract::State to inject a sqlx::postgres::PgPool into your handlers and execute queries directly.

use axum::{extract::State, routing::get, Router};
use sqlx::postgres::{PgPool, PgPoolOptions};
use std::time::Duration;

#[tokio::main]
async fn main() {
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .acquire_timeout(Duration::from_secs(3))
        .connect("postgres://postgres:password@localhost")
        .await
        .expect("can't connect to database");

    let app = Router::new()
        .route("/", get(handler))
        .with_state(pool);

    axum::serve(tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap(), app).await.unwrap();
}

async fn handler(State(pool): State<PgPool>) -> String {
    let result: String = sqlx::query_scalar("select 'hello world from pg'")
        .fetch_one(&pool)
        .await
        .expect("query failed");
    result
}