Skip to content

Instantly share code, notes, and snippets.

@entrity
Last active August 29, 2015 14:16
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 entrity/0d02978dbf1d1c850c27 to your computer and use it in GitHub Desktop.
Save entrity/0d02978dbf1d1c850c27 to your computer and use it in GitHub Desktop.
Connect to MySQL by parsing Rails database.yml
#!/bin/bash
usage () {
echo "Usage:"
echo -e "\t$0 [options] [dir] [rails env]"
echo "Options:"
echo -e "\t-e rails_env"
echo -e "\t-f yaml_file"
echo "Inclusion of 'file' option overrides 'dir' arg"
echo "@arg dir defaults to pwd"
echo "@arg rails env defaults to 'development'"
exit 1
}
increment_arg_i () {
arg_i=$(( $arg_i + 1 ))
}
IFS=$"\n"
args=( $@ )
arg_i=0
while (( $arg_i < ${#args[@]} )); do
arg=${args[$arg_i]}
echo -E "$arg_i"
case "$arg" in
-e*)
if [[ "-e" == "$arg" ]]; then
increment_arg_i;
renv="${args[$arg_i]}"
else
renv="${arg:2}"
fi;;
-f*)
if [[ "-f" == "$arg" ]]; then
increment_arg_i;
file="${args[$arg_i]}"
else
file="${arg:2}"
fi;;
*)
if [ ! $dir ]; then
dir="$arg"
elif [ ! $renv ]; then
renv="$arg"
fi;;
esac
increment_arg_i
done
[ $dir ] || dir=`pwd`
[ $renv ] || renv=development
[ $file ] || file="$dir/config/database.yml"
echo "Reading $file for $renv ..."
load_yaml_val () {
yaml_val=$( echo -e "$yaml_block" | grep -m1 "$1" | cut -d' ' -f4 )
}
# Parse yaml file
start_line=$(grep -n -m1 "$renv" "$file" | cut -d: -f1)
block_len=$(tail -n +"$start_line" "$file" | grep -m1 -n -P '^\s*$' | cut -d: -f1)
yaml_block=$(tail -n +"$start_line" "$file" | head -n "$block_len")
echo -e "yaml_block:\n$yaml_block"
load_yaml_val adapter; adapter=$yaml_val
load_yaml_val username; username=$yaml_val
load_yaml_val password; password=$yaml_val
load_yaml_val host; host=$yaml_val
load_yaml_val port; port=$yaml_val
load_yaml_val database; schema=$yaml_val
[ $host ] || host='127.0.0.1'
[ $port ] || port='3306'
echo adapter "$adapter"
echo username "$username"
echo password "$password"
echo host "$host"
echo port "$port"
echo schema "$schema"
# execute mysql statement
mysql -u"$username" -p"$password" -P"$port" -h"$host" "$schema"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment