Permalink
Browse files

fk: dump foreign keys at the bottom to make sure tables exist.

  • Loading branch information...
1 parent 9ae1a2c commit 0938d5305758dfcbec4e813c777bb627e82a5906 @senny senny committed Jun 11, 2014
Showing with 16 additions and 6 deletions.
  1. +9 −6 activerecord/lib/active_record/schema_dumper.rb
  2. +7 −0 activerecord/test/cases/schema_dumper_test.rb
@@ -91,7 +91,8 @@ def extensions(stream)
end
def tables(stream)
- @connection.tables.sort.each do |tbl|
+ sorted_tables = @connection.tables.sort
+ sorted_tables.each do |tbl|
next if ['schema_migrations', ignore_tables].flatten.any? do |ignored|
case ignored
when String; remove_prefix_and_suffix(tbl) == ignored
@@ -102,6 +103,13 @@ def tables(stream)
end
table(tbl, stream)
end
+
+ # dump foreign keys at the end to make sure all dependent tables exist.
+ if @connection.supports_foreign_keys?
+ sorted_tables.each do |tbl|
+ foreign_keys(tbl, stream)
+ end
+ end
end
def table(table, stream)
@@ -171,8 +179,6 @@ def table(table, stream)
indexes(table, tbl)
- foreign_keys(table, tbl)
-
tbl.rewind
stream.print tbl.read
rescue => e
@@ -215,8 +221,6 @@ def indexes(table, stream)
end
def foreign_keys(table, stream)
- return unless @connection.supports_foreign_keys?
-
if (foreign_keys = @connection.foreign_keys(table)).any?
add_foreign_key_statements = foreign_keys.map do |foreign_key|
parts = [
@@ -233,7 +237,6 @@ def foreign_keys(table, stream)
end
stream.puts add_foreign_key_statements.sort.join("\n")
- stream.puts
end
end
@@ -372,6 +372,13 @@ def test_schema_dump_keeps_id_false_when_id_is_false_and_unique_not_null_column_
assert_match %r{create_table "subscribers", id: false}, output
end
+ if ActiveRecord::Base.connection.supports_foreign_keys?
+ def test_foreign_keys_are_dumped_at_the_bottom_to_circumvent_dependency_issues
+ output = standard_dump
+ assert_match(/^\s+add_foreign_key "fk_test_has_fk"[^\n]+\n\s+add_foreign_key "lessons_students"/, output)
+ end
+ end
+
class CreateDogMigration < ActiveRecord::Migration
def up
create_table("dog_owners") do |t|

0 comments on commit 0938d53

Please sign in to comment.