Files
dobotai-platform/deploy/dobotai-dingtalk/rds-schema-init.sh
T

32 lines
2.2 KiB
Bash

#!/usr/bin/env bash
set -euo pipefail
home="${DOBOTAI_HOME:-/opt/dobotai}"
app_env="$home/config/dobotai.env"
migrations_dir="$home/container/migrations"
[[ -r "$app_env" && -d "$migrations_dir" ]] || { echo "RDS检查资产未安装。" >&2; exit 1; }
temp_env="$(mktemp)"; trap 'rm -f "$temp_env"' EXIT
python3 - "$app_env" "$temp_env" <<'PY'
from pathlib import Path
import os,sys
values={}
for line in Path(sys.argv[1]).read_text(encoding='utf-8').splitlines():
if line and not line.startswith('#') and '=' in line:
key,value=line.split('=',1); values[key]=value
url=values.get('DATABASE_URL','').strip()
if not (url.startswith('postgres://') or url.startswith('postgresql://')): raise SystemExit('DATABASE_URL必须是阿里云RDS PostgreSQL连接串。')
Path(sys.argv[2]).write_text('DATABASE_URL='+url+'\n',encoding='utf-8'); os.chmod(sys.argv[2],0o600)
PY
rds_shell() { docker run --rm -i --network host --env-file "$temp_env" postgres:16-alpine sh -ec "$1"; }
rds_shell 'pg_isready -d "$DATABASE_URL" >/dev/null'
sql() { rds_shell 'exec psql -v ON_ERROR_STOP=1 "$DATABASE_URL"'; }
sql_at() { rds_shell 'exec psql -At -v ON_ERROR_STOP=1 "$DATABASE_URL"'; }
state=$(printf "%s\n" "WITH expected(name) AS (VALUES ('turns'),('session_mappings'),('messages'),('coverage_decisions'),('support_cases'),('system_config_revisions'),('administrators'),('setting_sessions'),('user_preferences'),('reasoning_mode_states'),('reasoning_mode_turns')) SELECT CASE WHEN to_regclass('public.turns') IS NULL AND (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public')=0 THEN 'empty' WHEN (SELECT COUNT(*) FROM expected e JOIN information_schema.tables t ON t.table_schema='public' AND t.table_name=e.name)=11 THEN 'normal' ELSE 'inconsistent' END;" | sql_at)
case "$state" in
normal) echo "阿里云RDS表结构检查通过;不执行初始化。"; exit 0;;
inconsistent) echo "阿里云RDS表结构不完整或不是空库,拒绝初始化和启动。" >&2; exit 1;;
empty) echo "阿里云RDS为空,开始初始化DobotAI表。";;
*) echo "无法判定阿里云RDS表状态。" >&2; exit 1;;
esac
for migration in "$migrations_dir"/*.up.sql; do printf 'BEGIN;\n'; cat "$migration"; printf '\nCOMMIT;\n'; done | sql
echo "阿里云RDS初始化完成。"