Welcome to mirror list, hosted at ThFree Co, Russian Federation.

tables_sorted_by_foreign_keys.rb « database « gitlab « lib - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9f096904d311993ab3b7b55a1e809af6073c33e4 (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
41
# frozen_string_literal: true

module Gitlab
  module Database
    class TablesSortedByForeignKeys
      include TSort

      def initialize(connection, tables)
        @connection = connection
        @tables = tables
      end

      def execute
        strongly_connected_components
      end

      private

      def tsort_each_node(&block)
        tables_dependencies.each_key(&block)
      end

      def tsort_each_child(node, &block)
        tables_dependencies[node].each(&block)
      end

      # it maps the tables to the tables that depend on it
      def tables_dependencies
        @tables.to_h do |table_name|
          [table_name, all_foreign_keys[table_name]&.map(&:from_table).to_a]
        end
      end

      def all_foreign_keys
        @all_foreign_keys ||= @tables.flat_map do |table_name|
          @connection.foreign_keys(table_name)
        end.group_by(&:to_table)
      end
    end
  end
end