Froze rails gems
[depot.git] / vendor / rails / railties / lib / commands / dbconsole.rb
1 require 'erb'
2 require 'yaml'
3 require 'optparse'
4
5 include_password = false
6
7 OptionParser.new do |opt|
8 opt.banner = "Usage: dbconsole [options] [environment]"
9 opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v|
10 include_password = true
11 end
12 opt.parse!(ARGV)
13 abort opt.to_s unless (0..1).include?(ARGV.size)
14 end
15
16 env = ARGV.first || ENV['RAILS_ENV'] || 'development'
17 unless config = YAML::load(ERB.new(IO.read(RAILS_ROOT + "/config/database.yml")).result)[env]
18 abort "No database is configured for the environment '#{env}'"
19 end
20
21
22 def find_cmd(*commands)
23 dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR)
24 commands += commands.map{|cmd| "#{cmd}.exe"} if RUBY_PLATFORM =~ /win32/
25 commands.detect do |cmd|
26 dirs_on_path.detect do |path|
27 File.executable? File.join(path, cmd)
28 end
29 end || abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.")
30 end
31
32 case config["adapter"]
33 when "mysql"
34 args = {
35 'host' => '--host',
36 'port' => '--port',
37 'socket' => '--socket',
38 'username' => '--user',
39 'encoding' => '--default-character-set'
40 }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact
41
42 if config['password'] && include_password
43 args << "--password=#{config['password']}"
44 elsif config['password'] && !config['password'].empty?
45 args << "-p"
46 end
47
48 args << config['database']
49
50 exec(find_cmd('mysql', 'mysql5'), *args)
51
52 when "postgresql"
53 ENV['PGUSER'] = config["username"] if config["username"]
54 ENV['PGHOST'] = config["host"] if config["host"]
55 ENV['PGPORT'] = config["port"].to_s if config["port"]
56 ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && include_password
57 exec(find_cmd('psql'), config["database"])
58
59 when "sqlite"
60 exec(find_cmd('sqlite'), config["database"])
61
62 when "sqlite3"
63 exec(find_cmd('sqlite3'), config["database"])
64
65 else
66 abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!"
67 end