2023-04-06 13:46:19 +08:00
|
|
|
package model
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"gorm.io/driver/mysql"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"gorm.io/gorm/logger"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
db *gorm.DB = nil
|
|
|
|
)
|
|
|
|
|
|
|
|
func SetDb(b *gorm.DB) {
|
|
|
|
db = b
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetOrm() *gorm.DB {
|
|
|
|
return db
|
|
|
|
}
|
|
|
|
|
|
|
|
type DBLogger struct {
|
|
|
|
level logger.LogLevel
|
|
|
|
}
|
|
|
|
|
|
|
|
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 {
|
2023-04-08 20:33:48 +08:00
|
|
|
if time.Since(begin).Milliseconds() > 1000 {
|
2023-04-06 13:46:19 +08:00
|
|
|
log.Errorf("[SQL]sql=%s affect=%d cost=%dms", sql, affects, time.Since(begin).Milliseconds())
|
|
|
|
} else {
|
2023-04-09 09:58:23 +08:00
|
|
|
log.Tracef("[SQL]sql=%s affect=%d cost=%dms", sql, affects, time.Since(begin).Milliseconds())
|
2023-04-06 13:46:19 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func Init(dsn string) (*gorm.DB, error) {
|
|
|
|
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 nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
db.Logger = &DBLogger{}
|
|
|
|
return db, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func Ping() error {
|
|
|
|
d, err := db.DB()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := d.Ping(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|