gormpkg

package
v0.3.12 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2024 License: Apache-2.0 Imports: 22 Imported by: 6

Documentation

Index

Constants

View Source
const (
	FieldID          = "id"
	FieldCreatedTime = "created_time"
	FieldUpdatedTime = "updated_time"
	FieldDeletedTime = "deleted_time"
	FieldIsDeleted   = "is_deleted"
)
View Source
const (
	OptionKeyTableOptions = "gorm:table_options"
	OptionKeyCreate       = "gorm:create"
	OptionKeyUpdate       = "gorm:update"
	OptionKeyQuery        = "gorm:query"
	OptionKeyDelete       = "gorm:delete"

	OptionValueEngineInnoDB = "ENGINE=InnoDB CHARSET=utf8mb4"
)
View Source
const (
	DefaultOrderColumn = "id"   // default order column
	DefaultOrderAsc    = "asc"  // order direction : asc
	DefaultOrderDesc   = "desc" // order direction : desc
)
View Source
const (
	DefaultBatchInsertConflictAlias = "excluded"
)
View Source
const (
	DefaultPlaceholder = "?" // param placeholder
)

Variables

View Source
var (
	DefaultBatchInsertConflictActionForMySQL = BatchInsertConflictActionReq{
		OnConflictValueAlias:  "AS " + DefaultBatchInsertConflictAlias,
		OnConflictTarget:      "ON DUPLICATE KEY",
		OnConflictAction:      "UPDATE",
		OnConflictPrepareData: nil,
	}
	DefaultBatchInsertConflictActionPostgres = BatchInsertConflictActionReq{
		OnConflictValueAlias:  "",
		OnConflictTarget:      "ON CONFLICT",
		OnConflictAction:      "DO UPDATE SET",
		OnConflictPrepareData: nil,
	}
)

Functions

func AssembleOrders

func AssembleOrders(db *gorm.DB, orders []*Order) *gorm.DB

AssembleOrders 组装排序

func AssembleWheres

func AssembleWheres(db *gorm.DB, wheres []*Where) *gorm.DB

AssembleWheres 组装条件

func BatchInsert

func BatchInsert(db *gorm.DB, repo BatchInsertRepo, opts ...BatchInsertOption) error

BatchInsert 批量插入

func BatchInsertWithContext

func BatchInsertWithContext(ctx context.Context, db *gorm.DB, repo BatchInsertRepo, opts ...BatchInsertOption) error

BatchInsertWithContext 批量插入

func Deleted added in v0.2.18

func Deleted(dbConn *gorm.DB, value interface{}, conditions ...interface{}) *gorm.DB

func ExecWithTransaction added in v0.3.7

func ExecWithTransaction(dbConn *gorm.DB, fc func(tx *gorm.DB) error, opts ...*sql.TxOptions) (err error)

ExecWithTransaction 在事务中执行一系列操作; 无需手动开启事务 DOCS: https://gorm.io/zh_CN/docs/transactions.html

func ForShareOfTable

func ForShareOfTable(db *gorm.DB) *gorm.DB

ForShareOfTable FOR SHARE OF `table_name`

func ForUpdate

func ForUpdate(db *gorm.DB) *gorm.DB

ForUpdate FOR UPDATE

func ForUpdateNowait

func ForUpdateNowait(db *gorm.DB) *gorm.DB

ForUpdateNowait FOR UPDATE NOWAIT

func ForceIndex

func ForceIndex(db *gorm.DB, indexNameList ...string) *gorm.DB

ForceIndex 强制使用索引

func IgnoreIndex

func IgnoreIndex(db *gorm.DB, indexNameList ...string) *gorm.DB

IgnoreIndex 忽略使用索引

func IsErrDuplicatedKey added in v0.3.2

func IsErrDuplicatedKey(err error) bool

IsErrDuplicatedKey ...

func IsErrRecordNotFound added in v0.3.1

func IsErrRecordNotFound(err error) bool

IsErrRecordNotFound ...

func IsValidColumnName added in v0.3.7

func IsValidColumnName(field string) bool

IsValidColumnName 判断是否为有效的字段名

func NewDB

func NewDB(dialect gorm.Dialector, connOption *ConnOption) (db *gorm.DB, err error)

NewDB creates a new DB instance

func NewDummyWriter

func NewDummyWriter() logger.Writer

NewDummyWriter .

func NewJSONWriter

func NewJSONWriter(w io.Writer) logger.Writer

NewJSONWriter .

func NewLogger

func NewLogger(conf *logger.Config, writers ...logger.Writer) logger.Interface

NewLogger 数据库日志

func NewLoggerForConn

func NewLoggerForConn(opt *ConnOption) logger.Interface

NewLoggerForConn 数据库链接日志

func NewStdWriter

func NewStdWriter() logger.Writer

NewStdWriter .

func NewWriter

func NewWriter(w io.Writer) logger.Writer

NewWriter .

func Paginator

func Paginator(db *gorm.DB, pageOption *pagepkg.PageOption) *gorm.DB

Paginator 分页

func ParseLoggerLevel

func ParseLoggerLevel(lv string) logger.LogLevel

ParseLoggerLevel 日志级别

func ParseOrderDirection

func ParseOrderDirection(orderDirection string) string

ParseOrderDirection 排序方向

func QueryDeletedData added in v0.2.18

func QueryDeletedData(dbConn *gorm.DB) *gorm.DB

QueryDeletedData 删除的数据

func QueryUndeletedData added in v0.2.18

func QueryUndeletedData(dbConn *gorm.DB) *gorm.DB

QueryUndeletedData 未删除的数据

func RemoveCallback

func RemoveCallback(db *gorm.DB) error

RemoveCallback 移除回调 参考文档: https://gorm.io/docs/write_plugins.html#Callbacks 参考func: callbacks.RegisterDefaultCallbacks

func SetCreateTime added in v0.2.18

func SetCreateTime(updates map[string]interface{})

func SetOption

func SetOption(db *gorm.DB, key, value string) *gorm.DB

SetOption set option

func SetUpdateTime added in v0.2.18

func SetUpdateTime(updates map[string]interface{})

func SoftDelete added in v0.2.18

func SoftDelete(dbConn *gorm.DB) *gorm.DB

func UnsafeAssembleOrders

func UnsafeAssembleOrders(db *gorm.DB, orders []*Order) *gorm.DB

UnsafeAssembleOrders 不安全的组装排序

func UnsafeAssembleWheres

func UnsafeAssembleWheres(db *gorm.DB, wheres []*Where) *gorm.DB

UnsafeAssembleWheres 不安全的组装条件

func UseIndex

func UseIndex(db *gorm.DB, indexNameList ...string) *gorm.DB

UseIndex 使用索引

Types

type BatchInsertConflictActionReq

type BatchInsertConflictActionReq struct {
	// OnConflictValueAlias 值的别名
	// MySQL : INSERT INTO ... VALUES (...) AS alias ON DUPLICATE KEY UPDATE a = alias.a
	// Postgres : 默认:excluded
	OnConflictValueAlias string
	// OnConflictTarget 条件
	// MySQL : ON DUPLICATE KEY
	// Postgres : ON CONFLICT (targetColumn, ...)
	OnConflictTarget string
	// OnConflictAction 执行冲突解决方案
	// MySQL : DO NOTHING
	OnConflictAction string
	// OnConflictPrepareData 冲突解决方案数据;DO UPDATE SET column_2 = ?
	OnConflictPrepareData []interface{}
}

BatchInsertConflictActionReq 批量插入冲突解决请求

type BatchInsertOption

type BatchInsertOption func(*batchInsertOptions)

BatchInsertOption 批量插入选项

func WithBatchInsertConflictAction

func WithBatchInsertConflictAction(req *BatchInsertConflictActionReq) BatchInsertOption

WithBatchInsertConflictAction 执行冲突解决 MySQL : INSERT INTO ... VALUES (...) AS alias ON DUPLICATE KEY UPDATE a = alias.a Postgres : ON CONFLICT(id) DO UPDATE SET column_2= CONCAT(test_table.column_2, excluded.column_2);

func WithBatchInsertIgnore

func WithBatchInsertIgnore() BatchInsertOption

WithBatchInsertIgnore 忽略重复插入 INSERT IGNORE INTO ...

type BatchInsertRepo

type BatchInsertRepo interface {
	// TableName 表名
	TableName() string
	// Len 数据长度
	// 例子:length := len([]*User{})
	Len() int
	// InsertColumns 插入的列
	// @param columnList 插入的列名数组;例:[]string{"id","name","age"}
	// @param placeholder 列的占位符;例:"?, ?, ?"
	// 在实现此方法时:需要自行拼接占位符;
	InsertColumns() (columnList []string, placeholder string)
	// InsertValues 插入的值
	// @result prepareData 插入的值;例:[]interface{}{1, "张三", 18, 2, "李四", 20, 3, "小明", 30}
	// @result prepareDataLen 插入的占位符;例:[]string{"(?, ?, ?)", "(?, ?, ?)", "(?, ?, ?)"}
	InsertValues(args *BatchInsertValueArgs) (prepareData []interface{}, placeholderSlice []string)
}

BatchInsertRepo 批量插入

type BatchInsertValueArgs

type BatchInsertValueArgs struct {
	// StepStart 开始步长:索引
	StepStart int
	// StepEnd 结束步长:索引
	StepEnd int

	// InsertPlaceholder 列的占位符;例:"?, ?, ?"
	InsertPlaceholder string
	// InsertSQL 入库的SQL;INSERT INTO ... VALUES (...) AS alias
	InsertSQL string
	// ConflictActionSQL 存在冲突,执行冲突动作
	//insertSQL += "ON DUPLICATE KEY UPDATE " + strings.Join(s.UpdateColumnFromMtdReportData(), ",")
	//insertSQL += "ON CONFLICT (id) DO UPDATE SET column_2= CONCAT(test_table.column_2, excluded.column_2)"
	ConflictActionSQL   string
	ConflictPrepareData []interface{}
}

BatchInsertValueArgs 批量插入值的参数

type ConnOption

type ConnOption struct {
	LoggerEnable              bool
	LoggerLevel               logger.LogLevel
	LoggerWriters             []logger.Writer
	LoggerColorful            bool
	SlowThreshold             time.Duration
	IgnoreRecordNotFoundError bool

	ConnMaxActive   int
	ConnMaxLifetime time.Duration
	ConnMaxIdle     int
	ConnMaxIdleTime time.Duration
}

ConnOption 连接配置

type Model added in v0.2.18

type Model struct {
	Id          uint64    `gorm:"column:id;type:uint;autoIncrement;comment:ID" json:"id"`
	CreatedTime time.Time `gorm:"column:created_time;type:time;not null;comment:创建时间" json:"created_time"`
	UpdatedTime time.Time `gorm:"column:updated_time;type:time;not null;comment:更新时间" json:"updated_time"`
	IsDeleted   bool      `gorm:"column:is_deleted;type:uint;default:0;comment:是否已删除" json:"is_deleted"`
	DeletedTime time.Time `gorm:"column:deleted_time;type:time;comment:删除时间" json:"deleted_time"`
}

type ModelForMysql added in v0.3.1

type ModelForMysql struct {
	Id          uint64    `gorm:"column:id;type:uint;autoIncrement;default:current_timestamp();comment:ID" json:"id"`
	CreatedTime time.Time `gorm:"column:created_time;type:time;not null;default:current_timestamp();comment:创建时间" json:"created_time"`
	UpdatedTime time.Time `gorm:"column:updated_time;type:time;not null;default:current_timestamp();comment:更新时间" json:"updated_time"`
	IsDeleted   bool      `gorm:"column:is_deleted;type:uint;default:0;comment:是否已删除" json:"is_deleted"`
	DeletedTime time.Time `gorm:"column:deleted_time;type:time;comment:删除时间" json:"deleted_time"`
}

type ModelForPostgres added in v0.3.1

type ModelForPostgres struct {
	Id          uint64    `gorm:"column:id;type:uint;autoIncrement;default:current_timestamp;comment:ID" json:"id"`
	CreatedTime time.Time `gorm:"column:created_time;type:time;not null;default:current_timestamp;comment:创建时间" json:"created_time"`
	UpdatedTime time.Time `gorm:"column:updated_time;type:time;not null;default:current_timestamp;comment:更新时间" json:"updated_time"`
	IsDeleted   bool      `gorm:"column:is_deleted;type:uint;default:0;comment:是否已删除" json:"is_deleted"`
	DeletedTime time.Time `gorm:"column:deleted_time;type:time;comment:删除时间" json:"deleted_time"`
}

type Option

type Option func(*ConnOption)

Option is config option.

func WithWriters

func WithWriters(writers ...logger.Writer) Option

WithWriters with config writers.

type Order

type Order struct {
	// Field 排序的字段(例子:id)
	Field string
	// Order 排序的方向(例子:desc)
	Order string
}

Order 排序(例子:order by id desc)

func NewOrder

func NewOrder(field, orderDirection string) *Order

NewOrder order

type PaginatorArgs

type PaginatorArgs struct {
	// PageRequest 分页
	PageRequest *pagepkg.PageRequest
	// PageOption 分页
	PageOption *pagepkg.PageOption
	// PageOrders 排序
	PageOrders []*Order
	// PageWheres 条件
	PageWheres []*Where
}

PaginatorArgs 列表参数

func InitPaginatorArgs added in v0.2.19

func InitPaginatorArgs(page, pageSize uint32) *PaginatorArgs

func InitPaginatorArgsByPageRequest added in v0.2.19

func InitPaginatorArgsByPageRequest(pageRequest *pagepkg.PageRequest) *PaginatorArgs

type TransactionInterface added in v0.3.7

type TransactionInterface interface {
	Do(ctx context.Context, fc func(ctx context.Context, tx *gorm.DB) error) error
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error
	CommitAndErrRollback(ctx context.Context, resultErr error) (err error)
}

func NewTransaction added in v0.2.38

func NewTransaction(ctx context.Context, db *gorm.DB, opts ...*sql.TxOptions) TransactionInterface

type Where

type Where struct {
	// Field 字段
	Field string
	// Operator 运算符
	Operator string
	// Placeholder 占位符
	Placeholder string
	// Value 数据
	Value interface{}
}

Where 条件;例:where id = ?(where id = 1)

func NewWhere

func NewWhere(field, operator string, value interface{}) *Where

NewWhere where

Jump to

Keyboard shortcuts

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