Load a structure.sql into a rails database via rake

Ruby on-RailsSchema

Ruby on-Rails Problem Overview


rake db:schema:load will load a schema.rb file into a rails database. Is there a way to load a structure.sql file into the database through rake or do I just need to do this manually?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Use rake db:structure:load, which will load db/structure.sql.

[Update]

If you want to load another file, you can specify its path via

  • SCHEMA environment variable (Rails 5.0 or later)
  • DB_STRUCTURE environment variable (Rails 4.x)

For example, run

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

or

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

Solution 2 - Ruby on-Rails

Just use

rake db:setup

which will use either schema.rb or structure.sql depending on your configuration.

Solution 3 - Ruby on-Rails

Use the database's own SQL load mechanism.

For Postgres this should work (at least if the database exists and you don't need a password):

psql -d databaseName < db/structure.sql

On Heroku where rake db:setup doesn't work as you can't create a database like that you can do this:

heroku pg:psql < db/structure.sql

Solution 4 - Ruby on-Rails

Once you load your schema, you can try:

rails dbconsole < structure.sql

OR

rails db < structure.sql

Solution 5 - Ruby on-Rails

Sometimes you want to load a file that is not the default db/structure.sql.

For rails 4.2 and earlier, use

DB_STRUCTURE=some_file.sql rake db:structure:load

As of rails 5 use

SCHEMA=some_file.sql rake db:structure:load

Solution 6 - Ruby on-Rails

Make your seeds.rb file like:

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.

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
QuestionlocoboyView Question on Stackoverflow
Solution 1 - Ruby on-RailsTsutomuView Answer on Stackoverflow
Solution 2 - Ruby on-RailsnathanvdaView Answer on Stackoverflow
Solution 3 - Ruby on-RailsJoseph LordView Answer on Stackoverflow
Solution 4 - Ruby on-RailsJstRoRRView Answer on Stackoverflow
Solution 5 - Ruby on-RailsjpayneView Answer on Stackoverflow
Solution 6 - Ruby on-RailsLenin Raj RajasekaranView Answer on Stackoverflow