I have a test container for Mysql and I need to import the dump file after the container started. I’ve tried two options below.
public class AbstractTest {
public static MySQLContainer<?> mySQLContainer = new MySQLContainer<>("mysql:5.7");
static {
mySQLContainer
.withDatabaseName("myDatabase")
.withCopyFileToContainer(
MountableFile.forClasspathResource("init.sql", 0744),
"init.sql")
.withUsername("root")
.withPassword("root")
.start();
}
@PostConstruct
@SneakyThrows
public void init() {
option 1 // mySQLContainer.execInContainer("mysql -u root -proot myDatabase < init.sql");
option 2 // mySQLContainer.execInContainer("mysql", "-u", "root", "-proot", "myDatabase", "<", "init.sql");
}
////
}
and still no success – it looks like mysql can’t parse my command properly cause I get next as an answer:
mysql Ver 14.14 Distrib 5.7.35, for Linux (x86_64) using EditLine wrapper
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Usage: mysql [OPTIONS] [database]
-?, --help Display this help and exit.
-I, --help Synonym for -?
--auto-rehash Enable automatic rehashing. One doesn't need to use
'rehash' to get table and field completion, but startup
////.....
If use next command
option 2 // mySQLContainer.execInContainer("mysql", "-u", "root", "-proot");
it works fine, but this is not what I wanted
mysql -u root -proot mydatabase < init.sql
command works fine if I just connect to the container via bash from cli.
So my question – how to import SQL dump file in MySQLContainer in JUnit test containers by executing the command in image?
UPDATE:
I figured out that there is some thing wrong with parsing of "<" sign.
So, basically this works fine from CLI:
docker exec -i mycontainer mysql -uroot -proot myDatabase < init.sql
But this is not working from Java:
mySQLContainer.execInContainer("mysql","-uroot","-proot","myDatabase","<","init.sql");
2
Answers
You need an applications.properties suitable for MySql, something like:
Then you can add a data.sql in your /src/test/resources which will automatically be run.
MySQL can load a dump file automatically if you put it at a special path.
From the docs of the MySQL Docker image:
So the easiest is to copy the file there with something like: