#!/bin/sh set -eu # Defaults match the compose topology; the BaoTa host runs MySQL outside Docker # on the loopback, so host and port are overridable there. mysql_host="${MYSQL_HOST:-mysql}" mysql_port="${MYSQL_PORT:-3306}" # The BaoTa host keeps one Go-style DSN instead of the compose MYSQL_* set, and # its bundled client cannot speak caching_sha2_password, so the 8.x client has # to be selectable. Explicit MYSQL_* values still win. if [ -z "${MYSQL_USER:-}" ] && [ -n "${IM_DB_DSN:-}" ]; then dsn="${IM_DB_DSN}" MYSQL_USER="${dsn%%:*}" rest="${dsn#*:}" MYSQL_PASSWORD="${rest%@tcp(*}" hostport="${rest##*@tcp(}" hostport="${hostport%%)*}" mysql_host="${hostport%%:*}" mysql_port="${hostport##*:}" database="${dsn##*)/}" MYSQL_DATABASE="${database%%\?*}" fi mysql_bin="${MYSQL_CLIENT:-mysql}" mysql_args="--host=${mysql_host} --port=${mysql_port} --user=${MYSQL_USER} --database=${MYSQL_DATABASE} --default-character-set=utf8mb4 --batch --skip-column-names" until MYSQL_PWD="${MYSQL_PASSWORD}" "${mysql_bin}" ${mysql_args} --execute "SELECT 1" >/dev/null 2>&1; do sleep 2 done MYSQL_PWD="${MYSQL_PASSWORD}" "${mysql_bin}" ${mysql_args} --execute "CREATE TABLE IF NOT EXISTS schema_migrations (version VARCHAR(255) NOT NULL PRIMARY KEY, checksum CHAR(64) NOT NULL, applied_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" migrations_dir="${MIGRATIONS_DIR:-/migrations}" for file in "${migrations_dir}"/*.sql; do version="$(basename "${file}")" checksum="$(sha256sum "${file}" | awk '{print $1}')" existing="$(MYSQL_PWD="${MYSQL_PASSWORD}" "${mysql_bin}" ${mysql_args} --execute "SELECT checksum FROM schema_migrations WHERE version='${version}'" 2>/dev/null || true)" if [ -n "${existing}" ]; then if [ "${existing}" != "${checksum}" ]; then echo "Migration checksum mismatch: ${version}" >&2 exit 1 fi echo "Already applied: ${version}" continue fi echo "Applying: ${version}" MYSQL_PWD="${MYSQL_PASSWORD}" "${mysql_bin}" ${mysql_args} < "${file}" MYSQL_PWD="${MYSQL_PASSWORD}" "${mysql_bin}" ${mysql_args} --execute "INSERT INTO schema_migrations(version,checksum) VALUES('${version}','${checksum}')" done