What's the difference between db:test:clone, db:test:clone_structure, db:test:load, and db:test:prepare? What's the difference between db:test:clone, db:test:clone_structure, db:test:load, and db:test:prepare? database database

What's the difference between db:test:clone, db:test:clone_structure, db:test:load, and db:test:prepare?


Very good question. Had me stumped so I dove into the rails source and pulled up database.rake. Now it's more clear:

  • db:test:clone is just a combination of db:schema:dump and db:test:load:

    task :clone => %w(db:schema:dump db:test:load)
  • db:test:clone_structure uses the {rails_env}_structure.sql file:

    task :clone_structure => [ 'db:structure:dump', 'db:test:purge' ] do  # skipped some code, here's what happens for MySQL:  ActiveRecord::Base.establish_connection(:test)  # ...  IO.readlines("#{Rails.root}/db/#{Rails.env}_structure.sql").join.split("\n\n").each do |table|    ActiveRecord::Base.connection.execute(table)  endend
  • db:test:load is the same as db:schema:load, but invokes it on the test database:

    task :load => 'db:test:purge' do  ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])  # ...  db_namespace['schema:load'].invokeend
  • db:test:prepare alerts you if any migrations are pending, and if not, either runs db:test:clone_structure (using the {rails_env}_structure.sql file) or db:test:load (using the schema.rb file), depending on the schema format (this is a little confusing to me, maybe someone else can expand on it):

    task :prepare => 'db:abort_if_pending_migrations' do  # ...  db_namespace[{ :sql  => 'test:clone_structure', :ruby => 'test:load' }[ActiveRecord::Base.schema_format]].invokeend

Hope this clears it up! Again, going through the database.rake file is easy and will clear up any other questions you might have. That link goes to the line that is the beginning of the :test namespace.


They are actually not quite the same thing. Any of those tasks that contain the word 'schema' act on the .../db/schema.rb file. schema.rb is effectively the state of your schema after applying all migrations. It can be executed to restore your schema rather than running all of the db migrations (which can take a long time if you have lots of migrations).

Any of the tasks with the word 'structure', act on the {Rails.env}_structure.sql file. This file is used when your schema contains constructs that can't be expressed in the schema.rb file. For example, if you use features specific to a particular RDBMS. Under the covers, rails produces this file using whatever schema dump utility it appropriate for your RDBMS. To restore the schema, it reads the file in and executes the SQL statements agains using an RDBMS-specific tool.

Rails knows whether to go the schema.rb route or the structure.sql route based on whether or not you've set

config.active_record.schema_format = :sql

in your .../config/application.rb