From e7d2683c58d460c0ed75f2e14f191bf4711c719d Mon Sep 17 00:00:00 2001 From: Steve Purcell Date: Sat, 3 May 2008 21:25:08 +0200 Subject: [PATCH] Add db:console:* tasks --- railties/lib/tasks/databases.rake | 43 +++++++++++++++++++++++++++++++++++++ 1 files changed, 43 insertions(+), 0 deletions(-) diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake index e39f9ca..403d4a0 100644 --- a/railties/lib/tasks/databases.rake +++ b/railties/lib/tasks/databases.rake @@ -364,8 +364,51 @@ namespace :db do ActiveRecord::Base.connection.execute "DELETE FROM #{session_table_name}" end end + + namespace :console do + require 'yaml' + YAML::load(File.read(RAILS_ROOT + "/config/database.yml")).each do |env, config| + desc "Connect to the '#{env}' DB using a console tool" + task env.to_sym do + case config["adapter"] + when "mysql" + system(find_cmd(*%w(mysql5 mysql)), + '-u', config["username"], + "-p#{config["password"]}", + '-h', config["host"], + '--default-character-set', config["encoding"], + '-D', config["database"]) + when "postgresql" + ENV['PGHOST'] = config["host"] if config["host"] + ENV['PGPORT'] = config["port"].to_s if config["port"] + ENV['PGPASSWORD'] = config["password"].to_s if config["password"] + system(find_cmd('psql'), '-U', config["username"], config["database"]) + when "sqlite" + system(find_cmd('sqlite'), config["database"]) + when "sqlite3" + system(find_cmd('sqlite3'), config["database"]) + else raise "not supported for this database type" + end + end + end + end + + task :console do + Rake::Task["db:console:" + (ENV['DB'] || RAILS_ENV || 'development')].invoke + end end +def find_cmd(*commands) + dirs_on_path = ENV['PATH'].split(File::PATH_SEPARATOR) + commands += commands.map{|cmd| "#{cmd}.exe"} if RUBY_PLATFORM =~ /win32/ + commands.detect do |cmd| + dirs_on_path.detect do |path| + File.executable? File.join(path, cmd) + end + end || raise("couldn't find matching executable: #{commands.join(', ')}") +end + + def drop_database(config) case config['adapter'] when 'mysql' -- 1.5.5.1