DATABASE_URL

Learn what the DATABASE_URL connection string is, how to read each part of a postgres URL, where to keep it, and what happens when it is missing or wrong

DATABASE_URL is the environment variable that holds the connection string for the database. A connection string 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 application reads the variable once at startup, hands the string to the pool, and never looks at it again. Every database tool in this chapter, the application, the migration commands, and the offline query checker, reads the same variable, which is what makes one variable enough for the whole project.

Where This Fits

The pool pages created a pool from a string called database_url without explaining where that string comes from or what it looks like. This page is that explanation. The variable is the single source of truth for the connection: change it, and the application, the migrations, and the compile-time query checks all point at a different database. The pool size page used the pool, and the query pages will use the database, but this page is about the address itself.

Think of the connection string as a postal address with a key attached. The host and port say which building, the database name says which flat, and the username and password are the key that opens the door. One line carries all four pieces, so the program needs only one variable instead of four, and the same line works for every tool that needs to find the database.

The Smallest Working Version

The connection string for the project database looks like this:

postgres://postgres:password@127.0.0.1:5432/ch12_sqlx

Read it left to right. postgres:// is the scheme, and it says which database driver to use: PostgreSQL. postgres before the colon is the username. password after the colon is the password. 127.0.0.1 is the host, the machine the database runs on, and 127.0.0.1 means this computer. 5432 is the port, the channel on that machine where PostgreSQL listens. ch12_sqlx after the slash is the database name.

The program reads it from the environment in main:

src/main.rs
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();
}

std::env::var reads an environment variable by name and returns its value. An environment variable is a named piece of text the operating system holds for a running program, set before the program starts. expect says what to do when the variable is missing: stop the program with the given message. The program sets the variable when it starts the server:

DATABASE_URL=postgres://postgres:password@127.0.0.1:5432/ch12_sqlx cargo run

The part before the command sets the variable for that one run only. When the server prints its startup line, the variable was read, the pool connected, and the address was right.

Each Part of the String

The 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.

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 for a bare URL. A string with no scheme, or with a scheme the crate does not know, fails before any network work happens, with an error about the configuration. The error for a bare word with no scheme at all is relative URL without a base, which is the URL parser saying the string is not a URL.

The username and password come next, separated by a colon, before the @ sign. The username is the PostgreSQL role the program logs in as, and the password is that role's password. A wrong password is rejected by the server 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. A password with no special characters needs no encoding.

The host is the machine. 127.0.0.1 is the loopback address, which always means the machine the program itself runs on. localhost means the same thing in most setups. A hostname such as db.example.com means a remote machine, reached over the network. A wrong host fails, and the failure is slow: the pool retries until the acquire timeout, thirty seconds by default, and then reports pool timed out while waiting for an open connection. That wait is the pool retrying a connection that may come back, not the program hanging.

The port is the channel. PostgreSQL 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. When the message appears, the host and the port are the first two things to check.

The database name is the last part, after the slash. A PostgreSQL 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, where the name in quotes is the one the program asked for. Unlike the host and port failures, this one is instant, because the server answers and says no.

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://postgres:password@127.0.0.1:5432/ch12_sqlx?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. Other options exist, such as statement-cache-capacity for the prepared statement cache, but a beginner needs none of them. The connection string in this project carries no options, because the defaults are right for a local database.

Keeping the String Out of the Code

The connection string holds a password, so it must never be written into source code. Source code is committed to version control, shared, and copied, and a password in source code travels with it. The string lives in the environment instead, which is per-machine and never committed.

For development, the usual place is a file named .env in the project root:

DATABASE_URL=postgres://postgres:password@127.0.0.1:5432/ch12_sqlx

A .env file is a plain text file with one VARIABLE=value pair per line. SQLx tools, including the sqlx-cli migration commands and the query macros at compile time, read this file automatically when the variable is not already set in the environment. The application itself does not read .env files: std::env::var only sees real environment variables. To run the server from a .env file, the variable must be exported first, or a tool must load the file into the environment before starting the program.

The .env file must be listed in .gitignore, the file that tells Git which files never to commit:

.env

One line is enough. With it in place, the file stays on the machine and never reaches the repository. A teammate who clones the project creates their own .env with their own credentials, and the program reads it the same way.

A Password in Source Code Is a Leak:

Never write the connection string, or any password, into a .rs file, a Cargo.toml, or a committed file of any kind. Keep it in the environment or in an ignored .env file. A password that reaches version control is compromised the moment it is pushed, even to a private repository, and changing it afterwards does not undo the exposure.

What Happens When the Variable Is Missing

Run the server without setting the variable:

cargo run

The program stops at once, before the server starts, with the message from expect:

thread 'main' panicked at src/main.rs:
DATABASE_URL must be set, for example postgres://postgres:password@127.0.0.1:5432/ch12_sqlx
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

That is the expect doing its job. The first line names the thread and the file and line of the expect call, the second line is the message itself, and the third is Rust's standard note about backtraces. The message names the variable and shows an example value, so the fix is visible in the error itself: set the variable and run again. The panic happens before any pool is created, before any port is bound, and before any request is served, which is the right order: a server that cannot reach its database should fail at startup, loudly, rather than serving broken responses.

The compile-time query macros have their own version of this failure. When code uses query! or query_as!, the compiler needs DATABASE_URL at build time to check the SQL against the database. Without it, the build fails with set DATABASE_URL to use query macros online, or run cargo sqlx prepare to update the query cache. That message names the two ways out: set the variable while compiling, or generate an offline cache of query metadata with cargo sqlx prepare. The query macro pages explain both in full.

One Variable for Every Tool

The same variable feeds four consumers, and that is by design. The application reads it in main to build the pool. The sqlx-cli migration commands read it to find the database they should migrate. The query macros read it at compile time to check SQL. And the offline preparation command reads it to generate the cached query metadata. One variable, four readers, zero duplication.

That sharing is also a source of mistakes. A variable set for the application but pointing at the wrong database migrates the wrong database too, because the CLI reads the same value. The protection is a habit: before running a migration command, print the variable and check the database name at the end of the string. The name is the last thing in the string, and it is the thing that decides which data changes.

Different Values for Different Machines

A development machine and a production server need different connection strings: different hosts, different users, different passwords, and different database names. The environment variable is what makes that possible without changing code. The program reads the same name on both machines, and each machine holds its own value. The code never branches on the environment, and the same binary runs in both places with a different string.

For a learner, the values to remember are simple. Development uses the local server, 127.0.0.1:5432, a local user, and a database named for the project. Anything else is a deployment concern, and the mechanism is the same: set the variable on the machine, and the program finds it.

Common Beginner Mistakes

Quoting the Value in the Shell

# Wrong - the quotes become part of the value on some shells
DATABASE_URL="postgres://postgres:password@127.0.0.1:5432/ch12_sqlx" cargo run

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. The same applies to spaces: a value with a space after the = sign includes the space, and the URL breaks.

A Password With a Special Character

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

The URL parser reads the first @ as the separator between the credentials and the host, so it takes postgres: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. The same applies to : in a password, which becomes %3A, and to /, which becomes %2F. When a connection fails and the credentials look right, check the password for characters that have meaning in a URL.

Two Databases With the Same Name on Different Machines

A program that works on one machine and fails on another with a "relation does not exist" error is usually pointing at a different database than the programmer thinks. The variable on the second machine names a database that exists but has no tables, because the migrations were never run there. The fix is to run the migrations against the database the variable names, not to change the code. The error message names the missing relation, and the variable names the database, and the two together say where the tables actually are.

The Full Picture in One Place

Here is the whole chain for this page: the variable, the read, and the pool that receives it.

DATABASE_URL=postgres://postgres:password@127.0.0.1:5432/ch12_sqlx
src/main.rs
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");
.env

One variable, one read, one pool. Everything else in the chapter assumes this chain works, and every connection error in the chapter is diagnosed by reading the string it starts from.

Summary

DATABASE_URL is a small idea doing a large job: one line of text carries the driver, the credentials, the address, and the database name, and one variable carries that line to every tool that needs it. The insight worth keeping is that connection failures are almost always string failures. Read the string part by part, match each part against the error message, and the cause is usually visible: a wrong password says so, a missing database says so, and a wrong host or port says so after a thirty-second wait.

The string decides where the database is, and the pool decides how many connections to hold against it. How many is the right number is not a property of the string, it is a property of the traffic, and that sizing question is what the pool size page answers.