gorms

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2024 License: Apache-2.0 Imports: 14 Imported by: 0

README

Go Version 1.18

go get gorm.io/gorm 
go get gorm.io/driver/mysql
go get gorm.io/driver/sqlserver
go get gorm.io/driver/sqlite@v1.5.0
go get gorm.io/driver/clickhouse@v0.5.1
go get gorm.io/driver/postgres@v1.4.7

Documentation

Index

Constants

View Source
const (
	ErrDBMapAddExist int = iota + 1
	ErrDBMapGetNotFind
	ErrDBMapStruct
)
View Source
const (
	ConnectorAnd = "AND"
	ConnectorOr  = "OR"
)
View Source
const (
	OperatorIn         = "IN"
	OperatorNot        = "NOT"
	OperatorLike       = "LIKE"
	OperatorEq         = "="
	OperatorNe         = "<>"
	OperatorGt         = ">"
	OperatorGe         = ">="
	OperatorLt         = "<"
	OperatorLe         = "<="
	OperatorIsNull     = "IS NULL"
	OperatorIsNotNull  = "IS NOT NULL"
	OperatorBetween    = "BETWEEN"
	OperatorNotBetween = OperatorNot + " " + OperatorBetween
	OperatorNotIn      = OperatorNot + " " + OperatorIn
	OperatorNotLike    = OperatorNot + " " + OperatorLike
)
View Source
const (
	OrderByDesc = "DESC"
	OrderByAsc  = "ASC"
)
View Source
const (
	SUM   = "SUM"
	AVG   = "AVG"
	MAX   = "MAX"
	MIN   = "MIN"
	COUNT = "COUNT"
)
View Source
const (
	DBMapENVMainDB = "main_db"
)

Variables

View Source
var (
	DefaultPageQueryPage        = "page"
	DefaultPageQuerySize        = "size"
	DefaultPageQueryMaxSize     = 100
	DefaultPageQueryDefaultSize = 10
)
View Source
var (
	DefaultLogger     = logger.Default
	DefaultGORMConfig = &gorm.Config{
		QueryFields: true,
		PrepareStmt: true,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: DefaultLogger,
	}
)

Functions

func CDN

func CDN(host, path string, replaces ...bool) string

CDN 完整的拼接成完整的路径地址

func CDNRelativePath

func CDNRelativePath(cdnPath string) string

CDNRelativePath 将完整的路径地址做成相对路径

func Dec

func Dec(db *gorm.DB, column string, values ...any) error

Dec 字段减 1 Dec(db.Table("test").Where("id = ?",1), "limit", 5)

func ErrDryRunModeUnsupported

func ErrDryRunModeUnsupported(err error) bool

func ErrDuplicatedKey

func ErrDuplicatedKey(err error) bool

func ErrEmptySlice

func ErrEmptySlice(err error) bool

func ErrForeignKeyViolated

func ErrForeignKeyViolated(err error) bool

func ErrInvalidDB

func ErrInvalidDB(err error) bool

func ErrInvalidData

func ErrInvalidData(err error) bool

func ErrInvalidField

func ErrInvalidField(err error) bool

func ErrInvalidTransaction

func ErrInvalidTransaction(err error) bool

func ErrInvalidValue

func ErrInvalidValue(err error) bool

func ErrInvalidValueOfLength

func ErrInvalidValueOfLength(err error) bool

func ErrMissingWhereClause

func ErrMissingWhereClause(err error) bool

func ErrModelAccessibleFieldsRequired

func ErrModelAccessibleFieldsRequired(err error) bool

func ErrModelValueRequired

func ErrModelValueRequired(err error) bool

func ErrNotImplemented

func ErrNotImplemented(err error) bool

func ErrPreloadNotAllowed

func ErrPreloadNotAllowed(err error) bool

func ErrPrimaryKeyRequired

func ErrPrimaryKeyRequired(err error) bool

func ErrRecordNotFound

func ErrRecordNotFound(err error) bool

func ErrRegistered

func ErrRegistered(err error) bool

func ErrSubQueryRequired

func ErrSubQueryRequired(err error) bool

func ErrUnsupportedDriver

func ErrUnsupportedDriver(err error) bool

func ErrUnsupportedRelation

func ErrUnsupportedRelation(err error) bool

func Inc

func Inc(db *gorm.DB, column string, values ...any) error

Inc 字段加 5 Inc(db.Table("test").Where("id = ?",1), "limit", 5)

func MigrateViews

func MigrateViews(db *gorm.DB, views ...IView) error

func ScopesCallbackWhereQueryArgs added in v0.0.2

func ScopesCallbackWhereQueryArgs(fns ...func(queryArgs *QueryArgs)) func(db *gorm.DB) *gorm.DB

func ScopesPage

func ScopesPage(page, size int) func(db *gorm.DB) *gorm.DB

ScopesPage db.Scopes(Paginate(r)).Find(&users)

func ScopesWhereQueryArgs

func ScopesWhereQueryArgs(queryArgs *QueryArgs) func(db *gorm.DB) *gorm.DB

ScopesWhereQueryArgs args = NewQueryArgs() db.Scopes(ScopesWhereQueryArgs(args)).Find(&users)

Types

type Criteria

type Criteria struct {
	Column    string
	Operator  string
	Value     []any
	Connector string
}

func (*Criteria) QueryArgs

func (c *Criteria) QueryArgs() (string, []any)

type DBCallback

type DBCallback func(name string, db *gorm.DB) error

func DBCallbackOnErrorOnNotFound

func DBCallbackOnErrorOnNotFound() DBCallback

DBCallbackOnErrorOnNotFound https://github.com/go-gorm/gorm/issues/3789

func DBCallbackOnPool

func DBCallbackOnPool(maxIdleConns, maxOpenConns int, d time.Duration) DBCallback

DBCallbackOnPool https://gorm.io/zh_CN/docs/generic_interface.html#%E8%BF%9E%E6%8E%A5%E6%B1%A0

type DBMap

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

func DefaultDBMap

func DefaultDBMap() *DBMap

func NewDBMap

func NewDBMap() *DBMap

func (*DBMap) DB

func (g *DBMap) DB() *gorm.DB

DB 根据定义环境变量读取db

func (*DBMap) Exist

func (g *DBMap) Exist(name string) bool

Exist 判断namedb 是否存在

func (*DBMap) Get

func (g *DBMap) Get(name string) (*gorm.DB, error)

Get 根据name 获取db

func (*DBMap) GetDBNames added in v0.0.3

func (g *DBMap) GetDBNames() []string

GetDBNames 获取所有注册的数据别名

func (*DBMap) MustGet

func (g *DBMap) MustGet(name string) *gorm.DB

MustGet 根据name强制读取db,否则就panic

func (*DBMap) OnRegisterCallback

func (g *DBMap) OnRegisterCallback(callback DBCallback) *DBMap

OnRegisterCallback 注入在注册的回掉函数

func (*DBMap) Register

func (g *DBMap) Register(name string, db *gorm.DB) error

Register 注册db

func (*DBMap) RegisterByConfig added in v0.0.3

func (g *DBMap) RegisterByConfig(config IConfig, names ...string) error

RegisterByConfig 根据config进行注册config exp mysql.Config

func (*DBMap) RegisterByNameDBConfig added in v0.0.3

func (g *DBMap) RegisterByNameDBConfig(config INameDBConfig) error

RegisterByNameDBConfig 批量注册db

func (*DBMap) RegisterByPtrConfig added in v0.0.3

func (g *DBMap) RegisterByPtrConfig(ptr any) error

RegisterByPtrConfig exp:

type DBMapConfig struct {
	Test *mysql.Config `gorm:"test"`
}

type ErrMapDB

type ErrMapDB struct {
	Errors  int
	Name    string
	Message string
}

func NewErrMapDB

func NewErrMapDB(name string, Errors int) *ErrMapDB

func (*ErrMapDB) Error

func (e *ErrMapDB) Error() string

type GORMConfig

type GORMConfig struct {
	// GORM perform single create, update, delete operations in transactions by default to ensure database data integrity
	// You can disable it by setting `SkipDefaultTransaction` to true
	SkipDefaultTransaction bool
	// FullSaveAssociations full save associations
	FullSaveAssociations bool
	// DryRun generate sql without execute
	DryRun bool
	// PrepareStmt executes the given query in cached statement
	PrepareStmt bool
	// DisableAutomaticPing
	DisableAutomaticPing bool
	// DisableForeignKeyConstraintWhenMigrating
	DisableForeignKeyConstraintWhenMigrating bool
	// IgnoreRelationshipsWhenMigrating
	IgnoreRelationshipsWhenMigrating bool
	// DisableNestedTransaction disable nested transaction
	DisableNestedTransaction bool
	// AllowGlobalUpdate allow global update
	AllowGlobalUpdate bool
	// QueryFields executes the SQL query with all fields of the table
	QueryFields bool
	// CreateBatchSize default create batch size
	CreateBatchSize int
	// TranslateError enabling error translation
	TranslateError bool
	//tables, columns naming strategy
	NamingStrategy *NamingStrategy
}

func (*GORMConfig) GORMConfig

func (config *GORMConfig) GORMConfig() *gorm.Config

type IConfig

type IConfig interface {
	GetName() string
	DB() (*gorm.DB, error)
}

type IDModel

type IDModel struct {
	ID uint `json:"id" xml:"ID" gorm:"primaryKey"`
}

type IModel

type IModel interface {
	TableName() string
}

type INameDBConfig added in v0.0.3

type INameDBConfig interface {
	NameDB() (map[string]*gorm.DB, error)
}

type IQueryArgs

type IQueryArgs interface {
	QueryArgs() (string, []any)
}

type IView

type IView interface {
	Name() string
	Query(db *gorm.DB) *gorm.DB // required subquery.
	Replace() bool              //If true, exec `CREATE`. If false, exec `CREATE OR REPLACE`
	CheckOption() string        // optional. e.g. `WITH [ CASCADED | LOCAL ] CHECK OPTION`
}

type NamingStrategy

type NamingStrategy struct {
	TablePrefix         string
	SingularTable       bool
	NoLowerCase         bool
	IdentifierMaxLength int
}

type PageResponse

type PageResponse[T any] struct {
	//当前分页数
	CurrentPage int `json:"current_page" xml:"CurrentPage"`
	//当前拉去多少条
	CurrentSize int `json:"current_size" xml:"CurrentSize"`
	//总数
	Total int64 `json:"total" xml:"Total"`
	//列表
	Items []T `json:"items" xml:"Items"`
}

func Paginate

func Paginate[T any](db *gorm.DB, r *http.Request) (*PageResponse[T], error)

Paginate https://gorm.io/zh_CN/docs/scopes.html#%E5%88%86%E9%A1%B5 db := db.Model(Model{}) paginate, _ := Paginate[*Model](db, context.Request)

type QueryArgs

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

func NewQueryArgs added in v0.0.2

func NewQueryArgs() *QueryArgs

func (*QueryArgs) Between

func (q *QueryArgs) Between(column string, s any, e any) *QueryArgs

Between BETWEEN 值1 AND 值2

func (*QueryArgs) Eq

func (q *QueryArgs) Eq(column string, value any) *QueryArgs

Eq 等于 =

func (*QueryArgs) Ge

func (q *QueryArgs) Ge(column string, value any) *QueryArgs

Ge 大于等于 >=

func (*QueryArgs) Gt

func (q *QueryArgs) Gt(column string, value any) *QueryArgs

Gt 大于 >

func (*QueryArgs) In

func (q *QueryArgs) In(column string, value []any) *QueryArgs

In 字段 IN (值1, 值2, ...)

func (*QueryArgs) IsNotNull

func (q *QueryArgs) IsNotNull(column string) *QueryArgs

IsNotNull 是否非空 字段 IS NOT NULL

func (*QueryArgs) IsNull

func (q *QueryArgs) IsNull(column string) *QueryArgs

IsNull 是否为空 字段 IS NULL

func (*QueryArgs) Le

func (q *QueryArgs) Le(column string, value any) *QueryArgs

Le 小于等于 <=

func (*QueryArgs) Like

func (q *QueryArgs) Like(column string, value any) *QueryArgs

Like 模糊 LIKE '%值%'

func (*QueryArgs) Lt

func (q *QueryArgs) Lt(column string, value any) *QueryArgs

Lt 小于 <

func (*QueryArgs) Ne

func (q *QueryArgs) Ne(column string, value any) *QueryArgs

Ne 不等于 !=

func (*QueryArgs) NotBetween

func (q *QueryArgs) NotBetween(column string, s any, e any) *QueryArgs

NotBetween NOT BETWEEN 值1 AND 值2

func (*QueryArgs) NotIn

func (q *QueryArgs) NotIn(column string, value []any) *QueryArgs

NotIn 字段 NOT IN (值1, 值2, ...)

func (*QueryArgs) NotLike

func (q *QueryArgs) NotLike(column string, value any) *QueryArgs

NotLike 非模糊 NOT LIKE '%值%'

func (*QueryArgs) OrWhere

func (q *QueryArgs) OrWhere(column string, operator string, value []any) *QueryArgs

func (*QueryArgs) Where

func (q *QueryArgs) Where(column string, operator string, value []any, connector string) *QueryArgs

func (*QueryArgs) WhereQueryArgs

func (q *QueryArgs) WhereQueryArgs() (string, []any)

WhereQueryArgs where 条件筛选 args = NewSQLArgs() db.Scopes(ScopesWhereQueryArgs(args)).Find(&users)

type SoftModel added in v0.0.2

type SoftModel struct {
	DeletedAt gorm.DeletedAt `json:"deleted_at" xml:"DeletedAt" gorm:"index"`
}

type TimeModel

type TimeModel struct {
	CreatedAt int64 `json:"created_at" xml:"CreatedAt"`
	UpdatedAt int64 `json:"updated_at" xml:"UpdatedAt"`
}

Directories

Path Synopsis
modules

Jump to

Keyboard shortcuts

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