Module: ActiveRecord::ConnectionAdapters::YugabyteDB::ReferentialIntegrity

Included in:
ActiveRecord::ConnectionAdapters::YugabyteDBAdapter
Defined in:
lib/active_record/connection_adapters/yugabytedb/referential_integrity.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#check_all_foreign_keys_valid!Object

:nodoc:



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/active_record/connection_adapters/yugabytedb/referential_integrity.rb', line 41

def check_all_foreign_keys_valid! # :nodoc:
  sql = <<~SQL
    do $$
      declare r record;
    BEGIN
    FOR r IN (
      SELECT FORMAT(
        'UPDATE pg_constraint SET convalidated=false WHERE conname = ''%I'' AND connamespace::regnamespace = ''%I''::regnamespace; ALTER TABLE %I.%I VALIDATE CONSTRAINT %I;',
        constraint_name,
        table_schema,
        table_schema,
        table_name,
        constraint_name
      ) AS constraint_check
      FROM information_schema.table_constraints WHERE constraint_type = 'FOREIGN KEY'
    )
      LOOP
        EXECUTE (r.constraint_check);
      END LOOP;
    END;
    $$;
  SQL

  transaction(requires_new: true) do
    execute(sql)
  end
end

#disable_referential_integrityObject

:nodoc:



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

def disable_referential_integrity # :nodoc:
  original_exception = nil

  begin
    transaction(requires_new: true) do
      execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";"))
    end
  rescue ActiveRecord::ActiveRecordError => e
    original_exception = e
  end

  begin
    yield
  rescue ActiveRecord::InvalidForeignKey => e
    warn <<-WARNING
WARNING: Rails was not able to disable referential integrity.

This is most likely caused due to missing permissions.
Rails needs superuser privileges to disable referential integrity.

    cause: #{original_exception&.message}

    WARNING
    raise e
  end

  begin
    transaction(requires_new: true) do
      execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";"))
    end
  rescue ActiveRecord::ActiveRecordError
  end
end