通过rake将structure.sql加载到rails数据库中

loc*_*boy 47 schema ruby-on-rails

rake db:schema:loadschema.rb文件加载到rails数据库中.有没有办法structure.sql通过rake 将文件加载到数据库中,或者我只需要手动执行此操作吗?

Tsu*_*omu 81

使用rake db:structure:load,将加载db/structure.sql.

[更新]

如果要加载另一个文件,可以指定其路径

  • SCHEMA 环境变量(Rails 5.0或更高版本)
  • DB_STRUCTURE 环境变量(Rails 4.x)

例如,运行

rake db:structure:load SCHEMA=db/another.sql
Run Code Online (Sandbox Code Playgroud)

要么

rake db:structure:load DB_STRUCTURE=db/another.sql
Run Code Online (Sandbox Code Playgroud)

  • 或者通过ENV变量指定文件路径,如下所示:`rake db:structure:load DB_STRUCTURE = db/another.sql` (3认同)
  • 似乎在最新的代码中,使用了环境变量`SCHEMA`。见 https://github.com/rails/rails/blob/b6d5e46311d7ea59539c1f45c6ffb269eeb23912/activerecord/lib/active_record/railties/databases.rake#L303 (2认同)

nat*_*vda 28

只是用

rake db:setup
Run Code Online (Sandbox Code Playgroud)

它将使用schema.rbstructure.sql取决于您的配置.

  • 在`application.rb`中,您可以编写`config.active_record.schema_format =:sql`,默认为`:schema`.[指南](http://guides.rubyonrails.org/active_record_migrations.html#setup-the-database)对此不清楚:他们只是说`rake db:setup`将从架构加载,这可能会或可能会采取配置到帐户(模式是指数据库模式,它是按配置存储的,还是仅仅是`schema.rb`).像往常一样,来源是明确的:https://github.com/rails/rails/blob/6201e62cc49720e9133759e9a19fd1cc11ab73e1/activerecord/lib/active_record/railties/databases.rake#L175 (13认同)

Jos*_*ord 6

使用数据库自​​己的SQL加载机制.

对于Postgres,这应该有效(至少如果数据库存在且您不需要密码):

psql -d databaseName < db/structure.sql
Run Code Online (Sandbox Code Playgroud)

在Heroku上rake db:setup不起作用,因为你无法创建像这样的数据库,你可以这样做:

heroku pg:psql < db/structure.sql
Run Code Online (Sandbox Code Playgroud)


jpa*_*yne 6

有时您想加载一个不是默认的文件db/structure.sql

对于 rails 4.2 及更早版本,请使用

DB_STRUCTURE=some_file.sql rake db:structure:load

截至 Rails 5 使用

SCHEMA=some_file.sql rake db:structure:load


Jst*_*oRR 5

加载架构后,您可以尝试:

rails dbconsole < structure.sql
Run Code Online (Sandbox Code Playgroud)

或者

rails db < structure.sql
Run Code Online (Sandbox Code Playgroud)


Len*_*ran 3

使您的 seeds.rb 文件如下:

unless Rails.env.production?
  connection = ActiveRecord::Base.connection

  sql = File.read('db/structure.sql')
  statements = sql.split(/;$/)
  statements.pop  # the last empty statement

  ActiveRecord::Base.transaction do
    statements.each do |statement|
      connection.execute(statement)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

来源