【问题标题】:Load a structure.sql into a rails database via rake通过 rake 将 structure.sql 加载到 rails 数据库
【发布时间】:2014-05-30 06:51:15
【问题描述】:

rake db:schema:load 会将schema.rb 文件加载到 Rails 数据库中。有没有办法通过 rake 将structure.sql 文件加载到数据库中,还是我只需要手动执行此操作?

【问题讨论】:

  • 将文件加载到 Rails 数据库中是什么意思?这是否意味着基于文件创建数据库结构(表、表名和属性)?

标签: ruby-on-rails schema


【解决方案1】:

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

[更新]

如果你想加载另一个文件,你可以通过指定它的路径

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

例如,运行

rake db:structure:load SCHEMA=db/another.sql

rake db:structure:load DB_STRUCTURE=db/another.sql

【讨论】:

  • 或通过 ENV 变量指定文件路径,如下所示:rake db:structure:load DB_STRUCTURE=db/another.sql
  • 为了指定SQL文件的路径,使用SCHEMA环境变量(不是DB_STRUCTURE)像rake db:structure:load SCHEMA=db/another.sql一样。
  • 不要将结构与架构混淆。 SCHEMA 用于 .rb 文件(架构),DB_STRUCTURE 用于 .sql 文件(数据库结构)github.com/rails/rails/blob/…
  • 好像在最新的代码上,使用了环境变量SCHEMA。见github.com/rails/rails/blob/…
  • 确实如此。我指的是 4.2.5.2。
【解决方案2】:

随便用

rake db:setup

这将使用schema.rbstructure.sql,具体取决于您的配置。

【讨论】:

  • 取决于什么配置?能否请您添加一些文档的链接?
  • 在你的application.rb你可以写config.active_record.schema_format = :sql,默认是:schemaguides 对此不清楚:他们只是说rake db:setup 将从模式加载,这可能会或可能会考虑配置(模式是指数据库模式,它是按配置存储的,还是仅schema.rb)。像往常一样,来源是确定的:github.com/rails/rails/blob/…
【解决方案3】:

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

对于 Postgres,这应该可以工作(至少在数据库存在并且您不需要密码的情况下):

psql -d databaseName < db/structure.sql

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

heroku pg:psql < db/structure.sql

【讨论】:

    【解决方案4】:

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

    rails dbconsole < structure.sql
    

    rails db < structure.sql
    

    【讨论】:

    • 天啊,这改变了游戏规则。经过近 8 年的 Rails 开发,我现在怎么才知道这一点!
    【解决方案5】:

    有时您想要加载不是默认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

    【讨论】:

      【解决方案6】:

      使你的种子.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
      

      Source.

      【讨论】:

      • 我添加了statements.reject! { |statement| statement.match?(%r{ar_internal_metadata|schema_migrations}) } 来删除已经存在的rails 默认表。
      猜你喜欢
      • 2011-05-15
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      相关资源
      最近更新 更多