Forum: Ruby on Rails how to import a dump .sql file in a rake task

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Kad K. (Guest)
on 2008-12-14 00:58
(Received via mailing list)
I have a dump of some tables to be filled when the app is setup

'.../db/dataset/regions_dpt_cities_codes.sql'

I would like to execute a task similar to the  >mysql source
<dump_file>
like :
ActiveRecord::Base.connection.execute("source #{path};")     (which
doesn't run fine,  of course....

is it possible in a rake task ? if yes, any  suggestion ?

thanks for your suggestions

erwin
Patrick D. (Guest)
on 2008-12-14 05:20
(Received via mailing list)
On Sat, Dec 13, 2008 at 5:57 PM, Erwin <removed_email_address@domain.invalid> 
wrote:

>
> is it possible in a rake task ? if yes, any  suggestion ?
>
> thanks for your suggestions
>
How about:

task :load_sql_dump
  sh 'mysql -u user -p password < regions_dpt_cities_codes.sql'
end

Personally, I like to see the shell commands as they are executed (a
legacy
of my misspent youth with Makefiles), so I put

verbose(true)

at the top my my Rakefiles.

--wpd
Kaushik katari (Guest)
on 2008-12-14 16:40
(Received via mailing list)
I had a similar problem, and started out declaring the username and
password
in every line of the rake tasks. Did not like that, since I had many
rake
tasks, and changing a database connection meant changing every line in
the
rake code.

A better way is as follows (I read this from some google post, but
cannot
remember who it was, so sorry about not giving credit where credit is
due):

1> DBConn is an active record connection.
2> Parse the sql file by splitting on ';'.
task :create_empty_schema do
    sql = File.open("path_to_your_file/dataload.sql").read
    sql.split(';').each do |sql_statement|
        DBConn.connection.execute(sql_statement)
    end
  puts "Empty Schema has been created '#{Time.now}' "
end

Remove blank lines from the end of the file, or else it complains. So,
it is
a little brittle.
This topic is locked and can not be replied to.