film/global/db.go

85 lines
1.7 KiB
Go

package global
import (
"context"
"film/config"
"fmt"
log "github.com/sirupsen/logrus"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"time"
)
var (
db *gorm.DB = nil
)
func GetDB() *gorm.DB {
return db
}
type DBLogger struct {
level logger.LogLevel
threshold int64
}
func (d *DBLogger) LogMode(level logger.LogLevel) logger.Interface {
d.level = level
return d
}
func (d *DBLogger) Info(context.Context, string, ...interface{}) {
}
func (d *DBLogger) Warn(context.Context, string, ...interface{}) {
}
func (d *DBLogger) Error(context.Context, string, ...interface{}) {
}
func (d *DBLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
sql, affects := fc()
if err != nil && err != gorm.ErrRecordNotFound {
log.Errorf("[SQL]sql=%s affect=%d cost=%dms error=%v", sql, affects, time.Since(begin).Milliseconds(), err)
} else {
if time.Since(begin).Milliseconds() > d.threshold {
log.Warnf("[SQL]sql=%s affect=%d cost=%dms", sql, affects, time.Since(begin).Milliseconds())
} else {
log.Debugf("[SQL]sql=%s affect=%d cost=%dms", sql, affects, time.Since(begin).Milliseconds())
}
}
}
func InitDB() error {
cfg := config.GetConfig()
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", cfg.Mysql.User,
cfg.Mysql.Pass, cfg.Mysql.Host, cfg.Mysql.Port, cfg.Mysql.Db)
var err error
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Errorf("open dsn[%s] error[%s]", dsn, err)
return err
}
db.Logger = &DBLogger{threshold: 1000}
return nil
}
func DBPing() error {
d, err := db.DB()
if err != nil {
return err
}
if err := d.Ping(); err != nil {
return err
}
return nil
}