Files
asset_assistant/backend/scripts/db-lanuch-entrypoint.sh
2025-11-17 15:17:36 +08:00

59 lines
1.7 KiB
Bash
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/sh
set -e
# 日志函数(带时间戳)
log_info() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] [DB_INIT] $1"
}
log_error() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] [DB_ERROR] $1" >&2
}
# 1. 启动PostgreSQL服务
log_info "启动PostgreSQL服务后台运行"
docker-entrypoint.sh postgres &
PG_PID=$!
log_info "PostgreSQL主进程ID: $PG_PID"
# 2. 等待数据库就绪
log_info "等待PostgreSQL服务就绪主机: localhost, 端口: 5432"
retry_count=0
max_retries=30 # 最多等待30秒
until pg_isready -U "$POSTGRES_USER" -d "$POSTGRES_DB" -h "localhost" -p "5432"; do
retry_count=$((retry_count + 1))
if [ $retry_count -ge $max_retries ]; then
log_error "等待PostgreSQL超时超过30秒"
exit 1
fi
log_info "数据库未就绪等待1秒重试次数: $retry_count"
sleep 1
done
log_info "PostgreSQL服务已就绪"
# 3. 执行SQL脚本
log_info "开始执行/docker-entrypoint-initdb.d目录下的SQL脚本"
script_count=0
for script in /docker-entrypoint-initdb.d/*.sql; do
if [ -f "$script" ]; then
script_count=$((script_count + 1))
log_info "执行脚本 ($script_count): $script"
if psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -h "localhost" -p "5432" -f "$script" --set=ON_ERROR_STOP=1; then
log_info "脚本执行成功: $script"
else
log_error "脚本执行失败: $script"
exit 1
fi
fi
done
if [ $script_count -eq 0 ]; then
log_info "未发现需要执行的SQL脚本"
else
log_info "所有SQL脚本执行完成$script_count个"
fi
# 4. 等待主进程
log_info "等待PostgreSQL主进程结束PID: $PG_PID"
wait $PG_PID
log_info "PostgreSQL进程已退出"