Import SQL file in Rails 4 ActiveRecord db?

I looked at a few other questions here, and they are vaguely similar, but not quite what I am looking for.

What I'm trying to do is import / "convert" a * .sql file, which contains 8 tables, each of which contains approximately 24 columns. This file is actually a fairly flat file, because as if only the previous previous queries were related to combining a common identifier between tables (therefore SELECT * FROM table1, table2 WHERE id = '1' will pull all the results that were fine in that time).

I searched around but can't find a smart way to do this, so now I ask you to get Rails support.

+4
source share
4 answers

If I understand your question correctly, you need to fill in your db from the .sql file. I do it like this:

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
Run codeHide result

Put your sql file in the db folder.

+1
source

I assume that you want to basically convert your SQL file to a Rails database schema file without having to go through and do it yourself manually.

One quick way to do this is to manually execute the SQL file, possibly by logging into your database and loading the file this way, or by doing something like the one done in this question :

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

After you have the schema defined in your .sql file loaded into your database, you will want to follow these steps in this question :

rake db:schema:dump, db/schema.rb .

db/migrate/001_original_schema.rb, schema.rb :

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

  def self.down
    # drop all the tables
  end
end
0

- rails dbconsole

.import FILE TABLE Import data from FILE into TABLE

, , .import ./path/to/file TABLE_NAME

.

0

, script SQL, 'execute ("' '') ' .

, , script. .

SQL, .

0
source

All Articles