1# frozen_string_literal: true
2
3module Gitlab
4  module Database
5    module SchemaCacheWithRenamedTable
6      # Override methods in ActiveRecord::ConnectionAdapters::SchemaCache
7
8      def clear!
9        super
10
11        clear_renamed_tables_cache!
12      end
13
14      def clear_data_source_cache!(name)
15        super(name)
16
17        clear_renamed_tables_cache!
18      end
19
20      def primary_keys(table_name)
21        super(underlying_table(table_name))
22      end
23
24      def columns(table_name)
25        super(underlying_table(table_name))
26      end
27
28      def columns_hash(table_name)
29        super(underlying_table(table_name))
30      end
31
32      def indexes(table_name)
33        super(underlying_table(table_name))
34      end
35
36      private
37
38      def underlying_table(table_name)
39        renamed_tables_cache.fetch(table_name, table_name)
40      end
41
42      def renamed_tables_cache
43        @renamed_tables ||= begin
44          Gitlab::Database::TABLES_TO_BE_RENAMED.select do |old_name, new_name|
45            connection.view_exists?(old_name)
46          end
47        end
48      end
49
50      def clear_renamed_tables_cache!
51        @renamed_tables = nil # rubocop:disable Gitlab/ModuleWithInstanceVariables
52      end
53    end
54  end
55end
56