spydon
spydon

Reputation: 11552

Database restore does not retain emojis

I am doing a naïve database backup and restore like this:

SCHEMA=${2:-mindlevel}
DB_HOST=$1
mysqldump -uroot -ppassword -h$DB_HOST --default-character-set=utf8mb4 --complete-insert --no-create-info $SCHEMA -r ${SCHEMA}_backup.sql 
mysqladmin -uroot -ppassword -h$DB_HOST -f drop $SCHEMA &&
mysql -uroot -ppassword -h$DB_HOST --default-character-set=utf8mb4 < ${SCHEMA}_schema.sql &&
mysql -uroot -ppassword -h$DB_HOST $SCHEMA --default-character-set0=utf8mb4 < ${SCHEMA}_backup.sql

But all emojis that I had before the restore are shown as ?, but if I enter an emoji again it is stored and shown correctly.

I have tried having --default-character-set=utf8 but with the same result.

UPDATE:

SHOW CREATE TABLE user;

CREATE TABLE `user` (
  `username` varchar(191) NOT NULL,
  `description` varchar(1024) DEFAULT NULL,
  `image` varchar(191) DEFAULT 'user.jpg',
  `score` int(11) DEFAULT 0,
  `level` int(11) DEFAULT 0,
  `created` bigint(20) NOT NULL,
  `last_active` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

The backup file:

file mindlevel_backup.sql 
mindlevel_backup.sql: UTF-8 Unicode text, with very long lines

The top part of mindlevel_backup.sql:

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=

Any ideas?

Upvotes: 1

Views: 775

Answers (2)

spydon
spydon

Reputation: 11552

The solution was to change one line. From:

mysql -uroot -ppassword -h$DB_HOST $SCHEMA --default-character-set=utf8mb4 < ${SCHEMA}_backup.sql

To:

mysql -uroot -ppassword -h$DB_HOST $SCHEMA --default-character-set=utf8mb4 -e "SET NAMES utf8mb4; SOURCE"${SCHEMA}"_backup.sql;"

I don't know why that worked, so if anyone care to explain that to me I'll update the answer.

Upvotes: 1

Rick James
Rick James

Reputation: 142346

The column in the table also needs to be declared CHARACTER SET utf8mb4. Please provide SHOW CREATE TABLE and the first part of backup.sql.

Upvotes: 1

Related Questions