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
Documentation
¶
Overview ¶
Package mysql is a library wrapped on top of gorm.io/gorm, with added features such as link tracing, paging queries, etc. Deprecated: moved to package pkg/ggorm, will be deleted in the future
Index ¶
- func Count(ctx context.Context, db *gorm.DB, table interface{}, ...) (int64, error)
- func Create(ctx context.Context, db *gorm.DB, table interface{}) error
- func Delete(ctx context.Context, db *gorm.DB, table interface{}, ...) error
- func DeleteByID(ctx context.Context, db *gorm.DB, table interface{}, id interface{}) error
- func Get(ctx context.Context, db *gorm.DB, table interface{}, ...) error
- func GetByID(ctx context.Context, db *gorm.DB, table interface{}, id interface{}) error
- func GetTableName(object interface{}) string
- func Init(dns string, opts ...Option) (*gorm.DB, error)
- func List(ctx context.Context, db *gorm.DB, tables interface{}, page *query.Page, ...) error
- func NewCustomGormLogger(o *options) logger.Interface
- func TableName(table interface{}) string
- func Update(ctx context.Context, db *gorm.DB, table interface{}, column string, ...) error
- func Updates(ctx context.Context, db *gorm.DB, table interface{}, update KV, ...) error
- type KV
- type Model
- type Model2
- type Option
- func WithConnMaxLifetime(t time.Duration) Option
- func WithEnableForeignKey() Option
- func WithEnableTrace() Option
- func WithGormPlugin(plugins ...gorm.Plugin) Option
- func WithLog() Option
- func WithLogRequestIDKey(key string) Option
- func WithLogging(l *zap.Logger, level ...logger.LogLevel) Option
- func WithMaxIdleConns(size int) Option
- func WithMaxOpenConns(size int) Option
- func WithRWSeparation(slavesDsn []string, mastersDsn ...string) Option
- func WithSlowThreshold(d time.Duration) Option
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Count ¶
func Count(ctx context.Context, db *gorm.DB, table interface{}, queryCondition interface{}, args ...interface{}) (int64, error)
Count number of records the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm Count
func Create ¶
Create a new record the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm Create
func Delete ¶
func Delete(ctx context.Context, db *gorm.DB, table interface{}, queryCondition interface{}, args ...interface{}) error
Delete record the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm Delete
func DeleteByID ¶
DeleteByID delete record by id the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm DeleteByID
func Get ¶
func Get(ctx context.Context, db *gorm.DB, table interface{}, queryCondition interface{}, args ...interface{}) error
Get one record the param of 'table' must be pointer, eg: &StructName Deprecated: moved to package pkg/ggorm Get
func GetTableName ¶
func GetTableName(object interface{}) string
GetTableName get table name Deprecated: moved to package pkg/ggorm GetTableName
func List ¶
func List(ctx context.Context, db *gorm.DB, tables interface{}, page *query.Page, queryCondition interface{}, args ...interface{}) error
List multiple records, starting from page 0 the param of 'tables' must be a slice, eg: []StructName Deprecated: moved to package pkg/ggorm List
func NewCustomGormLogger ¶
NewCustomGormLogger custom gorm logger Deprecated: moved to package pkg/ggorm NewCustomGormLogger
func TableName ¶
func TableName(table interface{}) string
TableName get table name Deprecated: moved to package pkg/ggorm TableName
Types ¶
type Model ¶
type Model struct { ID uint64 `gorm:"column:id;AUTO_INCREMENT;primary_key" json:"id"` CreatedAt time.Time `gorm:"column:created_at" json:"createdAt"` UpdatedAt time.Time `gorm:"column:updated_at" json:"updatedAt"` DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;index" json:"-"` }
Model embedded structs, add `gorm: "embedded"` when defining table structs Deprecated: moved to package pkg/ggorm Model
type Model2 ¶
type Model2 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:"-"` }
Model2 embedded structs, json tag named is snake case Deprecated: moved to package pkg/ggorm Model2
type Option ¶
type Option func(*options)
Option set the mysql options. Deprecated: moved to package pkg/ggorm Option
func WithConnMaxLifetime ¶
WithConnMaxLifetime set conn max lifetime Deprecated: moved to package pkg/ggorm WithConnMaxLifetime
func WithEnableForeignKey ¶
func WithEnableForeignKey() Option
WithEnableForeignKey use foreign keys Deprecated: moved to package pkg/ggorm WithEnableForeignKey
func WithEnableTrace ¶
func WithEnableTrace() Option
WithEnableTrace use trace Deprecated: moved to package pkg/ggorm WithEnableTrace
func WithGormPlugin ¶
WithGormPlugin setting gorm plugin Deprecated: moved to package pkg/ggorm WithGormPlugin
func WithLog ¶
func WithLog() Option
WithLog set log sql Deprecated: will be replaced by WithLogging
func WithLogRequestIDKey ¶
WithLogRequestIDKey log request id Deprecated: moved to package pkg/ggorm WithLogRequestIDKey
func WithLogging ¶
WithLogging set log sql, If l=nil, the gorm log library will be used Deprecated: moved to package pkg/ggorm WithLogging
func WithMaxIdleConns ¶
WithMaxIdleConns set max idle conns Deprecated: moved to package pkg/ggorm WithMaxIdleConns
func WithMaxOpenConns ¶
WithMaxOpenConns set max open conns Deprecated: moved to package pkg/ggorm WithMaxOpenConns
func WithRWSeparation ¶
WithRWSeparation setting read-write separation Deprecated: moved to package pkg/ggorm WithRWSeparation
func WithSlowThreshold ¶
WithSlowThreshold Set sql values greater than the threshold Deprecated: moved to package pkg/ggorm WithSlowThreshold