2022-08-16 23:30:23 +08:00
|
|
|
package db
|
|
|
|
|
2022-11-16 18:27:22 +08:00
|
|
|
import (
|
2023-01-29 16:38:34 +08:00
|
|
|
"fmt"
|
2023-04-05 20:17:52 +08:00
|
|
|
"gorm.io/gorm/logger"
|
|
|
|
"log"
|
2023-03-21 19:00:28 +08:00
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
2023-03-08 18:30:50 +08:00
|
|
|
"gorm.io/driver/sqlite"
|
2023-03-08 14:16:30 +08:00
|
|
|
"gorm.io/gorm"
|
2023-01-29 16:38:34 +08:00
|
|
|
|
2022-11-16 18:27:22 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/global"
|
|
|
|
)
|
2022-08-16 23:30:23 +08:00
|
|
|
|
|
|
|
func Init() {
|
2023-01-29 16:38:34 +08:00
|
|
|
if _, err := os.Stat(global.CONF.System.DbPath); err != nil {
|
|
|
|
if err := os.MkdirAll(global.CONF.System.DbPath, os.ModePerm); err != nil {
|
|
|
|
panic(fmt.Errorf("init db dir falied, err: %v", err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
fullPath := global.CONF.System.DbPath + "/" + global.CONF.System.DbFile
|
|
|
|
if _, err := os.Stat(fullPath); err != nil {
|
|
|
|
if _, err := os.Create(fullPath); err != nil {
|
|
|
|
panic(fmt.Errorf("init db file falied, err: %v", err))
|
|
|
|
}
|
|
|
|
}
|
2023-03-08 14:16:30 +08:00
|
|
|
|
2023-04-05 20:17:52 +08:00
|
|
|
newLogger := logger.New(
|
|
|
|
log.New(os.Stdout, "\r\n", log.LstdFlags),
|
|
|
|
logger.Config{
|
|
|
|
SlowThreshold: time.Second,
|
|
|
|
LogLevel: logger.Silent,
|
|
|
|
IgnoreRecordNotFoundError: true,
|
|
|
|
Colorful: false,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
2023-02-27 17:22:14 +08:00
|
|
|
db, err := gorm.Open(sqlite.Open(fullPath), &gorm.Config{
|
|
|
|
DisableForeignKeyConstraintWhenMigrating: true,
|
2023-04-05 20:17:52 +08:00
|
|
|
Logger: newLogger,
|
2023-02-27 17:22:14 +08:00
|
|
|
})
|
2022-11-16 18:27:22 +08:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
2022-08-16 23:30:23 +08:00
|
|
|
}
|
2023-03-21 19:00:28 +08:00
|
|
|
_ = db.Exec("PRAGMA journal_mode = WAL;")
|
|
|
|
sqlDB, dbError := db.DB()
|
|
|
|
if dbError != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
sqlDB.SetConnMaxIdleTime(10)
|
|
|
|
sqlDB.SetMaxOpenConns(100)
|
|
|
|
sqlDB.SetConnMaxLifetime(time.Hour)
|
|
|
|
|
2022-11-16 18:27:22 +08:00
|
|
|
global.DB = db
|
2023-03-01 18:17:31 +08:00
|
|
|
global.LOG.Info("init db successfully")
|
2022-08-16 23:30:23 +08:00
|
|
|
}
|