Wiki source code of Convert a MySQL Database to utf8mb4
Last modified by superadmin on 2026/11/25 21:31
Show last authors
| author | version | line-number | content |
|---|---|---|---|
| 1 | 1. Stop XWiki, then back up the database with the [[database backup commands>>doc:documentation.xs.admin.backup.database-commands.WebHome]]: the conversion to the pair [[MySQL Storage Engine and Character Set>>doc:documentation.xs.admin.installation.install-relational-database.configure-mysql.storage-engine-character-set.WebHome]] requires rewrites every table and cannot be undone. | ||
| 2 | 1. Save this script and run it as the MySQL root user, passing the database name as its only argument (it defaults to ##xwiki##):((( | ||
| 3 | {{code language="bash"}} | ||
| 4 | #!/bin/bash | ||
| 5 | |||
| 6 | db="${1:-xwiki}" | ||
| 7 | |||
| 8 | to_character_set=utf8mb4 | ||
| 9 | to_collation=utf8mb4_bin | ||
| 10 | |||
| 11 | mysql_cmd="mysql -u root" | ||
| 12 | |||
| 13 | echo "Changing ($db) character to $to_collation." | ||
| 14 | |||
| 15 | $mysql_cmd -e "ALTER DATABASE $db CHARACTER SET $to_character_set COLLATE $to_collation;" | ||
| 16 | |||
| 17 | TBL_LIST=$($mysql_cmd -N -s -r -e "use $db;show tables;") | ||
| 18 | |||
| 19 | for tbl_name in $TBL_LIST; | ||
| 20 | do | ||
| 21 | $mysql_cmd -e "SET FOREIGN_KEY_CHECKS=0; alter table $db.$tbl_name convert to character set $to_character_set collate $to_collation; SET FOREIGN_KEY_CHECKS=1;" | ||
| 22 | done | ||
| 23 | |||
| 24 | echo "Here the result of the operation:" | ||
| 25 | $mysql_cmd -e "USE $db;SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE();" | ||
| 26 | {{/code}} | ||
| 27 | |||
| 28 | It sets the database's own default character set and collation, converts each of its tables in turn, and prints the collation of every column it produced. If the MySQL root user has a password, add the ##-p## option to the ##mysql_cmd## line and each call prompts for it. | ||
| 29 | ))) | ||
| 30 | 1. Run the script again for each subwiki's database: it converts one database at a time. | ||
| 31 | 1. Start XWiki. | ||
| 32 | 1. Confirm that no column was left behind. The script's closing query lists the collation of every column; asking it for the columns that are //not// on the target collation turns it into a single check:((( | ||
| 33 | {{code language="sql"}} | ||
| 34 | SELECT TABLE_NAME, COLUMN_NAME, COLLATION_NAME | ||
| 35 | FROM INFORMATION_SCHEMA.COLUMNS | ||
| 36 | WHERE TABLE_SCHEMA = 'xwiki' AND COLLATION_NAME <> 'utf8mb4_bin'; | ||
| 37 | {{/code}} | ||
| 38 | |||
| 39 | An empty result is the confirmation: every text column of the database is on ##utf8mb4_bin##, and the wiki that starts on it stores four-byte characters correctly. | ||
| 40 | ))) |