Guide - Guides

How do I manage database schema changes with sqlx migrations?

#sqlx#migrations#database#sqlitepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Put numbered .sql files in a migrations folder, embed them with sqlx::migrate! and call run on the pool when the program starts. sqlx records each applied file in a _sqlx_migrations table, so a second run applies nothing new, and the app brings any database to the current schema itself.

Checked with rustc 1.93.0, sqlx 0.8.6 with the migrate and macros features (SQLite), tokio 1.54.1, Windows 11

Guide written by the Ruststudio team. Replies are open: corrections are welcome.

#1

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 sqlx and tokio (see the thread on the connection pool).
  • The migrate and macros features 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.

migrations/0001_create_todos.sqlsql
CREATE TABLE todos (
    id    INTEGER PRIMARY KEY,
    title TEXT NOT NULL
);
migrations/0002_add_done.sqlsql
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.

src/main.rsrust
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#

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

Cargo.tomltoml
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#

SymptomCauseFix
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.tomlcreate migrations there or pass the right path
a new migration file is not applied: the program still reports the old countthe 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:

build.rsrust
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):

text
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_as and on transactions).

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet