DEV Community

cychu42
cychu42

Posted on

Starchart: "Mocking" A Database Part 2

As a continuation from the previous post, I managed to make the test database work.
It's not mocking anymore, but I'm keeping the title for consistency.

The Solution

Let's have a snippet of the dock-compose YAML file, which is what I used to make the test database, so it's easier to talk about this:

code snippet of dock-compose YAML file

This file is an instruction that will be followed to create docker containers, when you run docker compose up command.
For this bit of code, it tells docker to:

  • create a container using image of MySQL version 8.x.x
  • name it "database"
  • bind port 3306 (left) to the container's port 3306 (right)
  • use local machine's directory (left) as source of container's virtual directory (right), such as ./mysql-data:/var/lib/mysql
  • set certain environment variables

MYSQL_DATABASE indicates the database to be made with the name starchart.
MYSQL_USER and MYSQL_PASSWORD are the account and password with superuser access to that database.
MYSQL_ROOT_PASSWORD sets the password for the root user, which is a super user. Only this environment variable is mandatory.

SQL File for Test Database

As you can see in that code snippet, I source a file 01-databases.sql, which as a few SQL commands to setup a test database on top of starchart database. The file looks like this:

-- create test databases
CREATE DATABASE IF NOT EXISTS `starchart_test`;

-- create root user and grant rights
CREATE USER 'root'@'localhost' IDENTIFIED BY 'root_password';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';
Enter fullscreen mode Exit fullscreen mode

First line creates the database if it doesn't exist already. The second line creates that user with specified password, and then it grants all access to that user.
When the MySQL database container is made, Docker checks for SQL files under /docker-entrypoint-initdb.d to run, so these lines would be executed.

What was the issue?

It turns out there were two issues with my connecting string to the test database.
As an example:
DATABASE_URL="mysql://root:root_password@127.0.0.1:3306/starchart_test"

starchart is the account to use to connect.
root_password is the password for the account.
127.0.0.1 the IP of the database.
3306 is the port.
starchart_test is the database name.

First, your system might refuse to connect to a high number port to avoid suspicious ports, so I needed to set it to be lower. A MySQL database docker container lists 2 ports: 3306 and 33060. I was trying to bind the 33060 port, which was too high, so a lower number port did the trick. Another issue was that I had the wrong name for the database. I mistakenly thought it was meant to be container name instead.

Top comments (0)