film/global/db.go

85 lines
1.7 KiB
Go
Raw Normal View History

2024-04-27 23:12:44 +08:00
package global
2023-04-06 13:46:19 +08:00
import (
"context"
2024-04-27 23:12:44 +08:00
"film/config"
"fmt"
2023-04-06 13:46:19 +08:00
log "github.com/sirupsen/logrus"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"time"
)
var (
db *gorm.DB = nil
)
2024-04-27 23:12:44 +08:00
func GetDB() *gorm.DB {
2023-04-06 13:46:19 +08:00
return db
}
type DBLogger struct {
2024-04-27 23:12:44 +08:00
level logger.LogLevel
threshold int64
2023-04-06 13:46:19 +08:00
}
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 {
2024-04-27 23:12:44 +08:00
if time.Since(begin).Milliseconds() > d.threshold {
log.Warnf("[SQL]sql=%s affect=%d cost=%dms", sql, affects, time.Since(begin).Milliseconds())
2023-04-06 13:46:19 +08:00
} else {
2024-04-27 23:12:44 +08:00
log.Debugf("[SQL]sql=%s affect=%d cost=%dms", sql, affects, time.Since(begin).Milliseconds())
2023-04-06 13:46:19 +08:00
}
}
}
2024-04-27 23:12:44 +08:00
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)
2023-04-06 13:46:19 +08:00
var err error
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Errorf("open dsn[%s] error[%s]", dsn, err)
2024-04-27 23:12:44 +08:00
return err
2023-04-06 13:46:19 +08:00
}
2024-04-27 23:12:44 +08:00
db.Logger = &DBLogger{threshold: 1000}
return nil
2023-04-06 13:46:19 +08:00
}
2024-04-27 23:12:44 +08:00
func DBPing() error {
2023-04-06 13:46:19 +08:00
d, err := db.DB()
if err != nil {
return err
}
if err := d.Ping(); err != nil {
return err
}
return nil
}