rails/rails — pull request #15394 by morgoth (2014-06-01 15:47:28+00:00)
Title: ActiveRecord::Migration.maintain_test_schema! doesn't work with structure.sql

Introduced in rails 4.1.
Checked using sqlite3 and postgres.

At the end of calling `ActiveRecord::Migration.maintain_test_schema!` this method is called: https://github.com/rails/rails/blob/99873ca1ea98d73c73f8be60dfce0a54224f4ea8/activerecord/lib/active_record/tasks/database_tasks.rb#L159 which later, after choosing database adapter calls i.e. method on sqlite3 adapter: https://github.com/rails/rails/blob/99873ca1ea98d73c73f8be60dfce0a54224f4ea8/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb#L35

So at the very end it runs: `sqlite3 db/test.sqlite3 < db/structure.sql`

This however can result in error like:

```
Error: near line 1: table "schema_migrations" already exists
Error: near line 2: index unique_schema_migrations already exists
Error: near line 3: table "users" already exists
Error: near line 4: UNIQUE constraint failed: schema_migrations.version
```

This error can happen when we created migration to add column to existing table.

It looks like it's necessary to always purge database before loading sql file and adding:

```
purge(current_config)
create(current_config)
```

before line https://github.com/rails/rails/blob/99873ca1ea98d73c73f8be60dfce0a54224f4ea8/activerecord/lib/active_record/tasks/database_tasks.rb#L168 fixes the issue.
I'm not sure if that is the best place however.

Similar issue was noted in https://github.com/rails/rails/pull/13528#issuecomment-40718912 by @kevintyll

Please, let me know if the issue is unclear, I can submit example app then.
If you think that's the correct way of fixing it, I can prepare a PR.

Addressing to @jonleighton as he is the author of this feature.