You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.2 KiB

  1. // Copyright 2019 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package core
  5. import (
  6. "bytes"
  7. "encoding/gob"
  8. "errors"
  9. "fmt"
  10. "strings"
  11. "time"
  12. )
  13. const (
  14. // default cache expired time
  15. CacheExpired = 60 * time.Minute
  16. // not use now
  17. CacheMaxMemory = 256
  18. // evey ten minutes to clear all expired nodes
  19. CacheGcInterval = 10 * time.Minute
  20. // each time when gc to removed max nodes
  21. CacheGcMaxRemoved = 20
  22. )
  23. var (
  24. ErrCacheMiss = errors.New("xorm/cache: key not found.")
  25. ErrNotStored = errors.New("xorm/cache: not stored.")
  26. )
  27. // CacheStore is a interface to store cache
  28. type CacheStore interface {
  29. // key is primary key or composite primary key
  30. // value is struct's pointer
  31. // key format : <tablename>-p-<pk1>-<pk2>...
  32. Put(key string, value interface{}) error
  33. Get(key string) (interface{}, error)
  34. Del(key string) error
  35. }
  36. // Cacher is an interface to provide cache
  37. // id format : u-<pk1>-<pk2>...
  38. type Cacher interface {
  39. GetIds(tableName, sql string) interface{}
  40. GetBean(tableName string, id string) interface{}
  41. PutIds(tableName, sql string, ids interface{})
  42. PutBean(tableName string, id string, obj interface{})
  43. DelIds(tableName, sql string)
  44. DelBean(tableName string, id string)
  45. ClearIds(tableName string)
  46. ClearBeans(tableName string)
  47. }
  48. func encodeIds(ids []PK) (string, error) {
  49. buf := new(bytes.Buffer)
  50. enc := gob.NewEncoder(buf)
  51. err := enc.Encode(ids)
  52. return buf.String(), err
  53. }
  54. func decodeIds(s string) ([]PK, error) {
  55. pks := make([]PK, 0)
  56. dec := gob.NewDecoder(strings.NewReader(s))
  57. err := dec.Decode(&pks)
  58. return pks, err
  59. }
  60. func GetCacheSql(m Cacher, tableName, sql string, args interface{}) ([]PK, error) {
  61. bytes := m.GetIds(tableName, GenSqlKey(sql, args))
  62. if bytes == nil {
  63. return nil, errors.New("Not Exist")
  64. }
  65. return decodeIds(bytes.(string))
  66. }
  67. func PutCacheSql(m Cacher, ids []PK, tableName, sql string, args interface{}) error {
  68. bytes, err := encodeIds(ids)
  69. if err != nil {
  70. return err
  71. }
  72. m.PutIds(tableName, GenSqlKey(sql, args), bytes)
  73. return nil
  74. }
  75. func GenSqlKey(sql string, args interface{}) string {
  76. return fmt.Sprintf("%v-%v", sql, args)
  77. }