Skip to content

Instantly share code, notes, and snippets.

@thej
Last active December 31, 2015 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thej/8022392 to your computer and use it in GitHub Desktop.
Save thej/8022392 to your computer and use it in GitHub Desktop.
Creates a new MySQL database with the given database name. Usage: ruby add_mysql_database.rb <database_name>
# https://gist.github.com/thej/8022392
require 'mysql2'
require 'securerandom'
require 'io/console'
# check for parameters
if ARGV.size != 1
puts "Usage: ruby add_mysql_database.rb <database_name>"
exit
end
# cconfigure database variables
database_name = ARGV.first.gsub(/[^0-9A-Za-z_-]/, '')
username = "#{database_name.slice(0..10)}_usr1"
password = SecureRandom.hex
# Ask for admin pw
print "Enter database admin password: "
admin_pw = STDIN.noecho(&:gets).chomp
# try to establish connection with given pw
begin
client = Mysql2::Client.new(host: "localhost", username: "root", password: "#{admin_pw}", flags: Mysql2::Client::MULTI_STATEMENTS)
rescue Exception => e
puts e.message
exit
end
#check if db exists
r = client.query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '#{database_name}'")
if r.count > 0
puts "Database already exists"
exit
end
# Print instructions
puts "\nThe following DB will be created:\n\n"
puts "Copy and paste for database.yml :\n"
puts "########################"
puts "production:"
puts " adapter: mysql2"
puts " encoding: utf8"
puts " database: #{database_name}"
puts " pool: 5"
puts " username: #{username}"
puts " password: #{password}"
puts " socket: /var/run/mysqld/mysqld.sock"
puts "########################"
print "\nPress <ENTER> to continue or <CTRL+C> to abort. "
STDIN.gets
# create database
client.query("CREATE DATABASE `#{database_name}`;")
client.query("CREATE USER '#{username}'@'localhost' IDENTIFIED BY '#{password}';")
client.query("GRANT ALL PRIVILEGES ON `#{database_name}` . * TO '#{username}'@'localhost';")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment