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