SQLx migrations are plain SQL files with a numeric version prefix. You create them with theDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/launchbadge/sqlx/llms.txt
Use this file to discover all available pages before exploring further.
sqlx migrate add command, edit them in any text editor, and apply them with sqlx migrate run. SQLx records every applied migration in the _sqlx_migrations table so subsequent runs only execute scripts that are still pending.
All CLI commands require a database URL. Set You can also pass it explicitly with
DATABASE_URL in your environment or in a .env file at the project root:--database-url <URL> on any command.Creating migration files
Usesqlx migrate add to generate a new migration file. SQLx writes the file to migrations/<timestamp>_<name>.sql and prefixes it with the current UTC time in YYYYMMDDHHmmss format so files sort in creation order.
Simple vs. reversible migrations
By default,sqlx migrate add creates a single .sql file. This is a simple (non-reversible) migration — it can be applied but not reverted.
To create a reversible migration that has both an apply and a revert script, pass the -r flag:
Once you add your first reversible migration, all subsequent
sqlx migrate add calls in that project also create .up.sql / .down.sql pairs, even without -r.Running migrations
sqlx migrate run compares the _sqlx_migrations table against the files in migrations/ and applies every pending script in version order:
Reverting migrations
sqlx migrate revert runs the .down.sql file for the most recently applied reversible migration:
-r can be reverted.
Checking migration status
sqlx migrate info lists all known migrations, whether each one is applied, and when it was run:
Using a custom migrations directory
Pass--source to any sqlx migrate subcommand to read migration files from a directory other than ./migrations:
Running migrations programmatically
Thesqlx::migrate!() macro embeds all files from ./migrations at compile time and returns a Migrator ready to run against any connection or pool:
CARGO_MANIFEST_DIR:
Migrator::new():
What the _sqlx_migrations table tracks
SQLx creates _sqlx_migrations automatically on the first run. Each row records:
- version — the numeric prefix from the filename
- description — the human-readable name from the filename
- checksum — SHA-384 hash of the migration SQL; changing an applied file causes an error on the next run
- installed_on — timestamp of when the migration was applied
- execution_time — duration in nanoseconds
- success — whether the migration completed without error
Opting out of transactions
By default, SQLx wraps each migration in a transaction. To run a migration outside a transaction — for example, when usingCREATE INDEX CONCURRENTLY in PostgreSQL — add -- no-transaction as the first line of the file: