【问题标题】:Is it possible to use an external SQL file in a Rails migration?是否可以在 Rails 迁移中使用外部 SQL 文件?
【发布时间】:2009-08-04 17:42:30
【问题描述】:

我必须创建一个 Rails 迁移,它会创建许多触发器和存储过程。

通常会使用execute 方法执行此操作,但由于语句的大小,我宁愿将它们保存在外部文件中并从迁移中引用它。

我该怎么做?有没有可能?

【问题讨论】:

    标签: sql ruby-on-rails migration


    【解决方案1】:

    您可以将它们存储在文本文件中,然后通过 File 对象读取它们。

    sql = ""
    source = File.new("./sql/procedures.sql", "r")
    while (line = source.gets)
      sql << line
    end
    source.close
    execute sql
    

    它很丑,但很有效。我强烈建议将存储过程/触发器保留在迁移中,以便于回滚。

    如果您使用“外部文件”方法,则每次迁移都需要维护两个额外的文件,一个用于添加所有内容,一个用于在以下情况下插入:

    rake db:rollback
    

    【讨论】:

    • ActiveRecord::Base.establish_connection ActiveRecord::Base.connection.execute(sql)
    【解决方案2】:

    我在需要的地方做了以下事情:

    class RawSqlMigration < ActiveRecord::Migration
      def up
        execute File.read(File.expand_path('../../sql_migrations/file.sql', __FILE__))
      end
    end
    

    【讨论】:

      【解决方案3】:

      如果文件中只有一个语句,Mike 的答案没有问题,但如果有更多语句(例如,多个插入和更新),ActiveRecord 将失败,因为它不支持默认情况下一次调用的多个语句.

      按照here 的指示,一种解决方案是修改 ActiveRecord 以支持多个语句。

      其他解决方案是确保您的 SQL 文件每行仅包含一条语句并使用类似循环

      source = File.open "db/foo.sql", "r"
      source.readlines.each do |line|
        line.strip!
        next if line.empty? # ensure that rows that contains newlines and nothing else does not get processed
        execute line
      end
      source.close
      

      【讨论】:

        猜你喜欢
        • 2012-11-11
        • 2019-01-01
        • 2016-01-03
        • 1970-01-01
        • 1970-01-01
        • 2012-01-22
        • 2018-02-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多