1 Star 0 Fork 0

yzsunjianguo/common_pkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

mysql

mysql library wrapped in gorm, with added features such as tracer, paging queries, etc.


Example of use

Initializing the connection

    import "gitee.com/yzsunjianguo/common_pkg/mysql"

    var dsn = "root:123456@(192.168.1.6:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"

    // (1) connect to the database using the default settings
    db, err := mysql.Init(dsn)

    // (2) customised settings to connect to the database
    db, err := mysql.Init(
        dsn,
        mysql.WithLogging(logger.Get()),  // print log
        mysql.WithLogRequestIDKey("request_id"),  // print request_id
        mysql.WithMaxIdleConns(5),
        mysql.WithMaxOpenConns(50),
        mysql.WithConnMaxLifetime(time.Minute*3),
        // mysql.WithSlowThreshold(time.Millisecond*100),  // only print logs that take longer than 100 milliseconds to execute
        // mysql.WithEnableTrace(),  // enable tracing
        // mysql.WithRWSeparation(SlavesDsn, MastersDsn...)  // read-write separation
        // mysql.WithGormPlugin(yourPlugin)  // custom gorm plugin
    )

Model

package model

import "gitee.com/yzsunjianguo/common_pkg/mysql"

// UserExample object fields mapping table
type UserExample struct {
	mysql.Model `gorm:"embedded"`

	Name   string `gorm:"type:varchar(40);unique_index;not null" json:"name"`
	Age    int    `gorm:"not null" json:"age"`
	Gender string `gorm:"type:varchar(10);not null" json:"gender"`
}

// TableName get table name
func (table *UserExample) TableName() string {
	return mysql.GetTableName(table)
}

Transaction

import "gitee.com/yzsunjianguo/common_pkg/mysql"

func createUser() error {
	// note that you should use tx as the database handle when you are in a transaction
	tx := db.Begin()
	defer func() {
		if err := recover(); err != nil { // rollback after a panic during transaction execution
			tx.Rollback()
			fmt.Printf("transaction failed, err = %v\n", err)
		}
	}()

	var err error
	if err = tx.Error; err != nil {
		return err
	}

	if err = tx.Where("id = ?", 1).First(table).Error; err != nil {
		tx.Rollback()
		return err
	}

	panic("mock panic")

	if err = tx.Create(&userExample{Name: "Mr Li", Age: table.Age + 2, Gender: "male"}).Error; err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}

gorm User Guide

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/yzsunjianguo/common_pkg.git
git@gitee.com:yzsunjianguo/common_pkg.git
yzsunjianguo
common_pkg
common_pkg
v1.0.1

搜索帮助