2022-06-25 13:36:35 +00:00
|
|
|
package db
|
2022-06-09 09:11:46 +00:00
|
|
|
|
|
|
|
import (
|
2023-01-09 06:09:21 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2022-08-03 06:26:59 +00:00
|
|
|
|
2022-09-16 14:21:43 +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"
|
|
|
|
)
|
|
|
|
|
2022-09-15 09:14:03 +00:00
|
|
|
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) {
|
2022-09-15 09:14:03 +00:00
|
|
|
db = d
|
2024-08-07 04:16:21 +00:00
|
|
|
err := AutoMigrate(new(model.Storage), new(model.User), new(model.Meta), new(model.SettingItem), new(model.SearchNode), new(model.TaskItem))
|
2022-11-28 05:45:25 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("failed migrate database: %s", err.Error())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func AutoMigrate(dst ...interface{}) error {
|
2022-09-16 14:21:43 +00:00
|
|
|
var err error
|
|
|
|
if conf.Conf.Database.Type == "mysql" {
|
2022-11-28 05:45:25 +00:00
|
|
|
err = db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4").AutoMigrate(dst...)
|
2022-09-16 14:21:43 +00:00
|
|
|
} else {
|
2022-11-28 05:45:25 +00:00
|
|
|
err = db.AutoMigrate(dst...)
|
2022-06-16 08:06:10 +00:00
|
|
|
}
|
2022-11-28 05:45:25 +00:00
|
|
|
return err
|
2022-06-14 11:44:25 +00:00
|
|
|
}
|
2023-01-09 06:09:21 +00:00
|
|
|
|
|
|
|
func GetDb() *gorm.DB {
|
2023-08-14 14:54:38 +00:00
|
|
|
return db
|
2023-01-09 06:09:21 +00:00
|
|
|
}
|
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
|
|
|
|
}
|
|
|
|
}
|