electron-vue-exam-single/electron/db/migration.js
chenqiang 7e8c417c48 p
2025-08-12 11:39:54 +08:00

53 lines
2.0 KiB
JavaScript

import path from 'path';
import fs from 'fs';
import { app } from 'electron';
import { getSystemDbPath, getUserDbPath } from './path.js';
// 迁移数据库文件
export async function migrateDatabases() {
// 开发环境下不执行迁移
if (process.env.NODE_ENV === 'development') {
console.log('开发环境下不执行数据库迁移');
return;
}
try {
// 获取数据库路径
const systemDbPath = getSystemDbPath();
const userDbPath = getUserDbPath();
const dataDir = path.dirname(systemDbPath);
// 确保数据目录存在
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
console.log(`创建数据目录: ${dataDir}`);
}
// 获取安装目录中的数据库文件路径
const appPath = app.getAppPath();
const installedSystemDbPath = path.join(appPath, 'data', 'system.db');
const installedUserDbPath = path.join(appPath, 'data', 'user.db');
// 检查并复制系统数据库文件(仅当目标文件不存在时)
if (fs.existsSync(installedSystemDbPath) && !fs.existsSync(systemDbPath)) {
fs.copyFileSync(installedSystemDbPath, systemDbPath);
console.log(`复制系统数据库: ${installedSystemDbPath} -> ${systemDbPath}`);
} else if (fs.existsSync(systemDbPath)) {
console.log(`系统数据库已存在: ${systemDbPath}`);
} else {
console.log(`系统数据库不存在: ${systemDbPath}`);
}
// 检查并复制用户数据库文件(仅当目标文件不存在时)
if (fs.existsSync(installedUserDbPath) && !fs.existsSync(userDbPath)) {
fs.copyFileSync(installedUserDbPath, userDbPath);
console.log(`复制用户数据库: ${installedUserDbPath} -> ${userDbPath}`);
} else if (fs.existsSync(userDbPath)) {
console.log(`用户数据库已存在: ${userDbPath}`);
} else {
console.log(`用户数据库不存在: ${userDbPath}`);
}
} catch (error) {
console.error('数据库迁移检查失败:', error);
}
}