Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

升级至gormv2 #106

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,13 @@ require (
github.com/google/gops v0.3.12
github.com/google/uuid v1.1.2
github.com/google/wire v0.4.0
github.com/jackc/pgproto3/v2 v2.0.7 // indirect
github.com/jinzhu/copier v0.0.0-20190924061706-b57f9002281a
github.com/jinzhu/gorm v1.9.16
github.com/json-iterator/go v1.1.10
github.com/koding/multiconfig v0.0.0-20171124222453-69c27309b2d7
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-sqlite3 v1.14.6 // indirect
github.com/mattn/go-sqlite3 v2.0.3+incompatible // indirect
github.com/pkg/errors v0.9.1
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sirupsen/logrus v1.6.0
Expand All @@ -34,9 +35,15 @@ require (
github.com/swaggo/swag v1.7.0
github.com/tidwall/buntdb v1.1.2
github.com/urfave/cli/v2 v2.3.0
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a // indirect
golang.org/x/net v0.0.0-20210326220855-61e056675ecf // indirect
golang.org/x/sys v0.0.0-20210326220804-49726bf1d181 // indirect
golang.org/x/text v0.3.6 // indirect
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e
golang.org/x/tools v0.1.0 // indirect
gopkg.in/yaml.v2 v2.4.0
gorm.io/driver/mysql v1.1.0
gorm.io/driver/postgres v1.1.0
gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.10
)
414 changes: 412 additions & 2 deletions go.sum

Large diffs are not rendered by default.

12 changes: 9 additions & 3 deletions internal/app/gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ package app

import (
"errors"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"os"
"path/filepath"

"github.com/LyricTian/gin-admin/v7/internal/app/config"
"github.com/LyricTian/gin-admin/v7/internal/app/model/gormx"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// InitGormDB 初始化gorm存储
Expand All @@ -32,22 +35,25 @@ func InitGormDB() (*gorm.DB, func(), error) {
func NewGormDB() (*gorm.DB, func(), error) {
cfg := config.C
var dsn string
var dialector gorm.Dialector
switch cfg.Gorm.DBType {
case "mysql":
dsn = cfg.MySQL.DSN()
dialector = mysql.Open(dsn)
case "sqlite3":
dsn = cfg.Sqlite3.DSN()
_ = os.MkdirAll(filepath.Dir(dsn), 0777)
dialector = sqlite.Open(dsn)
case "postgres":
dsn = cfg.Postgres.DSN()
dialector = postgres.Open(dsn)
default:
return nil, nil, errors.New("unknown db")
}

return gormx.NewDB(&gormx.Config{
Debug: cfg.Gorm.Debug,
DBType: cfg.Gorm.DBType,
DSN: dsn,
Dialector: &dialector,
MaxIdleConns: cfg.Gorm.MaxIdleConns,
MaxLifetime: cfg.Gorm.MaxLifetime,
MaxOpenConns: cfg.Gorm.MaxOpenConns,
Expand Down
11 changes: 9 additions & 2 deletions internal/app/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ package app

import (
"errors"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"os"
"path/filepath"

Expand Down Expand Up @@ -56,20 +60,23 @@ func InitLogger() (func(), error) {
hc := config.C.LogGormHook

var dsn string
var dialector gorm.Dialector
switch hc.DBType {
case "mysql":
dsn = config.C.MySQL.DSN()
dialector = mysql.Open(dsn)
case "sqlite3":
dsn = config.C.Sqlite3.DSN()
dialector = sqlite.Open(dsn)
case "postgres":
dsn = config.C.Postgres.DSN()
dialector = postgres.Open(dsn)
default:
return nil, errors.New("unknown db")
}

h := loggerhook.New(loggergormhook.New(&loggergormhook.Config{
DBType: hc.DBType,
DSN: dsn,
Dialector: &dialector,
MaxLifetime: hc.MaxLifetime,
MaxOpenConns: hc.MaxOpenConns,
MaxIdleConns: hc.MaxIdleConns,
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/entity/e_demo.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (

"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/util/structure"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// GetDemoDB 获取demo存储
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/entity/e_menu.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (

"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/util/structure"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// GetMenuDB 获取菜单存储
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/entity/e_menu_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (

"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/util/structure"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// GetMenuActionDB 菜单动作
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/entity/e_menu_action_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (

"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/util/structure"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// GetMenuActionResourceDB 菜单动作关联资源
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/entity/e_role.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (

"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/util/structure"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// GetRoleDB 获取角色存储
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/entity/e_role_menu.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (

"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/util/structure"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// GetRoleMenuDB 角色菜单
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/entity/e_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (

"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/util/structure"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// GetUserDB 获取用户存储
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/entity/e_user_role.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (

"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/util/structure"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// GetUserRoleDB 获取用户角色关联存储
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/entity/entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (

"github.com/LyricTian/gin-admin/v7/internal/app/config"
"github.com/LyricTian/gin-admin/v7/internal/app/contextx"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// GetDB ...
Expand Down
49 changes: 25 additions & 24 deletions internal/app/model/gormx/gorm.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
package gormx

import (
"gorm.io/gorm/schema"
"strings"
"time"

"github.com/LyricTian/gin-admin/v7/internal/app/config"
"github.com/LyricTian/gin-admin/v7/internal/app/model/gormx/entity"
"github.com/LyricTian/gin-admin/v7/pkg/logger"
"github.com/jinzhu/gorm"

// gorm存储注入
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/postgres"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"gorm.io/gorm"
)

// Config 配置参数
type Config struct {
Debug bool
DBType string
DSN string
Dialector *gorm.Dialector
MaxLifetime int
MaxOpenConns int
MaxIdleConns int
Expand All @@ -28,35 +23,41 @@ type Config struct {

// NewDB 创建DB实例
func NewDB(c *Config) (*gorm.DB, func(), error) {
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return c.TablePrefix + defaultTableName
}

db, err := gorm.Open(c.DBType, c.DSN)
db, err := gorm.Open(*c.Dialector, &gorm.Config{ // https://gorm.io/zh_CN/docs/gorm_config.html
NamingStrategy: schema.NamingStrategy{
TablePrefix: c.TablePrefix, // 全局表前缀
SingularTable: true, // 禁用表名复数
},
DisableForeignKeyConstraintWhenMigrating: true, // 禁用自动创建外键约束
SkipDefaultTransaction: true, // 跳过默认事务
})
if err != nil {
return nil, nil, err
}

if c.Debug {
db = db.Debug()
}

sqlDB, err := db.DB()
if err != nil {
return nil, nil, err
}
cleanFunc := func() {
err := db.Close()
err := sqlDB.Close()
if err != nil {
logger.Errorf("Gorm db close error: %s", err.Error())
}
}

err = db.DB().Ping()
if err != nil {
return nil, cleanFunc, err
}
//在完成初始化后,GORMV2 会自动ping数据库以检查数据库的可用性,以下代码注释
//err = sqlDB.Ping()
//if err != nil {
// return nil, cleanFunc, err
//}

db.SingularTable(true)
db.DB().SetMaxIdleConns(c.MaxIdleConns)
db.DB().SetMaxOpenConns(c.MaxOpenConns)
db.DB().SetConnMaxLifetime(time.Duration(c.MaxLifetime) * time.Second)
sqlDB.SetMaxIdleConns(c.MaxIdleConns)
sqlDB.SetMaxOpenConns(c.MaxOpenConns)
sqlDB.SetConnMaxLifetime(time.Duration(c.MaxLifetime) * time.Second)
return db, cleanFunc, nil
}

Expand All @@ -75,5 +76,5 @@ func AutoMigrate(db *gorm.DB) error {
new(entity.Role),
new(entity.UserRole),
new(entity.User),
).Error
)
}
10 changes: 5 additions & 5 deletions internal/app/model/gormx/model/m_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (

"github.com/LyricTian/gin-admin/v7/internal/app/contextx"
"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// TransFunc 定义事务执行函数
Expand All @@ -30,7 +30,7 @@ func ExecTransWithLock(ctx context.Context, db *gorm.DB, fn TransFunc) error {
// WrapPageQuery 包装带有分页的查询
func WrapPageQuery(ctx context.Context, db *gorm.DB, pp schema.PaginationParam, out interface{}) (*schema.PaginationResult, error) {
if pp.OnlyCount {
var count int
var count int64
err := db.Count(&count).Error
if err != nil {
return nil, err
Expand All @@ -54,8 +54,8 @@ func WrapPageQuery(ctx context.Context, db *gorm.DB, pp schema.PaginationParam,
}

// FindPage 查询分页数据
func FindPage(ctx context.Context, db *gorm.DB, pp schema.PaginationParam, out interface{}) (int, error) {
var count int
func FindPage(ctx context.Context, db *gorm.DB, pp schema.PaginationParam, out interface{}) (int64, error) {
var count int64
err := db.Count(&count).Error
if err != nil {
return 0, err
Expand Down Expand Up @@ -88,7 +88,7 @@ func FindOne(ctx context.Context, db *gorm.DB, out interface{}) (bool, error) {

// Check 检查数据是否存在
func Check(ctx context.Context, db *gorm.DB) (bool, error) {
var count int
var count int64
result := db.Count(&count)
if err := result.Error; err != nil {
return false, err
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/model/m_demo.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/errors"
"github.com/google/wire"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// DemoSet 注入Demo
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/model/m_menu.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/errors"
"github.com/google/wire"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// MenuSet 注入Menu
Expand Down
2 changes: 1 addition & 1 deletion internal/app/model/gormx/model/m_menu_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/errors"
"github.com/google/wire"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// MenuActionSet 注入MenuAction
Expand Down
17 changes: 10 additions & 7 deletions internal/app/model/gormx/model/m_menu_action_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/LyricTian/gin-admin/v7/internal/app/schema"
"github.com/LyricTian/gin-admin/v7/pkg/errors"
"github.com/google/wire"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)

// MenuActionResourceSet 注入MenuActionResource
Expand All @@ -32,14 +32,16 @@ func (a *MenuActionResource) Query(ctx context.Context, params schema.MenuAction

db := entity.GetMenuActionResourceDB(ctx, a.DB)
if v := params.MenuID; v != "" {
results := entity.MenuActions{}
subQuery := entity.GetMenuActionDB(ctx, a.DB).
Where("menu_id=?", v).
Select("id").SubQuery()
db = db.Where("action_id IN ?", subQuery)
Select("id").Find(&results)
db = db.Where("action_id IN (?)", subQuery)
}
if v := params.MenuIDs; len(v) > 0 {
subQuery := entity.GetMenuActionDB(ctx, a.DB).Where("menu_id IN (?)", v).Select("id").SubQuery()
db = db.Where("action_id IN ?", subQuery)
results := entity.MenuActions{}
subQuery := entity.GetMenuActionDB(ctx, a.DB).Where("menu_id IN (?)", v).Select("id").Find(&results)
db = db.Where("action_id IN (?)", subQuery)
}

opt.OrderFields = append(opt.OrderFields, schema.NewOrderField("id", schema.OrderByASC))
Expand Down Expand Up @@ -100,7 +102,8 @@ func (a *MenuActionResource) DeleteByActionID(ctx context.Context, actionID stri

// DeleteByMenuID 根据菜单ID删除数据
func (a *MenuActionResource) DeleteByMenuID(ctx context.Context, menuID string) error {
subQuery := entity.GetMenuActionDB(ctx, a.DB).Where("menu_id=?", menuID).Select("id").SubQuery()
result := entity.GetMenuActionResourceDB(ctx, a.DB).Where("action_id IN ?", subQuery).Delete(entity.MenuActionResource{})
results := entity.MenuActions{}
subQuery := entity.GetMenuActionDB(ctx, a.DB).Where("menu_id=?", menuID).Select("id").Find(&results)
result := entity.GetMenuActionResourceDB(ctx, a.DB).Where("action_id IN (?)", subQuery).Delete(entity.MenuActionResource{})
return errors.WithStack(result.Error)
}
Loading