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

#check_all_foreign_keys_valid!Object

CockroachDB will raise a ‘PG::ForeignKeyViolation` when re-enabling referential integrity (e.g: adding a foreign key with invalid data raises). So foreign keys should always be valid for that matter.



18
19
20
# File 'lib/active_record/connection_adapters/cockroachdb/referential_integrity.rb', line 18

def check_all_foreign_keys_valid!
  true
end

#disable_referential_integrityObject



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

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|
      # Avoid having PG:DuplicateObject error if a test is ran in transaction.
      # TODO: verify that there is no cache issue related to running this (e.g: fk
      #   still in cache but not in db)
      next if foreign_key_exists?(foreign_key.from_table, name: foreign_key.options[:name])

      add_foreign_key(foreign_key.from_table, foreign_key.to_table, **foreign_key.options)
    end
  ensure
    ActiveRecord::Base.table_name_prefix = old_prefix
    ActiveRecord::Base.table_name_suffix = old_suffix
  end
end