Created
September 9, 2011 14:06
-
-
Save alvin2ye/1206310 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
#curl https://raw.github.com/gist/1206310 --output create_mysql_db.rb && chmod +x create_mysql_db.rb | |
require 'rubygems' | |
require 'optparse' | |
require 'mysql' | |
options = {} | |
OptionParser.new do |opts| | |
opts.on_tail("-h", "--help", "get help for this CMD") { print(opts); exit() } | |
opts.on("-h", "--host String", "Mysql Host default 'localhost'") { |v| options[:host] = v } | |
opts.on("-p", "--pwd String", "Mysql root password") { |v| options[:pwd] = v } | |
opts.on("-d", "--ndb String", "New database name") { |v| options[:ndb] = v } | |
opts.on("-u", "--nuser String", "New database user") { |v| options[:nuser] = v } | |
opts.on("-w", "--npwd String", "New database password") { |v| options[:npwd] = v } | |
opts.on("-v", "--[no-]verbose", "Run verbosely") { |v| options[:verbose] = v } | |
end.parse(ARGV) | |
def keyword_input(alert) | |
puts alert | |
while s = $stdin.gets.chomp | |
return s | |
end | |
end | |
def with_db(options={}) | |
config = {:host => 'localhost', :user => 'root'}.merge(options) | |
config[:pwd] = keyword_input("Enter #{config[:user]} password:") if config[:pwd].nil? | |
config[:ndb] = keyword_input("Enter new database name:") if config[:ndb].nil? | |
config[:nuser] = keyword_input("Enter new database user:") if config[:nuser].nil? | |
config[:npwd] = keyword_input("Enter new database password:") if config[:npwd].nil? | |
dbh = Mysql.connect(config[:host], config[:user], config[:pwd]) | |
begin | |
yield dbh, config | |
ensure | |
dbh.close | |
end | |
end | |
def run(options={}) | |
with_db(options) do |dbh, config| | |
cmd = "CREATE DATABASE #{config[:ndb]} CHARACTER SET UTF8 COLLATE utf8_general_ci" | |
puts cmd if config[:verbose] | |
dbh.query(cmd) | |
cmd = "GRANT all ON #{config[:ndb]}.* TO '#{config[:nuser]}'@'localhost' IDENTIFIED BY '#{config[:npwd]}'" | |
puts cmd if config[:verbose] | |
dbh.query(cmd) | |
<<-TXT | |
New database name: #{config[:ndb]} | |
New database user: #{config[:nuser]} | |
New database pwd: #{config[:npwd]} | |
TXT | |
end | |
end | |
puts run(options) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment