summaryrefslogtreecommitdiff
path: root/db/post_migrate/20220519045133_bulk_insert_cluster_enabled_grants.rb
blob: 6c1d90586738aadb54d938d3963b29624bd5171d (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
# frozen_string_literal: true

class BulkInsertClusterEnabledGrants < Gitlab::Database::Migration[2.0]
  restrict_gitlab_migration gitlab_schema: :gitlab_main

  disable_ddl_transaction!

  def up
    return unless Gitlab.dev_or_test_env? || Gitlab.com?

    define_batchable_model('cluster_groups').each_batch do |batch|
      min, max = batch.pick('MIN(id), MAX(id)')

      bulk_insert = <<-SQL
        INSERT INTO cluster_enabled_grants (namespace_id, created_at)
        SELECT DISTINCT(traversal_ids[1]), NOW()
        FROM cluster_groups
        INNER JOIN namespaces ON cluster_groups.group_id = namespaces.id
        WHERE cluster_groups.id BETWEEN #{min} AND #{max}
        ON CONFLICT (namespace_id) DO NOTHING
      SQL

      connection.execute(bulk_insert)
    end

    define_batchable_model('cluster_projects').each_batch do |batch|
      min, max = batch.pick('MIN(id), MAX(id)')

      bulk_insert = <<-SQL
        INSERT INTO cluster_enabled_grants (namespace_id, created_at)
        SELECT DISTINCT(traversal_ids[1]), NOW()
        FROM cluster_projects
        INNER JOIN projects ON cluster_projects.project_id = projects.id
        INNER JOIN namespaces on projects.namespace_id = namespaces.id
        WHERE cluster_projects.id BETWEEN #{min} AND #{max}
        ON CONFLICT (namespace_id) DO NOTHING
      SQL

      connection.execute(bulk_insert)
    end
  end

  def down
    # no-op
  end
end