What you will build#
A program that creates its tables from migration files at start-up, and a way to add a column later without touching the old files.
Before you start#
- A crate with
sqlxandtokio(see the thread on the connection pool). - The
migrateandmacrosfeatures of sqlx.
Steps#
1. Create the migration files#
Name each file <number>_<description>.sql in a migrations folder next to Cargo.toml. The number orders them.
CREATE TABLE todos (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL
);ALTER TABLE todos ADD COLUMN done BOOLEAN NOT NULL DEFAULT 0;2. Run them when the program starts#
sqlx::migrate! reads the folder at compile time and embeds the SQL in the executable, so the program needs no loose files at run time.
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let path = std::env::temp_dir().join("rs-migrate-demo.db");
let _ = std::fs::remove_file(&path);
let pool = SqlitePoolOptions::new()
.connect_with(SqliteConnectOptions::new().filename(&path).create_if_missing(true))
.await?;
// The folder is read at compile time and the SQL is embedded in the executable.
let migrator = sqlx::migrate!("./migrations");
println!("embedded migrations: {}", migrator.iter().count());
migrator.run(&pool).await?;
migrator.run(&pool).await?; // a second run applies nothing new
let rows: Vec<(i64, String, bool)> =
sqlx::query_as("SELECT version, description, success FROM _sqlx_migrations ORDER BY version")
.fetch_all(&pool)
.await?;
for (version, description, success) in rows {
println!("{version} {description} success={success}");
}
let columns: Vec<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('todos')").fetch_all(&pool).await?;
println!("columns of todos: {:?}", columns.iter().map(|c| c.0.as_str()).collect::<Vec<_>>());
Ok(())
}3. Run the program#
embedded migrations: 2
1 create todos success=true
2 add done success=true
columns of todos: ["id", "title", "done"]Both files were applied in order, the second run did nothing, and the table has the column added by the second file. _sqlx_migrations is the table where sqlx records what was applied.
sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio", "sqlite", "migrate", "macros"] }Check that it works#
Run the program twice against the same database file: the list of migrations stays the same. To add a change, create the next numbered file (with the build.rs shown under Troubleshooting) and rebuild: the next start applies it.
Troubleshooting#
| Symptom | Cause | Fix |
|---|---|---|
the build stops with error canonicalizing migration directory ... The system cannot find the file specified (shown in full below) | the folder named in migrate! does not exist; the path is taken relative to the crate root, the folder with Cargo.toml | create migrations there or pass the right path |
| a new migration file is not applied: the program still reports the old count | the files are embedded at compile time, and in this test Cargo did not notice the new file (cargo build finished at once and the program still embedded 2 migrations) | add the build.rs shown below, or touch a source file |
A build script makes Cargo watch the folder. With this file next to Cargo.toml, adding 0003_add_note.sql and running cargo build made the program report 3 embedded migrations, and removing it brought the count back to 2:
fn main() {
// Rebuild when a migration file is added, removed or changed.
println!("cargo:rerun-if-changed=migrations");
}The error for a wrong folder name (./migration):
error: error canonicalizing migration directory C:\Users\hemant.kumar\AppData\Local\Temp\rs-web-seed\ax\./migration: The system cannot find the file specified. (os error 2)
--> examples\f30.rs:3:13
...Going further#
- Never edit a migration that has already run on another machine: add a new numbered file for the next change.
- Next: reading and writing rows (the threads on
query_asand on transactions).
Related questions#
Can the same files be applied by a command-line tool?#
sqlx has a separate command-line tool for that; this thread used only migrate! inside the program and did not run the tool.
Sources#
- sqlx,
migrate!: https://docs.rs/sqlx/0.8.6/sqlx/macro.migrate.html (read 2026-12-05)