github.com/gogf/gf@v1.16.9/database/gdb/gdb_model_cache.go (about) 1 // Copyright GoFrame Author(https://goframe.org). 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 7 package gdb 8 9 import ( 10 "time" 11 ) 12 13 // Cache sets the cache feature for the model. It caches the result of the sql, which means 14 // if there's another same sql request, it just reads and returns the result from cache, it 15 // but not committed and executed into the database. 16 // 17 // If the parameter `duration` < 0, which means it clear the cache with given `name`. 18 // If the parameter `duration` = 0, which means it never expires. 19 // If the parameter `duration` > 0, which means it expires after `duration`. 20 // 21 // The optional parameter `name` is used to bind a name to the cache, which means you can 22 // later control the cache like changing the `duration` or clearing the cache with specified 23 // `name`. 24 // 25 // Note that, the cache feature is disabled if the model is performing select statement 26 // on a transaction. 27 func (m *Model) Cache(duration time.Duration, name ...string) *Model { 28 model := m.getModel() 29 model.cacheDuration = duration 30 if len(name) > 0 { 31 model.cacheName = name[0] 32 } 33 model.cacheEnabled = true 34 return model 35 } 36 37 // checkAndRemoveCache checks and removes the cache in insert/update/delete statement if 38 // cache feature is enabled. 39 func (m *Model) checkAndRemoveCache() { 40 if m.cacheEnabled && m.cacheDuration < 0 && len(m.cacheName) > 0 { 41 m.db.GetCache().Ctx(m.GetCtx()).Remove(m.cacheName) 42 } 43 }