#!/bin/bash set -e # 标记文件路径(使用系统级目录) FLAG_DIR="/var/lib/db-init" FLAG_FILE="$FLAG_DIR/.db_initialized" LOG_FILE="/var/log/postgres-init.log" # 数据库连接配置 export PGUSER=supabase_admin export PGPASSWORD=postgres export PGHOST=127.0.0.1 export PGPORT=5432 export PGDATABASE=postgres # 创建标记目录和日志目录 mkdir -p "$FLAG_DIR" mkdir -p "$(dirname "$LOG_FILE")" # 如果标记已存在,跳过执行 if [ -f "$FLAG_FILE" ]; then echo "✅ Database has already been initialized, skipping." | tee -a "$LOG_FILE" exit 0 fi echo "🚀 Starting database initialization..." | tee -a "$LOG_FILE" # 封装重试逻辑 retry_until_success() { local sql_file="$1" while true; do echo " ▶ Executing $sql_file" | tee -a "$LOG_FILE" if psql -v ON_ERROR_STOP=1 -f "$sql_file" >> "$LOG_FILE" 2>&1; then echo " ✅ Success: $sql_file" | tee -a "$LOG_FILE" break else echo " ❌ ERROR in $sql_file" | tee -a "$LOG_FILE" echo " 🔁 Retrying in 5 seconds..." | tee -a "$LOG_FILE" sleep 5 fi done } # 执行 migrations echo "📂 Running migrations..." | tee -a "$LOG_FILE" for file in $(ls /supabase/chatdesk/supabase/migrations/*.sql | sort); do retry_until_success "$file" done # 执行 seed.sql echo "🌱 Running seed.sql..." | tee -a "$LOG_FILE" retry_until_success /supabase/chatdesk/supabase/seed.sql # 写入初始化标记 touch "$FLAG_FILE" echo "✅ Database initialization complete. Marked as initialized at $FLAG_FILE" | tee -a "$LOG_FILE"