#!/usr/bin/env bash set -euo pipefail home="${DOBOTAI_HOME:-/opt/dobotai}" container_dir="$home/container" compose_file="$container_dir/compose.yaml" runtime_env="$container_dir/runtime.env" migrations_dir="$container_dir/migrations" if [[ ! -r "$compose_file" || ! -r "$runtime_env" || ! -d "$migrations_dir" ]]; then echo "迁移运行文件未安装。请先执行 install-docker.sh。" >&2 exit 1 fi compose=(docker compose --env-file "$runtime_env" -f "$compose_file") "${compose[@]}" up -d --no-build dobotai-postgres for _ in $(seq 1 30); do status=$(docker inspect -f '{{.State.Health.Status}}' dobotai-postgres 2>/dev/null || true) [[ "$status" == "healthy" ]] && break sleep 1 done [[ "${status:-}" == "healthy" ]] || { echo "PostgreSQL 未健康,拒绝迁移。" >&2; exit 1; } psql_db() { "${compose[@]}" exec -T dobotai-postgres psql -v ON_ERROR_STOP=1 -U dobotai -d dobotai "$@" } psql_db -c 'CREATE TABLE IF NOT EXISTS dobotai_schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())' for file in "$migrations_dir"/*.up.sql; do [[ -f "$file" ]] || continue base="$(basename "$file")" version_text="${base%%_*}" version=$((10#$version_text)) name="${base#*_}" name="${name%.up.sql}" case "$name" in *[!a-z0-9_]* ) echo "非法迁移文件名:$base" >&2; exit 1;; esac applied=$(psql_db -At -c "SELECT EXISTS(SELECT 1 FROM dobotai_schema_migrations WHERE version=$version)") [[ "$applied" == "t" ]] && continue { printf 'BEGIN;\n' cat "$file" printf "\nINSERT INTO dobotai_schema_migrations(version,name) VALUES (%s,'%s');\nCOMMIT;\n" "$version" "$name" } | "${compose[@]}" exec -T dobotai-postgres psql -v ON_ERROR_STOP=1 -U dobotai -d dobotai echo "已应用迁移:$base" done