2021-11-11 11:23:49 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Gitlab
|
|
|
|
module Database
|
2021-11-18 22:05:49 +05:30
|
|
|
# This abstract class is used for models which need to exist in multiple de-composed databases.
|
2021-11-11 11:23:49 +05:30
|
|
|
class SharedModel < ActiveRecord::Base
|
|
|
|
self.abstract_class = true
|
|
|
|
|
2022-04-04 11:22:00 +05:30
|
|
|
# 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-11-11 11:23:49 +05:30
|
|
|
class << self
|
|
|
|
def using_connection(connection)
|
2021-12-11 22:18:48 +05:30
|
|
|
previous_connection = self.overriding_connection
|
|
|
|
|
|
|
|
unless previous_connection.nil? || previous_connection.equal?(connection)
|
2022-07-16 23:28:13 +05:30
|
|
|
raise "Cannot change connection for Gitlab::Database::SharedModel "\
|
|
|
|
"from '#{Gitlab::Database.db_config_name(previous_connection)}' "\
|
|
|
|
"to '#{Gitlab::Database.db_config_name(connection)}'"
|
2021-12-11 22:18:48 +05:30
|
|
|
end
|
2021-11-11 11:23:49 +05:30
|
|
|
|
2022-07-23 23:45:48 +05:30
|
|
|
# connection might not be yet adopted (returning nil, and no gitlab_schemas)
|
|
|
|
# in such cases it is fine to ignore such connections
|
|
|
|
gitlab_schemas = Gitlab::Database.gitlab_schemas_for_connection(connection)
|
|
|
|
|
|
|
|
unless gitlab_schemas.nil? || gitlab_schemas.include?(:gitlab_shared)
|
|
|
|
raise "Cannot set `SharedModel` to connection from `#{Gitlab::Database.db_config_name(connection)}` " \
|
|
|
|
"since this connection does not include `:gitlab_shared` schema."
|
|
|
|
end
|
|
|
|
|
2021-11-11 11:23:49 +05:30
|
|
|
self.overriding_connection = connection
|
|
|
|
|
|
|
|
yield
|
|
|
|
ensure
|
2022-07-16 23:28:13 +05:30
|
|
|
self.overriding_connection = previous_connection
|
2021-11-11 11:23:49 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
def connection
|
|
|
|
if connection = self.overriding_connection
|
|
|
|
connection
|
|
|
|
else
|
|
|
|
super
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-04-23 21:23:45 +05:30
|
|
|
# in case the connection has been switched with using_connection
|
|
|
|
def connection_pool
|
|
|
|
connection.pool
|
|
|
|
end
|
|
|
|
|
2021-11-11 11:23:49 +05:30
|
|
|
private
|
|
|
|
|
|
|
|
def overriding_connection
|
|
|
|
Thread.current[:overriding_connection]
|
|
|
|
end
|
|
|
|
|
|
|
|
def overriding_connection=(connection)
|
|
|
|
Thread.current[:overriding_connection] = connection
|
|
|
|
end
|
|
|
|
end
|
2022-01-26 12:08:38 +05:30
|
|
|
|
|
|
|
def connection_db_config
|
|
|
|
self.class.connection_db_config
|
|
|
|
end
|
2021-11-11 11:23:49 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|