Files
excel-api/models/db.go
2026-06-26 14:31:24 +08:00

84 lines
1.8 KiB
Go
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.
// Package models 提供数据库初始化和连接管理功能
package models
import (
"fmt"
"log"
"excel-api/config"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// DB 全局数据库连接实例
var DB *gorm.DB
// InitDB 初始化数据库连接
// 读取配置文件中的数据库连接信息建立MySQL连接并自动迁移表结构
func InitDB() error {
cfg := config.App.Database
// 构建MySQL DSNData Source Name连接字符串
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
cfg.Username,
cfg.Password,
cfg.Host,
cfg.Port,
cfg.DBName,
cfg.Charset,
)
var err error
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
return fmt.Errorf("数据库连接失败: %w", err)
}
// 获取底层 *sql.DB 用于配置连接池
sqlDB, err := DB.DB()
if err != nil {
return fmt.Errorf("获取数据库连接池失败: %w", err)
}
// 设置连接池参数
sqlDB.SetMaxIdleConns(10) // 最大空闲连接数
sqlDB.SetMaxOpenConns(100) // 最大打开连接数
// 自动迁移:根据模型结构体创建/更新数据库表
// 注意AutoMigrate 仅创建表和添加缺失列,不会删除已有列
// 完整的表结构变更请参照根目录 init.sql 文件
err = DB.AutoMigrate(
&User{},
&Role{},
&Permission{},
&RolePermission{},
&UserRole{},
&Document{},
&Workbook{},
&Sheet{},
&Cell{},
&DocumentRole{},
&UserDocument{},
&WorkbookPermission{},
&OperationLog{},
&ShareLink{},
&Comment{},
&Notification{},
&Tag{},
&DocumentTag{},
&Folder{},
&FileUpload{},
&Version{},
&CollaborationSession{},
&ExportHistory{},
&Setting{},
&ApiKey{},
&AuditLog{},
)
if err != nil {
return fmt.Errorf("数据库迁移失败: %w", err)
}
log.Println("数据库连接成功,表结构迁移完成")
return nil
}