From 500cd18f19d59a4ef9f15e8257f6eea71d429cac Mon Sep 17 00:00:00 2001 From: Paul Xu <40262910+xb284524239@users.noreply.github.com> Date: Tue, 9 Sep 2025 05:01:23 +0800 Subject: [PATCH] Add `Migrator::with_migrations()` constructor (#4020) * Add the helper function with_migrations() to Migrator. * cargo fmt * cargo fmt * cargo fmt * Improve comments. --- sqlx-core/src/migrate/migrator.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/sqlx-core/src/migrate/migrator.rs b/sqlx-core/src/migrate/migrator.rs index 1ae48131..375c2af3 100644 --- a/sqlx-core/src/migrate/migrator.rs +++ b/sqlx-core/src/migrate/migrator.rs @@ -69,6 +69,32 @@ impl Migrator { }) } + /// Creates a new instance with the given migrations. + /// + /// + /// # Examples + /// + /// ```rust,no_run + /// use sqlx::{ SqlSafeStr, migrate::{Migration, MigrationType::*, Migrator}}; + /// + /// // Define your migrations. + /// // You can also use include_str!("./xxx.sql") instead of hard-coded SQL statements. + /// let migrations = vec![ + /// Migration::new(1, "user".into(), ReversibleUp, "create table uesrs ( ... )".into_sql_str(), false), + /// Migration::new(2, "post".into(), ReversibleUp, "create table posts ( ... )".into_sql_str(), false), + /// // add more... + /// ]; + /// let m = Migrator::with_migrations(migrations); + /// ``` + pub fn with_migrations(mut migrations: Vec) -> Self { + // Ensure that we are sorted by version in ascending order. + migrations.sort_by_key(|m| m.version); + Self { + migrations: Cow::Owned(migrations), + ..Self::DEFAULT + } + } + /// Override the name of the table used to track executed migrations. /// /// May be schema-qualified and/or contain quotes. Defaults to `_sqlx_migrations`.