Skip to content

Foreign keys are expected in reverse order #1349

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ def foreign_keys(table_name)
identifier = SQLServer::Utils.extract_identifiers(table_name)
fk_info = execute_procedure :sp_fkeys, nil, identifier.schema, nil, identifier.object, identifier.schema

grouped_fk = fk_info.group_by { |row| row["FK_NAME"] }.values.each { |group| group.sort_by! { |row| row["KEY_SEQ"] } }
grouped_fk = fk_info.group_by { |row| row["FK_NAME"] }.values.each { |group| group.sort_by! { |row| row["KEY_SEQ"] } }.reverse
grouped_fk.map do |group|
row = group.first
options = {
Expand Down
28 changes: 28 additions & 0 deletions test/cases/coerced_tests.rb
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,34 @@ def migrate(x)
nil
end
end

# Foreign key count is the same as PostgreSQL/SQLite.
coerce_tests! :test_remove_foreign_key_on_8_0
def test_remove_foreign_key_on_8_0_coerced
connection.create_table(:sub_testings) do |t|
t.references :testing, foreign_key: true, type: :bigint
t.references :experiment, foreign_key: {to_table: :testings}, type: :bigint
end

migration = Class.new(ActiveRecord::Migration[8.0]) do
def up
change_table(:sub_testings) do |t|
t.remove_foreign_key :testings
t.remove_foreign_key :testings, column: :experiment_id
end
end
end

assert_raise(StandardError, match: /Table 'sub_testings' has no foreign key for testings$/) {
ActiveRecord::Migrator.new(:up, [migration], @schema_migration, @internal_metadata).migrate
}

foreign_keys = @connection.foreign_keys("sub_testings")
assert_equal 2, foreign_keys.size
ensure
connection.drop_table(:sub_testings, if_exists: true)
ActiveRecord::Base.clear_cache!
end
end
end
end
Expand Down
Loading