package
1.1.48
Repository: https://github.com/18721889353/sunshine.git
Documentation: pkg.go.dev

# README

mysql

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


Example of use

Initializing the connection

    import "github.com/18721889353/sunshine/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 "github.com/18721889353/sunshine/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 "github.com/18721889353/sunshine/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

# Packages

Package query is a library for mysql query, support for complex conditional paging queries.

# Functions

Count number of records the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm Count.
Create a new record the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm Create.
Delete record the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm Delete.
DeleteByID delete record by id the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm DeleteByID.
Get one record the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm Get.
GetByID get record by id Deprecated: moved to package pkg/ggorm GetByID.
GetTableName get table name Deprecated: moved to package pkg/ggorm GetTableName.
Init mysql Deprecated: moved to package pkg/ggorm InitMysql.
List multiple records, starting from page 0 the param of 'tables' must be a slice, eg: []StructName Deprecated: moved to package pkg/ggorm List.
NewCustomGormLogger custom gorm logger Deprecated: moved to package pkg/ggorm NewCustomGormLogger.
TableName get table name Deprecated: moved to package pkg/ggorm TableName.
Update record the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm Update.
Updates record the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm Updates.
WithConnMaxLifetime set conn max lifetime Deprecated: moved to package pkg/ggorm WithConnMaxLifetime.
WithEnableForeignKey use foreign keys Deprecated: moved to package pkg/ggorm WithEnableForeignKey.
WithEnableTrace use trace Deprecated: moved to package pkg/ggorm WithEnableTrace.
WithGormPlugin setting gorm plugin Deprecated: moved to package pkg/ggorm WithGormPlugin.
WithLog set log sql Deprecated: will be replaced by WithLogging.
WithLogging set log sql, If l=nil, the gorm log library will be used Deprecated: moved to package pkg/ggorm WithLogging.
WithLogRequestIDKey log request id Deprecated: moved to package pkg/ggorm WithLogRequestIDKey.
WithMaxIdleConns set max idle conns Deprecated: moved to package pkg/ggorm WithMaxIdleConns.
WithMaxOpenConns set max open conns Deprecated: moved to package pkg/ggorm WithMaxOpenConns.
WithRWSeparation setting read-write separation Deprecated: moved to package pkg/ggorm WithRWSeparation.
WithSlowThreshold Set sql values greater than the threshold Deprecated: moved to package pkg/ggorm WithSlowThreshold.

# Structs

Model embedded structs, add `gorm: "embedded"` when defining table structs Deprecated: moved to package pkg/ggorm Model.
Model2 embedded structs, json tag named is snake case Deprecated: moved to package pkg/ggorm Model2.

# Type aliases

KV map type Deprecated: moved to package pkg/ggorm KV.
Option set the mysql options.