Skip to content

Commit

Permalink
move into Migrations
Browse files Browse the repository at this point in the history
  • Loading branch information
jayvdb committed Apr 20, 2024
1 parent 7880768 commit 841be0a
Show file tree
Hide file tree
Showing 8 changed files with 45 additions and 51 deletions.
8 changes: 4 additions & 4 deletions butane/tests/migration-tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,15 +344,15 @@ fn test_migrate(
let to_apply = ms.unapplied_migrations(conn).unwrap();
assert_eq!(to_apply.len(), 2);

migrations::migrate(conn, &ms).unwrap();
ms.migrate(conn).unwrap();

let to_apply = ms.unapplied_migrations(conn).unwrap();
assert_eq!(to_apply.len(), 0);

verify_sql(conn, &ms, expected_up_sql, expected_down_sql);

// Now downgrade, just to make sure we can
migrations::rollback(conn, &ms).unwrap();
ms.unmigrate(conn).unwrap();

let to_apply = ms.unapplied_migrations(conn).unwrap();
assert_eq!(to_apply.len(), 2);
Expand Down Expand Up @@ -563,15 +563,15 @@ fn migration_delete_table(conn: &mut Connection, expected_up_sql: &str, expected
let to_apply = ms.unapplied_migrations(conn).unwrap();
assert_eq!(to_apply.len(), 2);

migrations::migrate(conn, &ms).unwrap();
ms.migrate(conn).unwrap();

let to_apply = ms.unapplied_migrations(conn).unwrap();
assert_eq!(to_apply.len(), 0);

verify_sql(conn, &ms, expected_up_sql, expected_down_sql);

// Now downgrade, just to make sure we can
migrations::rollback(conn, &ms).unwrap();
ms.unmigrate(conn).unwrap();

let to_apply = ms.unapplied_migrations(conn).unwrap();
assert_eq!(to_apply.len(), 2);
Expand Down
64 changes: 29 additions & 35 deletions butane_core/src/migrations/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::path::Path;
use fallible_iterator::FallibleIterator;
use nonempty::NonEmpty;

use crate::db::BackendRows;
use crate::db::{BackendConnection, BackendRows};
use crate::db::{Column, ConnectionMethods};
use crate::sqlval::{FromSql, SqlValRef, ToSql};
use crate::{db, query, DataObject, DataResult, Error, PrimaryKeyType, Result, SqlType};
Expand Down Expand Up @@ -109,6 +109,34 @@ pub trait Migrations {
}
Ok(None)
}

/// Migrate connection forward.
fn migrate(&self, connection: &mut impl BackendConnection) -> Result<()> {
let to_apply = self.unapplied_migrations(connection)?;
for migration in &to_apply {
crate::info!("Applying migration {}", migration.name());
migration.apply(connection)?;
}
Ok(())
}

/// Remove all applied migrations.
fn unmigrate(&self, connection: &mut impl BackendConnection) -> Result<()> {
let mut migration = match self.last_applied_migration(connection)? {
Some(migration) => migration,
None => return Ok(()),
};
migration.downgrade(connection)?;

while let Ok(Some(migration_name)) = migration.migration_from() {
migration = self
.get_migration(&migration_name)
.ok_or(Error::MigrationError("Migration not in chain".to_string()))?;
crate::info!("Rolling back migration {}", migration.name());
migration.downgrade(connection)?;
}
Ok(())
}
}

/// Extension of [`Migrations`] to modify the series of migrations.
Expand Down Expand Up @@ -326,37 +354,3 @@ impl crate::internal::DataObjectInternal for ButaneMigration {
Ok(()) // no-op
}
}

/// Migrate connection forward.
pub fn migrate<M: Migration>(
connection: &mut impl crate::db::BackendConnection,
migrations: &impl Migrations<M = M>,
) -> Result<()> {
let to_apply = migrations.unapplied_migrations(connection)?;
for migration in &to_apply {
crate::info!("Applying migration {}", migration.name());
migration.apply(connection)?;
}
Ok(())
}

/// Rollback all applied migrations.
pub fn rollback<M: Migration>(
connection: &mut impl crate::db::BackendConnection,
migrations: &impl Migrations<M = M>,
) -> Result<()> {
let mut migration = match migrations.last_applied_migration(connection)? {
Some(migration) => migration,
None => return Ok(()),
};
migration.downgrade(connection)?;

while let Ok(Some(migration_name)) = migration.migration_from() {
migration = migrations
.get_migration(&migration_name)
.ok_or(Error::MigrationError("Migration not in chain".to_string()))?;
crate::info!("Rolling back migration {}", migration.name());
migration.downgrade(connection)?;
}
Ok(())
}
4 changes: 2 additions & 2 deletions butane_test_helper/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::sync::Mutex;

use block_id::{Alphabet, BlockId};
use butane_core::db::{connect, get_backend, pg, sqlite, Backend, Connection, ConnectionSpec};
use butane_core::migrations::{self, MemMigrations, Migration, MigrationsMut};
use butane_core::migrations::{self, MemMigrations, Migration, Migrations, MigrationsMut};
use once_cell::sync::Lazy;
use uuid::Uuid;

Expand Down Expand Up @@ -209,7 +209,7 @@ pub fn setup_db(backend: Box<dyn Backend>, conn: &mut Connection, migrate: bool)
"expected to create migration"
);
log::info!("created current migration");
migrations::migrate(conn, &mem_migrations).unwrap();
mem_migrations.migrate(conn).unwrap();
}

/// Create a sqlite [`Connection`].
Expand Down
4 changes: 2 additions & 2 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -505,11 +505,11 @@ to use these migrations:

``` rust
pub fn establish_connection() -> Connection {
use butane::migrations;
use butane::migrations::Migrations;

let mut connection = butane::db::connect(&ConnectionSpec::load(".butane/connection.json").unwrap()).unwrap();
let migrations = butane_migrations::get_migrations().unwrap();
migrations::migrate(&mut connection, &migrations).unwrap();
migrations.migrate(&mut connection).unwrap();
connection
}
```
Expand Down
4 changes: 2 additions & 2 deletions examples/getting_started/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub mod butane_migrations;
pub mod models;

use butane::db::{Connection, ConnectionSpec};
use butane::migrations;
use butane::migrations::Migrations;
use butane::prelude::*;
use models::{Blog, Post};

Expand All @@ -15,7 +15,7 @@ pub fn establish_connection() -> Connection {
let mut connection =
butane::db::connect(&ConnectionSpec::load(".butane/connection.json").unwrap()).unwrap();
let migrations = butane_migrations::get_migrations().unwrap();
migrations::migrate(&mut connection, &migrations).unwrap();
migrations.migrate(&mut connection).unwrap();
connection
}

Expand Down
6 changes: 3 additions & 3 deletions examples/getting_started/tests/rollback.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use butane::db::{BackendConnection, Connection};
use butane::migrations;
use butane::migrations::Migrations;
use butane::DataObject;
use butane_test_helper::*;

Expand Down Expand Up @@ -39,11 +39,11 @@ fn migrate_and_rollback(mut connection: Connection) {
let base_dir = std::path::PathBuf::from(".butane");
let migrations = butane_cli::get_migrations(&base_dir).unwrap();

migrations::migrate(&mut connection, &migrations).unwrap();
migrations.migrate(&mut connection).unwrap();

insert_data(&connection);

// Rollback migrations.
migrations::rollback(&mut connection, &migrations).unwrap();
migrations.unmigrate(&mut connection).unwrap();
}
testall_no_migrate!(migrate_and_rollback);
4 changes: 2 additions & 2 deletions examples/newtype/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub mod butane_migrations;
pub mod models;

use butane::db::{Connection, ConnectionSpec};
use butane::migrations;
use butane::migrations::Migrations;
use butane::prelude::*;
use models::{Blog, Post};

Expand All @@ -15,7 +15,7 @@ pub fn establish_connection() -> Connection {
let mut connection =
butane::db::connect(&ConnectionSpec::load(".butane/connection.json").unwrap()).unwrap();
let migrations = butane_migrations::get_migrations().unwrap();
migrations::migrate(&mut connection, &migrations).unwrap();
migrations.migrate(&mut connection).unwrap();
connection
}

Expand Down
2 changes: 1 addition & 1 deletion examples/newtype/tests/rollback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ fn migrate_and_rollback(mut connection: Connection) {
let migrations = butane_cli::get_migrations(&base_dir).unwrap();
let to_apply = migrations.unapplied_migrations(&connection).unwrap();

migrations::migrate(&mut connection, &migrations).unwrap();
migrations.migrate(&mut connection).unwrap();

insert_data(&connection);

Expand Down

0 comments on commit 841be0a

Please sign in to comment.