rails/rails — Issue #4772: Environment loaded too late to affect db:setup
Author: wrs
Created: 2012-01-31 01:46:18+00:00
State: open

[In Rails 3.2.1]

https://github.com/rails/rails/pull/2948 fixed the inequity between Ruby and SQL schema dumps, and now theoretically the rake tasks should work. However, if you uncomment the line in application.rb:

```ruby
config.active_record.schema_format = :sql
```

The `db:reset` task still doesn't load `structure.sql`, instead failing on the missing `schema.rb`.

I think the problem is that the environment is loaded by `db:schema:load`, which is too late for the test that already happened in `db:schema:load_if_ruby`. Rake trace with debugging output:

```
** Invoke db:setup (first_time)
** Invoke db:schema:load_if_ruby (first_time)
** Invoke db:create (first_time)
** Invoke db:load_config (first_time)
** Invoke rails_env (first_time)
** Execute rails_env
** Execute db:load_config
** Execute db:create
** Execute db:schema:load_if_ruby
SCHEMA FORMAT IS :ruby
** Invoke db:schema:load (first_time)
** Invoke environment (first_time)
** Execute environment
SETTING SCHEMA FORMAT TO :sql
** Execute db:schema:load
db/schema.rb doesn't exist yet. Run `rake db:migrate` to create it then try again. If you do not intend to use a database, you should instead alter /tmp/packaging/config/application.rb to limit the frameworks that will be loaded
```

A workaround is to use `db:reset` instead, which will do a (usually) harmless drop first.

Simply changing :rails_env to :environment on line 5 of `databases.rake` seems to fix this. I'm not set up to test a patch at the moment but wanted to get the issue in regardless.