How can I import a SQL file into a Rails database?

SqlRuby on-Rails

Sql Problem Overview


I've got a .sql file that I'd like to load into my Rails database using a Rake task. How can I do this?

Sql Solutions


Solution 1 - Sql

The easiest way:

bundle exec rails db < $SQL_FILE

example:

bundle exec rails db < my_db.sql

Solution 2 - Sql

The Easy Way

This works for simple cases.

ActiveRecord::Base.connection.execute(IO.read("path/to/file"))

Solution found on the Ruby On Rails mailing list from 2006 (but still works in 2011 on Rails 3.1).

Footnotes

  • This related question implied this solution, but rejected it for big imports. I wanted to show it explicitly, since it works for smaller ones.

  • The file I was trying to import contained a LOCK TABLES followed by an insert. The data was for a MySQL database. Mysql2 said it had an invalid SQL syntax error until I removed the lock and unlock statements.

Solution 3 - Sql

On MySQL this gave me a syntax error. Splitting the sql into statements made it work.

sql = File.read(sql_file)
statements = sql.split(/;$/)
statements.pop # remove empty line
ActiveRecord::Base.transaction do
  statements.each do |statement|
    connection.execute(statement)
  end
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan LongView Question on Stackoverflow
Solution 1 - SqlAbelView Answer on Stackoverflow
Solution 2 - SqlNathan LongView Answer on Stackoverflow
Solution 3 - SqljoostView Answer on Stackoverflow