Skip to content

Commit

Permalink
Allow adding bigint foreign keys referencing integer primary keys
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuay03 authored and fatkodima committed Feb 27, 2024
1 parent 730b8a3 commit fa41279
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## master (unreleased)

- Allow adding bigint foreign keys referencing integer primary keys
- Fix `add_reference_concurrently` to check for mismatched key types

## 0.14.1 (2024-02-21)
Expand Down
8 changes: 7 additions & 1 deletion lib/online_migrations/command_checker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -854,8 +854,14 @@ def check_mismatched_foreign_key_type(table_name, column_name, type, **options)
if connection.table_exists?(foreign_table_name)
primary_key = options[:primary_key] || connection.primary_key(foreign_table_name)
primary_key_column = column_for(foreign_table_name, primary_key)
return if primary_key_column.nil?

if primary_key_column && type != primary_key_column.sql_type.to_sym
primary_key_type = primary_key_column.sql_type.to_sym
# Having bigint foreign keys is safe and people should
# detect integer primary keys via some other tools.
return if type == :bigint && primary_key_type == :integer

if type != primary_key_type
raise_error :mismatched_foreign_key_type,
table_name: table_name, column_name: column_name
end
Expand Down
11 changes: 11 additions & 0 deletions test/command_checker/add_reference_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,17 @@ def test_add_reference_concurrently_with_mismatching_type
MSG
end

class AddReferenceFromBigintToInteger < TestMigration
def change
add_reference :projects, :user, type: :bigint, index: false
end
end

def test_add_reference_from_bigint_to_integer
@connection.change_column(:users, :id, :integer)
assert_safe AddReferenceFromBigintToInteger
end

class AddReferenceForeignKey < TestMigration
def change
add_reference :projects, :user, index: false, foreign_key: true
Expand Down

0 comments on commit fa41279

Please sign in to comment.