Git and Rails : Switch your database.yml when changing branch
As a lot of people, I think, I have different database.yml file according to git branch I’m working on. I was constantly switching it manually until I discovered that git has more hooks that I thought.
I set up a post-checkout hooks script to automagically switch my database.yml when checking out a branch.
It is a simple script that recover the branch name a do a symlink.
if i checkout branch master it will look for a file named config/database.master.yml and create a symlink to config/database.yml
here it is :
#! /bin/sh
#
# .git/hooks/post-checkout
BRANCH=`git symbolic-ref HEAD 2> /dev/null | sed -e 's/^.*\///'`
GITPATH="`git rev-parse --git-dir 2>/dev/null`/.."
if [ "$BRANCH" == "" ]; then
echo "no branch name. do nothing"
exit 0
fi
if [ -f "$GITPATH/config/database.yml" ] && [ ! -L "$GITPATH/config/database.yml" ]; then
echo "database.yml exists and not a symlink. do nothing."
exit 0
fi
echo "look for $GITPATH/config/database.$BRANCH.yml"
if [ -f "$GITPATH/config/database.$BRANCH.yml" ]; then
echo "switch database configuration file to config/database.$BRANCH.yml"
rm -f "$GITPATH/config/database.yml";
ln -s "$GITPATH/config/database.$BRANCH.yml" \
"$GITPATH/config/database.yml"
fi
Rails : convert all tables to utf8 2
I sometimes need to convert old rails mysql databases to use unicode (utf8)
here is a way to do this quickly :
require 'rubygems'
require 'active_record'
db = "my_database"
sqlconn = ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "root",
:password => "",
:database => db
)
conn = ActiveRecord::Base.send(sqlconn.adapter_method,sqlconn.config)
conn.tables.each do |table|
q = "ALTER TABLE #{table} CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci"
puts q
conn.execute q
end
conn.execute("ALTER DATABASE #{db} DEFAULT CHARACTER SET utf8 ;")
edit : see Agouti’s comment

