Db: test: clone、 db: test: clone_struct、 db: test: load 和 db: test: ready 之间的区别是什么?

你必须承认,对于一个刚接触 Rails 和数据库的新手来说,rubyonRails.org 上的官方解释让这四个任务听起来完全一样。语录:

rake db:test:clone  Recreate the test database from
the current environment’s database schema


rake db:test:clone_structure    Recreate the test database from the
development structure


rake db:test:load   Recreate the test database from the current schema.rb


rake db:test:prepare    Check for pending migrations and load the test schema

我甚至不知道结构和模式之间的区别。加载当前环境的模式和只加载 schema.rb 有什么区别?

这些任务究竟有多相似(或不同) ?

21172 次浏览

问得好。我被难住了,所以我潜入轨道源,拉起 database.rake。现在事情变得更加清楚了:

  • db:test:clone只是 db:schema:dumpdb: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)
    end
    end
    
  • 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'].invoke
    end
    
  • 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]].invoke
    end
    

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.

它们实际上并不完全一样。在.../db/schema.rb 文件中包含单词“ schema”的任何任务。Rb 实际上是应用所有迁移之后模式的状态。可以执行它来恢复您的模式,而不是运行所有的 db 迁移(如果有大量迁移,这可能会花费很长时间)。

任何带有单词“ structure.sql”的任务都作用于{ Rails.env } _ structure.sql 文件。当您的模式包含无法在 schema.rb 文件中表示的构造时,将使用此文件。例如,如果您使用特定于特定 RDBMS 的特性。在这个掩护下,Rails 使用适合您的 RDBMS 的任何模式转储实用程序生成这个文件。为了还原模式,它将文件读入并使用特定于 RDBMS 的工具再次执行 SQL 语句。

Rails 根据您是否已经设置了 schema.rb 路由或 structure.sql 路由,知道是否使用 schema.rb 路由或 structure.sql 路由

Active _ record. schema _ format = : sql

在您的.../config/application.rb 中