简体   繁体   中英

Import SQL file to Rails 4 ActiveRecord db?

I've looked over several other questions on here, and they're vaguely similar, but not exactly what I'm looking for.

What I'm trying to do is import/"convert" a *.sql file which contains 8 tables, each of which contain roughly 24 columns. This file is actually fairly flat file, seeing as though the only queries that worked previous had to do with associating a shared :id between tables (so, SELECT * FROM table1, table2 WHERE id = '1' would pull all results, which was fine at the time).

I've searched around, but can't find a clever way to do this, so I'm asking you Rails pros for help now.

I'm assuming what you want is basically to convert your SQL file into a Rails database schema file without having to go through and do this yourself manually.

One quick way to do this would be to manually execute the SQL file, perhaps by logging into your database and loading the file that way, or by doing something like what was done in this question :

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

Once you have the schema that was defined in your .sql file actually loaded into your database, you will want to follow the steps outlined in this question :

First run rake db:schema:dump which will generate a db/schema.rb database file based on the current state of the database.

From here, you can create a db/migrate/001_original_schema.rb migration that references the schema.rb file as follows:

class OriginalDatabaseMigration < ActiveRecord::Migration
  def self.up
    # contents of schema.rb here
  end

  def self.down
    # drop all the tables
  end
end

If I understood your question right you need to populate your db from .sql file. I am doing it this way:

 connection = ActiveRecord::Base.connection ql = File.read('db/some_sql_file.sql') statements = sql.split(/;$/) statements.pop ActiveRecord::Base.transaction do statements.each do |statement| connection.execute(statement) end end 

Put your sql file to db folder.

One way I was able to do this - using rails dbconsole

.import FILE TABLE Import data from FILE into TABLE

And essentially .import ./path/to/file TABLE_NAME

Works like a champ.

I have faced the same problem, i just created a script and parsed all the SQL sentences adding 'execute("' at the begining and '")' at the end of each line.

Then i created a new migartion as usual, and pasted all the output on the migration up script. That works for me.

Be aware of avoid any comments on the SQL file so the parsing will be easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM