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

database.rb « schema_validation « database « gitlab « lib - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 07bd02e58e16382b552ec137dd0cad04f1841d8f (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# frozen_string_literal: true

module Gitlab
  module Database
    module SchemaValidation
      class Database
        STATIC_PARTITIONS_SCHEMA = 'gitlab_partitions_static'

        def initialize(connection)
          @connection = connection
        end

        def fetch_index_by_name(index_name)
          index_map[index_name]
        end

        def fetch_trigger_by_name(trigger_name)
          trigger_map[trigger_name]
        end

        def index_exists?(index_name)
          index_map[index_name].present?
        end

        def trigger_exists?(trigger_name)
          trigger_map[trigger_name].present?
        end

        def indexes
          index_map.values
        end

        def triggers
          trigger_map.values
        end

        private

        attr_reader :connection

        def schemas
          @schemas ||= [STATIC_PARTITIONS_SCHEMA, connection.current_schema]
        end

        def index_map
          @index_map ||=
            fetch_indexes.transform_values! do |index_stmt|
              SchemaObjects::Index.new(PgQuery.parse(index_stmt).tree.stmts.first.stmt.index_stmt)
            end
        end

        def trigger_map
          @trigger_map ||=
            fetch_triggers.transform_values! do |trigger_stmt|
              SchemaObjects::Trigger.new(PgQuery.parse(trigger_stmt).tree.stmts.first.stmt.create_trig_stmt)
            end
        end

        def fetch_indexes
          sql = <<~SQL
            SELECT indexname, indexdef
            FROM pg_indexes
            WHERE indexname NOT LIKE '%_pkey' AND schemaname IN ($1, $2);
          SQL

          connection.select_rows(sql, nil, schemas).to_h
        end

        def fetch_triggers
          sql = <<~SQL
            SELECT triggers.tgname, pg_get_triggerdef(triggers.oid)
            FROM pg_catalog.pg_trigger triggers
            INNER JOIN pg_catalog.pg_class rel ON triggers.tgrelid = rel.oid
            INNER JOIN pg_catalog.pg_namespace nsp ON nsp.oid = rel.relnamespace
            WHERE triggers.tgisinternal IS FALSE
            AND nsp.nspname IN ($1, $2)
          SQL

          connection.select_rows(sql, nil, schemas).to_h
        end
      end
    end
  end
end