Struct Migrator

Source
pub struct Migrator<Db>
where Db: Database, Db::Connection: Migrations,
{ /* private fields */ }
Expand description

A Migrator that is capable of managing migrations for a database.

§Example

use crate::{Error, Migration, Migrator};
use sqlx::{Executor, Postgres};

async fn migrate() -> Result<(), Error> {
   let mut migrator: Migrator<Postgres> =
        Migrator::connect("postgres://postgres:postgres@localhost:5432/postgres").await?;

    let migration = Migration::<Postgres>::new("initial migration", |tx| {
        Box::pin(async move {
            tx.execute("CREATE TABLE example ();").await?;
            Ok(())
        })
    })
    .reversible(|tx| {
        Box::pin(async move {
            tx.execute("DROP TABLE example;");
            Ok(())
        })
    });

    migrator.add_migrations([migration]);

    // Make sure all migrations are consistent with the database.
    migrator.check_migrations().await?;

    // Migrate
    let summary = migrator.migrate(migrator.local_migrations().len() as _).await?;

    assert_eq!(summary.new_version, Some(1));

    // List all migrations.
    let status = migrator.status().await?;

    // Verify that all of them are applied.
    for migration in status {
        assert!(migration.applied.is_some());
    }

    Ok(())
}

Implementations§

Source§

impl<Db> Migrator<Db>
where Db: Database, Db::Connection: Migrations, for<'a> &'a mut Db::Connection: Executor<'a>,

Source

pub fn new(conn: Db::Connection) -> Self

Create a new migrator that uses an existing connection.

Source

pub async fn connect(url: &str) -> Result<Self, Error>

Connect to a database given in the URL.

If this method is used, SQLx statement logging is explicitly disabled. To customize the connection, use Migrator::connect_with.

§Errors

An error is returned on connection failure.

Source

pub async fn connect_with( options: &<Db::Connection as Connection>::Options, ) -> Result<Self, Error>

Connect to a database with the given connection options.

§Errors

An error is returned on connection failure.

Source

pub async fn connect_with_pool(pool: &Pool<Db>) -> Result<Self, Error>

Use a connection from an existing connection pool.

note: A connection will be detached from the pool.

§Errors

An error is returned on connection failure.

Source

pub fn set_migrations_table(&mut self, name: impl AsRef<str>)

Set the table name for migration bookkeeping to override the default DEFAULT_MIGRATIONS_TABLE.

The table name is used as-is in queries, DO NOT USE UNTRUSTED STRINGS.

Source

pub fn add_migrations( &mut self, migrations: impl IntoIterator<Item = Migration<Db>>, )

Add migrations to the migrator.

Source

pub fn set_options(&mut self, options: MigratorOptions)

Override the migrator’s options.

Source

pub fn with<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self

With an extension that is available to the migrations.

Source

pub fn set<T: Send + Sync + 'static>(&mut self, value: T)

Add an extension that is available to the migrations.

Source

pub fn local_migrations(&self) -> &[Migration<Db>]

List all local migrations.

To list all migrations, use Migrator::status.

Source§

impl<Db> Migrator<Db>
where Db: Database, Db::Connection: Migrations, for<'a> &'a mut Db::Connection: Executor<'a>,

Source

pub async fn migrate( self, target_version: u64, ) -> Result<MigrationSummary, Error>

Apply all migrations to the given version.

Migration versions start at 1 and migrations are ordered the way they were added to the migrator.

§Errors

Whenever a migration fails, and error is returned and no database changes will be made.

Source

pub async fn migrate_all(self) -> Result<MigrationSummary, Error>

Apply all local migrations, if there are any.

§Errors

Uses Migrator::migrate internally, errors are propagated.

Source

pub async fn revert( self, target_version: u64, ) -> Result<MigrationSummary, Error>

Revert all migrations after and including the given version.

Any migrations that are “not reversible” and have no revert functions will be ignored.

§Errors

Whenever a migration fails, and error is returned and no database changes will be made.

Source

pub async fn revert_all(self) -> Result<MigrationSummary, Error>

Revert all applied migrations, if any.

§Errors

Uses Migrator::revert, any errors will be propagated.

Source

pub async fn force_version( self, version: u64, ) -> Result<MigrationSummary, Error>

Forcibly set a given migration version in the database. No migrations will be applied or reverted.

This function should be considered (almost) idempotent, and repeatedly calling it should result in the same state. Some database-specific values can change, such as timestamps.

§Errors

The forced migration version must exist locally.

Connection and database errors are returned.

Truncating the migrations table and applying migrations are done in separate transactions. As a consequence in some occasions the migrations table might be cleared and no migrations will be set.

Source

pub async fn verify(self) -> Result<(), Error>

Verify all the migrations.

§Errors

The following kind of errors can be returned:

  • connection and database errors
  • mismatch errors

Mismatch errors can happen if the local migrations’ name or checksum does not match the applied migration’s.

Both name and checksum validation can be turned off via MigratorOptions.

Source

pub async fn status(self) -> Result<Vec<MigrationStatus>, Error>

List all local and applied migrations.

§Errors

Errors are returned on connection and database errors. The migrations themselves are not verified.

Auto Trait Implementations§

§

impl<Db> Freeze for Migrator<Db>
where <Db as Database>::Connection: Freeze,

§

impl<Db> !RefUnwindSafe for Migrator<Db>

§

impl<Db> !Send for Migrator<Db>

§

impl<Db> !Sync for Migrator<Db>

§

impl<Db> Unpin for Migrator<Db>
where <Db as Database>::Connection: Unpin,

§

impl<Db> !UnwindSafe for Migrator<Db>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T