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

without_check_constraint.rb « database « support « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b361f4374b818659a73ea090da94137a683c241f (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
50
51
52
# frozen_string_literal: true

# Temporarily disable the named constraint on the table within the block.
#
# without_constraint('members', 'check_1234') do
#   create_invalid_data
# end
module Database
  module WithoutCheckConstraint
    def without_check_constraint(table, name, connection:)
      saved_constraint = constraint(table, name, connection)

      constraint_error!(table, name, connection) if saved_constraint.nil?

      begin
        connection.remove_check_constraint(table, name: name)
        connection.transaction do
          yield
          raise ActiveRecord::Rollback
        end
      ensure
        restore_constraint(saved_constraint, connection)
      end
    end

    private

    def constraint_error!(table, name, connection)
      msg = if connection.table_exists?(table)
              "'#{table}' table does not contain constraint called '#{name}'"
            else
              "'#{table}' does not exist"
            end

      raise msg
    end

    def constraint(table, name, connection)
      connection
        .check_constraints(table)
        .find { |constraint| constraint.options[:name] == name }
    end

    def restore_constraint(constraint, connection)
      connection.add_check_constraint(
        constraint.table_name,
        constraint.expression,
        **constraint.options
      )
    end
  end
end