Commit 9a6b11c4 by luoqi

fix:数据库备份3

parent a0f069dc
Pipeline #3230 passed with stage
in 22 seconds
......@@ -19,11 +19,12 @@ def run_command(command, description):
"""执行命令并处理错误"""
print(f"🔄 {description}...")
try:
# 使用bash -c来确保命令正确执行
result = subprocess.run(
command,
shell=True,
check=True,
capture_output=True,
f"bash -c '{command}'",
shell=True,
check=True,
capture_output=True,
text=True,
cwd=project_root
)
......@@ -40,25 +41,45 @@ def backup_database():
"""备份数据库"""
print("🚀 数据库备份工具启动")
print(f"📍 项目根目录: {project_root}")
# 确保备份目录存在
backup_dir = project_root / "database" / "backups"
backup_dir.mkdir(exist_ok=True)
# 生成带时间戳的备份文件名
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file = backup_dir / f"auto_backup_{timestamp}.sql"
# 构建备份命令(容器内直接连接MySQL)
backup_command = f"mysqldump -h mysql -u callback_user -pdev_password_123 callback_system > {backup_file}"
print(f"📁 备份文件: {backup_file}")
if run_command(backup_command, f"备份数据库到 {backup_file.name}"):
print("🎉 数据库备份完成")
return True
else:
print("❌ 数据库备份失败")
print(f"🔄 备份数据库到 {backup_file.name}...")
try:
# 分步执行备份(使用已验证的方法)
# 1. 创建配置文件
config_cmd = "echo '[client]\nhost=mysql\nuser=callback_user\npassword=dev_password_123\nssl=0' > /tmp/backup.cnf"
subprocess.run(config_cmd, shell=True, check=True)
# 2. 执行备份
backup_cmd = f"mysqldump --defaults-file=/tmp/backup.cnf --single-transaction --routines --triggers callback_system > {backup_file}"
result = subprocess.run(backup_cmd, shell=True, capture_output=True, text=True)
# 3. 清理配置文件
subprocess.run("rm -f /tmp/backup.cnf", shell=True)
# 检查备份文件大小
if backup_file.exists() and backup_file.stat().st_size > 0:
print("✅ 备份数据库成功")
print(f"📊 备份文件大小: {backup_file.stat().st_size} 字节")
print("🎉 数据库备份完成")
return True
else:
print(f"❌ 备份数据库失败")
if result.stderr:
print(f"错误: {result.stderr}")
return False
except Exception as e:
print(f"❌ 备份过程中发生异常: {e}")
return False
if __name__ == '__main__':
......
......@@ -49,6 +49,8 @@ services:
- DB_PASSWORD=dev_password_123
- DB_NAME=callback_system
- DB_CHARSET=utf8mb4
volumes:
- ./database/backups:/app/database/backups
depends_on:
mysql:
condition: service_healthy
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment