test_databases.rb 1.3 KB
Newer Older
E
eileencodes 已提交
1 2 3 4 5 6 7
# frozen_string_literal: true

require "active_support/testing/parallelization"

module ActiveRecord
  module TestDatabases # :nodoc:
    ActiveSupport::Testing::Parallelization.after_fork_hook do |i|
8
      create_and_load_schema(i, env_name: ActiveRecord::ConnectionHandling::DEFAULT_ENV.call)
E
eileencodes 已提交
9 10
    end

11
    def self.create_and_load_schema(i, env_name:)
E
eileencodes 已提交
12 13
      old, ENV["VERBOSE"] = ENV["VERBOSE"], "false"

14
      ActiveRecord::Base.configurations.configs_for(env_name: env_name).each do |db_config|
15 16 17 18 19 20 21 22
        database = "#{db_config.database}-#{i}"

        db_config_copy = ActiveRecord::DatabaseConfigurations::HashConfig.new(
          env_name,
          db_config.spec_name,
          db_config.configuration_hash.merge(database: database)
        )

23
        # Reconstruct with the new configuration
24
        ActiveRecord::Tasks::DatabaseTasks.reconstruct_from_schema(db_config_copy, ActiveRecord::Base.schema_format, nil)
25 26 27 28

        # Replace the original configuration with our replacement
        ActiveRecord::Base.configurations.configurations.delete(db_config)
        ActiveRecord::Base.configurations.configurations.push(db_config_copy)
29
      end
E
eileencodes 已提交
30
    ensure
31
      ActiveRecord::Base.establish_connection(ActiveRecord::ConnectionHandling::DEFAULT_ENV.call.to_sym)
E
eileencodes 已提交
32 33 34 35
      ENV["VERBOSE"] = old
    end
  end
end