Add EnvironmentMismatchError
Raise an error when a destructive action is made on a database where the current environment is different from the environment stored in the database.
This commit is contained in:
parent
350ae6cdc1
commit
a76c4233a9
@ -163,6 +163,15 @@ def initialize(env = "production")
|
||||
end
|
||||
end
|
||||
|
||||
class EnvironmentMismatchError < ActiveRecordError
|
||||
def initialize(current: current, stored: stored)
|
||||
msg = "You are attempting to modify a database that was last run in #{ stored } environment.\n"
|
||||
msg << "You are running in #{ current } environment."
|
||||
msg << "if you are sure you want to continue, run the same command with the environment variable\n"
|
||||
msg << "DISABLE_DATABASE_ENVIRONMENT_CHECK=1"
|
||||
end
|
||||
end
|
||||
|
||||
# = Active Record Migrations
|
||||
#
|
||||
# Migrations can manage the evolution of a schema used by several physical
|
||||
@ -1224,8 +1233,7 @@ def record_version_state_after_migrating(version)
|
||||
else
|
||||
migrated << version
|
||||
ActiveRecord::SchemaMigration.create!(version: version.to_s)
|
||||
environment = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call
|
||||
ActiveRecord::InternalMetadata.store(environment: environment)
|
||||
ActiveRecord::InternalMetadata.store(environment: current_environment)
|
||||
end
|
||||
end
|
||||
|
||||
@ -1233,6 +1241,10 @@ def self.last_stored_environment
|
||||
ActiveRecord::InternalMetadata.value_for(:environment)
|
||||
end
|
||||
|
||||
def current_environment
|
||||
ActiveRecord::ConnectionHandling::DEFAULT_ENV.call
|
||||
end
|
||||
|
||||
def self.protected_environment?
|
||||
return false if current_version == 0
|
||||
raise NoEnvironmentInSchemaError unless ActiveRecord::InternalMetadata.table_exists?
|
||||
|
@ -43,8 +43,17 @@ module DatabaseTasks
|
||||
LOCAL_HOSTS = ['127.0.0.1', 'localhost']
|
||||
|
||||
def check_protected_environments!
|
||||
if !ENV['DISABLE_DATABASE_internal_metadata'] && ActiveRecord::Migrator.protected_environment?
|
||||
raise ActiveRecord::ProtectedEnvironmentError.new(ActiveRecord::Migrator.last_stored_environment)
|
||||
unless ENV['DISABLE_DATABASE_internal_metadata']
|
||||
current = ActiveRecord::Migrator.current_environment
|
||||
stored = ActiveRecord::Migrator.last_stored_environment
|
||||
|
||||
if ActiveRecord::Migrator.protected_environment?
|
||||
raise ActiveRecord::ProtectedEnvironmentError.new(stored)
|
||||
end
|
||||
|
||||
if current != stored
|
||||
raise EnvironmentMismatchError.new(current: current, stored: stored)
|
||||
end
|
||||
end
|
||||
rescue ActiveRecord::NoDatabaseError
|
||||
end
|
||||
|
Loading…
Reference in New Issue
Block a user