Skip to content

Commit 882842c

Browse files
authored
Foreign keys are expected in reverse order (#1349)
1 parent 531a7a9 commit 882842c

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

lib/active_record/connection_adapters/sqlserver/schema_statements.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ def foreign_keys(table_name)
269269
identifier = SQLServer::Utils.extract_identifiers(table_name)
270270
fk_info = execute_procedure :sp_fkeys, nil, identifier.schema, nil, identifier.object, identifier.schema
271271

272-
grouped_fk = fk_info.group_by { |row| row["FK_NAME"] }.values.each { |group| group.sort_by! { |row| row["KEY_SEQ"] } }
272+
grouped_fk = fk_info.group_by { |row| row["FK_NAME"] }.values.each { |group| group.sort_by! { |row| row["KEY_SEQ"] } }.reverse
273273
grouped_fk.map do |group|
274274
row = group.first
275275
options = {

test/cases/coerced_tests.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -838,6 +838,34 @@ def migrate(x)
838838
nil
839839
end
840840
end
841+
842+
# Foreign key count is the same as PostgreSQL/SQLite.
843+
coerce_tests! :test_remove_foreign_key_on_8_0
844+
def test_remove_foreign_key_on_8_0_coerced
845+
connection.create_table(:sub_testings) do |t|
846+
t.references :testing, foreign_key: true, type: :bigint
847+
t.references :experiment, foreign_key: {to_table: :testings}, type: :bigint
848+
end
849+
850+
migration = Class.new(ActiveRecord::Migration[8.0]) do
851+
def up
852+
change_table(:sub_testings) do |t|
853+
t.remove_foreign_key :testings
854+
t.remove_foreign_key :testings, column: :experiment_id
855+
end
856+
end
857+
end
858+
859+
assert_raise(StandardError, match: /Table 'sub_testings' has no foreign key for testings$/) {
860+
ActiveRecord::Migrator.new(:up, [migration], @schema_migration, @internal_metadata).migrate
861+
}
862+
863+
foreign_keys = @connection.foreign_keys("sub_testings")
864+
assert_equal 2, foreign_keys.size
865+
ensure
866+
connection.drop_table(:sub_testings, if_exists: true)
867+
ActiveRecord::Base.clear_cache!
868+
end
841869
end
842870
end
843871
end

0 commit comments

Comments
 (0)