tablecache

package module
v0.0.0-...-912ae11 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2021 License: MIT Imports: 13 Imported by: 0

README

tablecache

Table cache with redis and gorm

Example

type TableCacheTest struct {
	suite.Suite
	users *tablecache.TableCache
}

func GetMysql() *gorm.DB {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: false,       // Ignore ErrRecordNotFound error for logger
			Colorful:                  false,       // Disable color
		},
	)
	// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
	dsn := "root:123456@tcp(127.0.0.1:3306)/cache?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger})
	if err != nil {
		panic(err)
	}
	return db
}

func GetRedis() *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "",
	})
}

type Base struct {
	ID        uint64    `gorm:"primarykey"`
	CreatedAt time.Time `gorm:"type:datetime not null;"`
	UpdatedAt time.Time `gorm:"type:datetime not null;"`
	// DeletedAt sql.NullTime `gorm:"index"`
}

type User struct {
	Base
	Name string `gorm:"type:varchar(100) not null;"`
}

var tables = []interface{}{
	&User{},
}


func GetMysql() *gorm.DB {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: false,       // Ignore ErrRecordNotFound error for logger
			Colorful:                  false,       // Disable color
		},
	)
	// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
	dsn := "root:123456@tcp(127.0.0.1:3306)/cache?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger})
	if err != nil {
		panic(err)
	}
	return db
}

func GetRedis() *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "",
	})
}

type Base struct {
	ID        uint64    `gorm:"primarykey"`
	CreatedAt time.Time `gorm:"type:datetime not null;"`
	UpdatedAt time.Time `gorm:"type:datetime not null;"`
	// DeletedAt sql.NullTime `gorm:"index"`
}

type User struct {
	Base
	Name string `gorm:"type:varchar(100) not null;"`
}

var tables = []interface{}{
	&User{},
}

func (s *TableCacheTest) SetupTest() {
	redisGorm := tablecache.NewRedisGorm(GetRedis(), GetMysql(), 3*time.Minute, "ID", "test",
		func() interface{} { return &User{} }, func() interface{} { return &([]User{}) })
	redisGorm.GetDB().AutoMigrate(tables)
	s.users = tablecache.NewTableCache(redisGorm, "User", [][]string{{"Name"}})
}

func (s *TableCacheTest) TestGet() {
	u, err := s.users.Get(14)
	s.Nil(err)
	fmt.Println(u.(*User))
	u, err = s.users.Get(12)
	s.Nil(err)
	fmt.Println(u, u == nil)
}

func (s *TableCacheTest) TestList() {
	u, err := s.users.List([]uint64{15, 123})
	s.Nil(err)
	fmt.Println(*u.(*[]User))
	u, err = s.users.List([]uint64{12, 120})
	s.Nil(err)
	fmt.Println(*u.(*[]User))
}

Documentation

Index

Constants

View Source
const NullStr = "null"

Variables

View Source
var EmptyStruct = struct{}{}

Functions

func GetStructFields

func GetStructFields(root reflect.Type) []string

func SubStrs

func SubStrs(a, b []string) []string

a-b , in a not inb

func ToStringSlice

func ToStringSlice(a interface{}) []string

Types

type CacheUtil

type CacheUtil struct{}

func (*CacheUtil) GetFieldValue

func (s *CacheUtil) GetFieldValue(structValue interface{}, field string) interface{}

Get field from

func (*CacheUtil) MakeKey

func (s *CacheUtil) MakeKey(kvs ...interface{}) string

func (*CacheUtil) MakeKeyWithMap

func (s *CacheUtil) MakeKeyWithMap(kvs map[string]interface{}) string

func (*CacheUtil) Stringify

func (s *CacheUtil) Stringify(value interface{}) string

Stringify transform value to string format

type DDL

type DDL struct {
	DefaultOnDelete FKAction
	DefaultOnUpdate FKAction
	// contains filtered or unexported fields
}

func NewDDL

func NewDDL(db *gorm.DB) *DDL

func (*DDL) AddFK

func (s *DDL) AddFK(table, target interface{}, fk string)

func (*DDL) AddFKs

func (s *DDL) AddFKs(table interface{})

func (*DDL) AddForeignKey

func (s *DDL) AddForeignKey(table, fkey, target, targetCol string, onDelete, onUpdate FKAction)

func (*DDL) AddTables

func (s *DDL) AddTables(tables ...interface{})

func (*DDL) GetSchema

func (s *DDL) GetSchema(obj interface{}) *schema.Schema

func (*DDL) GetSchemaByStructName

func (s *DDL) GetSchemaByStructName(structName string) *schema.Schema

func (*DDL) MakeFKName

func (s *DDL) MakeFKName(table, fkey, target, targetCol string) string

func (*DDL) MakeFKs

func (s *DDL) MakeFKs()

func (*DDL) MatchTableName

func (s *DDL) MatchTableName(structType reflect.Type, tableName string) bool

func (*DDL) ParseFKInfo

func (s *DDL) ParseFKInfo(tag string) FKInfo

tag: eg. FK:User,CASCADE,CASCADE Table,on delete %s,on update %s

func (*DDL) Range

func (s *DDL) Range(f func(structType reflect.Type, tableSchema *schema.Schema) bool)

type FKAction

type FKAction string
const (
	FKEmpty    FKAction = ""
	FKCascade  FKAction = "CASCADE"
	FKNoAction FKAction = "NO ACTION"
	FKSetNull  FKAction = "SET NULL"
	FKRestrict FKAction = "RESTRICT"
)

type FKInfo

type FKInfo struct {
	StructName string
	OnDelete   FKAction
	OnUpdate   FKAction
}

type FullTableCache

type FullTableCache struct {
	*RedisGorm
	// contains filtered or unexported fields
}

func NewFullTableCache

func NewFullTableCache(redisGorm *RedisGorm, key string) *FullTableCache

func (*FullTableCache) All

func (s *FullTableCache) All() (interface{}, error)

All return all record from cache. type is: *[]Table

func (*FullTableCache) Create

func (s *FullTableCache) Create(valueRef interface{}) error

func (*FullTableCache) Delete

func (s *FullTableCache) Delete(ids ...interface{}) error

Delete by ids

func (*FullTableCache) Exist

func (s *FullTableCache) Exist() (bool, error)

func (*FullTableCache) Get

func (s *FullTableCache) Get(id interface{}) (interface{}, error)

Get record by id, type is *Table

func (*FullTableCache) Load

func (s *FullTableCache) Load() error

func (*FullTableCache) Save

func (s *FullTableCache) Save(valueRef interface{}) error

func (*FullTableCache) Update

func (s *FullTableCache) Update(valueRef interface{}, fields ...string) error

type JSONMarshaller

type JSONMarshaller struct {
}

func (*JSONMarshaller) Marshal

func (s *JSONMarshaller) Marshal(value interface{}) (string, error)

func (*JSONMarshaller) Unmarshal

func (s *JSONMarshaller) Unmarshal(valueRef interface{}, bs string) error

type Marshaller

type Marshaller interface {
	Marshal(value interface{}) (string, error)
	Unmarshal(valueRef interface{}, bs string) error
}

type RedisGorm

type RedisGorm struct {
	FactorySingleRef func() interface{}
	FactoryListRef   func() interface{}
	// contains filtered or unexported fields
}

func NewRedisGorm

func NewRedisGorm(redisClient *redis.Client, db *gorm.DB, ttl time.Duration, idField, cachePrefix string, factorySingleRef, factoryListRef func() interface{}) *RedisGorm

func (*RedisGorm) GetDB

func (s *RedisGorm) GetDB() *gorm.DB

func (*RedisGorm) GetID

func (s *RedisGorm) GetID(value interface{}) interface{}

func (*RedisGorm) GetIDField

func (s *RedisGorm) GetIDField(value interface{}) string

func (*RedisGorm) GetRedis

func (s *RedisGorm) GetRedis() *redis.Client

func (*RedisGorm) GetTTL

func (s *RedisGorm) GetTTL() time.Duration

func (*RedisGorm) IsIDInteger

func (s *RedisGorm) IsIDInteger() bool

func (*RedisGorm) SetMarshaller

func (s *RedisGorm) SetMarshaller(marshaller Marshaller)

func (*RedisGorm) SetRedisCtx

func (s *RedisGorm) SetRedisCtx(redisCtx context.Context)

type TableCache

type TableCache struct {
	*RedisGorm

	Indexes [][]string
	// contains filtered or unexported fields
}

func NewTableCache

func NewTableCache(redisGorm *RedisGorm, structName string, indexes [][]string) *TableCache

func (*TableCache) AddIndex

func (s *TableCache) AddIndex(index []string)

func (*TableCache) ClearCache

func (s *TableCache) ClearCache(objs ...interface{}) error

func (*TableCache) ClearCacheWithMaps

func (s *TableCache) ClearCacheWithMaps(objs ...map[string]interface{}) error

func (*TableCache) Create

func (s *TableCache) Create(valueRef interface{}) error

func (*TableCache) CreateMany

func (s *TableCache) CreateMany(sliceRef interface{}) error

func (*TableCache) Delete

func (s *TableCache) Delete(ids ...interface{}) error

Delete by id , eg. Delete(1,2)

func (*TableCache) DeleteStrs

func (s *TableCache) DeleteStrs(ids []string) error

func (*TableCache) DeleteUint64s

func (s *TableCache) DeleteUint64s(ids []uint64) error

func (*TableCache) Get

func (s *TableCache) Get(id interface{}) (interface{}, error)

func (*TableCache) GetBy

func (s *TableCache) GetBy(index ...interface{}) (interface{}, error)

GetBy index ,index:eg. uid,1

func (*TableCache) GetByMap

func (s *TableCache) GetByMap(index map[string]interface{}) (interface{}, error)

redis key eg. projectusers/pid/2/uid/1 -> id

func (*TableCache) GetMaxID

func (s *TableCache) GetMaxID() (uint64, error)

func (*TableCache) List

func (s *TableCache) List(ids interface{}) (interface{}, error)

func (*TableCache) ListBy

func (s *TableCache) ListBy(index ...interface{}) (interface{}, error)

ListBy index ,index:eg. uid,1

func (*TableCache) ListByMap

func (s *TableCache) ListByMap(index map[string]interface{}) (interface{}, error)

redis key eg. projectusers/pid/2/uid/1 -> [id1,id2]

func (*TableCache) Save

func (s *TableCache) Save(valueRef interface{}) error

func (*TableCache) Update

func (s *TableCache) Update(resultRef interface{}, fields ...string) error

Jump to

Keyboard shortcuts

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