summaryrefslogtreecommitdiff
path: root/lib/initializer_connections.rb
blob: c8a6bb6c511363e60e24677f0a7f0582c7892e9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# frozen_string_literal: true

module InitializerConnections
  # Prevents any database connections within the block
  # by using an empty connection handler
  # rubocop:disable Database/MultipleDatabases
  def self.with_disabled_database_connections
    return yield if Gitlab::Utils.to_boolean(ENV['SKIP_RAISE_ON_INITIALIZE_CONNECTIONS'])

    original_handler = ActiveRecord::Base.connection_handler

    dummy_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
    ActiveRecord::Base.connection_handler = dummy_handler

    yield

    if dummy_handler&.connection_pool_names&.present?
      raise "Unxpected connection_pools (#{dummy_handler.connection_pool_names}) ! Call `connects_to` before this block"
    end
  rescue ActiveRecord::ConnectionNotEstablished
    message = "Database connection should not be called during initializers. Read more at https://docs.gitlab.com/ee/development/rails_initializers.html#database-connections-in-initializers"

    raise message
  ensure
    ActiveRecord::Base.connection_handler = original_handler
    dummy_handler&.clear_all_connections!
  end
  # rubocop:enable Database/MultipleDatabases
end