gopkg/middleware/mysql/client.go

66 lines
1.3 KiB
Go
Raw Normal View History

2021-03-01 23:01:54 +08:00
// Package mysql ...
//
// Description : mysql客户端
//
2021-07-25 19:05:59 +08:00
// Author : go_developer@163.com<白茶清欢>
2021-03-01 23:01:54 +08:00
//
// Date : 2021-03-01 9:20 下午
package mysql
import (
"fmt"
2021-07-25 18:50:56 +08:00
"git.zhangdeman.cn/zhangdeman/gopkg/logger/wrapper"
2021-03-01 23:01:54 +08:00
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// GetDatabaseClient 获取日志实例
//
2021-07-25 19:05:59 +08:00
// Author : go_developer@163.com<白茶清欢>
2021-03-01 23:01:54 +08:00
//
// Date : 10:49 下午 2021/3/1
func GetDatabaseClient(conf *DBConfig, logConf *LogConfig) (*gorm.DB, error) {
var (
instance *gorm.DB
err error
)
if instance, err = gorm.Open(mysql.Open(buildConnectionDSN(conf)), &gorm.Config{}); nil != err {
return nil, err
}
if len(logConf.TraceFieldName) == 0 {
logConf.TraceFieldName = defaultTraceFieldName
}
if instance.Logger, err = wrapper.NewGormV2(
logConf.Level,
logConf.ConsoleOutput,
logConf.Encoder,
logConf.SplitConfig,
2021-03-06 13:50:18 +08:00
logConf.TraceFieldName,
logConf.Skip); nil != err {
2021-03-01 23:01:54 +08:00
return nil, CreateDBLogError(err)
}
return instance, nil
}
// buildConnectionDSN 构建建立连接的DSN
//
2021-07-25 19:05:59 +08:00
// Author : go_developer@163.com<白茶清欢>
2021-03-01 23:01:54 +08:00
//
// Date : 9:34 下午 2021/3/1
func buildConnectionDSN(conf *DBConfig) string {
return fmt.Sprintf(
"%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
conf.Username,
conf.Password,
conf.Host,
conf.Port,
conf.Database,
conf.Charset,
)
}