Files
go_typecho/database/database.go
2026-02-13 10:53:54 +08:00

64 lines
1.2 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 database
import (
"goblog/config"
"goblog/models"
"log"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var DB *gorm.DB
func Init(cfg *config.DatabaseConfig) error {
var err error
DB, err = gorm.Open(sqlite.Open(cfg.DSN), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
return err
}
// 自动迁移
err = DB.AutoMigrate(
&models.User{},
&models.Post{},
&models.Category{},
&models.Tag{},
&models.Comment{},
&models.Page{},
&models.Option{},
)
if err != nil {
return err
}
log.Println("数据库连接成功")
return nil
}
// 创建默认管理员
func CreateDefaultAdmin() error {
var count int64
DB.Model(&models.User{}).Where("role = ?", "admin").Count(&count)
if count == 0 {
admin := &models.User{
Username: "admin",
Password: "$2a$10$XrrWkDB.DIpuXOYYrMiZdOBpl0gxrtziSCQ4OOnGFP10C8.xF30qq", // admin123
Nickname: "管理员",
Email: "admin@example.com",
Role: "admin",
Status: 1,
}
if err := DB.Create(admin).Error; err != nil {
return err
}
log.Println("默认管理员创建成功,用户名: admin密码: admin123")
}
return nil
}