Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing database.yml info through a rake task

I'm trying to write a rake task for loading data into my database. My plan is do something like

system "mysql -u foo -pbar database < backup.sql"

but I need to access the config/database.yml data for getting the user, pass and database info. The trick is I don't want to "parse" this file but to access this info in the same way tasks like rake db:reset do.

How can I do that?

like image 351
Erik Escobedo Avatar asked Jun 24 '10 15:06

Erik Escobedo


2 Answers

This will work.

task :demo_using_db_config => :environment do
  db_config = Rails.application.config.database_configuration[Rails.env]
  system "mysql -u#{db_config['username']} -p#{db_config['password']} #{db_config['database']} < backup.sql"
end

Since this is environment specific, we want the task to depend on the :environment task.

Alternatively, if you are using ActiveRecord, you can get to this information like below:

  abcs = ActiveRecord::Base.configurations
  puts abcs[Rails.env]["username"]
  puts abcs[Rails.env]["password"]

This works in rake tasks and elsewhere.

like image 195
Shyam Habarakada Avatar answered Oct 11 '22 16:10

Shyam Habarakada


In Rails 3, from the console, you can type the following to see various database login credentials you defined in database.yml

config = Rails.application.config.database_configuration

In your rake file, you could specify something like this:

task :mysqlimport_table
  db_config = Rails.application.config.database_configuration[Rails.env]
  sh "mysqlimport -u#{db_config['username']} -p#{db_config['password']} #{db_config['database']} --default-character-set=utf8 --local <path_to_your_file>"
end

task :mysqlrun_sql_script
  db_config = Rails.application.config.database_configuration[Rails.env]
  sh "mysql -u#{db_config['username']} -p#{db_config['password']} -D#{db_config['database']} < <path_to_your_sql_file>"

end
like image 44
Daniel Huang Avatar answered Oct 11 '22 16:10

Daniel Huang