1
1
mirror of https://github.com/go-gitea/gitea synced 2024-11-15 14:44:41 +00:00
gitea/vendor/xorm.io/core/cache.go

96 lines
2.4 KiB
Go
Raw Normal View History

// Copyright 2019 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
2016-11-03 22:16:01 +00:00
package core
import (
2018-01-27 15:20:59 +00:00
"bytes"
"encoding/gob"
2016-11-03 22:16:01 +00:00
"errors"
"fmt"
2018-01-27 15:20:59 +00:00
"strings"
2016-11-03 22:16:01 +00:00
"time"
)
const (
// CacheExpired is default cache expired time
2016-11-03 22:16:01 +00:00
CacheExpired = 60 * time.Minute
// CacheMaxMemory is not use now
2016-11-03 22:16:01 +00:00
CacheMaxMemory = 256
// CacheGcInterval represents interval time to clear all expired nodes
2016-11-03 22:16:01 +00:00
CacheGcInterval = 10 * time.Minute
// CacheGcMaxRemoved represents max nodes removed when gc
2016-11-03 22:16:01 +00:00
CacheGcMaxRemoved = 20
)
// list all the errors
2016-11-03 22:16:01 +00:00
var (
ErrCacheMiss = errors.New("xorm/cache: key not found")
ErrNotStored = errors.New("xorm/cache: not stored")
2016-11-03 22:16:01 +00:00
)
// CacheStore is a interface to store cache
type CacheStore interface {
// key is primary key or composite primary key
// value is struct's pointer
// key format : <tablename>-p-<pk1>-<pk2>...
Put(key string, value interface{}) error
Get(key string) (interface{}, error)
Del(key string) error
}
// Cacher is an interface to provide cache
// id format : u-<pk1>-<pk2>...
type Cacher interface {
GetIds(tableName, sql string) interface{}
GetBean(tableName string, id string) interface{}
PutIds(tableName, sql string, ids interface{})
PutBean(tableName string, id string, obj interface{})
DelIds(tableName, sql string)
DelBean(tableName string, id string)
ClearIds(tableName string)
ClearBeans(tableName string)
}
func encodeIds(ids []PK) (string, error) {
buf := new(bytes.Buffer)
enc := gob.NewEncoder(buf)
err := enc.Encode(ids)
return buf.String(), err
}
func decodeIds(s string) ([]PK, error) {
pks := make([]PK, 0)
2018-01-27 15:20:59 +00:00
dec := gob.NewDecoder(strings.NewReader(s))
2016-11-03 22:16:01 +00:00
err := dec.Decode(&pks)
return pks, err
}
// GetCacheSql returns cacher PKs via SQL
2016-11-03 22:16:01 +00:00
func GetCacheSql(m Cacher, tableName, sql string, args interface{}) ([]PK, error) {
bytes := m.GetIds(tableName, GenSqlKey(sql, args))
if bytes == nil {
return nil, errors.New("Not Exist")
}
return decodeIds(bytes.(string))
}
// PutCacheSql puts cacher SQL and PKs
2016-11-03 22:16:01 +00:00
func PutCacheSql(m Cacher, ids []PK, tableName, sql string, args interface{}) error {
bytes, err := encodeIds(ids)
if err != nil {
return err
}
m.PutIds(tableName, GenSqlKey(sql, args), bytes)
return nil
}
// GenSqlKey generates cache key
2016-11-03 22:16:01 +00:00
func GenSqlKey(sql string, args interface{}) string {
return fmt.Sprintf("%v-%v", sql, args)
}