mdb

package
v0.0.0-...-f4c41ab Latest Latest
Warning

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

Go to latest
Published: May 25, 2026 License: MIT Imports: 37 Imported by: 0

Documentation

Index

Constants

View Source
const NoCache = gormcache.NoCache

NoCache disables this plugin for the current GORM statement. Value forwards to gormcache.NoCache so callers using db.Set(mdb.NoCache, true) keep working against the underlying plugin.

Variables

View Source
var (
	DB              = NewGormDB()
	ErrRecordExists = errors.New("record exists")
)
View Source
var Gm2cCacheStat = Gm2cStats{}

Gm2cCacheStat exposes hit/miss counters as a package var so callers may read them via atomic.LoadUint64(&mdb.Gm2cCacheStat.Hit).

View Source
var Rdb = new(RedisV9)
View Source
var SeparatorColon = ":"

Functions

func AddModels

func AddModels(v ...interface{})

func AutoDelete

func AutoDelete(db *gorm.DB, bus interface{})

func BatchDeleteFromTop

func BatchDeleteFromTop(db *gorm.DB, model interface{}, count int)

BatchDeleteFromTop eachCount = 1000; count: count of delete rows , order by id asc

func CreateIfNotExists

func CreateIfNotExists(db *gorm.DB, bean interface{}, query interface{}, args ...interface{}) error

func FindRecords

func FindRecords[T any](val T, call func(tx *gorm.DB) *gorm.DB, args ...interface{}) (sliceResult []T, err error)

func FindRecordsWithDB

func FindRecordsWithDB[T any](db *gorm.DB, val T, call func(tx *gorm.DB) *gorm.DB, args ...interface{}) (sliceResult []T, err error)

FindRecordsWithDB ...

func GetDBLoggerLevel

func GetDBLoggerLevel(db *gorm.DB) logger.LogLevel

func HDeleter

func HDeleter(c *redis.Client, key string, args ...interface{}) func(fields ...string)

func HScanCallback

func HScanCallback(c *redis.Client, key, match string, fn func(k, v string))

func HasMigrateLockFile

func HasMigrateLockFile() bool

func Md5bit16

func Md5bit16(b []byte) string

Md5bit16 returns the MD5 checksum string of the data.

func ModelColumns

func ModelColumns(model interface{}) (columns []string)

func ModelTableName

func ModelTableName(model interface{}) string

func NewDBLoggerSilent

func NewDBLoggerSilent() logger.Interface

func NewDBLoggerWithLevel

func NewDBLoggerWithLevel(level logger.LogLevel) logger.Interface

func NewDBLoggerWithLevelOut

func NewDBLoggerWithLevelOut(level logger.LogLevel, logName string) logger.Interface

func NewPlugin

func NewPlugin(cfg Gm2cConfig) gorm.Plugin

NewPlugin builds a gorm.Plugin that wraps a gormcache.Plugin configured from cfg. The returned plugin is registered under cfg.Prefix so that the caller's *Gm2cConfig can later locate it for invalidations.

func ParseModel

func ParseModel(model interface{}) (s *schema.Schema, err error)

func SetModelBus

func SetModelBus(bus interface{})

func ValueIDUint64

func ValueIDUint64(val util.Map) (id uint64, ok bool)

Types

type BaseModel

type BaseModel struct {
	ID        int      `json:"id,omitempty" gorm:"primaryKey;autoIncrement:true;autoIncrementIncrement:1;"`
	CreatedAt *Time    `json:"created_at,omitempty" gorm:"notnull;default:CURRENT_TIMESTAMP;"`
	UpdatedAt *Time    `json:"updated_at,omitempty" gorm:"notnull;"`
	Version   *Version `json:"version,omitempty" gorm:"notnull;default:1;comment:版本号;"`
}

type CCStore

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

func GetCCacheStore

func GetCCacheStore() *CCStore

func NewCCacheStore

func NewCCacheStore() *CCStore

func (*CCStore) ClearAll

func (c *CCStore) ClearAll()

func (*CCStore) Del

func (c *CCStore) Del(key string)

func (*CCStore) DropPrefix

func (c *CCStore) DropPrefix(prefix ...string)

func (*CCStore) Get

func (c *CCStore) Get(key string) (data []byte, ok bool)

func (*CCStore) GetCCache

func (c *CCStore) GetCCache() *ccache.Cache[[]byte]

GetCCache ...

func (*CCStore) Set

func (c *CCStore) Set(key string, data []byte, ttl ...int64)

type CacheStore

type CacheStore interface {
	ItfStorageCache
}

CacheStore is the cache backend accepted by Gm2cConfig. It is intentionally an independent interface (not a type alias) so the mdb package keeps a stable surface. Because its method set matches gormcache.Store structurally, a CacheStore value is assignable to a gormcache.Store parameter without conversion.

type CreateClause

type CreateClause struct {
	Field *schema.Field
}

func (CreateClause) Build

func (v CreateClause) Build(clause.Builder)

func (CreateClause) MergeClause

func (v CreateClause) MergeClause(*clause.Clause)

func (CreateClause) ModifyStatement

func (v CreateClause) ModifyStatement(stmt *gorm.Statement)

func (CreateClause) Name

func (v CreateClause) Name() string

type CurdParams

type CurdParams struct {
	Table             string      `json:"table,omitempty"`
	Values            util.Map    `json:"values,omitempty"`
	Where             string      `json:"where,omitempty"`
	Model             interface{} `json:"-"`
	BeforeCall        func(bean interface{})
	Check             func(bean interface{}) (err error)
	CheckBeforeUpdate func(oldVal, newVal interface{}) (err error)
	DBWrapper         WrapperDBFunc

	AfterCall func(bean interface{}) (err error)
}

func (*CurdParams) AddUserIDCondition

func (c *CurdParams) AddUserIDCondition(bean interface{}, userID uint64)

func (*CurdParams) AddWhereCondition

func (c *CurdParams) AddWhereCondition(where string)

AddWhereCondition ... 添加where条件

func (*CurdParams) Create

func (c *CurdParams) Create(args ...any) (err error)

Create ...添加数据

func (*CurdParams) Delete

func (c *CurdParams) Delete(args ...any) (err error)

Delete ...删除数据

func (*CurdParams) Update

func (c *CurdParams) Update(args ...any) (err error)

Update ...更新数据

type DBOption

type DBOption struct {
	Type string `json:"type"`
	Host string `json:"host"`
	Port string `json:"port"`
	User string `json:"user"`
	Pwd  string `json:"pwd"`
	DB   string `json:"db"`

	SkipCache bool   `json:"skip_cache"`
	CacheType string `json:"cache_type"`

	Logger logger.Interface `json:"-"`

	MaxIdleConns       int   `json:"max_idle_conns"`
	MaxOpenConns       int   `json:"max_open_conns"`
	MaxIdleTimeSeconds int64 `json:"max_idle_time_seconds"`
	MaxLifetimeSeconds int64 `json:"max_lifetime_seconds"`

	SkipCreateDB bool `json:"skipCreateDb,omitempty"`

	Gm2cConfig *Gm2cConfig `json:"gm2c_config,omitempty"`
}

func NewOptionWithViper

func NewOptionWithViper(v *viper.Viper) *DBOption

func (*DBOption) DBInitiate

func (d *DBOption) DBInitiate() (db *gorm.DB, err error)

func (*DBOption) DSN

func (d *DBOption) DSN() string

DSN ...

func (*DBOption) DSNMd5

func (d *DBOption) DSNMd5() string

DSNMd5 ...

func (*DBOption) GetLogger

func (d *DBOption) GetLogger() logger.Interface

GetLogger ...

type FindByID

type FindByID struct {
	TableName string `json:"table_name,omitempty"`
	ID        uint64 `json:"id,omitempty"`
	Condition string `json:"condition,omitempty"`

	Dest interface{} `json:"-"`
}

func (*FindByID) AppendEqCondition

func (f *FindByID) AppendEqCondition(str string)

AppendEqCondition ...

func (*FindByID) FindByID

func (f *FindByID) FindByID() (result interface{}, err error)

FindByID ...

type FindParams

type FindParams struct {
	Table     string `json:"table,omitempty"`
	Condition string `json:"condition,omitempty"`
	Order     string `json:"order,omitempty"`
	PageIndex int    `json:"page_index,omitempty"`
	PageSize  int    `json:"page_size,omitempty"`

	Dest interface{} `json:"-"`
}

func (*FindParams) AppendEqCondition

func (f *FindParams) AppendEqCondition(str string)

AppendEqCondition ...

func (*FindParams) FindResultWithModel

func (f *FindParams) FindResultWithModel(tx *gorm.DB) (result *FindResult, err error)

FindResultWithModel get data

type FindResult

type FindResult struct {
	// Data
	Data interface{} `json:"data,omitempty"`
	// Pagination
	Pagination *Pagination `json:"pagination,omitempty"`
	// Extra
	Extra interface{} `json:"extra,omitempty"`
}

type FreeStore

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

func GetFreeCacheStore

func GetFreeCacheStore() *FreeStore

func NewFreeCacheStore

func NewFreeCacheStore() *FreeStore

func NewFreeCacheStoreWithSize

func NewFreeCacheStoreWithSize(size int) *FreeStore

func (*FreeStore) ClearAll

func (f *FreeStore) ClearAll()

func (*FreeStore) Del

func (f *FreeStore) Del(key string)

func (*FreeStore) DropPrefix

func (f *FreeStore) DropPrefix(prefix ...string)

func (*FreeStore) Get

func (f *FreeStore) Get(key string) (data []byte, ok bool)

func (*FreeStore) GetFC

func (f *FreeStore) GetFC() *freecache.Cache

func (*FreeStore) Set

func (f *FreeStore) Set(key string, data []byte, ttl ...int64)

type Gm2cConfig

type Gm2cConfig struct {
	Skip   bool
	Prefix string
	TTL    int64 // seconds
	Store  CacheStore
}

Gm2cConfig configures the single-record cache plugin. Field names, order, and exported types remain stable for external callers.

func (*Gm2cConfig) ClearBean

func (g *Gm2cConfig) ClearBean(bean interface{}) error

ClearBean invalidates the cache entry for the single row identified by bean.

func (*Gm2cConfig) ClearBeanByID

func (g *Gm2cConfig) ClearBeanByID(model, id interface{}) error

ClearBeanByID invalidates the cache entry for table(model) row with primary key id.

func (*Gm2cConfig) ClearTable

func (g *Gm2cConfig) ClearTable(table string)

ClearTable invalidates every cached row for table.

type Gm2cPlugin

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

Gm2cPlugin adapts a gormcache.Plugin to the legacy mdb plugin shape.

func (*Gm2cPlugin) Initialize

func (p *Gm2cPlugin) Initialize(db *gorm.DB) error

Initialize installs the underlying gormcache.Plugin and registers a post-query callback that mirrors gormcache counters into Gm2cCacheStat.

func (*Gm2cPlugin) Name

func (p *Gm2cPlugin) Name() string

Name preserves the legacy plugin name for backwards compatibility with any caller that inspects db.Plugins["single-record-cache"].

type Gm2cStats

type Gm2cStats struct {
	Hit  uint64 `json:"hit"`
	Miss uint64 `json:"miss"`
}

Gm2cStats holds atomic counters published by the cache plugin.

type GormDB

type GormDB struct {
	*gorm.DB
	// contains filtered or unexported fields
}

func NewGormDB

func NewGormDB() *GormDB

func (*GormDB) CheckDBNil

func (g *GormDB) CheckDBNil() (err error)

func (*GormDB) ClearBeanCache

func (g *GormDB) ClearBeanCache(bean any) error

func (*GormDB) ClearBeanCacheByID

func (g *GormDB) ClearBeanCacheByID(model, id any) error

func (*GormDB) ClearTableCache

func (g *GormDB) ClearTableCache(table string)

func (*GormDB) Close

func (g *GormDB) Close() (err error)

Close ...

func (*GormDB) CreateDB

func (g *GormDB) CreateDB()

func (*GormDB) DBInitializationWithViper

func (g *GormDB) DBInitializationWithViper(v *viper.Viper, modelBus interface{}, args ...interface{})

func (*GormDB) DropDB

func (g *GormDB) DropDB()

func (*GormDB) GetFindModel

func (g *GormDB) GetFindModel(table string) (interface{}, error)

GetFindModel ...

func (*GormDB) GetModel

func (g *GormDB) GetModel(table string) (interface{}, error)

GetModel ...

func (*GormDB) Initialize

func (g *GormDB) Initialize(opt *DBOption) *GormDB

Initialize GormDB

func (*GormDB) MigrateModels

func (g *GormDB) MigrateModels(v ...interface{})

MigrateModels ...

func (*GormDB) ModelByTableName

func (g *GormDB) ModelByTableName(tableName string) (model interface{}, err error)

ModelByTableName ...

func (*GormDB) ModelTableName

func (g *GormDB) ModelTableName(model interface{}) (name string)

ModelTableName ...

func (*GormDB) Models

func (g *GormDB) Models() map[string]interface{}

func (*GormDB) Opt

func (g *GormDB) Opt() *DBOption

func (*GormDB) RegModel

func (g *GormDB) RegModel(model interface{})

RegModel ...

func (*GormDB) RegModelBus

func (g *GormDB) RegModelBus(bus interface{})

RegModelBus ...

func (*GormDB) RegViewModel

func (g *GormDB) RegViewModel(model interface{})

RegViewModel ...

func (*GormDB) SetOpt

func (g *GormDB) SetOpt(opt *DBOption)

func (*GormDB) ViewModels

func (g *GormDB) ViewModels() map[string]interface{}

type ImplResultAfterFind

type ImplResultAfterFind interface {
	ResultAfterFind(tx *gorm.DB) error
}

type ItfModelInitializer

type ItfModelInitializer interface {
	InitData(db *gorm.DB) (interface{}, error)
}

type ItfStorageCache

type ItfStorageCache interface {
	Get(key string) ([]byte, bool)
	Set(key string, val []byte, ttl ...int64) // ttl in seconds
	Del(key string)
	DropPrefix(prefix ...string)
}

type Pagination

type Pagination struct {
	// Total number of records
	Total int64 `json:"total,omitempty"`
	// Size of each page
	Size int `json:"size,omitempty"`
	// Index of pages
	Index int `json:"index,omitempty"`
	// Pages Number of pages
	Pages int `json:"pages,omitempty"`
}

type RedisOptions

type RedisOptions struct {
	Addr     string
	Username string
	Password string
	DB       int
}

func (*RedisOptions) Copy

func (r *RedisOptions) Copy() *RedisOptions

Copy ...

type RedisStore

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

func GetRedisStore

func GetRedisStore(c *redis.Client, opts ...*RedisStoreOption) *RedisStore

func NewRedisStore

func NewRedisStore(c *redis.Client, opts ...*RedisStoreOption) *RedisStore

func (*RedisStore) ClearAll

func (r *RedisStore) ClearAll()

func (*RedisStore) Del

func (r *RedisStore) Del(key string)

func (*RedisStore) DropPrefix

func (r *RedisStore) DropPrefix(prefix ...string)

func (*RedisStore) Get

func (r *RedisStore) Get(key string) (data []byte, ok bool)

func (*RedisStore) GetKeyFieldOrNot

func (r *RedisStore) GetKeyFieldOrNot(key string) (k, f string, y bool)

func (*RedisStore) ScanKeys

func (r *RedisStore) ScanKeys(matchParam string) []string

func (*RedisStore) Set

func (r *RedisStore) Set(key string, data []byte, ttl ...int64)

func (*RedisStore) StoreGC

func (r *RedisStore) StoreGC(prefix string)

type RedisStoreOption

type RedisStoreOption struct {
	Separator string
}

type RedisV9

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

func (*RedisV9) Close

func (r *RedisV9) Close()

Close ...

func (*RedisV9) GetClient

func (r *RedisV9) GetClient(dbs ...int) *redis.Client

func (*RedisV9) Initialize

func (r *RedisV9) Initialize(opt *RedisOptions) *RedisV9

func (*RedisV9) Opt

func (r *RedisV9) Opt() *RedisOptions

type RedisValue

type RedisValue struct {
	Val      util.RawMessage `json:"val"`
	ExpireAt int64           `json:"expire_at"`
}

type Time

type Time = util.JSONTime

type UpdateClause

type UpdateClause struct {
	Field *schema.Field
}

func (UpdateClause) Build

func (v UpdateClause) Build(clause.Builder)

func (UpdateClause) MergeClause

func (v UpdateClause) MergeClause(*clause.Clause)

func (UpdateClause) ModifyStatement

func (v UpdateClause) ModifyStatement(stmt *gorm.Statement)

func (UpdateClause) Name

func (v UpdateClause) Name() string

type Version

type Version sql.NullInt64

func (*Version) CreateClauses

func (v *Version) CreateClauses(field *schema.Field) []clause.Interface

func (*Version) MarshalJSON

func (v *Version) MarshalJSON() ([]byte, error)

func (*Version) Scan

func (v *Version) Scan(value interface{}) error

func (*Version) UnmarshalJSON

func (v *Version) UnmarshalJSON(bytes []byte) error

func (*Version) UpdateClauses

func (v *Version) UpdateClauses(field *schema.Field) []clause.Interface

func (*Version) Value

func (v *Version) Value() (driver.Value, error)

type WrapperDBFunc

type WrapperDBFunc func(db *gorm.DB) *gorm.DB

Directories

Path Synopsis
Package gormcache provides a GORM plugin for single-row query caching on tables with exactly one primary-key field.
Package gormcache provides a GORM plugin for single-row query caching on tables with exactly one primary-key field.

Jump to

Keyboard shortcuts

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