A platform for community discussion. Free, open, simple.
Protect against accidental table renames
Gerhard Schlager19c5afc69d66
diff --git a/lib/migration/safe_migrate.rb b/lib/migration/safe_migrate.rbindex 92486fe67b0..18e1e14d308 100644--- a/lib/migration/safe_migrate.rb+++ b/lib/migration/safe_migrate.rb@@ -84,26 +84,26 @@ class Migration::SafeMigrateenddef self.protect!(sql)- if sql =~ /^\s*drop\s+table/i+ if sql =~ /^\s*(?:drop\s+table|alter\s+table.*rename\s+to)\s+/i$stdout.puts("", <<~STR)WARNING-------------------------------------------------------------------------------------- An attempt was made to drop a table in a migration+ An attempt was made to drop or rename a table in a migrationSQL used was: '#{sql}'- Please use the deferred pattrn using Migration::TableDropper in db/seeds to drop- the table.+ Please use the deferred pattern using Migration::TableDropper in db/seeds to drop+ or rename the table.This protection is in place to protect us against dropping tables that are currentlyin use by live applications.STRraise Discourse::InvalidMigration, "Attempt was made to drop a table"- elsif sql =~ /^\s*alter\s+table.*(rename|drop)/i+ elsif sql =~ /^\s*alter\s+table.*(?:rename|drop)\s+/i$stdout.puts("", <<~STR)WARNING-------------------------------------------------------------------------------------An attempt was made to drop or rename a column in a migrationSQL used was: '#{sql}'- Please use the deferred pattrn using Migration::ColumnDropper in db/seeds to drop+ Please use the deferred pattern using Migration::ColumnDropper in db/seeds to dropor rename columns.Note, to minimize disruption use self.ignored_columns = ["column name"] on yourdiff --git a/spec/components/migration/safe_migrate_spec.rb b/spec/components/migration/safe_migrate_spec.rbindex 846a4494cf8..15ffd7d62ab 100644--- a/spec/components/migration/safe_migrate_spec.rb+++ b/spec/components/migration/safe_migrate_spec.rb@@ -37,6 +37,22 @@ describe Migration::SafeMigrate doexpect(User.first).not_to eq(nil)end+ it "bans all table renames" do+ Migration::SafeMigrate.enable!++ path = File.expand_path "#{Rails.root}/spec/fixtures/migrate/rename_table"++ output = capture_stdout do+ expect(lambda do+ ActiveRecord::Migrator.up([path])+ end).to raise_error(StandardError)+ end++ expect(output).to include("TableDropper")++ expect(User.first).not_to eq(nil)+ end+it "bans all column removal" doMigration::SafeMigrate.enable!diff --git a/spec/fixtures/migrate/rename_table/20990309014014_rename_table.rb b/spec/fixtures/migrate/rename_table/20990309014014_rename_table.rbnew file mode 100644index 00000000000..7aca85e1555--- /dev/null+++ b/spec/fixtures/migrate/rename_table/20990309014014_rename_table.rb@@ -0,0 +1,9 @@+class RenameTable < ActiveRecord::Migration[5.1]+ def up+ rename_table :users, :persons+ end++ def down+ raise "not tested"+ end+end