The sqlx crate
Learn what the sqlx crate is, how to add it to an Axum project, and what it gives you for talking to PostgreSQL from Rust
SQLx is a Rust library, called a crate, that lets a Rust program talk to a SQL database. It is async, which means database work runs without blocking the rest of the program, and it is written in pure Rust, which means it does not need a C database library installed on the machine. You write plain SQL strings, and SQLx sends them to the database, reads the rows back, and converts each column into a Rust value.
Where This Fits
The comparison pages looked at three ways of working with a database from Rust: SQLx, SeaORM, and Diesel. This page starts the SQLx path. SQLx is the foundation for the rest of this cluster: the pool, the connection string, the checked query macros, and the migrations all come from this one crate. Nothing in this cluster works until the crate is in the project and compiling.
Think of SQLx as a translator who sits between your Rust code and the database. Your code speaks Rust, the database speaks the PostgreSQL wire protocol, and SQLx translates in both directions. It also checks your work: with the query macros it asks the real database whether your SQL is valid while your code is still compiling, so a typo in a column name becomes a compile error instead of a crash at midnight.
The Smallest Working Version
A crate is added to a project by listing it in Cargo.toml, the file that names the project and its dependencies. A dependency is another crate your project uses. Add one line for SQLx, then check that the project still compiles.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["postgres", "runtime-tokio", "macros", "derive"] }
Run the check:
cargo check
The output ends with a line like this when everything is fine:
Finished `dev` profile [unoptimized + debuginfo] target(s)
That line means the crate downloaded, compiled, and linked without errors. The project does not talk to a database yet. It only proves the dependency is installed correctly, which is the right first step: if this fails, the problem is the setup, not your SQL.
A Clean Check Means the Crate Is In:
If cargo check finishes with no errors after adding the line, SQLx 0.9.0 is installed and ready. You do not need a running database for this step. The database only becomes necessary once the code first opens a connection or checks a query.
The version number matters. version = "0.9" tells Cargo to use the newest 0.9 release, which is 0.9.0. Older tutorials show version = "0.8" or version = "0.7", and their feature names and behaviour differ in places this chapter points out as they come up. Pinning to the 0.9 line keeps the project on the version these pages were checked against.
What the Feature Names Mean
The features list after the version switches on parts of the crate. A feature is an optional piece of a crate that Cargo only builds when you ask for it. SQLx is built this way because it supports several databases and several async runtimes, and no single project needs all of them. The four features on this line are the ones this project needs, and the first two each have their own page next.
postgres switches on the PostgreSQL driver: the code that speaks the PostgreSQL wire protocol, the PgPool and PgRow types, and the PostgreSQL-specific query handling. Without it, SQLx has no idea what PostgreSQL is, and any code that mentions Postgres types fails to compile.
runtime-tokio switches on support for Tokio, the async runtime Axum is built on. A runtime is the engine that runs async code: it schedules tasks, wakes them when work is ready, and moves them between threads. SQLx needs to know which runtime the program uses because it runs its network work on that runtime.
macros switches on the query! and query_as! macros, which check SQL against a real database while the code compiles. derive switches on the derive macros such as FromRow, which generate the row-mapping code for structs used with the runtime query functions. One more piece, migrate, comes along without being listed, because it is on by default: it provides the migration support.
Old Feature Names No Longer Exist:
Tutorials written for SQLx 0.7 or 0.8 often show a combined feature such as runtime-tokio-rustls or runtime-tokio-native-tls, one name that picked the runtime and the TLS backend together. Those combined names were removed in SQLx 0.9.0. The replacement is two separate features, for example runtime-tokio plus tls-rustls. If you copy a dependency line from an old tutorial and Cargo reports that the feature does not exist, that is the cause. Use the separate names from this page.
What SQLx Is Not
SQLx is not an ORM. An ORM, short for object-relational mapper, is a library that hides SQL behind Rust methods: you call something like users.filter(name.eq("Asha")) and the library builds the SQL for you. SQLx does not do that. You write the SQL yourself, as a string, and SQLx checks it and runs it. This is a deliberate design choice, and it has two consequences a beginner should understand from the start.
First, you need to know SQL. There is no way around it with SQLx, and that is the point: the SQL you write is the SQL that runs, so what you learn about the database transfers directly. A query that is slow in SQLx is slow for the same reason it would be slow in any other tool, and the fix is the same.
Second, the compiler can check your SQL. Because the SQL is a plain string passed to a macro, the macro can send it to a real database at compile time and ask whether the table exists, whether the columns exist, and what types they have. A misspelt column name then fails the build instead of failing in production. That check is the headline feature of SQLx, and two pages in this cluster are devoted to the two macros that perform it.
The Pieces SQLx Gives You
SQLx is one crate, but it hands you several tools that each solve one part of talking to a database. Each tool has its own page, so this section only names them and says what job each one does, in one or two sentences each.
A connection pool holds a set of open database connections and hands them out to handlers as needed. Opening a fresh connection for every request would be slow, so the pool keeps connections ready and reuses them. The PostgreSQL pool type is PgPool, and it is the value the app hands to every handler through Axum state.
A connection string, kept in the DATABASE_URL environment variable, tells SQLx where the database lives: which machine, which port, which database, and which user and password to log in with. It is one line of text, and the whole project reads it from one place.
Query functions and macros run SQL. The plain functions, sqlx::query and sqlx::query_as, run at runtime with no compile-time checking. The macros, query! and query_as!, check the SQL against a real database while the code compiles, and query_as! maps each row straight into a Rust struct.
Migrations are versioned SQL files that build the database schema step by step, one file per change. The sqlx-cli command line tool creates and runs them, and the migrate feature lets the application run them itself at startup.
Why One Crate Instead of Three
A beginner might expect three separate libraries: one for connections, one for queries, one for migrations. SQLx bundles them because they share one piece of machinery, the PostgreSQL driver, and because the pieces need to agree with each other. The query macros need to know the same connection details the pool uses, and the migration runner needs the same driver the queries use. One crate means one version to keep up to date and one set of feature flags to get right.
The trade is compile time. SQLx is a large crate, and the first build downloads and compiles many dependencies. On this project the first cargo check after adding the line takes a few minutes, and later builds reuse that work. That cost is paid once, and it buys the compile-time query checking that no smaller crate offers.
The Project Shape for This Chapter
Every page in this cluster works on the same project, so the files stay the same from here on and only grow. The project is the one from the earlier chapters, with three small changes: the SQLx dependency above, a db module that creates the pool, and a pool passed into the app function.
use axum_project::{app, db::create_pool};
#[tokio::main]
async fn main() {
let database_url = std::env::var("DATABASE_URL").expect(
"DATABASE_URL must be set, for example postgres://postgres:password@127.0.0.1:5432/ch12_sqlx",
);
let pool = create_pool(&database_url)
.await
.expect("failed to create the database pool");
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app(pool)).await.unwrap();
}
pub mod db;
pub mod errors;
pub mod handlers;
use axum::{Router, routing::get};
use sqlx::postgres::PgPool;
pub fn app(pool: PgPool) -> Router {
Router::new()
.route("/users", get(handlers::list_users))
.route("/users/{id}", get(handlers::get_user))
.with_state(pool)
}
main reads the connection string from the environment, asks the db module to build a pool from it, and hands the pool to app. The app function takes the pool as a parameter and stores it as router state with with_state, which is how Axum makes one shared value available to every handler. The errors module is the AppError type from the error handling chapter, unchanged. The handlers module holds the user handlers, which start out using plain SQLx calls and gain the checked macros as the cluster progresses.
The db module itself is one function at this stage:
use sqlx::postgres::{PgPool, PgPoolOptions};
pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
PgPoolOptions::new()
.max_connections(5)
.connect(database_url)
.await
}
create_pool builds a pool with room for five connections and connects it to the URL it is given. If the database is unreachable or the credentials are wrong, it returns a sqlx::Error, and main stops with the expect message. The pool options and the connection string each get a full page of their own, so this file is shown here only so the shape is concrete.
How the Pieces Fit Together
Cargo.toml lists sqlx 0.9 with postgres and runtime-tokio
|
v
main reads DATABASE_URL from the environment
|
v
db::create_pool builds a PgPool from that URL
|
v
app(pool) stores the pool as router state
|
v
handlers take State<PgPool> and run SQL through it
The flow is a straight line: dependency, connection string, pool, router state, handler. Every page in this cluster fills in one box of that diagram, and none of them changes the shape. When something goes wrong later, this diagram is the map for finding which box broke: a compile error about a missing type points at the dependency line, a connection error points at the URL or the pool, and a query error points at the handler.
Checking the Setup Without a Database
Not every check needs a database. This test proves the project compiles and the router builds, with no database involved at all:
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use sqlx::postgres::PgPool;
use tower::ServiceExt;
#[tokio::test]
async fn test_users_route_exists() {
let pool = PgPool::connect_lazy("postgres://postgres:password@127.0.0.1:5432/ch12_sqlx")
.unwrap();
let router = app(pool);
let response = router
.oneshot(
Request::builder()
.uri("/users")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
PgPool::connect_lazy builds a pool value without opening any connection, which is why this test runs with no database. The lazy pool is only good for checks like this one: the moment a handler actually runs a query through it, the pool tries to connect for real. That split is worth remembering, because it explains a confusing result: a test like this one can pass while the real server fails to start, since the test never touches the database. The test needs one more dependency:
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run it with cargo test. It returns 200 only if the table and the data exist; before the migrations run it returns 500, which is the honest answer for a handler whose table is missing. The migration pages make that 200 real.
Common Beginner Mistakes
Adding SQLx Without Any Features
# Wrong - compiles, but cannot do anything
sqlx = "0.9"
A bare version with no features compiles fine, because SQLx with no database driver is still a valid crate. But the moment the code mentions PgPool or postgres, the compiler reports that the type does not exist. The fix is the feature list from this page. The confusing part is that the error points at the code, not at Cargo.toml, so a beginner can stare at a correct-looking use sqlx::postgres::PgPool; line for a long time. When a SQLx type is reported missing, check the features first.
A Missing Feature Looks Like a Missing Type:
If the compiler says it cannot find PgPool, PgRow, or anything under sqlx::postgres, the cause is almost always the missing postgres feature, not a wrong import. The same applies to runtime-tokio: without it, pool creation fails with an error about no runtime being enabled. Read the feature list before rewriting the code.
Copying a Dependency Line From an Old Tutorial
# Wrong on SQLx 0.9 - this feature no longer exists
sqlx = { version = "0.9", features = ["runtime-tokio-rustls", "postgres"] }
Cargo rejects this with an error naming the unknown feature. The combined runtime and TLS features were removed in 0.9.0, and the fix is to split them: runtime-tokio on its own, plus a separate TLS feature only if the database needs TLS. A local PostgreSQL does not, so this project lists no TLS feature at all.
Expecting the Crate to Create the Database
Adding SQLx does not create a database, a table, or a user. It only gives the program the ability to talk to a database that already exists. The database itself is created by the database server setup and by migrations, which the later pages cover. If create_pool fails with a connection error right after adding the dependency, the crate is fine and the database is simply not there yet.
The Full Setup in One Place
Here is everything from this page together: the dependency line, the three source files in their starting shape, and the test dependency. The handlers module is the only file not shown in full here, because its contents change on almost every page that follows, and each of those pages shows its own version.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["postgres", "runtime-tokio", "macros", "derive"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
use sqlx::postgres::{PgPool, PgPoolOptions};
pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
PgPoolOptions::new()
.max_connections(5)
.connect(database_url)
.await
}
pub mod db;
pub mod errors;
pub mod handlers;
use axum::{Router, routing::get};
use sqlx::postgres::PgPool;
pub fn app(pool: PgPool) -> Router {
Router::new()
.route("/users", get(handlers::list_users))
.route("/users/{id}", get(handlers::get_user))
.with_state(pool)
}
Run cargo check to confirm the setup. The database work starts with the postgres feature, which gets its own close look.
Summary
SQLx is a toolkit, not a framework: it gives a Rust program the pieces for talking to PostgreSQL, and the program assembles them. The single most important insight on this page is the feature list, because it is the one place where a small mistake produces a confusing error far away from the cause. postgres picks the database, runtime-tokio picks the runtime, and everything else in the cluster builds on those two choices.
The decision the reader makes here is small but real: SQLx means writing SQL by hand and letting the compiler check it, instead of letting a library write the SQL. That choice shapes every page that follows, from the pool that holds the connections to the macros that check the queries. The next thing to understand is what the postgres feature actually switches on inside the crate, and why the same crate can support four different databases from one dependency line.