1
0
mirror of https://github.com/1Panel-dev/1Panel.git synced 2025-01-19 16:29:17 +08:00
1Panel/core/init/db/db.go

90 lines
1.9 KiB
Go
Raw Normal View History

2024-07-19 19:04:11 +08:00
package db
import (
"fmt"
"log"
"os"
"path"
2024-07-19 19:04:11 +08:00
"time"
"github.com/1Panel-dev/1Panel/core/global"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func Init() {
initDB()
initTaskDB()
}
func initDB() {
dbPath := path.Join(global.CONF.System.BaseDir, "1panel/db")
if _, err := os.Stat(dbPath); err != nil {
if err := os.MkdirAll(dbPath, os.ModePerm); err != nil {
2024-07-19 19:04:11 +08:00
panic(fmt.Errorf("init db dir failed, err: %v", err))
}
}
fullPath := path.Join(dbPath, global.CONF.System.DbCoreFile)
2024-07-19 19:04:11 +08:00
if _, err := os.Stat(fullPath); err != nil {
f, err := os.Create(fullPath)
if err != nil {
panic(fmt.Errorf("init db file failed, err: %v", err))
}
_ = f.Close()
}
db, err := NewDBWithPath(fullPath)
if err != nil {
panic(err)
}
2024-07-19 19:04:11 +08:00
global.DB = db
global.LOG.Info("init db successfully")
}
func initTaskDB() {
fullPath := path.Join(global.CONF.System.BaseDir, "1panel/db/task.db")
if _, err := os.Stat(fullPath); err != nil {
f, err := os.Create(fullPath)
if err != nil {
panic(fmt.Errorf("init task db file failed, err: %v", err))
}
_ = f.Close()
}
db, err := NewDBWithPath(fullPath)
2024-07-19 19:04:11 +08:00
if err != nil {
panic(err)
}
global.TaskDB = db
global.LOG.Info("init task db successfully")
}
func NewDBWithPath(dbPath string) (*gorm.DB, error) {
db, _ := gorm.Open(sqlite.Open(dbPath), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
Logger: getLogger(),
})
2024-07-19 19:04:11 +08:00
sqlDB, dbError := db.DB()
if dbError != nil {
return nil, dbError
2024-07-19 19:04:11 +08:00
}
sqlDB.SetConnMaxIdleTime(10)
sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour)
return db, nil
}
func getLogger() logger.Interface {
return logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags),
logger.Config{
SlowThreshold: time.Second,
LogLevel: logger.Silent,
IgnoreRecordNotFoundError: true,
Colorful: false,
},
)
2024-07-19 19:04:11 +08:00
}