Axum is the most popular web framework in Rust at the time of writing. In this post, I'll show an easy and ergonomic pattern for connecting to a database using SQLx and Axum.
This is a small response to a question on a reddit thread about how to structure SQLx queries in Axum. The pattern I'll show here is not the only way to do it, but it's one that I've found to be simple and effective.
TL;DR: Store the database pool in your application state, create a struct to hold your queries, and
use the FromRef
trait to simplify the interaction between your handlers and the database.