database_url field

Learn what the database_url field holds, how the connection pool uses it to reach Postgres, and how the same value feeds the compile-time query checks and the test macro

The database_url field is the AppConfig field that holds the Postgres connection string. It is one line of text that says where the database lives and how to log in: which machine, which port, which database, and which username and password to use. The program reads it once at startup, hands it to the connection pool, and the pool opens connections with it for the rest of the run.

Where This Fits

The struct page built the whole AppConfig with four fields and a loader. This page takes the first field and follows it all the way to the database. The field itself is simple, a String that arrives from the DATABASE_URL environment variable, but the string has four different readers, and each one reads it at a different time: the application at startup, the migration commands when they run, the checked query macros at compile time, and the test macro at test time. Understanding the field means understanding all four readers, because a value that works for one and fails for another is the most common configuration surprise in a database-backed server.

Think of the field as the address written on a delivery slip. The slip is filled in once, and then the driver, the warehouse, and the returns desk all read the same slip. If the slip is wrong, every one of them goes to the wrong place, and fixing it in one place fixes it for all of them.

The Smallest Working Version

Start with the struct, the loader line for this field, and a main that builds a pool from it. The pool module is the same shape used for the users table work: a PgPoolOptions with a small connection cap.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "=0.9.0", features = ["runtime-tokio", "postgres", "macros", "derive", "migrate"] }
dotenvy = "=0.15.7"
src/config.rs
use std::net::SocketAddr;

#[derive(Clone)]
pub struct AppConfig {
    pub database_url: String,
    pub listen_address: SocketAddr,
    pub rust_log: String,
    pub jwt_secret: String,
}

impl AppConfig {
    pub fn from_env() -> Result<AppConfig, String> {
        let database_url = std::env::var("DATABASE_URL").map_err(|_| {
            "DATABASE_URL must be set, for example \
             postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config"
                .to_string()
        })?;
        let listen_address = std::env::var("LISTEN_ADDRESS")
            .unwrap_or_else(|_| "127.0.0.1:3000".to_string())
            .parse::<SocketAddr>()
            .map_err(|_| {
                "LISTEN_ADDRESS must be an address like 127.0.0.1:3000".to_string()
            })?;
        let rust_log = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
        let jwt_secret =
            std::env::var("JWT_SECRET").map_err(|_| "JWT_SECRET must be set".to_string())?;
        Ok(AppConfig {
            database_url,
            listen_address,
            rust_log,
            jwt_secret,
        })
    }
}
src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/lib.rs
pub mod config;
pub mod db;
src/main.rs
use axum_project::{config::AppConfig, db::create_pool};

#[tokio::main]
async fn main() {
    let _ = dotenvy::dotenv();
    let config = match AppConfig::from_env() {
        Ok(config) => config,
        Err(error) => {
            eprintln!("Configuration error: {error}");
            std::process::exit(1);
        }
    };
    let _pool = create_pool(&config.database_url)
        .await
        .expect("failed to create the database pool");
    println!("Connected to the database");
}

The .env file holds the local value. The user axumdocs with password axumdocs is the local development user, and ch21_config is the database for this work. Nothing here is a real credential, and the same shape with different values is what a production machine would hold.

.env
DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config
LISTEN_ADDRESS=127.0.0.1:3000
RUST_LOG=info
JWT_SECRET=test-secret-only-for-local-development

The database itself must exist before the program runs. Create it once with psql, the command-line tool for talking to Postgres, as the axumdocs user already has from the earlier database work.

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/postgres" -c "CREATE DATABASE ch21_config OWNER axumdocs;"

Run the program and it prints one line. That line proves the whole chain: the variable was read, the string was passed to the pool, and the pool opened a connection to the database named at the end of the string.

Connected to the database

Working Setup:

If that line appears, the field works end to end. The value came from the environment, the pool connected with it, and the database named in the string accepted the connection. A failure here is a failure in the string, and the errors in the mistakes section say how to read them.

Reading the String Part by Part

The connection string has five parts, and each one can go wrong in its own way. A beginner who can read the string can diagnose most connection failures without guessing.

postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config

The scheme, postgres://, picks the driver. SQLx supports other schemes, such as mysql:// and sqlite://, and the scheme is how the crate knows which driver to use. A string with no scheme fails before any network work happens, with an error about the configuration.

The username and password come next, separated by a colon, before the @ sign. The username is the Postgres role the program logs in as, and the password is that role's password. A wrong password is rejected by the server at once with password authentication failed for user "axumdocs", where the name in quotes is the username that failed. Special characters in a password, such as @, :, /, or #, must be percent-encoded, which means written as % followed by two hexadecimal digits, because those characters have meaning inside a URL. A password of p@ss becomes p%40ss in the string.

The host is the machine. 127.0.0.1 is the loopback address, which always means the machine the program itself runs on. A hostname such as db.example.com means a remote machine, reached over the network. A wrong host fails slowly: the pool retries until the acquire timeout, thirty seconds by default, and then reports pool timed out while waiting for an open connection.

The port is the channel. Postgres listens on 5432 unless it was configured otherwise, and 5432 is the default. A wrong port behaves exactly like a wrong host, because nothing is listening on that channel, so the pool waits the full timeout and reports the same message.

The database name is the last part, after the slash. A Postgres server holds many databases, and the name picks one. A name that does not exist is rejected at once, with database "no_such_db" does not exist. That instant failure was checked by running the server with a made-up database name: the pool creation panicked with exactly that message, naming no_such_db, before the server bound any port.

How the Pool Uses the Field

The pool takes the field value by reference, &config.database_url, and the .connect() call opens the first connection at once. That first connection is a check as much as an opening: if the server is down, the password is wrong, or the database does not exist, this is where the error appears, wrapped in a Result. The expect in main turns it into a panic with the message failed to create the database pool, which stops the program before any request is served.

The pool keeps the string for later too. Every new connection it opens uses the same value, so the field is read once and then used many times. That is why the field is a plain String in the struct and not something more elaborate: the pool wants text, the program hands it text, and the text never changes during the run.

The max_connections(5) call caps the pool at five open connections. Five is enough for a learning project and for tests, because a request rarely needs more than one connection at a time, and a small cap keeps a run of parallel tests from opening more connections than Postgres allows. The cap is a property of the pool, not of the string, and it lives in the pool module, not in the config.

The Field Is an Address, Not a Connection:

The field holds text, and the pool holds connections. Reading the field does not touch the network, and building the struct does not check that the database exists. The first network work happens in create_pool, which is why a typo in the string is discovered there and not in the loader. The validation page adds a shape check to the loader, but only the pool can prove the database answers.

The Same Value Has Four Readers

This is the part of the field that surprises beginners. The application is not the only reader of DATABASE_URL. Four different tools read the same variable, at four different times, and a value that satisfies one can still break another.

The application reads it at startup, through the field, to build the pool. That is the reader on this page.

The migration commands read it when they run. The sqlx-cli tool and the migrate! macro both find the database through the same variable, so a variable pointing at the wrong database migrates the wrong database too. Before running a migration command, print the variable and check the database name at the end of the string.

The checked query macros, query! and query_as!, read it at compile time. When code uses one of those macros, the compiler connects to the database while building and checks the SQL against the real tables. Without the variable set while compiling, the build fails. That failure was checked directly: compiling a test file that uses query! with no DATABASE_URL set and no .env file present stops with set DATABASE_URL to use query macros online, or run cargo sqlx prepare to update the query cache. With the .env file restored, the same file compiles, because the macros read the file as well as the exported variable.

The #[sqlx::test] macro reads it at test time. When a test runs, the macro connects to the server named in the variable, creates a fresh database next to the one named in it, runs the migrations there, and hands the test a pool for the fresh database. A test run with the variable pointing at a database the user cannot create databases in fails with a permission error before any test code runs.

The table below collects the four readers and when each one reads.

ReaderWhen it readsWhat it needs the value for
The application, through this fieldAt startupOpening the pool
Migration commandsWhen they runFinding the database to migrate
Checked query macros query! and query_as!At compile timeChecking SQL against the real tables
#[sqlx::test]At test timeCreating a fresh database per test

The untyped functions, sqlx::query and sqlx::query_as, are different from the macros. Their SQL is checked when it runs, not when it compiles, so they need no DATABASE_URL at all while building. That was checked directly too: a test file using only query_as compiled with no variable set and no .env file present. The macros with the exclamation mark need the variable at build time, and the plain functions need it only at run time, through the field. Mixing the two up is the most common compile-time confusion in a database project.

Options After the Question Mark

A connection string can carry extra settings after a ?, as key and value pairs joined by &. The most common is the SSL mode:

postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config?sslmode=disable

sslmode controls encryption. The default is prefer, which tries an encrypted connection first and falls back to plain when the server declines, so a local server works with no setting at all. disable skips the encrypted attempt and connects plain at once. require refuses to connect unless encryption succeeds, which is what a hosted database usually needs. The connection string in this project carries no options, because the defaults are right for a local database. Options belong in the string, not in a separate field, because every reader of the variable needs the same options, and the string is the one value they all share.

A Richer Version That Serves Data

The smallest version only proves the connection. A realistic version uses the pool to answer a request, which shows the field doing its job all the way from the environment to a response. The handler counts the rows in the users table, and the table comes from the migration file the project already has.

migrations/0001_create_users.sql
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

State holds one value, so the pool and the config travel together in one small struct. The handler reads the pool out of it and runs an untyped query, which needs no DATABASE_URL at compile time.

src/main.rs
use axum::{Json, extract::State, routing::get, Router};
use axum_project::{config::AppConfig, db::create_pool};
use serde::Serialize;
use sqlx::PgPool;

#[derive(Clone)]
struct AppState {
    config: AppConfig,
    pool: PgPool,
}

#[derive(Serialize)]
struct UserCount {
    count: i64,
}

async fn user_count(State(state): State<AppState>) -> Json<UserCount> {
    let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
        .fetch_one(&state.pool)
        .await
        .unwrap_or((0,));
    Json(UserCount { count })
}

#[tokio::main]
async fn main() {
    let _ = dotenvy::dotenv();
    let config = match AppConfig::from_env() {
        Ok(config) => config,
        Err(error) => {
            eprintln!("Configuration error: {error}");
            std::process::exit(1);
        }
    };
    let pool = create_pool(&config.database_url)
        .await
        .expect("failed to create the database pool");
    let app = Router::new()
        .route("/users/count", get(user_count))
        .with_state(AppState { config: config.clone(), pool });
    let listener = tokio::net::TcpListener::bind(config.listen_address)
        .await
        .unwrap();
    println!("Listening on http://{}", config.listen_address);
    axum::serve(listener, app).await.unwrap();
}

Run the migrations first, so the table exists, and then start the server and request the route. With an empty table the count is zero, and that zero is meaningful: it proves the query ran against the database named in the field, not against a missing table or a wrong database.

curl http://127.0.0.1:3000/users/count
{"count":0}

The AppState struct is the pattern to carry forward: the config and the pool are the two things handlers need, and one struct carries both. The config field is kept in the state even though this handler does not read it, because the next handler might, and one state shape for the whole router beats a different shape per route.

A Second Database for Tests

The same field with a different value points the program at a different database, and that is how tests stay away from development data. A test database is a separate database on the same server, with the same tables and nothing worth keeping in it.

DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests

That value is the one the test pages use. The user and the password are the same, the host and the port are the same, and only the database name at the end changes. Change that one part and the application, the migrations, and the compile-time checks all point at the test database instead. The habit to build is reading the last part of the string before running anything that writes: the name is the difference between a rehearsal and the real data.

The #[sqlx::test] macro takes the idea one step further. It reads the same variable at test time, but it does not use the named database directly. It creates a fresh database next to it for each test, runs the migrations there, and drops it when the test passes. That was checked by running a test with the variable set to the ch21_config database: the test passed, and the database list afterwards showed only the databases that existed before, because the macro had dropped its temporary one.

How the Field Flows Through the Program

The value travels in one direction, from the environment to the query, and the field is the only place it is stored.

DATABASE_URL in the environment or .env
        |
        v
database_url field in AppConfig
        |
        v
create_pool opens connections with the string
        |
        v
PgPool handed to handlers through AppState
        |
        v
queries run against the database named in the string

The compile-time readers sit outside that flow: the checked macros read the same variable while building, and the test macro reads it while testing. They never touch the field. That split is why the variable name matters as much as the field name: the field is for the running program, and the variable is the shared name every tool agrees on.

Testing the Field

Two tests prove the field works. The first connects with the field value and counts the rows in the users table, which proves the pool reaches the database the field names. The second uses the checked macro, which proves the compile-time reader can see the same value. The tests set the variables themselves at run time, because cargo test does not load the .env file: only the checked macro reads the file, at compile time, while the running test process sees only variables set in its own environment.

tests/database_url_test.rs
use axum_project::{config::AppConfig, db::create_pool};

fn set_full_env() {
    std::env::set_var(
        "DATABASE_URL",
        "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config",
    );
    std::env::set_var("LISTEN_ADDRESS", "127.0.0.1:3000");
    std::env::set_var("RUST_LOG", "info");
    std::env::set_var("JWT_SECRET", "test-secret-only-for-local-development");
}

#[tokio::test]
async fn field_value_connects_and_counts_users() {
    set_full_env();
    let config = AppConfig::from_env().unwrap();
    let pool = create_pool(&config.database_url).await.unwrap();
    let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
        .fetch_one(&pool)
        .await
        .unwrap();
    assert!(count >= 0);
}

#[tokio::test]
async fn checked_macro_reads_the_same_value_at_compile_time() {
    set_full_env();
    let config = AppConfig::from_env().unwrap();
    let pool = create_pool(&config.database_url).await.unwrap();
    let row = sqlx::query!("SELECT COUNT(*) AS count FROM users")
        .fetch_one(&pool)
        .await
        .unwrap();
    assert!(row.count.unwrap_or(0) >= 0);
}

The first test uses the untyped query_as, which compiles with no variable set, and the second uses the checked query!, which needs the variable at compile time. The .env file supplies it while building, because the macros read the file as well as the exported variable. Run them with:

cargo test --test database_url_test -- --test-threads=1
test field_value_connects_and_counts_users ... ok
test checked_macro_reads_the_same_value_at_compile_time ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Delete or move the .env file and unset the variable, and the second test fails to compile, while the first still compiles. That difference is the whole lesson of this page in one command: the macros with the exclamation mark need the variable at build time, and the plain functions need it only at run time.

A Test That Compiles Is Not a Test That Connects:

The checked macro test proves the SQL is valid against the database at build time, and then it still has to connect at run time to fetch the count. A test can pass the compile check and fail the connection, when the database is down or the variable changed between building and running. Both halves have to work, and they fail in different places with different messages.

Common Beginner Mistakes

Hard-coding the connection string in code

// Wrong - the password is now in the source, and in every copy of it
let pool = create_pool("postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config")
    .await
    .unwrap();

A string written in code travels with the code: into version control, into reviews, into clones. The fix is the field, which reads the value from the environment, so the code never contains a password at all.

Quoting the value in the env file

# Wrong - in a .env file the quotes become part of the value
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config"

In most shells the quotes are removed before the variable is set, and the command works. In a .env file, quotes are not removed: the value keeps the quote characters, and the URL parser fails on them. Write the value bare in .env, with no quotes around it.

A password with a special character

# Wrong - the @ in the password ends the userinfo part early
postgres://axumdocs:p@ssword@127.0.0.1:5432/ch21_config

The URL parser reads the first @ as the separator between the credentials and the host, so it takes axumdocs:p as the credentials and ssword@127.0.0.1 as the host, and the connection fails with a confusing host error. Percent-encode the character: p%40ssword. When a connection fails and the credentials look right, check the password for characters that have meaning in a URL.

Pointing tests at the development database

# Wrong - this is the development database, not the test database
DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config

Running tests with the development value deletes development rows, inserts test rows with confusing names, and fails on the second run when a unique email already exists. The fix is a database name that says test in it, and a habit of reading the last part of the connection string before running tests.

Expecting the checked macros to work without the variable at build time

// Wrong - this fails to compile with no DATABASE_URL set
let row = sqlx::query!("SELECT COUNT(*) AS count FROM users")
    .fetch_one(&pool)
    .await
    .unwrap();

The build fails with set DATABASE_URL to use query macros online, or run cargo sqlx prepare to update the query cache. The fix is the .env file or an exported variable while compiling, or the untyped query_as form when compile-time checking is not needed.

A Password in the Field Is a Password in the Logs If You Print It:

The field holds a password, so it must never be printed, logged, or returned in a response. The struct has no Debug derive for exactly this reason. If a connection error ever tempts you to log the whole config to see what went wrong, log the database name only, never the full string.

Final Complete Example

Everything on this page put together is one project: the config module, the pool module, the migration, the server that counts users, and the tests that prove both the runtime and the compile-time readers work.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "=0.9.0", features = ["runtime-tokio", "postgres", "macros", "derive", "migrate"] }
dotenvy = "=0.15.7"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
.env
DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config
LISTEN_ADDRESS=127.0.0.1:3000
RUST_LOG=info
JWT_SECRET=test-secret-only-for-local-development
migrations/0001_create_users.sql
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
src/config.rs
use std::net::SocketAddr;

#[derive(Clone)]
pub struct AppConfig {
    pub database_url: String,
    pub listen_address: SocketAddr,
    pub rust_log: String,
    pub jwt_secret: String,
}

impl AppConfig {
    pub fn from_env() -> Result<AppConfig, String> {
        let database_url = std::env::var("DATABASE_URL").map_err(|_| {
            "DATABASE_URL must be set, for example \
             postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config"
                .to_string()
        })?;
        let listen_address = std::env::var("LISTEN_ADDRESS")
            .unwrap_or_else(|_| "127.0.0.1:3000".to_string())
            .parse::<SocketAddr>()
            .map_err(|_| {
                "LISTEN_ADDRESS must be an address like 127.0.0.1:3000".to_string()
            })?;
        let rust_log = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
        let jwt_secret =
            std::env::var("JWT_SECRET").map_err(|_| "JWT_SECRET must be set".to_string())?;
        Ok(AppConfig {
            database_url,
            listen_address,
            rust_log,
            jwt_secret,
        })
    }
}
src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/lib.rs
pub mod config;
pub mod db;
src/main.rs
use axum::{Json, extract::State, routing::get, Router};
use axum_project::{config::AppConfig, db::create_pool};
use serde::Serialize;
use sqlx::PgPool;

#[derive(Clone)]
struct AppState {
    config: AppConfig,
    pool: PgPool,
}

#[derive(Serialize)]
struct UserCount {
    count: i64,
}

async fn user_count(State(state): State<AppState>) -> Json<UserCount> {
    let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
        .fetch_one(&state.pool)
        .await
        .unwrap_or((0,));
    Json(UserCount { count })
}

#[tokio::main]
async fn main() {
    let _ = dotenvy::dotenv();
    let config = match AppConfig::from_env() {
        Ok(config) => config,
        Err(error) => {
            eprintln!("Configuration error: {error}");
            std::process::exit(1);
        }
    };
    let pool = create_pool(&config.database_url)
        .await
        .expect("failed to create the database pool");
    let app = Router::new()
        .route("/users/count", get(user_count))
        .with_state(AppState { config: config.clone(), pool });
    let listener = tokio::net::TcpListener::bind(config.listen_address)
        .await
        .unwrap();
    println!("Listening on http://{}", config.listen_address);
    axum::serve(listener, app).await.unwrap();
}

Run the checks with these commands:

cargo check
cargo test --test database_url_test -- --test-threads=1
cargo run

Then request the route:

curl http://127.0.0.1:3000/users/count

A zero count on an empty table is a passing result: it means the pool connected to the database the field names, and the query ran against the real table.

Summary

The field is small, a single string, and the work around it is large, because that string is shared by four readers that run at four different times. The application reads it at startup, the migrations read it when they run, the checked macros read it at compile time, and the test macro reads it at test time. The rule that keeps all four honest is one value in one place: the variable holds the string, the field holds the copy the program uses, and nothing else in the code holds a second copy.

The decision framework is about which reader a failure belongs to. A build failure naming DATABASE_URL belongs to the checked macros and is fixed by setting the variable while compiling. A startup failure naming the database belongs to the pool and is fixed by reading the string part by part. A test that touches the wrong rows belongs to the value, and is fixed by reading the database name at the end of the string before running. When each failure is blamed on the right reader, the fix is usually one line, in one file.