Open mysql Command Using Rails Connection Details

Sometimes I need to quickly investigate something on the production server for one of my little apps.

Hunting down the password and trying to copy-paste it into the right mysql incantation is tedious.

So I automated it.

rails_mysql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/ruby
require 'rubygems'
require 'yaml'
config = YAML.load(File.read("config/database.yml"))
database= config[ENV["RAILS_ENV"] || "development"]
unless database["adapter"] =~ /mysql/
puts "Current RAILS_ENV is not a mysql database"
exit 1
end
cmd = "mysql -h\"#{database['host']}\" -u\"#{database['username']}\" -p\"#{database['password']}\" -P\"#{database['port']}\" -D\"#{database['database']}\""
puts cmd
exec cmd

Then you can launch it from the root of a rails app.

Terminal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
[/usr/share/www/secretagent.com]
[10:47:09 akatakritos]$ rails_mysql
mysql -h"database.secretagent.com" -u"bond007" -p"supersEcurepassw0rd" -P"3382" -D"secret_database"
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 676267
Server version: 5.1.56-log MySQL Server
Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show tables;
+---------------------------+
| Tables_in_secret_database |
+---------------------------+
| agents |
| blackmail_letters |
| enemies |
| schema_migrations |
| secrets |
+---------------------------+
5 rows in set (0.00 sec)