Module: ActiveRecord::ConnectionAdapters::CockroachDB::ReferentialIntegrity

Included in:
ActiveRecord::ConnectionAdapters::CockroachDBAdapter
Defined in:
lib/active_record/connection_adapters/cockroachdb/referential_integrity.rb

Instance Method Summary collapse

Instance Method Details

#disable_referential_integrityObject



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
# File 'lib/active_record/connection_adapters/cockroachdb/referential_integrity.rb', line 14

def disable_referential_integrity
  foreign_keys = tables.map { |table| foreign_keys(table) }.flatten

  foreign_keys.each do |foreign_key|
    remove_foreign_key(foreign_key.from_table, name: foreign_key.options[:name])
  end

  yield

  # Prefixes and suffixes are added in add_foreign_key
  # in AR7+ so we need to temporarily disable them here,
  # otherwise prefixes/suffixes will be erroneously added.
  old_prefix = ActiveRecord::Base.table_name_prefix
  old_suffix = ActiveRecord::Base.table_name_suffix

  ActiveRecord::Base.table_name_prefix = ""
  ActiveRecord::Base.table_name_suffix = ""

  begin
    foreign_keys.each do |foreign_key|
      begin
        add_foreign_key(foreign_key.from_table, foreign_key.to_table, **foreign_key.options)
      rescue ActiveRecord::StatementInvalid => error
        if error.cause.class == PG::DuplicateObject
          # This error is safe to ignore because the yielded caller
          # already re-added the foreign key constraint.
        else
          raise error
        end
      end
    end
  ensure
    ActiveRecord::Base.table_name_prefix = old_prefix
    ActiveRecord::Base.table_name_suffix = old_suffix
  end
end