gorm v2 support
This commit is contained in:
谢小军
2020-09-24 20:44:15 +08:00
parent a70ab3ff83
commit 33d22fe2d4
10 changed files with 221 additions and 192 deletions

View File

@@ -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

View File

@@ -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"`,
}

View File

@@ -11,8 +11,9 @@ func (m *{{.StructName}}) TableName() string {
package {{.PackageName}}
import (
"context"
"time"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)
var globalIsRelated bool = true // 全局预加载
@@ -20,12 +21,20 @@ 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
}
@@ -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.获取数据库名字
@@ -188,12 +199,12 @@ 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
}
@@ -201,12 +212,12 @@ func (obj *_{{$obj.StructName}}Mgr) GetBatchFrom{{$oem.ColStructName}}({{CapLowe
`
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
}

View File

@@ -3,12 +3,12 @@ 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"
)
/**
@@ -16,20 +16,46 @@ import (
*/
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() // 单条获取
@@ -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) // 打开预加载 (外键)
@@ -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) // 打开预加载 (外键)
@@ -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) // 打开预加载 (外键)

View File

@@ -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
}
@@ -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{}
}

View File

@@ -1,9 +1,11 @@
package model
import (
"context"
"fmt"
"time"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)
type _AccountMgr struct {
@@ -15,7 +17,9 @@ func AccountMgr(db *gorm.DB) *_AccountMgr {
if db == nil {
panic(fmt.Errorf("AccountMgr need init by db"))
}
return &_AccountMgr{_BaseMgr: &_BaseMgr{DB: db, isRelated: globalIsRelated}}
timeout := 10 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
return &_AccountMgr{_BaseMgr: &_BaseMgr{DB: db.Table("account"), isRelated: globalIsRelated, ctx: ctx, cancel: cancel, timeout: timeout}}
}
// GetTableName get sql table name.获取数据库名字
@@ -27,13 +31,10 @@ func (obj *_AccountMgr) GetTableName() string {
func (obj *_AccountMgr) Get() (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
if err = obj.new().Table("user").Where("user_id = ?", result.UserID).Find(&result.User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
result.User = info
}
}
@@ -45,13 +46,10 @@ func (obj *_AccountMgr) Gets() (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
if err = obj.Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
results[i].User = info
}
}
}
@@ -61,28 +59,28 @@ func (obj *_AccountMgr) Gets() (results []*Account, err error) {
//////////////////////////option case ////////////////////////////////////////////
// WithID id获取
func (obj *_AccountMgr) WithID(ID int) Option {
return optionFunc(func(o *options) { o.query["id"] = ID })
func (obj *_AccountMgr) WithID(id int) Option {
return optionFunc(func(o *options) { o.query["id"] = id })
}
// WithAccountID account_id获取
func (obj *_AccountMgr) WithAccountID(AccountID int) Option {
return optionFunc(func(o *options) { o.query["account_id"] = AccountID })
func (obj *_AccountMgr) WithAccountID(accountID int) Option {
return optionFunc(func(o *options) { o.query["account_id"] = accountID })
}
// WithUserID user_id获取
func (obj *_AccountMgr) WithUserID(UserID int) Option {
return optionFunc(func(o *options) { o.query["user_id"] = UserID })
func (obj *_AccountMgr) WithUserID(userID int) Option {
return optionFunc(func(o *options) { o.query["user_id"] = userID })
}
// WithType type获取
func (obj *_AccountMgr) WithType(Type int) Option {
return optionFunc(func(o *options) { o.query["type"] = Type })
func (obj *_AccountMgr) WithType(_type int) Option {
return optionFunc(func(o *options) { o.query["type"] = _type })
}
// WithName name获取
func (obj *_AccountMgr) WithName(Name string) Option {
return optionFunc(func(o *options) { o.query["name"] = Name })
func (obj *_AccountMgr) WithName(name string) Option {
return optionFunc(func(o *options) { o.query["name"] = name })
}
// GetByOption 功能选项模式获取
@@ -96,13 +94,10 @@ func (obj *_AccountMgr) GetByOption(opts ...Option) (result Account, err error)
err = obj.DB.Table(obj.GetTableName()).Where(options.query).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", result.UserID).Find(&result.User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
result.User = info
}
}
@@ -119,16 +114,12 @@ func (obj *_AccountMgr) GetByOptions(opts ...Option) (results []*Account, err er
}
err = obj.DB.Table(obj.GetTableName()).Where(options.query).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
results[i].User = info
}
}
}
@@ -138,16 +129,13 @@ func (obj *_AccountMgr) GetByOptions(opts ...Option) (results []*Account, err er
//////////////////////////enume case ////////////////////////////////////////////
// GetFromID 通过id获取内容
func (obj *_AccountMgr) GetFromID(ID int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id = ?", ID).Find(&result).Error
func (obj *_AccountMgr) GetFromID(id int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id = ?", id).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", result.UserID).Find(&result.User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
result.User = info
}
}
@@ -155,17 +143,14 @@ func (obj *_AccountMgr) GetFromID(ID int) (result Account, err error) {
}
// GetBatchFromID 批量唯一主键查找
func (obj *_AccountMgr) GetBatchFromID(IDs []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id IN (?)", IDs).Find(&results).Error
func (obj *_AccountMgr) GetBatchFromID(ids []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id IN (?)", ids).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
results[i].User = info
}
}
}
@@ -173,34 +158,29 @@ func (obj *_AccountMgr) GetBatchFromID(IDs []int) (results []*Account, err error
}
// GetFromAccountID 通过account_id获取内容
func (obj *_AccountMgr) GetFromAccountID(AccountID int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("account_id = ?", AccountID).Find(&result).Error
func (obj *_AccountMgr) GetFromAccountID(accountID int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("account_id = ?", accountID).Find(&results).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
return
for i := 0; i < len(results); i++ {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
}
result.User = info
}
}
return
}
// GetBatchFromAccountID 批量唯一主键查找
func (obj *_AccountMgr) GetBatchFromAccountID(AccountIDs []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("account_id IN (?)", AccountIDs).Find(&results).Error
func (obj *_AccountMgr) GetBatchFromAccountID(accountIDs []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("account_id IN (?)", accountIDs).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
results[i].User = info
}
}
}
@@ -208,34 +188,29 @@ func (obj *_AccountMgr) GetBatchFromAccountID(AccountIDs []int) (results []*Acco
}
// GetFromUserID 通过user_id获取内容
func (obj *_AccountMgr) GetFromUserID(UserID int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", UserID).Find(&result).Error
func (obj *_AccountMgr) GetFromUserID(userID int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", userID).Find(&results).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
return
for i := 0; i < len(results); i++ {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
}
result.User = info
}
}
return
}
// GetBatchFromUserID 批量唯一主键查找
func (obj *_AccountMgr) GetBatchFromUserID(UserIDs []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id IN (?)", UserIDs).Find(&results).Error
func (obj *_AccountMgr) GetBatchFromUserID(userIDs []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id IN (?)", userIDs).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
results[i].User = info
}
}
}
@@ -243,17 +218,14 @@ func (obj *_AccountMgr) GetBatchFromUserID(UserIDs []int) (results []*Account, e
}
// GetFromType 通过type获取内容
func (obj *_AccountMgr) GetFromType(Type int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("type = ?", Type).Find(&results).Error
func (obj *_AccountMgr) GetFromType(_type int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("type = ?", _type).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
results[i].User = info
}
}
}
@@ -261,17 +233,14 @@ func (obj *_AccountMgr) GetFromType(Type int) (results []*Account, err error) {
}
// GetBatchFromType 批量唯一主键查找
func (obj *_AccountMgr) GetBatchFromType(Types []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("type IN (?)", Types).Find(&results).Error
func (obj *_AccountMgr) GetBatchFromType(_types []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("type IN (?)", _types).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
results[i].User = info
}
}
}
@@ -279,17 +248,14 @@ func (obj *_AccountMgr) GetBatchFromType(Types []int) (results []*Account, err e
}
// GetFromName 通过name获取内容
func (obj *_AccountMgr) GetFromName(Name string) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name = ?", Name).Find(&results).Error
func (obj *_AccountMgr) GetFromName(name string) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name = ?", name).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
results[i].User = info
}
}
}
@@ -297,17 +263,14 @@ func (obj *_AccountMgr) GetFromName(Name string) (results []*Account, err error)
}
// GetBatchFromName 批量唯一主键查找
func (obj *_AccountMgr) GetBatchFromName(Names []string) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name IN (?)", Names).Find(&results).Error
func (obj *_AccountMgr) GetBatchFromName(names []string) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name IN (?)", names).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
results[i].User = info
}
}
}
@@ -317,16 +280,13 @@ func (obj *_AccountMgr) GetBatchFromName(Names []string) (results []*Account, er
//////////////////////////primary index case ////////////////////////////////////////////
// FetchByPrimaryKey primay or index 获取唯一内容
func (obj *_AccountMgr) FetchByPrimaryKey(ID int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id = ?", ID).Find(&result).Error
func (obj *_AccountMgr) FetchByPrimaryKey(id int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id = ?", id).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", result.UserID).Find(&result.User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
result.User = info
}
}
@@ -334,16 +294,13 @@ func (obj *_AccountMgr) FetchByPrimaryKey(ID int) (result Account, err error) {
}
// FetchUniqueIndexByAccount primay or index 获取唯一内容
func (obj *_AccountMgr) FetchUniqueIndexByAccount(AccountID int, UserID int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("account_id = ? AND user_id = ?", AccountID, UserID).Find(&result).Error
func (obj *_AccountMgr) FetchUniqueIndexByAccount(accountID int, userID int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("account_id = ? AND user_id = ?", accountID, userID).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", result.UserID).Find(&result.User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
result.User = info
}
}
@@ -351,17 +308,14 @@ func (obj *_AccountMgr) FetchUniqueIndexByAccount(AccountID int, UserID int) (re
}
// FetchIndexByTp 获取多个内容
func (obj *_AccountMgr) FetchIndexByTp(UserID int, Type int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ? AND type = ?", UserID, Type).Find(&results).Error
func (obj *_AccountMgr) FetchIndexByTp(userID int, _type int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ? AND type = ?", userID, _type).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
if err = obj.WithContext(obj.ctx).Table("user").Where("user_id = ?", results[i].UserID).Find(&results[i].User).Error; err != nil { //
if err != gorm.ErrRecordNotFound { // 非 没找到
return
}
results[i].User = info
}
}
}

View File

@@ -1,9 +1,11 @@
package model
import (
"context"
"fmt"
"time"
"github.com/jinzhu/gorm"
"gorm.io/gorm"
)
type _UserMgr struct {
@@ -15,7 +17,9 @@ func UserMgr(db *gorm.DB) *_UserMgr {
if db == nil {
panic(fmt.Errorf("UserMgr need init by db"))
}
return &_UserMgr{_BaseMgr: &_BaseMgr{DB: db, isRelated: globalIsRelated}}
timeout := 10 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
return &_UserMgr{_BaseMgr: &_BaseMgr{DB: db.Table("user"), isRelated: globalIsRelated, ctx: ctx, cancel: cancel, timeout: timeout}}
}
// GetTableName get sql table name.获取数据库名字
@@ -40,23 +44,23 @@ func (obj *_UserMgr) Gets() (results []*User, err error) {
//////////////////////////option case ////////////////////////////////////////////
// WithUserID user_id获取
func (obj *_UserMgr) WithUserID(UserID int) Option {
return optionFunc(func(o *options) { o.query["user_id"] = UserID })
func (obj *_UserMgr) WithUserID(userID int) Option {
return optionFunc(func(o *options) { o.query["user_id"] = userID })
}
// WithName name获取
func (obj *_UserMgr) WithName(Name string) Option {
return optionFunc(func(o *options) { o.query["name"] = Name })
func (obj *_UserMgr) WithName(name string) Option {
return optionFunc(func(o *options) { o.query["name"] = name })
}
// WithSex sex获取
func (obj *_UserMgr) WithSex(Sex int) Option {
return optionFunc(func(o *options) { o.query["sex"] = Sex })
func (obj *_UserMgr) WithSex(sex int) Option {
return optionFunc(func(o *options) { o.query["sex"] = sex })
}
// WithJob job获取
func (obj *_UserMgr) WithJob(Job int) Option {
return optionFunc(func(o *options) { o.query["job"] = Job })
func (obj *_UserMgr) WithJob(job int) Option {
return optionFunc(func(o *options) { o.query["job"] = job })
}
// GetByOption 功能选项模式获取
@@ -90,57 +94,57 @@ func (obj *_UserMgr) GetByOptions(opts ...Option) (results []*User, err error) {
//////////////////////////enume case ////////////////////////////////////////////
// GetFromUserID 通过user_id获取内容
func (obj *_UserMgr) GetFromUserID(UserID int) (result User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", UserID).Find(&result).Error
func (obj *_UserMgr) GetFromUserID(userID int) (result User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", userID).Find(&result).Error
return
}
// GetBatchFromUserID 批量唯一主键查找
func (obj *_UserMgr) GetBatchFromUserID(UserIDs []int) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id IN (?)", UserIDs).Find(&results).Error
func (obj *_UserMgr) GetBatchFromUserID(userIDs []int) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id IN (?)", userIDs).Find(&results).Error
return
}
// GetFromName 通过name获取内容
func (obj *_UserMgr) GetFromName(Name string) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name = ?", Name).Find(&results).Error
func (obj *_UserMgr) GetFromName(name string) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name = ?", name).Find(&results).Error
return
}
// GetBatchFromName 批量唯一主键查找
func (obj *_UserMgr) GetBatchFromName(Names []string) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name IN (?)", Names).Find(&results).Error
func (obj *_UserMgr) GetBatchFromName(names []string) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name IN (?)", names).Find(&results).Error
return
}
// GetFromSex 通过sex获取内容
func (obj *_UserMgr) GetFromSex(Sex int) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("sex = ?", Sex).Find(&results).Error
func (obj *_UserMgr) GetFromSex(sex int) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("sex = ?", sex).Find(&results).Error
return
}
// GetBatchFromSex 批量唯一主键查找
func (obj *_UserMgr) GetBatchFromSex(Sexs []int) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("sex IN (?)", Sexs).Find(&results).Error
func (obj *_UserMgr) GetBatchFromSex(sexs []int) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("sex IN (?)", sexs).Find(&results).Error
return
}
// GetFromJob 通过job获取内容
func (obj *_UserMgr) GetFromJob(Job int) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("job = ?", Job).Find(&results).Error
func (obj *_UserMgr) GetFromJob(job int) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("job = ?", job).Find(&results).Error
return
}
// GetBatchFromJob 批量唯一主键查找
func (obj *_UserMgr) GetBatchFromJob(Jobs []int) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("job IN (?)", Jobs).Find(&results).Error
func (obj *_UserMgr) GetBatchFromJob(jobs []int) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("job IN (?)", jobs).Find(&results).Error
return
}
@@ -148,8 +152,8 @@ func (obj *_UserMgr) GetBatchFromJob(Jobs []int) (results []*User, err error) {
//////////////////////////primary index case ////////////////////////////////////////////
// FetchByPrimaryKey primay or index 获取唯一内容
func (obj *_UserMgr) FetchByPrimaryKey(UserID int) (result User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", UserID).Find(&result).Error
func (obj *_UserMgr) FetchByPrimaryKey(userID int) (result User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", userID).Find(&result).Error
return
}

View File

@@ -2,18 +2,18 @@ package model
// Account [...]
type Account struct {
ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"`
AccountID int `gorm:"unique_index:account;column:account_id;type:int(11)" json:"account_id"`
UserID int `gorm:"unique_index:account;index:tp;column:user_id;type:int(11)" json:"user_id"`
ID int `gorm:"primary_key;column:id;type:int;not null" json:"-"`
AccountID int `gorm:"unique_index:account;column:account_id;type:int" json:"account_id"`
UserID int `gorm:"unique_index:account;index:tp;column:user_id;type:int" json:"user_id"`
User User `gorm:"association_foreignkey:user_id;foreignkey:user_id" json:"user_list"`
Type int `gorm:"index:tp;column:type;type:int(11)" json:"type"`
Type int `gorm:"index:tp;column:type;type:int" json:"type"`
Name string `gorm:"column:name;type:varchar(255)" json:"name"`
}
// User [...]
type User struct {
UserID int `gorm:"primary_key;column:user_id;type:int(11);not null" json:"user_id"`
UserID int `gorm:"primary_key;column:user_id;type:int;not null" json:"-"`
Name string `gorm:"column:name;type:varchar(30);not null" json:"name"`
Sex int `gorm:"column:sex;type:int(11);not null" json:"sex"`
Job int `gorm:"column:job;type:int(11);not null" json:"job"`
Sex int `gorm:"column:sex;type:int;not null" json:"sex"`
Job int `gorm:"column:job;type:int;not null" json:"job"`
}

2
go.mod
View File

@@ -16,6 +16,8 @@ require (
gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
gopkg.in/go-playground/validator.v9 v9.30.2
gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2
gorm.io/driver/mysql v1.0.1
gorm.io/gorm v1.20.1
)
// replace github.com/xxjwxc/public => ../public

7
go.sum
View File

@@ -103,6 +103,8 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M=
github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E=
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/jroimartin/gocui v0.4.0 h1:52jnalstgmc25FmtGcWqa0tcbMEWS6RpFLsOIO+I+E8=
github.com/jroimartin/gocui v0.4.0/go.mod h1:7i7bbj99OgFHzo7kB2zPb8pXLqMBSQegY7azfqXMkyY=
@@ -309,6 +311,11 @@ gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2 h1:XZx7nhd5GMaZpmDaEHFVafUZC7ya0fuo7cSJ3UCKYmM=
gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.0.1 h1:omJoilUzyrAp0xNoio88lGJCroGdIOen9hq2A/+3ifw=
gorm.io/driver/mysql v1.0.1/go.mod h1:KtqSthtg55lFp3S5kUXqlGaelnWpKitn4k1xZTnoiPw=
gorm.io/gorm v1.9.19/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.20.1 h1:+hOwlHDqvqmBIMflemMVPLJH7tZYK4RxFDBHEfJTup0=
gorm.io/gorm v1.20.1/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=