enterprise/common/global/db.go

96 lines
2.1 KiB
Go
Raw Normal View History

2023-08-04 11:13:41 +08:00
package global
import (
"context"
"enterprise/common/config"
2023-08-04 18:27:37 +08:00
"enterprise/common/dao"
2023-08-04 11:13:41 +08:00
"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.Errorf("[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: int64(2000)}
2023-08-04 18:27:37 +08:00
dao.SetDB(db)
2024-11-04 23:00:55 +08:00
unifyDsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", cfg.UnifyMysql.User,
cfg.UnifyMysql.Pass, cfg.UnifyMysql.Host, cfg.UnifyMysql.Port, cfg.UnifyMysql.Db)
db, err = gorm.Open(mysql.Open(unifyDsn), &gorm.Config{})
if err != nil {
log.Errorf("open dsn[%s] error[%s]", dsn, err)
return err
}
db.Logger = &DBLogger{threshold: int64(2000)}
dao.SetUnifyDB(db)
2023-08-04 11:13:41 +08:00
return nil
}
func DBPing() error {
d, err := db.DB()
if err != nil {
return err
}
if err := d.Ping(); err != nil {
return err
}
return nil
}