sqlx-cli
Learn what the sqlx-cli command line tool is, how to install it with cargo install sqlx-cli, and what its database, prepare, and migrate commands do
sqlx-cli is the command line companion to the SQLx crate. A command line tool is a program run from the terminal, and this one manages the database side of a SQLx project: it creates and drops databases, creates and runs migrations, and prepares the offline cache the query macros use when no database is available at build time. The library handles the application at runtime, and the CLI handles the database at development time, and the two meet through the same DATABASE_URL.
Where This Fits
The migrations page described the files, and the migrate commands are what run them. This page is the tool that does both, and more. The CLI is installed once, on the development machine, and it is not part of the application: it never ships with the server, it never runs in production, and the application does not depend on it. It is a development tool, like the compiler, and its job is to make the database match the code.
Think of the CLI as the groundskeeper for the database. The application is the house, and the groundskeeper prepares the land, builds the paths, and keeps the records of what was done. The house does not contain the groundskeeper, and the groundskeeper does not live in the house, but the house cannot stand on unprepared land. The CLI prepares the database so the application can live on it.
The Smallest Working Version
Install the tool with Cargo, which downloads it from crates.io, the public registry of Rust crates, and builds it:
cargo install sqlx-cli
The build takes a while, several minutes on an ordinary machine, because the tool includes the SQLx library with all of its database drivers. When it finishes, the sqlx binary is in the Cargo binary directory, and the command is available:
sqlx --version
sqlx-cli 0.9.0
The version number matches the library version, 0.9.0, and keeping them in step matters: a CLI from one version and a library from another can disagree about the migration format or the offline cache. Install the CLI at the same version as the library, and upgrade them together.
A Version Line Means the Install Worked:
If sqlx --version prints a version number, the tool is installed and on the path. If the terminal reports the command was not found, the Cargo binary directory is not on the path, and the fix is to add it: the directory is ~/.cargo/bin on most systems, and it must be listed in the PATH environment variable.
What the Install Includes
A plain cargo install sqlx-cli builds the tool with its default features: the PostgreSQL, MySQL, and SQLite drivers, the native TLS backend, shell completions, and the sqlx.toml configuration support. The PostgreSQL driver is what this project needs, and it is included by default, so the plain install works with no extra flags.
A smaller install is possible by turning the defaults off and picking features by hand:
cargo install sqlx-cli --no-default-features --features postgres,rustls
That build includes only the PostgreSQL driver and the rustls TLS backend, and it compiles faster and produces a smaller binary. The trade is that it cannot touch a MySQL or SQLite database, and it cannot use the native TLS backend. For a project that only uses PostgreSQL, the smaller install is enough, and the plain install is the safer default for a beginner who may touch other databases later.
A CLI Without the Postgres Driver Cannot See Postgres:
A sqlx-cli built without the postgres feature reports no driver found for URL scheme "postgres" for every command, even though the URL is correct. The error names the scheme, not the missing feature, which makes it easy to misread as a bad URL. When that error appears, check how the tool was installed: the plain install includes the driver, and a custom install may not.
The Three Command Groups
The tool has three groups of commands, and each group does one job. Run the tool with --help to see them:
cargo sqlx --help
Command-line utility for SQLx, the Rust SQL toolkit.
Usage: cargo sqlx [OPTIONS] <COMMAND>
Commands:
database Group of commands for creating and dropping your database
prepare Generate query metadata to support offline compile-time verification
migrate Group of commands for creating and running migrations
cargo sqlx and sqlx run the same tool. Cargo treats any binary named cargo-sqlx as a subcommand, so cargo sqlx forwards to it, and the direct sqlx binary runs it too. The two spellings are interchangeable, and these pages use cargo sqlx because it works even when the binary directory is not on the path, as long as Cargo itself is.
Every command needs a database URL. The tool reads it from the --database-url flag first, then from the DATABASE_URL environment variable, then from a .env file in the current directory. The .env file is the usual source during development, because the application reads the same file, and one value serves both. A command run from the wrong directory, where no .env file exists, fails with a missing URL error, and the fix is to run it from the project root.
database: Creating and Dropping the Database
The database group manages the database itself, not its tables. It has four commands:
cargo sqlx database --help
Commands:
create Creates the database specified in your DATABASE_URL
drop Drops the database specified in your DATABASE_URL
reset Drops the database specified in your DATABASE_URL, re-creates it, and runs any pending migrations
setup Creates the database specified in your DATABASE_URL and runs any pending migrations
database create creates the empty database named in the URL. It is safe to run when the database already exists: it succeeds quietly and changes nothing. database drop deletes the database and everything in it, and it is destructive in the plain sense: the data is gone, and no migration can bring it back. database setup creates the database and then runs the pending migrations, which is the one command that takes a fresh checkout from nothing to a working database. database reset drops, recreates, and migrates, which is the fastest way to return a development database to a clean state.
The usual first run on a new machine is database setup: one command, and the database exists with the schema applied. The usual recovery from a tangled development database is database reset: one command, and the mess is gone. Both commands read the URL, so both act on the database the URL names, and the name at the end of the string is worth checking before running either.
prepare: The Offline Query Cache
The prepare command generates the offline cache for the query macros. It connects to the database, checks every query! and query_as! macro in the project, and writes the results into a .sqlx directory in the project root:
cargo sqlx prepare
query data written to .sqlx in the current directory; please check this into version control
Each macro gets one JSON file in that directory, named with a hash of the query, and the file records the columns, their types, and the parameter types the database reported. Later builds with SQLX_OFFLINE=true read those files instead of connecting, so the project compiles with no database running:
SQLX_OFFLINE=true cargo check
The cache must be regenerated whenever a query changes or the schema changes, because a stale cache describes the old query, and the build trusts it. The generated files are committed to version control, so other machines and the build server can compile offline too. A build with no database and no cache fails, and the error names the two ways out: set DATABASE_URL, or run prepare.
The --check flag turns prepare into a test: it exits with a failure when the cache is out of date, instead of regenerating it. A continuous integration pipeline runs cargo sqlx prepare --check to prove the committed cache matches the code, and fails the build when someone changed a query without regenerating the cache.
migrate: The Migration Commands
The migrate group is the largest, and it gets a full walkthrough of its own. Its commands are:
cargo sqlx migrate --help
Commands:
add Create a new migration with the given description
run Run all pending migrations
override Override migration state, potentially dangerous operations
revert Revert the latest migration with a down file
info List all available migrations
build-script Generate a `build.rs` to trigger recompilation when a new migration is added
help Print this message or the help of the given subcommand(s)
add creates a file, run applies the pending ones, info lists them with their state, revert undoes the latest reversible one, build-script generates a small build script that makes Cargo recompile when a migration file is added, and override is a set of dangerous operations for repairing a tracking table that has gone wrong. The walkthrough covers add, run, info, and revert with real output, and the build script belongs with the macro that embeds migrations into the application binary.
How the CLI Finds the Project
The CLI works from the current directory. It reads the .env file there, it creates the migrations directory there, and it writes the .sqlx directory there. Running a command from a subdirectory, such as src, finds no .env file and no migrations directory, and the command either fails or creates a new, empty migrations directory in the wrong place. The rule is to run every sqlx command from the project root, the directory that holds Cargo.toml.
The --source flag points the migration commands at a different directory when the migrations live elsewhere, and --database-url overrides the URL for one command without changing the environment. Both are escapes for unusual layouts, not everyday options. The everyday layout is the default: project root, .env file, migrations directory, .sqlx directory, all in one place.
Common Beginner Mistakes
Installing the CLI but Not the Library, or the Reverse
The CLI and the library are separate installs. cargo install sqlx-cli gives the terminal tool, and the Cargo.toml dependency gives the library. A project with the library but no CLI cannot run migrations from the terminal, and a machine with the CLI but no library in the project cannot compile the application. Both are needed, and they are installed by different commands.
Running Commands From the Wrong Directory
A migrate run from the wrong directory reports no migrations, or creates an empty migrations folder where it does not belong. The command does not search upward for the project root; it works where it stands. Check the prompt before running a migration command, and confirm Cargo.toml is in the current directory.
Forgetting the Version Match
A CLI at 0.8 and a library at 0.9 can disagree about the offline cache format, and the disagreement shows up as a confusing error at build time. Keep the versions together: when the library moves to a new version, reinstall the CLI at the same version. The cargo install command with a --version flag pins the version, and running it again at the new version replaces the old binary.
Summary
The CLI is three tools in one binary: a database creator, a migration runner, and an offline cache generator, all reading the same DATABASE_URL. The insight worth keeping is the split of labour. The library runs queries at runtime, and the CLI prepares everything the library needs before runtime: the database, the schema, and the cached query metadata. A project that keeps both installed, at the same version, has its database work covered from the first migration to the last build.