Created
November 9, 2015 13:53
-
-
Save samuelpismel/f41c3e7ec7861f39bf59 to your computer and use it in GitHub Desktop.
Shell script to change and convert mysql databases charset and collate.
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
#!/bin/bash | |
database='database' | |
user='user' | |
pass='pass' | |
charset='utf8mb4' | |
collate='utf8mb4_unicode_ci' | |
echo "Changing charset of database: $database" | |
mysql -u $user -p$pass $database -s -e "ALTER DATABASE $database CHARACTER SET = $charset COLLATE = $collate;" | |
for table in $(mysql $database -s --skip-column-names -e 'show tables') | |
do | |
echo '' | |
echo "Changing charset of table: $table" | |
mysql -u $user -p$pass $database -s -e "ALTER TABLE $table CHARACTER SET $charset COLLATE $collate" | |
echo "Converting charset of table: $table" | |
mysql -u $user -p$pass $database -s -e "ALTER TABLE $table CONVERT TO CHARACTER SET $charset COLLATE $collate" | |
done | |
echo '' | |
echo 'Conversion done!' | |
echo '' | |
echo 'Optimizing tables...' | |
echo '' | |
mysqlcheck -u $user -p$pass $database --auto-repair --optimize | |
echo '' | |
echo 'Done! Have a nice day! ;)' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice - you might have to add "SET FOREIGN_KEY_CHECKS=0;" to line 20 so it reads:
mysql -u $user -p$pass $database -s -e "SET FOREIGN_KEY_CHECKS=0;ALTER TABLE $table CONVERT TO CHARACTER SET $charset COLLATE $collate"
If your database has foreign keys that are characters (like uuid or names) you will get an error "Cannot change column 'uuid': used in a foreign key constraint..." Although not usual in traditional SQL where you would always use int for keys in lots of newer stuff uuid is becoming popular.