@@ -5,7 +5,7 @@ use crate::{
6use anyhow::{anyhow, Context};
6use anyhow::{anyhow, Context};
7use colored::*;
7use colored::*;
8−use db::{Conn, DbConn};
8+use db::{Conn, DbConn, DbLocker};
9use postgres::Config;
9use postgres::Config;
10use schema::Table;
10use schema::Table;
@@ -15,11 +15,10 @@ pub mod migrations;
15mod schema;
15mod schema;
18−pub use crate::state::{State, Status};
18+pub use crate::state::State;
20pub struct Reshape {
20pub struct Reshape {
21− pub state: State,
21+ db: DbLocker,
25impl Reshape {
24impl Reshape {
@@ -31,6 +30,7 @@ impl Reshape {
31 pub fn new_with_options(
30 pub fn new_with_options(
32 host: &str,
31 host: &str,
33 port: u16,
32 port: u16,
34 username: &str,
34 username: &str,
35 password: &str,
35 password: &str,
36 ) -> anyhow::Result<Reshape> {
36 ) -> anyhow::Result<Reshape> {
@@ -39,504 +39,488 @@ impl Reshape {
39 .host(host)
39 .host(host)
40 .port(port)
40 .port(port)
41 .user(username)
41 .user(username)
42 .password(password);
43 .password(password);
44 Self::new_with_config(&config)
45 Self::new_with_config(&config)
47 fn new_with_config(config: &Config) -> anyhow::Result<Reshape> {
48 fn new_with_config(config: &Config) -> anyhow::Result<Reshape> {
48− let mut db = DbConn::connect(config)?;
49+ let db = DbLocker::connect(config)?;
49− let state = State::load(&mut db);
51− Ok(Reshape { db, state })
50+ Ok(Reshape { db })
54− pub fn migrate<T>(&mut self, migrations: T) -> anyhow::Result<()>
53+ pub fn migrate(
56− T: IntoIterator<Item = Migration>,
55+ migrations: impl IntoIterator<Item = Migration>,
57− {
56+ ) -> anyhow::Result<()> {
58− self.state = State::load(&mut self.db);
58+ let mut state = State::load(db)?;
59+ migrate(db, &mut state, migrations)
60− // Make sure no migration is in progress
63+ pub fn complete(&mut self) -> anyhow::Result<()> {
61− if let state::Status::InProgress { .. } = &self.state.status {
64+ self.db.lock(|db| {
62− println!("Migration already in progress, please complete using 'reshape complete'");
65+ let mut state = State::load(db)?;
63− return Ok(());
66+ complete(db, &mut state)
66− if let state::Status::Completing { .. } = &self.state.status {
70+ pub fn abort(&mut self) -> anyhow::Result<()> {
67− println!(
71+ self.db.lock(|db| {
68− "Migration already in progress and has started completion, please finish using 'reshape complete'"
72+ let mut state = State::load(db)?;
69− );
73+ abort(db, &mut state)
73− // Determine which migrations need to be applied by comparing the provided migrations
77+ pub fn remove(&mut self) -> anyhow::Result<()> {
74− // with the already applied ones stored in the state. This will throw an error if the
78+ self.db.lock(|db| {
75− // two sets of migrations don't agree, for example if a new migration has been added
79+ let mut state = State::load(db)?;
76− // in between two existing ones.
77− let current_migration = &self.state.current_migration.clone();
78− let remaining_migrations = self.state.get_remaining_migrations(migrations)?;
79− if remaining_migrations.is_empty() {
80− println!("No migrations left to apply");
84− // If we have already started applying some migrations we need to ensure that
81+ // Remove migration schemas and views
85− // they are the same ones we want to apply now
82+ if let Some(current_migration) = &state::current_migration(db)? {
86− if let state::Status::Applying {
83+ db.run(&format!(
87− migrations: existing_migrations,
84+ "DROP SCHEMA IF EXISTS {} CASCADE",
88− } = &self.state.status
85+ schema_name_for_migration(current_migration)
90− if existing_migrations != &remaining_migrations {
92− "a previous migration seems to have failed without cleaning up. Please run `reshape abort` and then run migrate again."
97− // Move to the "Applying" state which is necessary as we can't run the migrations
98− // and state update as a single transaction. If a migration unexpectedly fails without
99− // automatically aborting, this state saves us from dangling migrations. It forces the user
100− // to either run migrate again (which works as all migrations are idempotent) or abort.
101− self.state.applying(remaining_migrations.clone());
102− self.state.save(&mut self.db)?;
104− println!("Applying {} migrations\n", remaining_migrations.len());
106− helpers::set_up_helpers(&mut self.db, current_migration)
89+ if let State::InProgress { migrations } = &state {
107− .context("failed to set up helpers")?;
90+ let target_migration = migrations.last().unwrap().name.to_string();
92+ "DROP SCHEMA IF EXISTS {} CASCADE",
93+ schema_name_for_migration(&target_migration)
109− let mut new_schema = Schema::new();
98+ let schema = Schema::new();
110− let mut last_migration_index = usize::MAX;
99+ for table in schema.get_tables(db)? {
111− let mut last_action_index = usize::MAX;
100+ db.run(&format!(
112− let mut result: anyhow::Result<()> = Ok(());
101+ r#"
102+ DROP TABLE IF EXISTS "{}" CASCADE
114− for (migration_index, migration) in remaining_migrations.iter().enumerate() {
108+ // Remove all enums
115− println!("Migrating '{}':", migration.name);
109+ let enums: Vec<String> = db
116− last_migration_index = migration_index;
110+ .query("SELECT typname FROM pg_type WHERE typcategory = 'E'")?
112+ .map(|row| row.get("typname"))
114+ for enum_type in enums {
115+ db.run(&format!("DROP TYPE {}", enum_type))?;
118− for (action_index, action) in migration.actions.iter().enumerate() {
118+ // Reset state
119− last_action_index = action_index;
119+ state.clear(db)?;
121− let description = action.describe();
121+ println!("Reshape and all data has been removed");
122− print!(" + {} ", description);
124− let ctx = MigrationContext::new(migration_index, action_index);
123+ Ok(())
125− result = action
124+ })
126− .run(&ctx, &mut self.db, &new_schema)
125+ }
127− .with_context(|| format!("failed to {}", description));
126+}
129− if result.is_ok() {
128+pub fn latest_schema_from_migrations(migrations: &[Migration]) -> Option<String> {
130− action.update_schema(&ctx, &mut new_schema);
129+ migrations
131− println!("{}", "done".green());
130+ .last()
132− } else {
131+ .map(|migration| schema_name_for_migration(&migration.name))
133− println!("{}", "failed".red());
138− println!();
134+pub fn schema_query_for_migration(migration_name: &str) -> String {
135+ let schema_name = schema_name_for_migration(migration_name);
136+ format!("SET search_path TO {}", schema_name)
141− // If a migration failed, we abort all the migrations that were applied
139+fn schema_name_for_migration(migration_name: &str) -> String {
142− if let Err(err) = result {
140+ format!("migration_{}", migration_name)
143− println!("A migration failed, aborting migrations that have already been applied");
141+}
145− // Set to the Aborting state. This is to ensure that the failed
143+fn migrate(
146− // migration is fully aborted and nothing is left dangling.
144+ db: &mut DbConn,
147− // If the abort is interrupted for any reason, the user can try again
145+ state: &mut State,
148− // by running `reshape abort`.
146+ migrations: impl IntoIterator<Item = Migration>,
149− self.state.aborting(
147+) -> anyhow::Result<()> {
150− remaining_migrations.clone(),
148+ // Make sure no migration is in progress
151− last_migration_index + 1,
149+ if let State::InProgress { .. } = &state {
152− last_action_index + 1,
150+ println!(
153− );
151+ "Migration already in progress, please complete using 'reshape migration complete'"
155− // Abort will only
156+ if let State::Completing { .. } = &state {
156− self.abort()?;
157+ println!(
158+ "Migration already in progress and has started completion, please finish using 'reshape migration complete'"
163+ // Determine which migrations need to be applied by comparing the provided migrations
164+ // with the already applied ones stored in the state. This will throw an error if the
165+ // two sets of migrations don't agree, for example if a new migration has been added
166+ // in between two existing ones.
167+ let remaining_migrations = state::remaining_migrations(db, migrations)?;
168+ if remaining_migrations.is_empty() {
169+ println!("No migrations left to apply");
158− return Err(err);
170+ return Ok(());
161− // Create schema and views for migration
173+ // If we have already started applying some migrations we need to ensure that
162− let target_migration = remaining_migrations.last().unwrap().name.to_string();
174+ // they are the same ones we want to apply now
163− self.create_schema_for_migration(&target_migration, &new_schema)
175+ if let State::Applying {
164− .with_context(|| {
176+ migrations: existing_migrations,
165− format!("failed to create schema for migration {}", target_migration)
177+ } = &state
167−
179+ if existing_migrations != &remaining_migrations {
168− // Update state once migrations have been performed
180+ return Err(anyhow!(
169− self.state.in_progress(remaining_migrations);
181+ "a previous migration seems to have failed without cleaning up. Please run `reshape migration abort` and then run migrate again."
172− .context("failed to save in-progress state")?;
174− // If we started from a blank slate, we can finish the migration immediately
175− if current_migration.is_none() {
176− println!("Automatically completing migrations\n");
177− self.complete_migration()
178− .context("failed to automatically complete migrations")?;
180− println!("Migrations complete:");
182− " - Run '{}' from your application to use the latest schema",
183− schema_query_for_migration(&target_migration)
186− println!("Migrations have been applied and the new schema is ready for use:");
188− " - Run '{}' from your application to use the latest schema",
189− schema_query_for_migration(&target_migration)
192− " - Run 'reshape complete' once your application has been updated and the previous schema is no longer in use"
199− pub fn complete_migration(&mut self) -> anyhow::Result<()> {
186+ // Move to the "Applying" state which is necessary as we can't run the migrations
200− // Make sure a migration is in progress
187+ // and state update as a single transaction. If a migration unexpectedly fails without
201− let (remaining_migrations, starting_migration_index, starting_action_index) = match self.state.status.clone() {
188+ // automatically aborting, this state saves us from dangling migrations. It forces the user
202− state::Status::InProgress { migrations } => {
189+ // to either run migrate again (which works as all migrations are idempotent) or abort.
203− // Move into the Completing state. Once in this state,
190+ state.applying(remaining_migrations.clone());
204− // the migration can't be aborted and must be completed.
191+ state.save(db)?;
205− self.state.completing(migrations.clone(), 0, 0);
192+
206− self.state.save(&mut self.db).context("failed to save state")?;
193+ println!("Applying {} migrations\n", remaining_migrations.len());
208− (migrations, 0, 0)
195+ let target_migration = remaining_migrations.last().unwrap().name.to_string();
209− },
196+ helpers::set_up_helpers(db, &target_migration).context("failed to set up helpers")?;
210− state::Status::Completing {
197+
211− migrations,
198+ let mut new_schema = Schema::new();
212− current_migration_index,
199+ let mut last_migration_index = usize::MAX;
213− current_action_index
200+ let mut last_action_index = usize::MAX;
214− } => (migrations, current_migration_index, current_action_index),
201+ let mut result: anyhow::Result<()> = Ok(());
215− state::Status::Aborting { .. } => {
202+
216− return Err(anyhow!("migration been aborted and can't be completed. Please finish using `reshape abort`."))
203+ 'outer: for (migration_index, migration) in remaining_migrations.iter().enumerate() {
217− }
204+ println!("Migrating '{}':", migration.name);
218− state::Status::Applying { .. } => {
205+ last_migration_index = migration_index;
219− return Err(anyhow!("a previous migration unexpectedly failed. Please run `reshape migrate` to try applying the migration again."))
206+
220− }
207+ for (action_index, action) in migration.actions.iter().enumerate() {
221− state::Status::Idle => {
208+ last_action_index = action_index;
222− println!("No migration in progress");
209+
223− return Ok(());
210+ let description = action.describe();
211+ print!(" + {} ", description);
214+ MigrationContext::new(migration_index, action_index, state::current_migration(db)?);
216+ .run(&ctx, db, &new_schema)
217+ .with_context(|| format!("failed to {}", description));
220+ action.update_schema(&ctx, &mut new_schema);
221+ println!("{}", "done".green());
223+ println!("{}", "failed".red());
227− // Remove previous migration's schema
228− if let Some(current_migration) = &self.state.current_migration {
231− "DROP SCHEMA IF EXISTS {} CASCADE",
232− schema_name_for_migration(current_migration)
234− .context("failed to remove previous migration's schema")?;
237− for (migration_index, migration) in remaining_migrations.iter().enumerate() {
228+ println!();
238− // Skip all the migrations which have already been completed
229+ }
239− if migration_index < starting_migration_index {
243− println!("Completing '{}':", migration.name);
245− for (action_index, action) in migration.actions.iter().enumerate() {
231+ // If a migration failed, we abort all the migrations that were applied
246− // Skip all actions which have already been completed
232+ if let Err(err) = result {
247− if migration_index == starting_migration_index
233+ println!("A migration failed, aborting migrations that have already been applied");
248− && action_index < starting_action_index
253− let description = action.describe();
235+ // Set to the Aborting state. This is to ensure that the failed
254− print!(" + {} ", description);
236+ // migration is fully aborted and nothing is left dangling.
237+ // If the abort is interrupted for any reason, the user can try again
238+ // by running `reshape migration abort`.
240+ remaining_migrations.clone(),
241+ last_migration_index + 1,
242+ last_action_index + 1,
256− let ctx = MigrationContext::new(migration_index, action_index);
245+ // Abort will only
258− // Update state to indicate that this action has been completed.
248+ return Err(err);
259− // We won't save this new state until after the action has completed.
249+ }
260− self.state.completing(
261− remaining_migrations.clone(),
262− migration_index + 1,
266− // This did_save check is necessary because of the borrow checker.
251+ // Create schema and views for migration
267− // The Transaction which might be returned from action.complete
252+ create_schema_for_migration(db, &target_migration, &new_schema)
268− // contains a mutable reference to self.db. We need the Transaction
253+ .with_context(|| format!("failed to create schema for migration {}", target_migration))?;
269− // to be dropped before we can save the state using self.db instead,
254+
270− // which we achieve here by limiting the lifetime of the Transaction
255+ // Update state once migrations have been performed
271− // with a new block.
256+ state.in_progress(remaining_migrations);
272− let did_save = {
257+ state.save(db).context("failed to save in-progress state")?;
273− let result = action
258+
274− .complete(&ctx, &mut self.db)
259+ println!("Migrations have been applied and the new schema is ready for use:");
275− .with_context(|| format!("failed to complete migration {}", migration.name))
260+ println!(
276− .with_context(|| format!("failed to complete action: {}", description));
261+ " - Run '{}' from your application to use the latest schema",
277−
262+ schema_query_for_migration(&target_migration)
278− let maybe_transaction = match result {
263+ );
279− Ok(maybe_transaction) => {
264+ println!(
280− println!("{}", "done".green());
265+ " - Run 'reshape migration complete' once your application has been updated and the previous schema is no longer in use"
281− maybe_transaction
266+ );
284− println!("{}", "failed".red());
289− // Update state with which migrations and actions have been completed.
290− // Each action can create and return a transaction if they need atomicity.
291− // We use this transaction to update the state to ensure the action only completes.
293− // We want to use a single transaction for each action to keep the length of
294− // the transaction as short as possible. Wherever possible, we don't want to
295− // use a transaction at all.
296− if let Some(mut transaction) = maybe_transaction {
298− .save(&mut transaction)
299− .context("failed to save state after completing action")?;
302− .context("failed to commit transaction")?;
310− // If the action didn't return a transaction we save the state normally instead
270+fn complete(db: &mut DbConn, state: &mut State) -> anyhow::Result<()> {
311− if !did_save {
271+ // Make sure a migration is in progress
312− self.state
272+ let (remaining_migrations, starting_migration_index, starting_action_index) = match state.clone() {
313− .save(&mut self.db)
273+ State::InProgress { migrations } => {
274+ // Move into the Completing state. Once in this state,
275+ // the migration can't be aborted and must be completed.
276+ state.completing(migrations.clone(), 0, 0);
314− .context("failed to save state after completing action")?;
277+ state.save(db).context("failed to save state")?;
283+ current_migration_index,
284+ current_action_index
285+ } => (migrations, current_migration_index, current_action_index),
286+ State::Aborting { .. } => {
287+ return Err(anyhow!("migration been aborted and can't be completed. Please finish using `reshape migration abort`."))
289+ State::Applying { .. } => {
290+ return Err(anyhow!("a previous migration unexpectedly failed. Please run `reshape migrate` to try applying the migration again."))
293+ println!("No migration in progress");
318− println!();
298+ // Remove previous migration's schema
299+ if let Some(current_migration) = &state::current_migration(db)? {
301+ "DROP SCHEMA IF EXISTS {} CASCADE",
302+ schema_name_for_migration(current_migration)
304+ .context("failed to remove previous migration's schema")?;
307+ for (migration_index, migration) in remaining_migrations.iter().enumerate() {
308+ // Skip all the migrations which have already been completed
309+ if migration_index < starting_migration_index {
321− // Remove helpers which are no longer in use
313+ println!("Completing '{}':", migration.name);
322− helpers::tear_down_helpers(&mut self.db).context("failed to tear down helpers")?;
324− self.state
315+ for (action_index, action) in migration.actions.iter().enumerate() {
325− .complete()
316+ // Skip all actions which have already been completed
326− .context("failed to update state as completed")?;
317+ if migration_index == starting_migration_index && action_index < starting_action_index {
327− self.state
318+ continue;
328− .save(&mut self.db)
319+ }
329− .context("failed to save state after setting as completed")?;
331− Ok(())
321+ let description = action.describe();
332− }
322+ print!(" + {} ", description);
334− fn create_schema_for_migration(
324+ let ctx =
335− &mut self,
325+ MigrationContext::new(migration_index, action_index, state::current_migration(db)?);
336− migration_name: &str,
338− ) -> anyhow::Result<()> {
339− // Create schema for migration
340− let schema_name = schema_name_for_migration(migration_name);
342− .run(&format!("CREATE SCHEMA IF NOT EXISTS {}", schema_name))
345− "failed to create schema {} for migration {}",
346− schema_name, migration_name
350− // Create views inside schema
351− for table in schema.get_tables(&mut self.db)? {
352− Self::create_view_for_table(&mut self.db, &table, &schema_name)?;
355− Ok(())
327+ // Update state to indicate that this action has been completed.
356− }
328+ // We won't save this new state until after the action has completed.
330+ remaining_migrations.clone(),
331+ migration_index + 1,
358− fn create_view_for_table(
335+ // This did_save check is necessary because of the borrow checker.
359− db: &mut impl Conn,
336+ // The Transaction which might be returned from action.complete
360− table: &Table,
337+ // contains a mutable reference to self.db. We need the Transaction
361− schema: &str,
338+ // to be dropped before we can save the state using self.db instead,
362− ) -> anyhow::Result<()> {
339+ // which we achieve here by limiting the lifetime of the Transaction
363− let select_columns: Vec<String> = table
340+ // with a new block.
364− .columns
341+ let did_save = {
365− .iter()
342+ let result = action
366− .map(|column| {
343+ .complete(&ctx, db)
367− format!(
344+ .with_context(|| format!("failed to complete migration {}", migration.name))
368− r#"
345+ .with_context(|| format!("failed to complete action: {}", description));
369− "{real_name}" AS "{alias}"
346+
370− "#,
347+ let maybe_transaction = match result {
371− real_name = column.real_name,
348+ Ok(maybe_transaction) => {
372− alias = column.name,
349+ println!("{}", "done".green());
373− )
350+ maybe_transaction
375− .collect();
352+ Err(e) => {
353+ println!("{}", "failed".red());
377− db.run(&format!(
358+ // Update state with which migrations and actions have been completed.
378− r#"
359+ // Each action can create and return a transaction if they need atomicity.
379− CREATE OR REPLACE VIEW {schema}."{view_name}" AS
360+ // We use this transaction to update the state to ensure the action only completes.
380− SELECT {columns}
361+ // once.
381− FROM "{table_name}"
362+ // We want to use a single transaction for each action to keep the length of
382− "#,
363+ // the transaction as short as possible. Wherever possible, we don't want to
383− schema = schema,
364+ // use a transaction at all.
384− table_name = table.real_name,
365+ if let Some(mut transaction) = maybe_transaction {
385− view_name = table.name,
366+ state
386− columns = select_columns.join(","),
367+ .save(&mut transaction)
387− ))
368+ .context("failed to save state after completing action")?;
388− .with_context(|| format!("failed to create view for table {}", table.name))?;
369+ transaction
371+ .context("failed to commit transaction")?;
393− pub fn remove(&mut self) -> anyhow::Result<()> {
379+ // If the action didn't return a transaction we save the state normally instead
394− // Remove migration schemas and views
380+ if !did_save {
395− if let Some(current_migration) = &self.state.current_migration {
381+ state
396− self.db.run(&format!(
382+ .save(db)
397− "DROP SCHEMA IF EXISTS {} CASCADE",
383+ .context("failed to save state after completing action")?;
398− schema_name_for_migration(current_migration)
384+ }
402− if let Status::InProgress { migrations } = &self.state.status {
387+ println!();
403− let target_migration = migrations.last().unwrap().name.to_string();
404− self.db.run(&format!(
405− "DROP SCHEMA IF EXISTS {} CASCADE",
406− schema_name_for_migration(&target_migration)
410− // Remove all tables
390+ // Remove helpers which are no longer in use
411− let schema = Schema::new();
391+ helpers::tear_down_helpers(db).context("failed to tear down helpers")?;
412− for table in schema.get_tables(&mut self.db)? {
413− self.db.run(&format!(
415− DROP TABLE IF EXISTS "{}" CASCADE
421− // Reset state
393+ state
422− self.state.clear(&mut self.db)?;
394+ .complete(db)
395+ .context("failed to update state as completed")?;
424− println!("Reshape and all data has been removed");
397+ Ok(())
426− Ok(())
400+fn abort(db: &mut DbConn, state: &mut State) -> anyhow::Result<()> {
427− }
401+ let (remaining_migrations, last_migration_index, last_action_index) = match state.clone() {
402+ State::InProgress { migrations } | State::Applying { migrations } => {
403+ // Set to the Aborting state. Once this is done, the migration has to
404+ // be fully aborted and can't be completed.
405+ state.aborting(migrations.clone(), 0, 0);
429− pub fn abort(&mut self) -> anyhow::Result<()> {
430− let (remaining_migrations, last_migration_index, last_action_index) = match self
435− Status::InProgress { migrations } | Status::Applying { migrations } => {
436− // Set to the Aborting state. Once this is done, the migration has to
437− // be fully aborted and can't be completed.
438− self.state.aborting(migrations.clone(), 0, 0);
439− self.state.save(&mut self.db)?;
441− (migrations, usize::MAX, usize::MAX)
408+ (migrations, usize::MAX, usize::MAX)
443− Status::Aborting {
410+ State::Aborting {
445− last_migration_index,
447− } => (migrations, last_migration_index, last_action_index),
448− Status::Completing { .. } => {
449− return Err(anyhow!("Migration completion has already been started. Please run `reshape complete` again to finish it."));
452− println!("No migration is in progress");
457− // Remove new migration's schema
458− let target_migration = remaining_migrations.last().unwrap().name.to_string();
459− let schema_name = schema_name_for_migration(&target_migration);
461− .run(&format!("DROP SCHEMA IF EXISTS {} CASCADE", schema_name,))
462− .with_context(|| format!("failed to drop schema {}", schema_name))?;
464− // Abort all pending migrations
411+ migrations,
465− self.abort_migrations(
466− &remaining_migrations,
467 last_migration_index,
412 last_migration_index,
468 last_action_index,
413 last_action_index,
469− )?;
414+ } => (migrations, last_migration_index, last_action_index),
470−
415+ State::Completing { .. } => {
471− helpers::tear_down_helpers(&mut self.db).context("failed to tear down helpers")?;
416+ return Err(anyhow!("migration completion has already been started. Please run `reshape migration complete` again to finish it."));
473− self.state.status = state::Status::Idle;
418+ State::Idle => {
474− self.state
419+ println!("No migration is in progress");
475− .save(&mut self.db)
420+ return Ok(());
476− .context("failed to save state")?;
421+ }
424+ // Remove new migration's schema
425+ let target_migration = remaining_migrations.last().unwrap().name.to_string();
426+ let schema_name = schema_name_for_migration(&target_migration);
427+ db.run(&format!("DROP SCHEMA IF EXISTS {} CASCADE", schema_name,))
428+ .with_context(|| format!("failed to drop schema {}", schema_name))?;
430+ // Abort all pending migrations
431+ // Abort all migrations in reverse order
432+ for (migration_index, migration) in remaining_migrations.iter().enumerate().rev() {
433+ // Skip migrations which shouldn't be aborted
434+ // The reason can be that they have already been aborted or that
435+ // the migration was never applied in the first place.
436+ if migration_index >= last_migration_index {
478− Ok(())
440+ print!("Aborting '{}' ", migration.name);
481− fn abort_migrations(
483− migrations: &[Migration],
484− upper_migration_index: usize,
485− upper_action_index: usize,
486− ) -> anyhow::Result<()> {
487− // Abort all migrations in reverse order
488− for (migration_index, migration) in migrations.iter().enumerate().rev() {
442+ for (action_index, action) in migration.actions.iter().enumerate().rev() {
489− // Skip migrations which shouldn't be aborted
443+ // Skip actions which shouldn't be aborted
490 // The reason can be that they have already been aborted or that
444 // The reason can be that they have already been aborted or that
491− // the migration was never applied in the first place.
445+ // the action was never applied in the first place.
492− if migration_index >= upper_migration_index {
446+ if migration_index == last_migration_index - 1 && action_index >= last_action_index {
493 continue;
447 continue;
496− print!("Aborting '{}' ", migration.name);
450+ let ctx =
451+ MigrationContext::new(migration_index, action_index, state::current_migration(db)?);
454+ .with_context(|| format!("failed to abort migration {}", migration.name))
455+ .with_context(|| format!("failed to abort action: {}", action.describe()))?;
457+ // Update state with which migrations and actions have been aborted.
458+ // We don't need to run this in a transaction as aborts are idempotent.
459+ state.aborting(remaining_migrations.to_vec(), migration_index, action_index);
460+ state.save(db).context("failed to save state")?;
498− for (action_index, action) in migration.actions.iter().enumerate().rev() {
463+ println!("{}", "done".green());
499− // Skip actions which shouldn't be aborted
500− // The reason can be that they have already been aborted or that
501− // the action was never applied in the first place.
502− if migration_index == upper_migration_index - 1
503− && action_index >= upper_action_index
508− let ctx = MigrationContext::new(migration_index, action_index);
466+ helpers::tear_down_helpers(db).context("failed to tear down helpers")?;
510− .abort(&ctx, &mut self.db)
511− .with_context(|| format!("failed to abort migration {}", migration.name))
512− .with_context(|| format!("failed to abort action: {}", action.describe()))?;
514− // Update state with which migrations and actions have been aborted.
515− // We don't need to run this in a transaction as aborts are idempotent.
517− .aborting(migrations.to_vec(), migration_index, action_index);
520− .context("failed to save state")?;
523− println!("{}", "done".green());
468+ *state = State::Idle;
524− }
469+ state.save(db).context("failed to save state")?;
529−pub fn latest_schema_from_migrations(migrations: &[Migration]) -> Option<String> {
471+ Ok(())
532− .map(|migration| schema_name_for_migration(&migration.name))
474+fn create_schema_for_migration(
535−pub fn schema_query_for_migration(migration_name: &str) -> String {
476+ migration_name: &str,
478+) -> anyhow::Result<()> {
479+ // Create schema for migration
536 let schema_name = schema_name_for_migration(migration_name);
480 let schema_name = schema_name_for_migration(migration_name);
537− format!("SET search_path TO {}", schema_name)
481+ db.run(&format!("CREATE SCHEMA IF NOT EXISTS {}", schema_name))
484+ "failed to create schema {} for migration {}",
485+ schema_name, migration_name
489+ // Create views inside schema
490+ for table in schema.get_tables(db)? {
491+ create_view_for_table(db, &table, &schema_name)?;
540−fn schema_name_for_migration(migration_name: &str) -> String {
497+fn create_view_for_table(db: &mut impl Conn, table: &Table, schema: &str) -> anyhow::Result<()> {
541− format!("migration_{}", migration_name)
498+ let select_columns: Vec<String> = table
504+ "{real_name}" AS "{alias}"
506+ real_name = column.real_name,
507+ alias = column.name,
514+ CREATE OR REPLACE VIEW {schema}."{view_name}" AS
519+ table_name = table.real_name,
520+ view_name = table.name,
521+ columns = select_columns.join(","),
523+ .with_context(|| format!("failed to create view for table {}", table.name))?;