MariaDB / mariadb-docker

Docker Official Image packaging for MariaDB
https://mariadb.org
GNU General Public License v2.0
770 stars 438 forks source link

"No database selected" when trying to restore from a dump file #341

Closed o-alquimista closed 3 years ago

o-alquimista commented 3 years ago

The command:

docker exec -i mariadb_container_name sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"' database_name < /path/to/dump.sql

Since the dump file doesn't do a DROP/CREATE or USE the database, I have created the database (indicated as database_name) prior to running the command. The error I get is this:

ERROR 1046 (3D000) at line 27: No database selected

The dump file is way too large to open and edit, so I thought of asking for help here.

tianon commented 3 years ago

Instead of < /path/to/dump.sql, you could do something like { echo 'CREATE DATABASE database_name IF NOT EXISTS; USE database_name;'; cat /path/to/dump.sql; } | mysql ... (or set MYSQL_DATABASE so that the image will pre-create your desired database automatically).

o-alquimista commented 3 years ago

Thanks to your command suggestion and a bit of searching around, I found something that works for me:

cat <(echo 'USE database_name;') /path/to/dump.sql | docker exec -i mariadb_container_name sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"'

I just wonder why the first command didn't work...

tianon commented 3 years ago

In looking at this with fresh eyes, I think I just realized why your first command didn't work, and it all comes down to quoting: :sweat_smile:

Before: docker exec -i mariadb_container_name sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"' database_name < /path/to/dump.sql

After: docker exec -i mariadb_container_name sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD" database_name' < /path/to/dump.sql

(In other words, database_name was being passed as an argument to sh, not to mysql :smile:)