Skip to content

Commit

Permalink
new
Browse files Browse the repository at this point in the history
gorm v2 support
  • Loading branch information
xxjwxc committed Sep 24, 2020
1 parent a70ab3f commit 33d22fe
Show file tree
Hide file tree
Showing 10 changed files with 221 additions and 192 deletions.
2 changes: 1 addition & 1 deletion config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ db_info:
port : 3306
username : root
password : 123456
database : oauth_db
database : matrix
type: 0 # 数据库类型:0:mysql , 1:sqlite , 2:mssql

# sqlite
Expand Down
2 changes: 1 addition & 1 deletion data/view/cnf/def.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ package cnf
var EImportsHead = map[string]string{
"stirng": `"string"`,
"time.Time": `"time"`,
"gorm.Model": `"github.com/jinzhu/gorm"`,
"gorm.Model": `"gorm.io/gorm"`,
"fmt": `"fmt"`,
}

Expand Down
27 changes: 19 additions & 8 deletions data/view/genfunc/def.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,30 @@ func (m *{{.StructName}}) TableName() string {
package {{.PackageName}}
import (
"context"
"time"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)
var globalIsRelated bool = true // 全局预加载
// prepare for other
type _BaseMgr struct {
*gorm.DB
ctx *context.Context
ctx context.Context
cancel context.CancelFunc
timeout time.Duration
isRelated bool
}
// SetCtx set context
func (obj *_BaseMgr) SetCtx(c *context.Context) {
func (obj *_BaseMgr) SetTimeOut(timeout time.Duration) {
obj.ctx, obj.cancel = context.WithTimeout(context.Background(), timeout)
obj.timeout = timeout
}
// SetCtx set context
func (obj *_BaseMgr) SetCtx(c context.Context) {
obj.ctx = c
}
Expand Down Expand Up @@ -87,7 +96,9 @@ func {{$obj.StructName}}Mgr(db *gorm.DB) *_{{$obj.StructName}}Mgr {
if db == nil {
panic(fmt.Errorf("{{$obj.StructName}}Mgr need init by db"))
}
return &_{{$obj.StructName}}Mgr{_BaseMgr: &_BaseMgr{DB: db.Table("{{$obj.TableName}}"), isRelated: globalIsRelated}}
timeout := 10 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
return &_{{$obj.StructName}}Mgr{_BaseMgr: &_BaseMgr{DB: db.Table("{{$obj.TableName}}"), isRelated: globalIsRelated,ctx:ctx,cancel:cancel,timeout:timeout}}
}
// GetTableName get sql table name.获取数据库名字
Expand Down Expand Up @@ -188,25 +199,25 @@ func (obj *_{{$obj.StructName}}Mgr) GetBatchFrom{{$oem.ColStructName}}({{CapLowe
`
genPreload = `if err == nil && obj.isRelated { {{range $obj := .}}{{if $obj.IsMulti}}
if err = obj.DB.New().Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", result.{{$obj.ColStructName}}).Find(&result.{{$obj.ForeignkeyStructName}}List).Error;err != nil { // {{$obj.Notes}}
if err = obj.WithContext(obj.ctx).Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", result.{{$obj.ColStructName}}).Find(&result.{{$obj.ForeignkeyStructName}}List).Error;err != nil { // {{$obj.Notes}}
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
} {{else}}
if err = obj.DB.New().Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", result.{{$obj.ColStructName}}).Find(&result.{{$obj.ForeignkeyStructName}}).Error; err != nil { // {{$obj.Notes}}
if err = obj.WithContext(obj.ctx).Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", result.{{$obj.ColStructName}}).Find(&result.{{$obj.ForeignkeyStructName}}).Error; err != nil { // {{$obj.Notes}}
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
}{{end}} {{end}}}
`
genPreloadMulti = `if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ { {{range $obj := .}}{{if $obj.IsMulti}}
if err = obj.DB.New().Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", results[i].{{$obj.ColStructName}}).Find(&results[i].{{$obj.ForeignkeyStructName}}List).Error;err != nil { // {{$obj.Notes}}
if err = obj.WithContext(obj.ctx).Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", results[i].{{$obj.ColStructName}}).Find(&results[i].{{$obj.ForeignkeyStructName}}List).Error;err != nil { // {{$obj.Notes}}
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
} {{else}}
if err = obj.DB.New().Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", results[i].{{$obj.ColStructName}}).Find(&results[i].{{$obj.ForeignkeyStructName}}).Error; err != nil { // {{$obj.Notes}}
if err = obj.WithContext(obj.ctx).Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", results[i].{{$obj.ColStructName}}).Find(&results[i].{{$obj.ForeignkeyStructName}}).Error; err != nil { // {{$obj.Notes}}
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
Expand Down
65 changes: 50 additions & 15 deletions data/view/genfunc/genfunc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,59 @@ package genfunc
import (
"fmt"
"testing"
"time"

"github.com/jinzhu/gorm"
"github.com/xxjwxc/gormt/data/view/genfunc/model"
"gorm.io/gorm"

_ "github.com/go-sql-driver/mysql"
"github.com/xxjwxc/public/mysqldb"
"gorm.io/driver/mysql"
)

/**
测试数据库地址:https://github.com/xxjwxc/gormt/blob/master/data/view/genfunc/model/matrix.sql
*/

func GetGorm(dataSourceName string) *gorm.DB {
db, err := gorm.Open("mysql", dataSourceName)
db, err := gorm.Open(mysql.Open(dataSourceName), &gorm.Config{PrepareStmt: false})
if err != nil {
panic(err)
}
db.LogMode(true)
return db
sqlDB, err := db.DB()
if err != nil {
panic(err)
}
// SetMaxIdleConns 设置空闲连接池中连接的最大数量
sqlDB.SetMaxIdleConns(10)

// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(100)

// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(time.Hour)

return db.Debug()
}

func NewDB(){
db, _ := gorm.Open(...)
db.Model(&AAA).Where("aaa = ?", 2)
}

func CallFunc(db *gorm.DB){
// select a...
var bbb BBB
db.Table("bbb").Where("bbb = ?", 2).Find()
}

// TestFuncGet 测试条件获(Get/Gets)
func TestFuncGet(t *testing.T) {
model.OpenRelated() // 打开全局预加载 (外键)

db := GetGorm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True")
defer db.Close()
db := GetGorm("root:123456@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True")
defer func() {
sqldb, _ := db.DB()
sqldb.Close()
}()

accountMgr := model.AccountMgr(db.Where("account_id = ?", 2))
account, err := accountMgr.Get() // 单条获取
Expand All @@ -45,11 +71,14 @@ func TestFuncGet(t *testing.T) {

// TestFuncOption 功能选项方式获取
func TestFuncOption(t *testing.T) {
// db := GetGorm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True")
// defer db.Close()
orm := mysqldb.OnInitDBOrm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True") // 推荐方式
defer orm.OnDestoryDB()
db := orm.DB
db := GetGorm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True")
defer func() {
sqldb, _ := db.DB()
sqldb.Close()
}()
// orm := mysqldb.OnInitDBOrm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True") // 推荐方式
// defer orm.OnDestoryDB()
// db := orm.DB

accountMgr := model.AccountMgr(db)
accountMgr.SetIsRelated(true) // 打开预加载 (外键)
Expand All @@ -65,7 +94,10 @@ func TestFuncOption(t *testing.T) {
// TestFuncFrom 单元素方式获取
func TestFuncFrom(t *testing.T) {
db := GetGorm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True")
defer db.Close()
defer func() {
sqldb, _ := db.DB()
sqldb.Close()
}()

accountMgr := model.AccountMgr(db)
accountMgr.SetIsRelated(true) // 打开预加载 (外键)
Expand All @@ -82,7 +114,10 @@ func TestFuncFrom(t *testing.T) {
// TestFuncFetchBy 索引方式获取
func TestFuncFetchBy(t *testing.T) {
db := GetGorm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True")
defer db.Close()
defer func() {
sqldb, _ := db.DB()
sqldb.Close()
}()

accountMgr := model.AccountMgr(db)
accountMgr.SetIsRelated(true) // 打开预加载 (外键)
Expand Down
24 changes: 20 additions & 4 deletions data/view/genfunc/model/gen.base.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,31 @@ package model

import (
"context"
"time"

"github.com/jinzhu/gorm"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)

var globalIsRelated bool // 全局预加载
var globalIsRelated bool = true // 全局预加载

// prepare for other
type _BaseMgr struct {
*gorm.DB
ctx *context.Context
ctx context.Context
cancel context.CancelFunc
timeout time.Duration
isRelated bool
}

// SetCtx set context
func (obj *_BaseMgr) SetCtx(c *context.Context) {
func (obj *_BaseMgr) SetTimeOut(timeout time.Duration) {
obj.ctx, obj.cancel = context.WithTimeout(context.Background(), timeout)
obj.timeout = timeout
}

// SetCtx set context
func (obj *_BaseMgr) SetCtx(c context.Context) {
obj.ctx = c
}

Expand All @@ -40,6 +50,12 @@ func (obj *_BaseMgr) SetIsRelated(b bool) {
obj.isRelated = b
}

func (obj *_BaseMgr) new() *gorm.DB {
newDb := obj.DB.WithContext(obj.ctx)
newDb.Statement.Clauses = make(map[string]clause.Clause)
return newDb
}

type options struct {
query map[string]interface{}
}
Expand Down
Loading

0 comments on commit 33d22fe

Please sign in to comment.