Skip to content

Commit 9789e22

Browse files
committed
feat: Add script to initialize MySQL container and seed database
1 parent f15d005 commit 9789e22

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

deploy/scripts/init-db-and-seed.sh

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#!/usr/bin/env bash
2+
# Initialize MySQL container and seed SmallTrend data.sql on Azure VM.
3+
set -euo pipefail
4+
5+
DEPLOY_PATH="${DEPLOY_PATH:-/opt/smalltrend}"
6+
COMPOSE_FILE="$DEPLOY_PATH/docker-compose.prod.yml"
7+
ENV_FILE="$DEPLOY_PATH/deploy/env/backend.env"
8+
SEED_FILE="$DEPLOY_PATH/backend/src/main/resources/data.sql"
9+
10+
log() {
11+
printf "[%s] %s\n" "$1" "$2"
12+
}
13+
14+
require_file() {
15+
local path="$1"
16+
[ -f "$path" ] || {
17+
echo "Missing required file: $path"
18+
exit 1
19+
}
20+
}
21+
22+
log "1/7" "Checking required files"
23+
require_file "$COMPOSE_FILE"
24+
require_file "$ENV_FILE"
25+
require_file "$SEED_FILE"
26+
27+
cd "$DEPLOY_PATH"
28+
29+
log "2/7" "Loading environment"
30+
set -a
31+
# shellcheck disable=SC1090
32+
. "$ENV_FILE"
33+
set +a
34+
35+
: "${MYSQL_DATABASE:=smalltrend}"
36+
: "${MYSQL_ROOT_PASSWORD:=root1234}"
37+
38+
log "3/7" "Starting mysql service"
39+
docker compose -f "$COMPOSE_FILE" up -d mysql
40+
41+
log "4/7" "Waiting for mysql health"
42+
MYSQL_CONTAINER_ID="$(docker compose -f "$COMPOSE_FILE" ps -q mysql)"
43+
[ -n "$MYSQL_CONTAINER_ID" ] || {
44+
echo "Could not resolve mysql container ID"
45+
exit 1
46+
}
47+
48+
MAX_ATTEMPTS=60
49+
ATTEMPT=1
50+
while [ "$ATTEMPT" -le "$MAX_ATTEMPTS" ]; do
51+
HEALTH="$(docker inspect --format='{{if .State.Health}}{{.State.Health.Status}}{{else}}unknown{{end}}' "$MYSQL_CONTAINER_ID")"
52+
if [ "$HEALTH" = "healthy" ]; then
53+
echo "MySQL is healthy"
54+
break
55+
fi
56+
echo "MySQL health: $HEALTH (attempt $ATTEMPT/$MAX_ATTEMPTS). Waiting 5s..."
57+
sleep 5
58+
ATTEMPT=$((ATTEMPT + 1))
59+
done
60+
61+
if [ "$ATTEMPT" -gt "$MAX_ATTEMPTS" ]; then
62+
echo "MySQL did not become healthy in time"
63+
docker compose -f "$COMPOSE_FILE" logs --tail=120 mysql || true
64+
exit 1
65+
fi
66+
67+
log "5/7" "Ensuring database exists"
68+
docker compose -f "$COMPOSE_FILE" exec -T mysql sh -lc \
69+
'mysql -uroot -p"$MYSQL_ROOT_PASSWORD" -e "CREATE DATABASE IF NOT EXISTS $MYSQL_DATABASE CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"'
70+
71+
log "6/7" "Seeding database from data.sql"
72+
docker compose -f "$COMPOSE_FILE" exec -T mysql sh -lc \
73+
'mysql --default-character-set=utf8mb4 -uroot -p"$MYSQL_ROOT_PASSWORD" "$MYSQL_DATABASE"' < "$SEED_FILE"
74+
75+
log "7/7" "Done"
76+
echo "Seed completed for database: $MYSQL_DATABASE"
77+
78+
echo "Next command (optional):"
79+
echo " docker compose -f $COMPOSE_FILE up -d --remove-orphans"

0 commit comments

Comments
 (0)