If you haven’t installed Sake yet, stop whatever it is you’re doing and get it running on your system.
Ok, with that done you’ll probably want some sake tasks to actually make this new tool useful. Below is an updated version of one my favorite tasks.
desc 'Launches the database shell using the values defined in config/database.yml'
task 'db:shell' => [ 'environment' ] do
config = ActiveRecord::Base.configurations[(RAILS_ENV or "development")]
command = ""
case config["adapter"]
when "mysql" then
command << "mysql "
command << "--host=#{(config["host"] or "localhost")} "
command << "--port=#{(config["port"] or 3306)} "
command << "--user=#{(config["username"] or "root")} "
command << "--password=#{(config["password"] or "")} "
command << config["database"])
when "postgresql" then
command << "export PGPASSWORD=#{config["password"]} && " unless config["password"].blank?
command << "psql "
command << "-h #{(config["host"])} " unless config ["host"].blank?
command << "-p #{(config["port"])} ") unless config ["port"].blank?
command << "-U #{(config["username"])} " unless config["username"].blank?
command << config["database"]
when "sqlite3"
command << "sqlite3 #{config["database"]}"
else
command << "echo Unsupported database adapter: #{config["adapter"]}"
end
system(command)
end
With the above task you be in any RAILS_ROOT and type sake db:shell and be automatically placed into the appropriate database shell with your username/password/host/port setup already. You can even do sake db:shell RAILS_ENV=production.
I can’t take credit for this task, in fact I originally found it on the Sake Bomb blog post by Err The Blog. The link found in the comments on that page no longer works, but some googling turned up the source code elsewhere. I’ve added Postgres and sqlite3 to the mix as it only supported MySQL originally. If you know who the original author is please let me know as I would like to credit them.