#4891·gf

database/gdb: CacheOption.Force never caches an empty result, every miss still hits the database

Author: lingcoderCreated Sep 23, 2026Updated Sep 23, 2026

问题

gdb.CacheOption.Force 的注释是:

Force caches the query result whatever the result is nil or not.

用途是防缓存穿透:查一个不存在的键,把"查无此行"也缓存起来。实测它对空结果从未生效:开了 Force: true,查不到行的查询每次仍然打库,和没开一样。

复现

go
force := gdb.CacheOption{Duration: 30 * time.Second, Name: "probe", Force: true}

one, _ := db.Model(table).Cache(force).Where("id", 100).One()   // 表里没有 id=100
// one.IsEmpty() == true

// 用 raw Exec 插入,绕过 Model 写路径,不会触发缓存失效
db.Exec(ctx, "INSERT INTO `"+table+"`(id,passport,password) VALUES(100,'p','w')")

one, _ = db.Model(table).Cache(force).Where("id", 100).One()
// 期望:one.IsEmpty() == true(命中缓存的空结果)
// 实际:one.IsEmpty() == false(打库,读到了新插入的行)

此时缓存里 SelectCache:probe 这个 key 是存在的,但 item 的 Result 是 nil 而不是空切片。

对照:同样 Force: true 缓存一个非空结果,raw UPDATE 后再查仍返回旧值 —— 缓存机制本身正常,只有"空结果"这条路坏。

原因

database/gdb/gdb_model_cache.go saveSelectResultToCache:

go
if result != nil && result.IsEmpty() {
    if m.cacheOption.Force {
        result = Result{}
    } else {
        result = nil
    }
}

查不到行时 All() 返回的 Result 是 nil,result != nil 为 false,整个分支被跳过,存进缓存的是 nil。读缓存时 getSelectResultFromCache 返回 nil,调用方 if result != nil { return } 把它当成 cache miss,于是打库。

附带

contrib/drivers/mysql/mysql_z_unit_feature_cache_test.go 里的 Test_Model_Cache_Force 是一个空函数体,注释说"INSERT 会清缓存所以测试逻辑有问题而删除"。清缓存是事实,但不是这个测试失败的原因 —— 用 raw Exec 绕开失效后问题依旧。

环境

  • master dbaf57f60
  • MySQL 5.7 与 SQLite 上结果一致(Core 逻辑,与驱动无关)
  • 补 SQLite 驱动测试时发现(ref #4689)