alist/internal/db/db.go

48 lines
953 B
Go
Raw Normal View History

2022-06-25 13:36:35 +00:00
package db
2022-06-09 09:11:46 +00:00
import (
log "github.com/sirupsen/logrus"
2022-08-03 06:26:59 +00:00
"github.com/alist-org/alist/v3/internal/conf"
2022-06-14 11:44:25 +00:00
"github.com/alist-org/alist/v3/internal/model"
2022-06-09 09:11:46 +00:00
"gorm.io/gorm"
)
var db *gorm.DB
2022-06-14 11:44:25 +00:00
2022-06-16 08:06:10 +00:00
func Init(d *gorm.DB) {
db = d
2022-12-30 06:20:04 +00:00
err := AutoMigrate(new(model.Storage), new(model.User), new(model.Meta), new(model.SettingItem), new(model.SearchNode))
if err != nil {
log.Fatalf("failed migrate database: %s", err.Error())
}
}
func AutoMigrate(dst ...interface{}) error {
var err error
if conf.Conf.Database.Type == "mysql" {
err = db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4").AutoMigrate(dst...)
} else {
err = db.AutoMigrate(dst...)
2022-06-16 08:06:10 +00:00
}
return err
2022-06-14 11:44:25 +00:00
}
func GetDb() *gorm.DB {
return db
}
2023-09-05 05:04:27 +00:00
func Close() {
log.Info("closing db")
sqlDB, err := db.DB()
if err != nil {
log.Errorf("failed to get db: %s", err.Error())
return
}
err = sqlDB.Close()
if err != nil {
log.Errorf("failed to close db: %s", err.Error())
return
}
}