summaryrefslogtreecommitdiff
path: root/db/migrate/20220722203840_update_lock_writes_function_disabled_via_setting.rb
blob: f78d2b7f155ad7a1737b5da7c381944cb3d94638 (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 UpdateLockWritesFunctionDisabledViaSetting < Gitlab::Database::Migration[2.0]
  TRIGGER_FUNCTION_NAME = 'gitlab_schema_prevent_write'

  def up
    execute(<<~SQL)
      CREATE OR REPLACE FUNCTION #{TRIGGER_FUNCTION_NAME}()
        RETURNS TRIGGER AS
        $$
      BEGIN
          IF COALESCE(NULLIF(current_setting(CONCAT('lock_writes.', TG_TABLE_NAME), true), ''), 'true') THEN
            RAISE EXCEPTION 'Table: "%" is write protected within this Gitlab database.', TG_TABLE_NAME
              USING ERRCODE = 'modifying_sql_data_not_permitted',
              HINT = 'Make sure you are using the right database connection';
          END IF;
          RETURN NEW;
      END
      $$ LANGUAGE PLPGSQL;
    SQL
  end

  def down
    execute(<<~SQL)
      CREATE OR REPLACE FUNCTION #{TRIGGER_FUNCTION_NAME}()
        RETURNS TRIGGER AS
        $$
      BEGIN
          RAISE EXCEPTION 'Table: "%" is write protected within this Gitlab database.', TG_TABLE_NAME
            USING ERRCODE = 'modifying_sql_data_not_permitted',
            HINT = 'Make sure you are using the right database connection';
      END
      $$ LANGUAGE PLPGSQL
    SQL
  end
end