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

20230807085752_ensure_id_uniqueness_for_p_ci_builds.rb « post_migrate « db - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: cdd68e7f5dc1e266d2f8d7d939686836d710b40f (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
# frozen_string_literal: true

class EnsureIdUniquenessForPCiBuilds < Gitlab::Database::Migration[2.1]
  include Gitlab::Database::SchemaHelpers
  include Gitlab::Database::MigrationHelpers::WraparoundAutovacuum

  enable_lock_retries!

  TABLE_NAME = :p_ci_builds
  FUNCTION_NAME = :assign_p_ci_builds_id_value
  TRIGGER_NAME = :assign_p_ci_builds_id_trigger

  def up
    return unless should_run?

    change_column_default(TABLE_NAME, :id, nil)

    create_trigger_function(FUNCTION_NAME) do
      <<~SQL
        IF NEW."id" IS NOT NULL THEN
          RAISE WARNING 'Manually assigning ids is not allowed, the value will be ignored';
        END IF;
        NEW."id" := nextval('ci_builds_id_seq'::regclass);
        RETURN NEW;
      SQL
    end

    Gitlab::Database::PostgresPartitionedTable.each_partition(TABLE_NAME) do |partition|
      create_trigger(partition.identifier, TRIGGER_NAME, FUNCTION_NAME, fires: 'BEFORE INSERT')
    end
  end

  def down
    return unless should_run?

    execute(<<~SQL.squish)
      ALTER TABLE #{TABLE_NAME}
        ALTER COLUMN id SET DEFAULT nextval('ci_builds_id_seq'::regclass);

      DROP FUNCTION IF EXISTS #{FUNCTION_NAME} CASCADE;
    SQL
  end

  private

  def should_run?
    can_execute_on?(:ci_builds)
  end
end