2021-09-16 14:11:32 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Gitlab
|
|
|
|
module Database
|
2021-10-01 05:11:45 -04:00
|
|
|
# This abstract class is used for models which need to exist in multiple de-composed databases.
|
2021-09-16 14:11:32 -04:00
|
|
|
class SharedModel < ActiveRecord::Base
|
|
|
|
self.abstract_class = true
|
|
|
|
|
2022-02-01 13:17:05 -05:00
|
|
|
# if shared model is used, this allows to limit connections
|
|
|
|
# on which this model is being shared
|
|
|
|
class_attribute :limit_connection_names, default: nil
|
|
|
|
|
2021-09-16 14:11:32 -04:00
|
|
|
class << self
|
|
|
|
def using_connection(connection)
|
2021-11-07 22:10:16 -05:00
|
|
|
previous_connection = self.overriding_connection
|
|
|
|
|
|
|
|
unless previous_connection.nil? || previous_connection.equal?(connection)
|
|
|
|
raise 'cannot nest connection overrides for shared models with different connections'
|
|
|
|
end
|
2021-09-16 14:11:32 -04:00
|
|
|
|
|
|
|
self.overriding_connection = connection
|
|
|
|
|
|
|
|
yield
|
|
|
|
ensure
|
2021-11-07 22:10:16 -05:00
|
|
|
self.overriding_connection = nil unless previous_connection.equal?(self.overriding_connection)
|
2021-09-16 14:11:32 -04:00
|
|
|
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
|
2021-12-13 22:13:32 -05:00
|
|
|
|
|
|
|
def connection_db_config
|
|
|
|
self.class.connection_db_config
|
|
|
|
end
|
2021-09-16 14:11:32 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|