Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:zap: Improve database view performance https://github.com/siyuan-note/siyuan/issues/17830

Daniel16bcf20dc81e
diff --git a/kernel/av/av.go b/kernel/av/av.go
index 2f4c6f60fc..dca0609daf 100644
--- a/kernel/av/av.go
+++ b/kernel/av/av.go
@@ -47,8 +47,6 @@ type AttributeView struct {
Views []*View `json:"views"` // 视图
RenderedViewables map[string]Viewable `json:"-"` // 已经渲染好的视图
-
- keysOnlyParsed bool `json:"-"` // 标记是否为 keys-only 流式解析的结果(Values 被跳过,禁止落盘)
}
// KeyValues 描述了属性视图属性键值列表的结构。
@@ -591,93 +589,7 @@ func ParseAttributeViewByPath(avJSONPath string) (ret *AttributeView, err error)
return
}
-// ParseAttributeViewKeys 仅解析 av.json 中的字段/视图元数据(Key + Views + 基本信息),
-// 跳过 keyValues[].values 中的行数据,适用于只读元数据的场景(如配置菜单)。
-// 若 av.json 版本非当前版本(CurrentSpec),自动回退全量 ParseAttributeView 以保证兼容性。
-func ParseAttributeViewKeys(avID string) (ret *AttributeView, err error) {
- avJSONPath := GetAttributeViewDataPath(avID)
- return ParseAttributeViewKeysByPath(avJSONPath)
-}
-
-// ParseAttributeViewKeysByPath 是 ParseAttributeViewKeys 的路径版本。
-// 参考 filesys.DocIAL(tree.go)的流式解析技术:用 jsoniter.Parse 流式遍历顶层对象,
-// keyValues 数组仅解析 key,调用 iter.Skip() 跳过 values。
-func ParseAttributeViewKeysByPath(avJSONPath string) (ret *AttributeView, err error) {
- if !filelock.IsExist(avJSONPath) {
- err = ErrViewNotFound
- return
- }
-
- avID := filepath.Base(avJSONPath)
- avID = strings.TrimSuffix(avID, filepath.Ext(avID))
-
- var data []byte
- if cached, ok := cache.GetAVData(avID); ok {
- data = cached
- } else {
- var readErr error
- data, readErr = filelock.ReadFile(avJSONPath)
- if nil != readErr {
- logging.LogErrorf("read attribute view [%s] failed: %s", avID, readErr)
- return
- }
- cache.SetAVData(avID, data)
- }
-
- // 惰性读取 spec 判断版本,非当前版本回退全量解析以保持旧版兼容
- specVal := jsoniter.Get(data, "spec")
- if specVal.ValueType() == jsoniter.InvalidValue || specVal.ToInt() != CurrentSpec {
- return ParseAttributeViewByPath(avJSONPath)
- }
-
- // 流式 keys-only 解析:仅解码 Key/Views 元数据,通过 Skip() 跳过 values 数组
- iter := jsoniter.Parse(jsoniter.ConfigCompatibleWithStandardLibrary, bytes.NewReader(data), 512)
- ret = &AttributeView{RenderedViewables: map[string]Viewable{}}
- for field := iter.ReadObject(); field != ""; field = iter.ReadObject() {
- switch field {
- case "spec":
- ret.Spec = iter.ReadInt()
- case "id":
- ret.ID = iter.ReadString()
- case "name":
- ret.Name = iter.ReadString()
- case "viewID":
- ret.ViewID = iter.ReadString()
- case "keyIDs":
- iter.ReadVal(&ret.KeyIDs)
- case "views":
- iter.ReadVal(&ret.Views)
- case "keyValues":
- for ok := iter.ReadArray(); ok; ok = iter.ReadArray() {
- kv := &KeyValues{Values: []*Value{}}
- for kvField := iter.ReadObject(); kvField != ""; kvField = iter.ReadObject() {
- if kvField == "key" {
- iter.ReadVal(&kv.Key)
- } else {
- iter.Skip()
- }
- }
- ret.KeyValues = append(ret.KeyValues, kv)
- }
- default:
- iter.Skip()
- }
- }
-
- if err = CheckSpec(ret); err != nil {
- return nil, err
- }
- ret.keysOnlyParsed = true // 标记为 keys-only 解析结果,禁止后续 SaveAttributeView 落盘
- return
-}
-
func SaveAttributeView(av *AttributeView) (err error) {
- if av.keysOnlyParsed {
- // keys-only 解析结果不含行数据(Values 被流式跳过),落盘会丢失行数据。
- // 这里静默跳过(只读菜单场景的副作用不应落盘),避免中断调用链。
- logging.LogWarnf("skip save attribute view [%s]: it is a keys-only parsed snapshot", av.ID)
- return
- }
if "" == av.ID {
err = errors.New("av id is empty")
logging.LogErrorf("save attribute view failed: %s", err)
diff --git a/kernel/av/av_keys_test.go b/kernel/av/av_keys_test.go
deleted file mode 100644
index e45619795a..0000000000
--- a/kernel/av/av_keys_test.go
+++ /dev/null
@@ -1,188 +0,0 @@
-// SiYuan - Refactor your thinking
-// Copyright (c) 2020-present, b3log.org
-//
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU Affero General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU Affero General Public License for more details.
-//
-// You should have received a copy of the GNU Affero General Public License
-// along with this program. If not, see <https://www.gnu.org/licenses/>.
-
-package av
-
-import (
- "os"
- "path/filepath"
- "testing"
-
- "github.com/siyuan-note/siyuan/kernel/cache"
-)
-
-// TestParseAttributeViewKeysByPath 校验流式 keys-only 解析读出的元数据完整,且 Values 被跳过。
-func TestParseAttributeViewKeysByPath(t *testing.T) {
- tmpDir := t.TempDir()
- avID := "20260611104916-testkeys01"
- avJSONPath := filepath.Join(tmpDir, avID+".json")
- // 字段顺序与真实 av.json 一致;values 含嵌套对象/数组,覆盖 Skip 对复杂结构的处理
- avJSON := `{
- "spec": 5,
- "id": "` + avID + `",
- "name": "测试库",
- "viewID": "20260611104916-v01",
- "keyIDs": ["k1", "k2"],
- "keyValues": [
- {
- "key": {"id": "k1", "name": "主键", "type": "block"},
- "values": [
- {"id": "v1", "keyID": "k1", "blockID": "b1", "type": "block", "number": {"content": 1.5, "isNotEmpty": true}, "mSelect": [{"content": "选项A", "color": "1"}]},
- {"id": "v2", "keyID": "k1", "blockID": "b2", "type": "block"}
- ]
- },
- {
- "key": {"id": "k2", "name": "字段B", "type": "text"},
- "values": [
- {"id": "v3", "keyID": "k2", "blockID": "b1", "type": "text"}
- ]
- }
- ],
- "views": [
- {"id": "20260611104916-v01", "name": "视图1", "layoutType": 0}
- ]
- }`
- if err := os.WriteFile(avJSONPath, []byte(avJSON), 0644); err != nil {
- t.Fatalf("write temp av.json failed: %s", err)
- }
- cache.ClearAVCache()
-
- keysAV, err := ParseAttributeViewKeysByPath(avJSONPath)
- if err != nil {
- t.Fatalf("ParseAttributeViewKeysByPath failed: %s", err)
- }
-
- if keysAV.Spec != CurrentSpec {
- t.Errorf("Spec = %d, want %d", keysAV.Spec, CurrentSpec)
- }
- if keysAV.ID != avID {
- t.Errorf("ID = %q, want %q", keysAV.ID, avID)
- }
- if keysAV.Name != "测试库" {
- t.Errorf("Name = %q, want %q", keysAV.Name, "测试库")
- }
- if keysAV.ViewID != "20260611104916-v01" {
- t.Errorf("ViewID = %q, want %q", keysAV.ViewID, "20260611104916-v01")
- }
- if len(keysAV.KeyIDs) != 2 || keysAV.KeyIDs[0] != "k1" || keysAV.KeyIDs[1] != "k2" {
- t.Errorf("KeyIDs = %v, want [k1 k2]", keysAV.KeyIDs)
- }
- if len(keysAV.Views) != 1 || keysAV.Views[0].ID != "20260611104916-v01" {
- t.Errorf("Views = %+v, want 1 view with id 20260611104916-v01", keysAV.Views)
- }
-
- if len(keysAV.KeyValues) != 2 {
- t.Fatalf("KeyValues len = %d, want 2", len(keysAV.KeyValues))
- }
- for i, kv := range keysAV.KeyValues {
- if kv.Key == nil {
- t.Fatalf("KeyValues[%d].Key is nil", i)
- }
- if len(kv.Values) != 0 {
- t.Errorf("KeyValues[%d] (key %s) Values len = %d, want 0", i, kv.Key.ID, len(kv.Values))
- }
- }
- if keysAV.KeyValues[0].Key.ID != "k1" || keysAV.KeyValues[0].Key.Name != "主键" {
- t.Errorf("KeyValues[0].Key = %+v, want id=k1 name=主键", keysAV.KeyValues[0].Key)
- }
- if keysAV.KeyValues[1].Key.ID != "k2" || keysAV.KeyValues[1].Key.Name != "字段B" {
- t.Errorf("KeyValues[1].Key = %+v, want id=k2 name=字段B", keysAV.KeyValues[1].Key)
- }
-
- if keysAV.RenderedViewables == nil {
- t.Error("RenderedViewables is nil, want empty map")
- }
-}
-
-// TestParseAttributeViewKeysByPath_OldSpecFallback 校验非当前 spec 回退全量解析,全量能读出 Values。
-func TestParseAttributeViewKeysByPath_OldSpecFallback(t *testing.T) {
- tmpDir := t.TempDir()
- avID := "20260611104916-testold01"
- avJSONPath := filepath.Join(tmpDir, avID+".json")
- avJSON := `{
- "spec": 0,
- "id": "` + avID + `",
- "name": "旧版本库",
- "keyValues": [
- {
- "key": {"id": "k1", "name": "字段A", "type": "block"},
- "values": [
- {"id": "v1", "keyID": "k1", "blockID": "20260101000000-abc123", "type": "block"}
- ]
- }
- ]
- }`
- if err := os.WriteFile(avJSONPath, []byte(avJSON), 0644); err != nil {
- t.Fatalf("write temp av.json failed: %s", err)
- }
- cache.ClearAVCache()
-
- oldAV, err := ParseAttributeViewKeysByPath(avJSONPath)
- if err != nil {
- t.Fatalf("ParseAttributeViewKeysByPath (old spec) failed: %s", err)
- }
-
- if len(oldAV.KeyValues) != 1 {
- t.Fatalf("KeyValues len = %d, want 1", len(oldAV.KeyValues))
- }
- if len(oldAV.KeyValues[0].Values) != 1 {
- t.Errorf("fallback: KeyValues[0].Values len = %d, want 1", len(oldAV.KeyValues[0].Values))
- }
-}
-
-// TestParseAttributeViewKeysByPath_NotExist 校验文件不存在时返回 ErrViewNotFound。
-func TestParseAttributeViewKeysByPath_NotExist(t *testing.T) {
- _, err := ParseAttributeViewKeysByPath("/nonexistent/path/av.json")
- if err != ErrViewNotFound {
- t.Errorf("err = %v, want ErrViewNotFound", err)
- }
-}
-
-// TestSaveAttributeView_RejectKeysOnly 校验 keys-only 解析结果不会被落盘(静默跳过),避免数据丢失。
-func TestSaveAttributeView_RejectKeysOnly(t *testing.T) {
- tmpDir := t.TempDir()
- avID := "20260611104916-testsave01"
- avJSONPath := filepath.Join(tmpDir, avID+".json")
- avJSON := `{"spec":5,"id":"` + avID + `","name":"库","keyValues":[{"key":{"id":"k1","name":"主键","type":"block"},"values":[{"id":"v1","keyID":"k1","blockID":"b1","type":"block"}]}],"views":[]}`
- if err := os.WriteFile(avJSONPath, []byte(avJSON), 0644); err != nil {
- t.Fatalf("write av.json failed: %s", err)
- }
- cache.ClearAVCache()
-
- // keys-only 解析:Values 被跳过
- keysAV, err := ParseAttributeViewKeysByPath(avJSONPath)
- if err != nil {
- t.Fatalf("parse failed: %s", err)
- }
- if !keysAV.keysOnlyParsed {
- t.Fatal("keysOnlyParsed flag not set")
- }
-
- // 尝试保存 keys-only 对象:应静默跳过(无 error),不写文件
- if err := SaveAttributeView(keysAV); err != nil {
- t.Fatalf("SaveAttributeView returned error for keys-only: %s", err)
- }
-
- // 重新全量解析,确认磁盘上的 Values 仍在(未被空 Values 覆盖)
- cache.ClearAVCache()
- fullAV, err := ParseAttributeViewByPath(avJSONPath)
- if err != nil {
- t.Fatalf("re-parse failed: %s", err)
- }
- if len(fullAV.KeyValues) != 1 || len(fullAV.KeyValues[0].Values) != 1 {
- t.Errorf("disk data corrupted: KeyValues[0].Values len = %d, want 1 (keys-only save must not overwrite)", len(fullAV.KeyValues[0].Values))
- }
-}
diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.go
index 4007c34a9d..9b286819c7 100644
--- a/kernel/model/attribute_view_render.go
+++ b/kernel/model/attribute_view_render.go
@@ -56,12 +56,7 @@ func RenderAttributeView(blockID, avID, viewID, query string, page, pageSize int
}
}
- // ignoreRows 时只需字段/视图元数据,用流式 keys-only 解析跳过行数据反序列化
- if ignoreRows {
- attrView, err = av.ParseAttributeViewKeys(avID)
- } else {
- attrView, err = av.ParseAttributeView(avID)
- }
+ attrView, err = av.ParseAttributeView(avID)
if err != nil {
logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err)
return