query

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2023 License: MIT Imports: 9 Imported by: 0

README

gorm-normalize

让gorm使用过程中更加规范, 简洁

安装

go get -u github.com/aide-cloud/gorm-normalize@latest
  • 区别于直接使用gorm, 使其更加规范

    1. 结构上的规范
    2. DB操作上的规范
  • 区别于使用gorm gen, 使其更加灵活

    1. 不用生成代码, 直接使用
    2. 减少代码量, 更加简洁灵活

使用

1. Model

声明model时, 需要继承query.BaseModel

  • user.go
package model

import query "github.com/aide-cloud/gorm-normalize"

type User struct {
	query.BaseModel
	Name  string  `gorm:"column:name;type:varchar(20);not null;default:'';comment:用户名" json:"name"`
	Files []*File `gorm:"foreignKey:UserID" json:"files"`
}

const (
	userTableName = "users"
)

const (
	// PreloadFiles 预加载关联文件
	PreloadFiles = "Files"
)

func (User) TableName() string {
	return userTableName
}
  • file.go
package model

import (
	query "github.com/aide-cloud/gorm-normalize"
)

type FileType int8

type File struct {
	query.BaseModel
	UserID   uint     `gorm:"column:user_id;type:int(10) unsigned;not null;default:0;comment:用户ID" json:"user_id"`
	Name     string   `gorm:"column:name;type:varchar(20);not null;default:'';comment:文件名" json:"name"`
	Url      string   `gorm:"column:url;type:varchar(255);not null;default:'';comment:文件地址" json:"url"`
	FileType FileType `gorm:"column:file_type;type:tinyint(1);not null;default:0;comment:文件类型" json:"file_type"`
	Ext      string   `gorm:"column:ext;type:varchar(10);not null;default:'';comment:文件后缀" json:"ext"`
	Size     int64    `gorm:"column:size;type:bigint(20) unsigned;not null;default:0;comment:文件大小" json:"size"`
}

const (
	fileTableName = "files"
)

const (
	// FileTypeImage 图片
	FileTypeImage FileType = iota + 1
	// FileTypeVideo 视频
	FileTypeVideo
	// FileTypeAudio 音频
	FileTypeAudio
	// FileTypeDocument 文档
	FileTypeDocument
	// FileTypeOther 其他
	FileTypeOther
)

func (File) TableName() string {
	return fileTableName
}
2. Data

声明data操作时, 需要继承query.IAction, 这是一个接口, 里面包含了常用的操作方法, 可以自定义实现

当然, 如果query.IAction内置的方法不能满足你的需求, 你也可以自定义方法, 只需要在你的模块上声明即可, 例如, 下面的PreloadFiles方法就是自定义的方法, 用于预加载用户关联的文件列表

  • user.go
package user

import (
	"gin-plus-admin/pkg/conn"
	"gin-plus-admin/pkg/model"

	query "github.com/aide-cloud/gorm-normalize"
	"gorm.io/gorm"
)

type (
	// User ...
	User struct {
		query.IAction[model.User]

		PreloadFilesKey string
	}
)

// NewUser ...
func NewUser() *User {
	return &User{
		IAction:         query.NewAction(query.WithDB[model.User](conn.GetMysqlDB())),
		PreloadFilesKey: model.PreloadFiles,
	}
}

// PreloadFiles 预加载关联文件
func (l *User) PreloadFiles(scops ...query.Scopemethod) query.Scopemethod {
	return func(db *gorm.DB) *gorm.DB {
		if len(scops) == 0 {
			return db.Preload(l.PreloadFilesKey)
		}
		// add your code here
		return db.Preload(l.PreloadFilesKey, func(db *gorm.DB) *gorm.DB {
			return db.Scopes(scops...)
		})
	}
}
3. service

声明service, 用于处理业务逻辑, 例如, 你需要获取用户详情, 那么你可以在这里处理, 如下所示

下面的GetDetail方法就是获取用户详情的方法, 标准的输入输出, 你可以根据自己的需求来定义

  • user.go
package user

import (
	"context"

	dataUser "gin-plus-admin/internal/data/user"
	"gin-plus-admin/pkg/model"

	ginplus "github.com/aide-cloud/gin-plus"
	query "github.com/aide-cloud/gorm-normalize"
	"go.uber.org/zap"
)

type (
	// DetailReq ...
	DetailReq struct {
		// add request params
		ID int `uri:"id"`
	}

	// DetailResp ...
	DetailResp struct {
		// add response params
		ID        uint   `json:"id"`
		Name      string `json:"name"`
		CreatedAt int64  `json:"created_at"`
		UpdateAt  int64  `json:"update_at"`

		Files []*model.File `json:"files"`
	}
)

// GetDetail ...
func (l *User) GetDetail(ctx context.Context, req *DetailReq) (*DetailResp, error) {
	userData := dataUser.NewUser()

	first, err := userData.WithContext(ctx).First(query.WhereID(req.ID), userData.PreloadFiles())
	if err != nil {
		ginplus.Logger().Error("get user detail failed", zap.Any("req", req), zap.Error(err))
		return nil, err
	}

	// add your code here
	return &DetailResp{
		ID:        first.ID,
		Name:      first.Name,
		CreatedAt: first.CreatedAt.Unix(),
		UpdateAt:  first.UpdatedAt.Unix(),
		Files:     first.Files,
	}, nil
}

Documentation

Index

Constants

View Source
const (
	ASC  orderType = true
	DESC orderType = false
)

Variables

This section is empty.

Functions

func WithDefaultCurr added in v0.4.2

func WithDefaultCurr(curr int32)

WithDefaultCurr is used to set default curr

func WithDefaultSize added in v0.4.2

func WithDefaultSize(size int32)

WithDefaultSize is used to set default size

func WithTrashed added in v0.4.0

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

WithTrashed 包含软删除数据

Types

type ActionOption

type ActionOption[T any] func(a *action[T])

func WithContext

func WithContext[T any](ctx context.Context) ActionOption[T]

WithContext 设置Ctx

func WithDB

func WithDB[T any](db *gorm.DB) ActionOption[T]

WithDB 设置DB

func WithIAssociation added in v0.4.0

func WithIAssociation[T any](o IAssociation) ActionOption[T]

WithIAssociation 设置IAssociation

func WithICtx added in v0.4.1

func WithICtx[T any](ctx ICtx) ActionOption[T]

WithICtx 设置ICtx

func WithIOperation added in v0.4.0

func WithIOperation[T any](o IOperation[T]) ActionOption[T]

WithIOperation 设置IOperation

func WithIOperationX added in v0.4.0

func WithIOperationX[T any](o IOperationX[T]) ActionOption[T]

WithIOperationX 设置IOperationX

func WithTable added in v0.4.0

func WithTable[T any](table schema.Tabler) ActionOption[T]

WithTable 设置Table

func WithTracer added in v0.4.0

func WithTracer[T any](t Tracer) ActionOption[T]

WithTracer 设置Tracer

type AssociationKey added in v0.3.1

type AssociationKey string

type BaseModel

type BaseModel struct {
	ID        uint32                `gorm:"primary_key" json:"id"`
	CreatedAt time.Time             `gorm:"column:created_at;type:timestamp;not null;default:CURRENT_TIMESTAMP;comment:创建时间" json:"createdAt"`
	UpdatedAt time.Time             `` /* 140-byte string literal not displayed */
	DeletedAt soft_delete.DeletedAt `gorm:"column:deleted_at;type:bigint;not null;default:0;" json:"deletedAt"`
}

type Ctx added in v0.4.1

type Ctx struct {
	// contains filtered or unexported fields
}

func (*Ctx) GetCtx added in v0.4.1

func (l *Ctx) GetCtx() context.Context

type IAction

type IAction[T any] interface {
	IOperation[T]
	IOperationX[T]
	IBind[T]

	IAssociation
}

IAction 操作接口

func NewAction

func NewAction[T any](opts ...ActionOption[T]) IAction[T]

NewAction 创建GORM操作接口实例

type IAssociation added in v0.3.1

type IAssociation interface {
	// AssociationAppend 添加关联
	AssociationAppend(associationKey AssociationKey, list ...schema.Tabler) error
	// AssociationReplace 替换关联
	AssociationReplace(associationKey AssociationKey, list ...schema.Tabler) error
	// AssociationDelete 删除关联
	AssociationDelete(associationKey AssociationKey, list ...schema.Tabler) error
	// AssociationClear 清除关联
	AssociationClear(associationKey AssociationKey) error
	// AssociationCount 关联数量
	AssociationCount(associationKey AssociationKey) int64
}

IAssociation 关联操作

func NewDefaultAssociation added in v0.3.1

func NewDefaultAssociation(db *gorm.DB) IAssociation

NewDefaultAssociation 创建默认关联

type IBind added in v0.1.0

type IBind[T any] interface {
	// WithDB 设置DB
	WithDB(db *gorm.DB) IAction[T]
	// WithContext 设置Ctx
	WithContext(ctx context.Context) IAction[T]
	// WithTable 设置Table
	WithTable(table schema.Tabler) IAction[T]
	// WithModel 设置Model
	WithModel(model any) IAction[T]
	// Preload 预加载
	Preload(preloadKey string, wheres ...ScopeMethod) IAction[T]
	// Joins 设置关联
	Joins(joinsKey string, wheres ...ScopeMethod) IAction[T]
	// Scopes 设置作用域
	Scopes(wheres ...ScopeMethod) IAction[T]

	// Order 排序
	Order(column string) IOrder[T]

	// Clauses 设置Clauses
	Clauses(condList ...clause.Expression) IAction[T]

	DB() *gorm.DB
}

IBind 绑定操作, 用于链式操作

type ICtx added in v0.4.0

type ICtx interface {
	GetCtx() context.Context
}

func NewCtx added in v0.4.1

func NewCtx(ctx context.Context) ICtx

NewCtx 实例化上下文

type IOperation added in v0.4.0

type IOperation[T any] interface {
	IOperationQuery[T]
	IOperationMutation[T]
}

func NewOperationImpl added in v0.4.0

func NewOperationImpl[T any](opts ...OperationImplOption[T]) IOperation[T]

NewOperationImpl 实例化操作

type IOperationMutation added in v0.4.0

type IOperationMutation[T any] interface {
	// Create 创建数据
	Create(m *T) error
	// BatchCreate 批量创建数据
	BatchCreate(m []*T, max int) error
	// Update 更新数据
	Update(m *T, wheres ...ScopeMethod) error
	// UpdateMap 通过map更新数据
	UpdateMap(m map[string]any, wheres ...ScopeMethod) error
	// UpdateByID 根据ID更新数据
	UpdateByID(id uint32, m *T, wheres ...ScopeMethod) error
	// UpdateMapByID 根据ID更新数据
	UpdateMapByID(id uint32, m map[string]any, wheres ...ScopeMethod) error
	// Delete 删除数据
	Delete(wheres ...ScopeMethod) error
	// DeleteByID 根据ID删除数据
	DeleteByID(id uint32, wheres ...ScopeMethod) error
	// ForcedDelete 强制删除数据
	ForcedDelete(wheres ...ScopeMethod) error
	// ForcedDeleteByID 根据ID强制删除数据
	ForcedDeleteByID(id uint32, wheres ...ScopeMethod) error
}

IOperationMutation 变更操作, 返回error

func NewOperationMutation added in v0.4.0

func NewOperationMutation[T any](opts ...OperationMutationOption[T]) IOperationMutation[T]

NewOperationMutation 实例化操作

type IOperationMutationX added in v0.4.0

type IOperationMutationX[T any] interface {
	// CreateX 创建数据
	CreateX(m *T)
	// BatchCreateX 批量创建数据
	BatchCreateX(m []*T, batchSize int)
	// UpdateX 更新数据
	UpdateX(m *T, wheres ...ScopeMethod)
	// UpdateMapX 通过map更新数据
	UpdateMapX(m map[string]any, wheres ...ScopeMethod)
	// UpdateByIDX 根据ID更新数据
	UpdateByIDX(id uint32, m *T, wheres ...ScopeMethod)
	// UpdateMapByIDX 根据ID更新数据
	UpdateMapByIDX(id uint32, m map[string]any, wheres ...ScopeMethod)
	// DeleteX 删除数据
	DeleteX(wheres ...ScopeMethod)
	// DeleteByIDX 根据ID删除数据
	DeleteByIDX(id uint32, wheres ...ScopeMethod)
	// ForcedDeleteX 强制删除数据
	ForcedDeleteX(wheres ...ScopeMethod)
	// ForcedDeleteByIDX 根据ID强制删除数据
	ForcedDeleteByIDX(id uint32, wheres ...ScopeMethod)

	GetMutationErr() error
}

IOperationMutationX 变更操作, 不返回error

func NewOperationMutationX added in v0.4.0

func NewOperationMutationX[T any](opts ...OperationMutationXOption[T]) IOperationMutationX[T]

NewOperationMutationX 实例化操作

type IOperationQuery added in v0.4.0

type IOperationQuery[T any] interface {
	// First 查询单条数据
	First(wheres ...ScopeMethod) (*T, error)
	// FirstWithTrashed 查询单条数据(包含软删除数据)
	FirstWithTrashed(wheres ...ScopeMethod) (*T, error)
	// FirstByID 根据ID查询单条数据
	FirstByID(id uint32, wheres ...ScopeMethod) (*T, error)
	// FirstByIDWithTrashed 根据ID查询单条数据(包含软删除数据)
	FirstByIDWithTrashed(id uint32, wheres ...ScopeMethod) (*T, error)
	// Last 查询单条数据
	Last(wheres ...ScopeMethod) (*T, error)
	// LastWithTrashed 查询单条数据(包含软删除数据)
	LastWithTrashed(wheres ...ScopeMethod) (*T, error)
	// LastByID 根据ID查询单条数据
	LastByID(id uint32, wheres ...ScopeMethod) (*T, error)
	// LastByIDWithTrashed 根据ID查询单条数据(包含软删除数据)
	LastByIDWithTrashed(id uint32, wheres ...ScopeMethod) (*T, error)
	// List 查询多条数据
	List(pgInfo Pagination, wheres ...ScopeMethod) ([]*T, error)
	// ListWithTrashed 查询多条数据(包含软删除数据)
	ListWithTrashed(pgInfo Pagination, wheres ...ScopeMethod) ([]*T, error)
	// Count 查询数量
	Count(wheres ...ScopeMethod) (int64, error)
	// CountWithTrashed 查询数量(包含软删除数据)
	CountWithTrashed(wheres ...ScopeMethod) (int64, error)
}

IOperationQuery 扩展查询操作, 返回error

func NewOperationQuery added in v0.4.0

func NewOperationQuery[T any](opts ...OperationQueryOption[T]) IOperationQuery[T]

NewOperationQuery 实例化查询操作

type IOperationQueryX added in v0.4.0

type IOperationQueryX[T any] interface {
	// FirstX 查询单条数据
	FirstX(wheres ...ScopeMethod) *T
	// FirstWithTrashedX 查询单条数据(包含软删除数据)
	FirstWithTrashedX(wheres ...ScopeMethod) *T
	// FirstByIDX 根据ID查询单条数据
	FirstByIDX(id uint32, wheres ...ScopeMethod) *T
	// FirstByIDWithTrashedX 根据ID查询单条数据(包含软删除数据)
	FirstByIDWithTrashedX(id uint32, wheres ...ScopeMethod) *T
	// LastX 查询单条数据
	LastX(wheres ...ScopeMethod) *T
	// LastWithTrashedX 查询单条数据(包含软删除数据)
	LastWithTrashedX(wheres ...ScopeMethod) *T
	// LastByIDX 根据ID查询单条数据
	LastByIDX(id uint32, wheres ...ScopeMethod) *T
	// LastByIDWithTrashedX 根据ID查询单条数据(包含软删除数据)
	LastByIDWithTrashedX(id uint32, wheres ...ScopeMethod) *T
	// ListX 查询多条数据
	ListX(pgInfo Pagination, wheres ...ScopeMethod) []*T
	// ListWithTrashedX 查询多条数据(包含软删除数据)
	ListWithTrashedX(pgInfo Pagination, wheres ...ScopeMethod) []*T
	// CountX 查询数量
	CountX(wheres ...ScopeMethod) int64
	// CountWithTrashedX 查询数量(包含软删除数据)
	CountWithTrashedX(wheres ...ScopeMethod) int64

	GetQueryErr() error
}

IOperationQueryX 扩展查询操作, 不返回error

func NewOperationQueryX added in v0.4.0

func NewOperationQueryX[T any](opts ...OperationQueryXOption[T]) IOperationQueryX[T]

NewOperationQueryX 实例化查询操作

type IOperationX added in v0.4.0

type IOperationX[T any] interface {
	IOperationQueryX[T]
	IOperationMutationX[T]
	Err() error
}

IOperationX 扩展操作, 不返回error

func NewOperationXImpl added in v0.4.0

func NewOperationXImpl[T any](opts ...OperationXImplOption[T]) IOperationX[T]

NewOperationXImpl 实例化操作

type IOrder added in v0.1.0

type IOrder[T any] interface {
	Desc() IAction[T]
	Asc() IAction[T]
}

type OpentracingPlugin added in v0.1.0

type OpentracingPlugin struct{}

func NewOpentracingPlugin added in v0.1.0

func NewOpentracingPlugin() *OpentracingPlugin

NewOpentracingPlugin 创建一个opentracing插件

func (*OpentracingPlugin) Initialize added in v0.1.0

func (op *OpentracingPlugin) Initialize(db *gorm.DB) (err error)

func (*OpentracingPlugin) Name added in v0.1.0

func (op *OpentracingPlugin) Name() string

type OperationImpl added in v0.4.0

type OperationImpl[T any] struct {
	IOperationQuery[T]
	IOperationMutation[T]
}

type OperationImplOption added in v0.4.0

type OperationImplOption[T any] func(*OperationImpl[T])

func WithOperationMutation added in v0.4.0

func WithOperationMutation[T any](mutation IOperationMutation[T]) OperationImplOption[T]

WithOperationMutation 设置变更

func WithOperationQuery added in v0.4.0

func WithOperationQuery[T any](query IOperationQuery[T]) OperationImplOption[T]

WithOperationQuery 设置查询

type OperationMutationOption added in v0.4.0

type OperationMutationOption[T any] func(*operationMutation[T])

func WithOperationMutationIBind added in v0.4.1

func WithOperationMutationIBind[T any](bind IBind[T]) OperationMutationOption[T]

WithOperationMutationIBind 设置数据库

func WithOperationMutationICtx added in v0.4.1

func WithOperationMutationICtx[T any](ctx ICtx) OperationMutationOption[T]

WithOperationMutationICtx 设置上下文

func WithOperationMutationTracer added in v0.4.0

func WithOperationMutationTracer[T any](tracer Tracer) OperationMutationOption[T]

WithOperationMutationTracer 设置跟踪

type OperationMutationXOption added in v0.4.0

type OperationMutationXOption[T any] func(*operationMutationX[T])

func WithOperationMutationXIBind added in v0.4.1

func WithOperationMutationXIBind[T any](bind IBind[T]) OperationMutationXOption[T]

WithOperationMutationXIBind 设置绑定

func WithOperationMutationXICtx added in v0.4.1

func WithOperationMutationXICtx[T any](ctx ICtx) OperationMutationXOption[T]

WithOperationMutationXICtx 设置上下文

func WithOperationMutationXTracer added in v0.4.0

func WithOperationMutationXTracer[T any](tracer Tracer) OperationMutationXOption[T]

WithOperationMutationXTracer 设置跟踪

type OperationQueryOption added in v0.4.0

type OperationQueryOption[T any] func(*operationQuery[T])

func WithOperationQueryIBind added in v0.4.0

func WithOperationQueryIBind[T any](b IBind[T]) OperationQueryOption[T]

WithOperationQueryIBind 设置IBind

func WithOperationQueryICtx added in v0.4.0

func WithOperationQueryICtx[T any](c ICtx) OperationQueryOption[T]

WithOperationQueryICtx 设置ICtx

func WithOperationQueryTracer added in v0.4.0

func WithOperationQueryTracer[T any](t Tracer) OperationQueryOption[T]

WithOperationQueryTracer 设置Tracer

type OperationQueryXOption added in v0.4.0

type OperationQueryXOption[T any] func(*operationQueryX[T])

func WithOperationQueryXIBind added in v0.4.0

func WithOperationQueryXIBind[T any](b IBind[T]) OperationQueryXOption[T]

WithOperationQueryXIBind 设置IBind

func WithOperationQueryXICtx added in v0.4.0

func WithOperationQueryXICtx[T any](c ICtx) OperationQueryXOption[T]

WithOperationQueryXICtx 设置ICtx

func WithOperationQueryXTracer added in v0.4.0

func WithOperationQueryXTracer[T any](t Tracer) OperationQueryXOption[T]

WithOperationQueryXTracer 设置Tracer

type OperationXImplOption added in v0.4.0

type OperationXImplOption[T any] func(*operationXImpl[T])

func WithOperationMutationX added in v0.4.0

func WithOperationMutationX[T any](mutation IOperationMutationX[T]) OperationXImplOption[T]

WithOperationMutationX 设置变更

func WithOperationQueryX added in v0.4.0

func WithOperationQueryX[T any](query IOperationQueryX[T]) OperationXImplOption[T]

WithOperationQueryX 设置查询

type Order added in v0.1.0

type Order[T any] struct {
	IAction[T]
	// contains filtered or unexported fields
}

func NewOrder added in v0.1.0

func NewOrder[T any](column string) *Order[T]

NewOrder 实例化排序

func (*Order[T]) Asc added in v0.1.0

func (o *Order[T]) Asc() IAction[T]

func (*Order[T]) Desc added in v0.1.0

func (o *Order[T]) Desc() IAction[T]

func (*Order[T]) WithIAction added in v0.1.0

func (o *Order[T]) WithIAction(action IAction[T]) *Order[T]

type Page added in v0.1.0

type Page struct {
	Curr  int32 `json:"curr"`
	Size  int32 `json:"size"`
	Total int64 `json:"total"`
}

func NewPage added in v0.1.0

func NewPage(curr, size int32) *Page

func (*Page) GetCurr added in v0.2.0

func (p *Page) GetCurr() int32

func (*Page) GetSize added in v0.2.0

func (p *Page) GetSize() int32

func (*Page) GetTotal added in v0.4.2

func (p *Page) GetTotal() int64

func (*Page) SetTotal added in v0.1.0

func (p *Page) SetTotal(total int64)

type Pagination

type Pagination interface {
	GetCurr() int32
	GetSize() int32
	SetTotal(total int64)
	GetTotal() int64
}

type ScopeMethod added in v0.4.0

type ScopeMethod = func(db *gorm.DB) *gorm.DB

func BetweenColumn added in v0.1.0

func BetweenColumn[T any](column string, min, max T) ScopeMethod

BetweenColumn 通过字段名和值列表进行查询

func Paginate

func Paginate(pgInfo Pagination) ScopeMethod

Paginate 分页

func WhereColumn added in v0.1.0

func WhereColumn[T any](column string, val ...T) ScopeMethod

WhereColumn 通过字段名和值进行查询

func WhereID

func WhereID(ids ...uint32) ScopeMethod

WhereID 通过ID列表进行查询

func WhereInColumn

func WhereInColumn[T any](column string, values ...T) ScopeMethod

WhereInColumn 通过字段名和值列表进行查询

func WhereLikeKeyword

func WhereLikeKeyword(keyword string, columns ...string) ScopeMethod

WhereLikeKeyword 模糊查询

type Tracer added in v0.4.0

type Tracer interface {
	IsEnableTrace() bool
	// OpenTrace 开启trace
	OpenTrace() Tracer
	// CloseTrace 关闭trace
	CloseTrace() Tracer
}

func NewITracer added in v0.4.0

func NewITracer() Tracer

NewITracer 创建Tracer

Jump to

Keyboard shortcuts

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