Skip to content

Commit

Permalink
missing_foreign_keys: consider column type for foreign key candidates (
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima authored Jan 3, 2025
1 parent ad7f04a commit 38753de
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/active_record_doctor/detectors/missing_foreign_keys.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def detect
# We need to skip polymorphic associations as they can reference
# multiple tables but a foreign key constraint can reference
# a single predefined table.
next unless named_like_foreign_key?(column)
next unless looks_like_foreign_key?(column)
next if foreign_key?(table, column)
next if polymorphic_foreign_key?(table, column)

Expand All @@ -37,8 +37,11 @@ def detect
end
end

def named_like_foreign_key?(column)
column.name.end_with?("_id")
def looks_like_foreign_key?(column)
type = column.type.to_s

column.name.end_with?("_id") &&
(type == "integer" || type.include?("uuid"))
end

def foreign_key?(table, column)
Expand Down
20 changes: 20 additions & 0 deletions test/active_record_doctor/detectors/missing_foreign_keys_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,26 @@ def test_present_foreign_key_is_not_reported
refute_problems
end

def test_non_integer_missing_foreign_key_is_reported
Context.create_table(:users) do |t|
t.string :external_id
end

refute_problems
end

def test_uuid_missing_foreign_key_is_reported
require_uuid_column_type!

Context.create_table(:users) do |t|
t.uuid :company_id
end

assert_problems(<<~OUTPUT)
create a foreign key on users.company_id - looks like an association without a foreign key constraint
OUTPUT
end

def test_config_ignore_models
Context.create_table(:companies)
Context.create_table(:users) do |t|
Expand Down

0 comments on commit 38753de

Please sign in to comment.