mysql

package
v1.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2022 License: MIT Imports: 14 Imported by: 6

README

mysql

gorm基础上封装的库,添加了链路跟踪,分页查询等功能。


使用示例

初始化连接示例

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

    // (1) 使用默认设置连接数据库
    db, err := mysql.Init(dsn)

    // (2) 自定义设置连接数据库
	db, err := Init(
		dsn,
		//WithLog(), // 打印所有日志
		WithSlowThreshold(time.Millisecond*100), // 只打印执行时间超过100毫秒的日志
		WithEnableTrace(),                       // 开启链路跟踪
		WithMaxIdleConns(5),
		WithMaxOpenConns(50),
		WithConnMaxLifetime(time.Minute*3),
	)

model示例

package model

import (
	"github.com/zhufuyi/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)
}

事务示例

func createUser() error {
	// 注意,当你在一个事务中应使用 tx 作为数据库句柄
	tx := db.Begin()
	defer func() {
		if err := recover(); err != nil { // 在事务执行过程发生panic后回滚
			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("发生了异常")

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

	return tx.Commit().Error
}

更多使用查看gorm的使用指南

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Count added in v1.3.0

func Count(ctx context.Context, db *gorm.DB, table interface{}, query interface{}, args ...interface{}) (int64, error)

Count number of records the param of 'table' must be pointer, eg: &StructName

func Create added in v1.3.0

func Create(ctx context.Context, db *gorm.DB, table interface{}) error

Create a new record the param of 'table' must be pointer, eg: &StructName

func Delete added in v1.3.0

func Delete(ctx context.Context, db *gorm.DB, table interface{}, query interface{}, args ...interface{}) error

Delete record the param of 'table' must be pointer, eg: &StructName

func DeleteByID added in v1.3.0

func DeleteByID(ctx context.Context, db *gorm.DB, table interface{}, id interface{}) error

DeleteByID delete record by id the param of 'table' must be pointer, eg: &StructName

func Get added in v1.3.0

func Get(ctx context.Context, db *gorm.DB, table interface{}, query interface{}, args ...interface{}) error

Get one record the param of 'table' must be pointer, eg: &StructName

func GetByID added in v1.3.0

func GetByID(ctx context.Context, db *gorm.DB, table interface{}, id interface{}) error

GetByID get record by id

func GetTableName

func GetTableName(object interface{}) string

GetTableName 获取表名

func Init

func Init(dns string, opts ...Option) (*gorm.DB, error)

Init 初始化mysql

func List added in v1.3.0

func List(ctx context.Context, db *gorm.DB, tables interface{}, page *query.Page, query interface{}, args ...interface{}) error

List multiple records, starting from page 0 the param of 'tables' must be slice, eg: []StructName

func TableName added in v1.3.0

func TableName(table interface{}) string

TableName get table name

func Update added in v1.3.0

func Update(ctx context.Context, db *gorm.DB, table interface{}, column string, value interface{}, query interface{}, args ...interface{}) error

Update record the param of 'table' must be pointer, eg: &StructName

func Updates added in v1.3.0

func Updates(ctx context.Context, db *gorm.DB, table interface{}, update KV, query interface{}, args ...interface{}) error

Updates record the param of 'table' must be pointer, eg: &StructName

Types

type KV

type KV = map[string]interface{}

KV map类型

type Model

type Model struct {
	ID        uint64         `gorm:"column:id;AUTO_INCREMENT;primary_key" json:"id"`
	CreatedAt time.Time      `gorm:"column:created_at" json:"created_at"`
	UpdatedAt time.Time      `gorm:"column:updated_at" json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;index" json:"-"`
}

Model 表内嵌字段,嵌入到其他表结构体时添加 `gorm:"embedded"`

type Option

type Option func(*options)

Option set the mysql options.

func WithConnMaxLifetime

func WithConnMaxLifetime(t time.Duration) Option

WithConnMaxLifetime set conn max lifetime

func WithEnableForeignKey added in v1.3.0

func WithEnableForeignKey() Option

WithEnableForeignKey use foreign keys

func WithEnableTrace added in v1.3.0

func WithEnableTrace() Option

WithEnableTrace use trace

func WithLog

func WithLog() Option

WithLog set log sql

func WithMaxIdleConns

func WithMaxIdleConns(size int) Option

WithMaxIdleConns set max idle conns

func WithMaxOpenConns

func WithMaxOpenConns(size int) Option

WithMaxOpenConns set max open conns

func WithSlowThreshold added in v1.3.0

func WithSlowThreshold(d time.Duration) Option

WithSlowThreshold Set sql values greater than the threshold

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL