Module: ActiveRecord::ConnectionAdapters::PostgreSQL::ReferentialIntegrity

Included in:
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
Defined in:
lib/active_record/connection_adapters/postgresql/referential_integrity.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#all_foreign_keys_valid?Boolean

:nodoc:

Returns:

  • (Boolean)


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
68
69
70
71
72
73
# File 'lib/active_record/connection_adapters/postgresql/referential_integrity.rb', line 41

def all_foreign_keys_valid? # :nodoc:
  sql = "    do $$\n      declare r record;\n    BEGIN\n    FOR r IN (\n      SELECT FORMAT(\n        'UPDATE pg_constraint SET convalidated=false WHERE conname = ''%I'' AND connamespace::regnamespace = ''%I''::regnamespace; ALTER TABLE %I.%I VALIDATE CONSTRAINT %I;',\n        constraint_name,\n        table_schema,\n        table_schema,\n        table_name,\n        constraint_name\n      ) AS constraint_check\n      FROM information_schema.table_constraints WHERE constraint_type = 'FOREIGN KEY'\n    )\n      LOOP\n        EXECUTE (r.constraint_check);\n      END LOOP;\n    END;\n    $$;\n  SQL\n\n  begin\n    transaction(requires_new: true) do\n      execute(sql)\n    end\n\n    true\n  rescue ActiveRecord::StatementInvalid\n    false\n  end\nend\n"

#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/postgresql/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: Rails was not able to disable referential integrity.\n\nThis is most likely caused due to missing permissions.\nRails needs superuser privileges to disable referential integrity.\n\n    cause: \#{original_exception&.message}\n\n    WARNING\n    raise e\n  end\n\n  begin\n    transaction(requires_new: true) do\n      execute(tables.collect { |name| \"ALTER TABLE \#{quote_table_name(name)} ENABLE TRIGGER ALL\" }.join(\";\"))\n    end\n  rescue ActiveRecord::ActiveRecordError\n  end\nend\n"