summaryrefslogtreecommitdiff
path: root/lib/gitlab/database/shared_model.rb
blob: f304c32d73134109d49c9ab68639a0b02041ec2b (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
30
31
32
33
34
35
36
37
38
39
40
# frozen_string_literal: true

module Gitlab
  module Database
    # This abstract class is used for models which need to exist in multiple de-composed databases.
    class SharedModel < ActiveRecord::Base
      self.abstract_class = true

      class << self
        def using_connection(connection)
          raise 'cannot nest connection overrides for shared models' unless overriding_connection.nil?

          self.overriding_connection = connection

          yield
        ensure
          self.overriding_connection = nil
        end

        def connection
          if connection = self.overriding_connection
            connection
          else
            super
          end
        end

        private

        def overriding_connection
          Thread.current[:overriding_connection]
        end

        def overriding_connection=(connection)
          Thread.current[:overriding_connection] = connection
        end
      end
    end
  end
end