Skip to content

Commit

Permalink
feat(db): add gorm db connection
Browse files Browse the repository at this point in the history
  • Loading branch information
lastares committed Aug 29, 2024
1 parent 1d4d161 commit 3d1f127
Show file tree
Hide file tree
Showing 11 changed files with 577 additions and 14 deletions.
9 changes: 9 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CONF_PROTO_FILES=$(shell find ./protobuf/conf/ -name *.proto)

.PHONY: conf
# generate conf proto
conf:
protoc --proto_path=. \
--go_out=paths=source_relative:. \
$(CONF_PROTO_FILES)

8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Claymore :tada::tada::tada: :tada::tada::tada:

> 当前包使用的go版本 `go 1.22.6`
> 本包开发使用的go版本 `go 1.22.6`
go开发中经常使用一些工具函数,每次新项目或者到了一个新坑位都要重新去写,很是麻烦
所以,这个项目就是封装一些常用的工具函数,方便 Gopher 开发,希望能成为 Gopher 开发中经常使用的 **claymore**
Expand Down Expand Up @@ -49,6 +49,12 @@ go开发中经常使用一些工具函数,每次新项目或者到了一个新
| 001 | JsonEncode() | json 序列化 |
| 002 | JsonDecode() | json 反序列化 |

### Gorm(dbutil) ###

| 编号 | 函数 | 功能 |
|-----|--------------|----------------|
| 001 | New() | 连接数据库,获取Gorm实例 |

### 其他(generalutil) ###

| 编号 | 函数 | 功能 |
Expand Down
71 changes: 71 additions & 0 deletions dbutil/db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package dbutil

import (
"log"
"os"
"time"

"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"

"github.com/lastares/claymore/protobuf/conf"
)

func New(dbConfig *conf.Data_Database, gormConfig gorm.Config) (*gorm.DB, error) {
mysqlConfig := InitConfig(
WithDriver(dbConfig.Driver),
DSN(dbConfig.Source),
DefaultStringSize(256), // 为字符串(string)字段设置大小。默认情况下,对于没有大小、没有主键、没有定义索引且没有默认值的字段,将使用db类型“longext”

DisableDatetimePrecision(true), // 禁用日期时间精度支持。但是这在MySQL 5.6之前不支持
DontSupportRenameColumn(true), // 重命名列时使用change,但是在MySQL 8、MariaDB之前不支持重命名
DontSupportRenameIndex(true), // 重命名索引时删除并创建索引。但是在MySQL 5.7、MariaDB之前不支持重命名索引
SkipInitializeWithVersion(true), // 是否根据当前 MySQL 版本自动配置
)
db, err := gorm.Open(mysql.New(mysqlConfig), &gormConfig)
if err != nil {
return nil, err
}
sqlDB, err := db.DB()
if err != nil {
return db, err
}
// 连接池配置
sqlDB.SetConnMaxLifetime(dbConfig.ConnectionLifeTime.AsDuration()) // 每一个连接的生命周期
sqlDB.SetMaxIdleConns(int(dbConfig.MaxIdleConnections)) // 是设置空闲时的最大连接数
sqlDB.SetMaxOpenConns(int(dbConfig.MaxOpenConnections)) // 设置与数据库的最大打开连接数
return db, err
}

// GormConfig 配置GORM的日志和事务设置。
// 参数:
//
// app - 提供应用配置,用于判断当前环境以设置日志级别。
//
// 返回值:
//
// 返回一个gorm.Config对象,用于配置GORM的行为。
func GormConfig(app *conf.App) gorm.Config {
// 根据应用环境设置日志模式,默认为警告级别
logMode := logger.Warn
// 如果是开发环境,切换到信息级别日志,记录所有SQL执行
if app.IsDevelopment() {
logMode = logger.Info
}
// 创建一个新的logger实例,配置GORM日志行为
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer,将日志输出到标准输出
logger.Config{
SlowThreshold: 1 * time.Second, // 慢查询阈值设置为1秒
LogLevel: logMode, // 设置日志级别
IgnoreRecordNotFoundError: true, // 忽略记录未找到错误
},
)
// 返回配置的GORM配置对象
return gorm.Config{
Logger: newLogger, // 使用新创建的logger实例
SkipDefaultTransaction: true, // 跳过默认事务,通常用于提高性能
PrepareStmt: true, // 启用预处理语句,可以提高性能和安全性
}
}
41 changes: 41 additions & 0 deletions dbutil/db_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package dbutil

import (
"testing"

"google.golang.org/protobuf/types/known/durationpb"

"github.com/lastares/claymore/generalutil"
"github.com/lastares/claymore/protobuf/conf"
)

func TestNewDB(t *testing.T) {
dsn := "root:root@tcp(127.0.0.1:3306)/my_test?charset=utf8mb4&parseTime=True&loc=Local"
databaseConf := &conf.Data_Database{
Driver: "mysql",
Source: dsn,
MaxOpenConnections: 100,
MaxIdleConnections: 100,
ConnectionLifeTime: &durationpb.Duration{
Seconds: 3600,
},
}
app := &conf.App{
Name: "test",
Env: "dev",
}
gormConfig := GormConfig(app)
gorm, err := New(databaseConf, gormConfig)
if err != nil {
t.Errorf("NewDB error: %v", err)
}
type User struct {
ID int32
Name string
}
var u *User
if err = gorm.Table("user").Select("*").First(&u).Error; err != nil {
t.Errorf("NewDB error: %v", err)
}
generalutil.PrettyPrintStruct(u)
}
63 changes: 63 additions & 0 deletions dbutil/mysqlconfig.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package dbutil

import (
"gorm.io/driver/mysql"
)

type Config func(*mysql.Config)

// DSN data source name
func DSN(dsn string) Config {
return func(c *mysql.Config) {
c.DSN = dsn
}
}

func WithDriver(driver string) Config {
return func(c *mysql.Config) {
c.DriverName = driver
}
}

// DefaultStringSize string 类型字段的默认长度
func DefaultStringSize(size uint) Config {
return func(c *mysql.Config) {
c.DefaultStringSize = size
}
}

// DisableDatetimePrecision 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
func DisableDatetimePrecision(disabled bool) Config {
return func(c *mysql.Config) {
c.DisableDatetimePrecision = disabled
}
}

// DontSupportRenameIndex 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
func DontSupportRenameIndex(dontSupport bool) Config {
return func(c *mysql.Config) {
c.DontSupportRenameIndex = dontSupport
}
}

// DontSupportRenameColumn 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
func DontSupportRenameColumn(dontSupport bool) Config {
return func(c *mysql.Config) {
c.DontSupportRenameColumn = dontSupport
}
}

// SkipInitializeWithVersion 根据当前 MySQL 版本自动配置
func SkipInitializeWithVersion(skipped bool) Config {
return func(c *mysql.Config) {
c.SkipInitializeWithVersion = skipped
}
}

func InitConfig(cfgs ...Config) mysql.Config {
config := mysql.Config{}
for _, cfg := range cfgs {
cfg(&config)
}
return config
}
7 changes: 4 additions & 3 deletions generalutil/general_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import (

func TestBeautifyPrintStruct(t *testing.T) {
type User struct {
Name string
Age int
Name string
Age int
Address []int
}
u := User{Name: "John", Age: 30}
u := User{Name: "John", Age: 30, Address: []int{1, 2, 3, 4}}
PrettyPrintStruct(u)
}
8 changes: 5 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ go 1.22.6
require (
golang.org/x/text v0.17.0
google.golang.org/protobuf v1.34.2
gorm.io/driver/mysql v1.5.7
gorm.io/gorm v1.25.11
)

require (
github.com/tidwall/gjson v1.17.3 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/go-sql-driver/mysql v1.7.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
)
18 changes: 11 additions & 7 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/tidwall/gjson v1.17.3 h1:bwWLZU7icoKRG+C+0PNwIKC6FCJO/Q3p2pZvuP0jN94=
github.com/tidwall/gjson v1.17.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.25.11 h1:/Wfyg1B/je1hnDx3sMkX+gAlxrlZpn6X0BXRlwXlvHg=
gorm.io/gorm v1.25.11/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
5 changes: 5 additions & 0 deletions protobuf/conf/conf.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package conf

func (a *App) IsDevelopment() bool {
return a.Env == "dev"
}
Loading

0 comments on commit 3d1f127

Please sign in to comment.