import mysql from 'mysql2/promise'; import dotenv from 'dotenv'; import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; dotenv.config(); const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const initDb = async () => { // 创建不带数据库的连接 const connection = await mysql.createConnection({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD }); try { // 创建数据库 await connection.query(`CREATE DATABASE IF NOT EXISTS ${process.env.DB_NAME}`); console.log(`数据库 ${process.env.DB_NAME} 创建成功或已存在`); // 使用数据库 await connection.query(`USE ${process.env.DB_NAME}`); // 创建用户表 await connection.query(` CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(255) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) `); console.log('用户表创建成功'); // 创建任务表 await connection.query(` CREATE TABLE IF NOT EXISTS tasks ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, name VARCHAR(255) NOT NULL, created_date DATE NOT NULL, expected_completion_date DATE NOT NULL, importance INT NOT NULL, notes TEXT, completed BOOLEAN DEFAULT FALSE, completion_date DATE, FOREIGN KEY (user_id) REFERENCES users(id) ) `); console.log('任务表创建成功'); // 创建时间表 await connection.query(` CREATE TABLE IF NOT EXISTS schedules ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, day_of_week INT NOT NULL, /* 1-5 代表周一到周五 */ time_slot VARCHAR(50) NOT NULL, activity VARCHAR(255) NOT NULL, completed BOOLEAN DEFAULT FALSE, FOREIGN KEY (user_id) REFERENCES users(id) ) `); console.log('时间表创建成功'); // 创建心情表 await connection.query(` CREATE TABLE IF NOT EXISTS moods ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, date DATE NOT NULL, mood_value INT NOT NULL, /* 1-5 代表心情从差到好 */ FOREIGN KEY (user_id) REFERENCES users(id), UNIQUE KEY unique_user_date (user_id, date) ) `); console.log('心情表创建成功'); console.log('数据库初始化完成'); } catch (error) { console.error('数据库初始化失败:', error); } finally { await connection.end(); } }; initDb();