summaryrefslogtreecommitdiff
path: root/db/migrate/20220211214605_update_integrations_trigger_type_new_on_insert_null_safe.rb
blob: 7a60ea48f402528f476adb76141a60703d807eb9 (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
# frozen_string_literal: true

class UpdateIntegrationsTriggerTypeNewOnInsertNullSafe < Gitlab::Database::Migration[1.0]
  include Gitlab::Database::SchemaHelpers

  FUNCTION_NAME = 'integrations_set_type_new'

  def up
    # Update `type_new` dynamically based on `type`, if `type_new` is null
    # and `type` dynamically based on `type_new`, if `type` is null.
    #
    # The old class names are in the format `AbcService`, and the new ones `Integrations::Abc`.
    create_trigger_function(FUNCTION_NAME, replace: true) do
      <<~SQL.squish
        UPDATE integrations
           SET type_new = COALESCE(NEW.type_new, regexp_replace(NEW.type, '\\A(.+)Service\\Z', 'Integrations::\\1'))
             , type     = COALESCE(NEW.type, regexp_replace(NEW.type_new, '\\AIntegrations::(.+)\\Z', '\\1Service'))
        WHERE integrations.id = NEW.id;
        RETURN NULL;
      SQL
    end
  end

  def down
    # Update `type_new` dynamically based on `type`.
    #
    # The old class names are in the format `AbcService`, and the new ones `Integrations::Abc`.
    create_trigger_function(FUNCTION_NAME, replace: true) do
      <<~SQL
        UPDATE integrations SET type_new = regexp_replace(NEW.type, '\\A(.+)Service\\Z', 'Integrations::\\1')
        WHERE integrations.id = NEW.id;
        RETURN NULL;
      SQL
    end
  end
end