Files
17th-UnitTracker-API/api/db/main.go

80 lines
1.3 KiB
Go

package db
import (
"database/sql"
"sync"
"time"
"github.com/spf13/viper"
"gopkg.in/guregu/null.v3"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var ActiveDB *gorm.DB
var activeSQL *sql.DB
var lock = new(sync.Mutex)
type ObjectBase struct {
ID int `json:"id" gorm:"primarykey"`
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime; not null"`
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime; not null"`
Deleted bool `json:"deleted" gorm:"default:false; index; not null"`
DeletedAt null.Time `json:"deleted_at"`
}
func AutoMigrate() error {
db, err := GetDB()
if err != nil {
return err
}
err = db.AutoMigrate(
&Award{},
&Course{},
&Member{},
&Rank{},
&TrainingEvent{},
)
return err
}
func GetDB() (*gorm.DB, error) {
if ActiveDB != nil {
return ActiveDB, nil
}
db, err := ConnectDB()
if err != nil {
return nil, err
}
ActiveDB = db
return db, nil
}
func ConnectDB() (*gorm.DB, error) {
lock.Lock()
defer lock.Unlock()
if activeSQL != nil {
activeSQL.Close()
activeSQL = nil
}
cfg := viper.GetViper()
db, err := gorm.Open(mysql.Open(cfg.GetString("MARIADB_CONNSTRING")), &gorm.Config{
FullSaveAssociations: true,
PrepareStmt: true,
})
activeSQL, err = db.DB()
if err != nil {
return nil, err
}
ActiveDB = db
return db, nil
}