init repo
This commit is contained in:
50
cmd/db.go
Normal file
50
cmd/db.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/nose7en/ToyBoomServer/common"
|
||||
"github.com/nose7en/ToyBoomServer/config"
|
||||
"github.com/nose7en/ToyBoomServer/models"
|
||||
"github.com/nose7en/ToyBoomServer/storage"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func initDatabase() {
|
||||
c := context.Background()
|
||||
|
||||
common.Logger(c).Infof("start to init database, type: %s", config.GetSettings().DB.Type)
|
||||
storage.MustInitDBManager(nil, config.GetSettings().DB.Type)
|
||||
|
||||
switch config.GetSettings().DB.Type {
|
||||
case "sqlite":
|
||||
if sqlitedb, err := gorm.Open(sqlite.Open(config.GetSettings().DB.DSN), &gorm.Config{}); err != nil {
|
||||
common.Logger(c).Panic(err)
|
||||
} else {
|
||||
storage.GetDBManager().SetDB("sqlite", storage.DefaultDBName, sqlitedb)
|
||||
common.Logger(c).Infof("init database success, data location: [%s]", config.GetSettings().DB.DSN)
|
||||
}
|
||||
case "mysql":
|
||||
if mysqlDB, err := gorm.Open(mysql.Open(config.GetSettings().DB.DSN), &gorm.Config{}); err != nil {
|
||||
common.Logger(c).Panic(err)
|
||||
} else {
|
||||
storage.GetDBManager().SetDB("mysql", storage.DefaultDBName, mysqlDB)
|
||||
common.Logger(c).Infof("init database success, data type: [%s]", "mysql")
|
||||
}
|
||||
case "postgres":
|
||||
if postgresDB, err := gorm.Open(postgres.Open(config.GetSettings().DB.DSN), &gorm.Config{}); err != nil {
|
||||
common.Logger(c).Panic(err)
|
||||
} else {
|
||||
storage.GetDBManager().SetDB("postgres", storage.DefaultDBName, postgresDB)
|
||||
common.Logger(c).Infof("init database success, data type: [%s]", "postgres")
|
||||
}
|
||||
default:
|
||||
common.Logger(c).Panicf("currently unsupported database type: %s", config.GetSettings().DB.Type)
|
||||
}
|
||||
|
||||
storage.GetDBManager().Init(models.Models()...)
|
||||
}
|
||||
Reference in New Issue
Block a user