gdb_model_cache.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright GoFrame Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gdb
  7. import (
  8. "time"
  9. )
  10. // Cache sets the cache feature for the model. It caches the result of the sql, which means
  11. // if there's another same sql request, it just reads and returns the result from cache, it
  12. // but not committed and executed into the database.
  13. //
  14. // If the parameter <duration> < 0, which means it clear the cache with given <name>.
  15. // If the parameter <duration> = 0, which means it never expires.
  16. // If the parameter <duration> > 0, which means it expires after <duration>.
  17. //
  18. // The optional parameter <name> is used to bind a name to the cache, which means you can
  19. // later control the cache like changing the <duration> or clearing the cache with specified
  20. // <name>.
  21. //
  22. // Note that, the cache feature is disabled if the model is performing select statement
  23. // on a transaction.
  24. func (m *Model) Cache(duration time.Duration, name ...string) *Model {
  25. model := m.getModel()
  26. model.cacheDuration = duration
  27. if len(name) > 0 {
  28. model.cacheName = name[0]
  29. }
  30. model.cacheEnabled = true
  31. return model
  32. }
  33. // checkAndRemoveCache checks and removes the cache in insert/update/delete statement if
  34. // cache feature is enabled.
  35. func (m *Model) checkAndRemoveCache() {
  36. if m.cacheEnabled && m.cacheDuration < 0 && len(m.cacheName) > 0 {
  37. m.db.GetCache().Remove(m.cacheName)
  38. }
  39. }