Skip to content

Commit

Permalink
Allow mismatching bigint FK to integer PK types
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuay03 committed Feb 26, 2024
1 parent 730b8a3 commit d823335
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/online_migrations/command_checker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -855,7 +855,8 @@ def check_mismatched_foreign_key_type(table_name, column_name, type, **options)
primary_key = options[:primary_key] || connection.primary_key(foreign_table_name)
primary_key_column = column_for(foreign_table_name, primary_key)

if primary_key_column && type != primary_key_column.sql_type.to_sym
if primary_key_column && type != (primary_key_column_type = primary_key_column.sql_type.to_sym) &&
!(type == :bigint && primary_key_column_type == :integer)
raise_error :mismatched_foreign_key_type,
table_name: table_name, column_name: column_name
end
Expand Down
18 changes: 17 additions & 1 deletion test/command_checker/add_reference_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,22 @@ def test_add_reference_no_index
assert_safe AddReferenceNoIndex
end

class AddReferenceFromTypeBigIntToInt < TestMigration
disable_ddl_transaction!

def change
add_reference :projects, :user, type: :bigint, index: false
end
end

def test_add_reference_from_type_bigint_to_int
@connection.drop_table(:users, if_exists: true)
@connection.create_table(:users, id: :integer, force: :cascade)

assert_equal :integer, @connection.columns(:users).find { |c| c.name == "id" }.sql_type.to_sym
assert_safe AddReferenceFromTypeBigIntToInt
end

class AddReferenceIndexConcurrently < TestMigration
disable_ddl_transaction!

Expand Down Expand Up @@ -89,7 +105,7 @@ def change
end

def test_add_reference_concurrently_with_mismatching_type
assert_not_equal :uuid, @connection.columns(:users).find { |c| c.name == "id" }.type
assert_not_equal :uuid, @connection.columns(:users).find { |c| c.name == "id" }.sql_type.to_sym
assert_unsafe AddReferenceConcurrentlyWithMismatchingType, <<~MSG
projects.user_id references a column of different type - foreign keys should be of the same type as the referenced primary key.
Otherwise, there's a risk of errors caused by IDs representable by one type but not the other.
Expand Down

0 comments on commit d823335

Please sign in to comment.