Files
taiji-AI-PAD/scripts/migrate_to_new_db.sh
T
2026-03-10 06:40:38 +00:00

84 lines
3.0 KiB
Bash
Executable File
Raw 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/bash
# 数据库迁移脚本:从 postgres 迁移到 taiji_prod
#
# 使用方法:./migrate_to_new_db.sh [new_db_name]
# 默认新数据库名:taiji_prod
set -e
# 配置
DB_HOST="taijipda.postgres.database.azure.com"
DB_USER="taiji"
DB_PASSWORD="By@123456."
OLD_DB="postgres"
NEW_DB="${1:-taiji_prod}"
BACKUP_FILE="postgres_backup.dump"
echo "=========================================="
echo "数据库迁移脚本"
echo "=========================================="
echo "源数据库: ${OLD_DB}"
echo "目标数据库: ${NEW_DB}"
echo "服务器: ${DB_HOST}"
echo "=========================================="
# 设置 PGPASSWORD 环境变量避免密码提示
export PGPASSWORD="${DB_PASSWORD}"
# 步骤 1: 创建新数据库
echo ""
echo "Step 1: 创建新数据库 ${NEW_DB}..."
psql -h "${DB_HOST}" -U "${DB_USER}" -d "postgres" -c "CREATE DATABASE ${NEW_DB};" 2>/dev/null || echo "数据库可能已存在,继续..."
# 步骤 2: 从备份文件恢复数据(如果存在)
if [ -f "${BACKUP_FILE}" ]; then
echo ""
echo "Step 2: 从备份文件恢复数据到 ${NEW_DB}..."
pg_restore -h "${DB_HOST}" -U "${DB_USER}" -d "${NEW_DB}" -v --no-owner --no-acl "${BACKUP_FILE}" || echo "部分恢复可能失败,这是正常的"
else
echo ""
echo "Step 2: 备份文件不存在,直接从 ${OLD_DB} 导出并导入..."
# 创建临时备份
TEMP_BACKUP="temp_postgres_$(date +%Y%m%d_%H%M%S).dump"
echo " 创建临时备份: ${TEMP_BACKUP}"
pg_dump -h "${DB_HOST}" -U "${DB_USER}" -d "${OLD_DB}" -Fc -f "${TEMP_BACKUP}"
echo " 恢复到新数据库..."
pg_restore -h "${DB_HOST}" -U "${DB_USER}" -d "${NEW_DB}" -v --no-owner --no-acl "${TEMP_BACKUP}" || echo "部分恢复可能失败,这是正常的"
echo " 保留备份文件: ${TEMP_BACKUP}"
fi
# 步骤 3: 验证数据迁移
echo ""
echo "Step 3: 验证数据迁移..."
echo " 源数据库表数量:"
psql -h "${DB_HOST}" -U "${DB_USER}" -d "${OLD_DB}" -c "SELECT COUNT(*) as table_count FROM information_schema.tables WHERE table_schema = 'public';" -t
echo " 目标数据库表数量:"
psql -h "${DB_HOST}" -U "${DB_USER}" -d "${NEW_DB}" -c "SELECT COUNT(*) as table_count FROM information_schema.tables WHERE table_schema = 'public';" -t
# 步骤 4: 显示新数据库的表列表
echo ""
echo "Step 4: 新数据库 ${NEW_DB} 的表列表:"
psql -h "${DB_HOST}" -U "${DB_USER}" -d "${NEW_DB}" -c "\dt" || echo "没有表或连接失败"
# 清除密码环境变量
unset PGPASSWORD
echo ""
echo "=========================================="
echo "迁移完成!"
echo "=========================================="
echo ""
echo "下一步操作:"
echo "1. 验证新数据库数据完整性"
echo "2. 更新配置文件中的数据库名称(从 postgres 改为 ${NEW_DB})"
echo "3. 重新部署应用"
echo "4. 确认应用正常运行后,可选择删除旧的 postgres 数据库"
echo ""
echo "更新配置文件的命令:"
echo " ./scripts/update_db_config.sh ${NEW_DB}"
echo ""