1# frozen_string_literal: true
2
3# When the `ci_sources_pipelines` table was first introduced in GitLab
4# 9.3 EE, the foreign key names generate for the table appeared to
5# have been calculated via a hash using the table name
6# `ci_pipeline_source_pipelines`. This led to a merge conflict and
7# confusion during a CE to EE merge in GitLab 10.0, which regenerated
8# the schema with the correct foreign key names.
9#
10# Hence anyone who installed GitLab prior to 10.0 may have been seeded
11# the database with stale, incorrect foreign key names.
12#
13# During the Great BigInt Conversion of 2021, several migrations
14# assumed that the foreign key `fk_be5624bf37` existed for
15# `ci_sources_pipeline`. However, older installations may have had the
16# correct foreign key under the name `fk_3f0c88d7dc`.
17#
18# To eliminate future confusion and migration failures, we now rename
19# the foreign key constraints and index to what they should be today.
20class FixCiSourcesPipelinesIndexNames < ActiveRecord::Migration[6.1]
21  include Gitlab::Database::MigrationHelpers
22
23  disable_ddl_transaction!
24
25  TABLE_NAME = 'ci_sources_pipelines'
26
27  # GitLab 9.5.4: https://gitlab.com/gitlab-org/gitlab/-/blob/v9.5.4-ee/db/schema.rb#L2026-2030
28  # GitLab 10.0: https://gitlab.com/gitlab-org/gitlab/-/blob/v10.0.0-ee/db/schema.rb#L2064-2068
29  OLD_TO_NEW_FOREIGN_KEY_DEFS = {
30    'fk_3f0c88d7dc' => { table: :ci_builds, column: :source_job_id, name: 'fk_be5624bf37' },
31    'fk_b8c0fac459' => { table: :ci_pipelines, column: :pipeline_id, name: 'fk_e1bad85861' },
32    'fk_3a3e3cb83a' => { table: :ci_pipelines, column: :source_pipeline_id, name: 'fk_d4e29af7d7' },
33    'fk_8868d0f3e4' => { table: :projects, column: :source_project_id, name: 'fk_acd9737679' },
34    'fk_83b4346e48' => { table: :projects, name: 'fk_1e53c97c0a' }
35  }
36  OLD_INDEX_NAME = 'index_ci_pipeline_source_pipelines_on_source_job_id'
37  NEW_INDEX_NAME = 'index_ci_sources_pipelines_on_source_job_id'
38
39  def up
40    OLD_TO_NEW_FOREIGN_KEY_DEFS.each do |old_name, entry|
41      options = { column: entry[:column], name: old_name }.compact
42
43      if foreign_key_exists?(TABLE_NAME, entry[:table], **options)
44        rename_constraint(TABLE_NAME, old_name, entry[:name])
45      end
46    end
47
48    if index_exists_by_name?(TABLE_NAME, OLD_INDEX_NAME)
49      if index_exists_by_name?(TABLE_NAME, NEW_INDEX_NAME)
50        remove_concurrent_index_by_name(TABLE_NAME, OLD_INDEX_NAME)
51      else
52        rename_index(TABLE_NAME, OLD_INDEX_NAME, NEW_INDEX_NAME)
53      end
54    end
55  end
56
57  # There's no reason to revert this change since it should apply on stale schemas
58  def down; end
59end
60