Skip to content
Latchkey

mysql < dump.sql: Import SQL and Migrations

mysql -u app appdb < dump.sql streams a SQL file into the server, the standard way to restore a mysqldump backup.

MySQL restores are plain SQL replayed through the client. You either redirect the file on stdin or use the SOURCE command inside the client. In CI the concern is stopping on the first error rather than plowing through.

What it does

The mysql client reads SQL statements from stdin and executes them in order. Redirecting a dump file into it (< file.sql) replays a mysqldump backup or a migration. By default a statement error aborts the batch and returns non-zero, which is the behavior you want in CI.

Common usage

Terminal
# restore a dump into an existing database
MYSQL_PWD=secret mysql -h db -u app appdb < dump.sql
# apply a migration file
MYSQL_PWD=secret mysql -h db -u app appdb < migrate.sql
# from inside the client, the SOURCE command does the same
mysql -h db -u app appdb -e "SOURCE seed.sql"

Options

ItemWhat it does
< file.sqlRedirect a SQL file to the client on stdin
SOURCE file.sqlIn-client command to run a SQL file
--force / -fKeep going after errors instead of aborting
-D <db> / <db>Database the statements apply to
--max-allowed-packet=<n>Raise the packet limit for large rows

In CI

Do not pass --force for migrations: the default abort-on-error is what makes a broken migration fail the job. Name the target database on the command line (or ensure the dump has a USE statement) so statements land in the right place. For very large dumps, raise --max-allowed-packet on both client and server.

Common errors in CI

"ERROR 1049 (42000): Unknown database \"appdb\"" means the target database does not exist; create it first with mysql -e "CREATE DATABASE appdb". "ERROR 1153 (08S01): Got a packet bigger than \"max_allowed_packet\" bytes" means a row exceeds the limit; raise --max-allowed-packet. "ERROR 1050 (42S01): Table \"users\" already exists" on a re-run means the dump is not idempotent; drop and recreate the database first.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →