github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/mysql/trans/transaction_test.go (about)

     1  package trans
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  
     7  	_ "github.com/go-sql-driver/mysql"
     8  
     9  	"golib/gorm"
    10  )
    11  
    12  type Role struct {
    13  	// 主键id
    14  	// Read Only : true
    15  	Id uint64 `gorm:"primary_key;column:F_id" sql:"type:bigint(64) unsigned auto_increment;not null" json:"id"`
    16  	// 角色名称,唯一
    17  	// Maximum length : 64
    18  	Name       string `gorm:"column:F_name" sql:"type:varchar(64);not null;unique_index:I_name" json:"name"`
    19  	CreateTime uint64 `gorm:"column:F_create_time" sql:"type:bigint(64) unsigned;not null;default:0" json:"-"`
    20  	UpdateTime uint64 `gorm:"column:F_update_time" sql:"type:bigint(64) unsigned;not null;default:0;index:I_update_time" json:"-"`
    21  	Enabled    uint8  `gorm:"column:F_enabled" sql:"type:tinyint(8) unsigned;not null;default:1" json:"-"`
    22  }
    23  
    24  func (role Role) TableName() string {
    25  	return "access.t_role"
    26  }
    27  
    28  func TestTrans(t *testing.T) {
    29  	//init mysql connect pool
    30  	db, err := gorm.Open("mysql", "root:root@tcp(127.0.0.1:3306)/?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai")
    31  	if err != nil {
    32  		fmt.Printf("Error:%s", err.Error())
    33  		return
    34  	}
    35  
    36  	db.DB().SetMaxOpenConns(10)
    37  	db.DB().SetMaxIdleConns(5)
    38  	db.SingularTable(true)
    39  
    40  	err = db.DB().Ping()
    41  	if err != nil {
    42  		fmt.Printf("Error:%s", err.Error())
    43  		return
    44  	}
    45  
    46  	var test_func = func(test_db *gorm.DB) error {
    47  		role := Role{Name: "richard"}
    48  		if err := test_db.Create(&role).Error; err != nil {
    49  			return fmt.Errorf("Error:%s", err.Error())
    50  		}
    51  		panic("test cache transaction")
    52  	}
    53  
    54  	err = ExecTransaction(&db, test_func)
    55  	if err != nil {
    56  		fmt.Printf("56:Error:%s", err.Error())
    57  	}
    58  }