You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Open-IM-Server/pkg/common/db/relation/mysql_init.go

143 lines
4.8 KiB

2 years ago
package relation
import (
2 years ago
"context"
"errors"
2 years ago
"fmt"
2 years ago
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mw/specialerror"
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
2 years ago
mysqlDriver "github.com/go-sql-driver/mysql"
2 years ago
"gorm.io/driver/mysql"
gormUtils "gorm.io/gorm/utils"
2 years ago
"time"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
2 years ago
func newMysqlGormDB() (*gorm.DB, error) {
2 years ago
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
config.Config.Mysql.DBUserName, config.Config.Mysql.DBPassword, config.Config.Mysql.DBAddress[0], "mysql")
db, err := gorm.Open(mysql.Open(dsn), nil)
if err != nil {
time.Sleep(time.Duration(30) * time.Second)
db, err = gorm.Open(mysql.Open(dsn), nil)
if err != nil {
panic(err.Error() + " open failed " + dsn)
}
}
sqlDB, err := db.DB()
if err != nil {
return nil, err
}
defer sqlDB.Close()
sql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s default charset utf8 COLLATE utf8_general_ci;", config.Config.Mysql.DBDatabaseName)
err = db.Exec(sql).Error
if err != nil {
return nil, fmt.Errorf("init db %w", err)
}
dsn = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
config.Config.Mysql.DBUserName, config.Config.Mysql.DBPassword, config.Config.Mysql.DBAddress[0], config.Config.Mysql.DBDatabaseName)
sqlLogger := NewSqlLogger(logger.LogLevel(config.Config.Mysql.LogLevel), true, time.Duration(config.Config.Mysql.SlowThreshold)*time.Millisecond)
2 years ago
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: sqlLogger,
2 years ago
})
if err != nil {
return nil, err
}
sqlDB, err = db.DB()
if err != nil {
return nil, err
}
sqlDB.SetConnMaxLifetime(time.Second * time.Duration(config.Config.Mysql.DBMaxLifeTime))
sqlDB.SetMaxOpenConns(config.Config.Mysql.DBMaxOpenConns)
sqlDB.SetMaxIdleConns(config.Config.Mysql.DBMaxIdleConns)
return db, nil
}
// gorm mysql
2 years ago
func NewGormDB() (*gorm.DB, error) {
2 years ago
specialerror.AddReplace(gorm.ErrRecordNotFound, errs.ErrRecordNotFound)
2 years ago
specialerror.AddErrHandler(replaceDuplicateKey)
2 years ago
return newMysqlGormDB()
2 years ago
}
2 years ago
func replaceDuplicateKey(err error) errs.CodeError {
if IsMysqlDuplicateKey(err) {
return errs.ErrDuplicateKey
}
return nil
}
func IsMysqlDuplicateKey(err error) bool {
if mysqlErr, ok := err.(*mysqlDriver.MySQLError); ok {
return mysqlErr.Number == 1062
}
return false
}
type SqlLogger struct {
LogLevel logger.LogLevel
IgnoreRecordNotFoundError bool
SlowThreshold time.Duration
}
func NewSqlLogger(logLevel logger.LogLevel, ignoreRecordNotFoundError bool, slowThreshold time.Duration) *SqlLogger {
return &SqlLogger{
LogLevel: logLevel,
IgnoreRecordNotFoundError: ignoreRecordNotFoundError,
SlowThreshold: slowThreshold,
}
}
func (l *SqlLogger) LogMode(logLevel logger.LogLevel) logger.Interface {
newLogger := *l
newLogger.LogLevel = logLevel
return &newLogger
}
func (SqlLogger) Info(ctx context.Context, msg string, args ...interface{}) {
log.ZInfo(ctx, msg, args)
}
2 years ago
func (SqlLogger) Warn(ctx context.Context, msg string, args ...interface{}) {
log.ZWarn(ctx, msg, nil, args)
}
func (SqlLogger) Error(ctx context.Context, msg string, args ...interface{}) {
log.ZError(ctx, msg, nil, args)
}
func (l SqlLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
if l.LogLevel <= logger.Silent {
return
}
elapsed := time.Since(begin)
switch {
case err != nil && l.LogLevel >= logger.Error && (!errors.Is(err, gorm.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError):
sql, rows := fc()
if rows == -1 {
log.ZError(ctx, "sql exec detail", err, "gorm", gormUtils.FileWithLineNum(), "time(ms)", float64(elapsed.Nanoseconds())/1e6, "sql", sql)
} else {
log.ZError(ctx, "sql exec detail", err, "gorm", gormUtils.FileWithLineNum(), "time(ms)", float64(elapsed.Nanoseconds())/1e6, "rows", rows, "sql", sql)
}
case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= logger.Warn:
sql, rows := fc()
slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
if rows == -1 {
log.ZWarn(ctx, "sql exec detail", nil, "gorm", gormUtils.FileWithLineNum(), nil, "slow sql", slowLog, "time(ms)", float64(elapsed.Nanoseconds())/1e6, "sql", sql)
} else {
log.ZWarn(ctx, "sql exec detail", nil, "gorm", gormUtils.FileWithLineNum(), nil, "slow sql", slowLog, "time(ms)", float64(elapsed.Nanoseconds())/1e6, "rows", rows, "sql", sql)
}
case l.LogLevel == logger.Info:
sql, rows := fc()
if rows == -1 {
log.ZDebug(ctx, "sql exec detail", "gorm", gormUtils.FileWithLineNum(), "time(ms)", float64(elapsed.Nanoseconds())/1e6, "sql", sql)
} else {
log.ZDebug(ctx, "sql exec detail", "gorm", gormUtils.FileWithLineNum(), "time(ms)", float64(elapsed.Nanoseconds())/1e6, "rows", rows, "sql", sql)
}
2 years ago
}
2 years ago
}