An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Prevent database item addition panics https://github.com/siyuan-note/siyuan/issues/18438
Daniel1e282dcf97e5
diff --git a/kernel/cli/cmd/database.go b/kernel/cli/cmd/database.goindex 3db74890ee..88bed5a129 100644--- a/kernel/cli/cmd/database.go+++ b/kernel/cli/cmd/database.go@@ -280,7 +280,7 @@ var databaseItemAddCmd = &cobra.Command{}srcs := []map[string]any{src}- if err := model.AddAttributeViewBlock(nil, srcs, avID, blockID, viewID, groupID, previousID, ignoreFill); err != nil {+ if err := model.AddAttributeViewBlock(nil, srcs, avID, "", viewID, groupID, previousID, ignoreFill); err != nil {return err}model.AppendPushReloadAttrViewEntry(avID)@@ -501,7 +501,7 @@ func init() {databaseKeyAddCmd.Flags().String("av", "", "attribute view ID (required)")databaseKeyAddCmd.Flags().String("name", "", "key name (required)")- databaseKeyAddCmd.Flags().String("type", "", "key type (required): block/text/number/date/select/mSelect/url/email/phone/mAsset/template/created/updated/checkbox/relation/rollup/lineNumber")+ databaseKeyAddCmd.Flags().String("type", "", "key type (required): text/number/date/select/mSelect/url/email/phone/mAsset/template/created/updated/checkbox/relation/rollup/lineNumber")databaseKeyAddCmd.Flags().String("icon", "", "key icon (optional)")databaseKeyAddCmd.Flags().String("prev", "", "previous key ID for ordering (optional)")diff --git a/kernel/mcp/tools/database.go b/kernel/mcp/tools/database.goindex 5e7590841c..6191fed689 100644--- a/kernel/mcp/tools/database.go+++ b/kernel/mcp/tools/database.go@@ -40,7 +40,7 @@ var DatabaseTool = &Tool{"page": {Type: "number", Description: "Page number (default 1)"},"pageSize": {Type: "number", Description: "Results per page (default 50)"},"name": {Type: "string", Description: "Key name (for key_add)"},- "type": {Type: "string", Description: "Key type: block/text/number/date/select/mSelect/url/email/phone/mAsset/template/created/updated/checkbox/relation/rollup/lineNumber (for key_add)"},+ "type": {Type: "string", Description: "Key type: text/number/date/select/mSelect/url/email/phone/mAsset/template/created/updated/checkbox/relation/rollup/lineNumber (for key_add)"},"icon": {Type: "string", Description: "Key icon (for key_add, optional)"},"prev": {Type: "string", Description: "Previous key ID for ordering (for key_add, optional)"},"keyID": {Type: "string", Description: "Key ID (for key_remove, item_update)"},@@ -257,7 +257,7 @@ func databaseItemAdd(args map[string]any) (CallToolResult, error) {src["content"] = content}srcs := []map[string]any{src}- if err := model.AddAttributeViewBlock(nil, srcs, id, blockID, viewID, groupID, previousID, ignoreFill); err != nil {+ if err := model.AddAttributeViewBlock(nil, srcs, id, "", viewID, groupID, previousID, ignoreFill); err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "add item failed: " + err.Error()}}, IsError: true}, nil}model.ReloadAttrView(id)diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex 9f9f673f8e..70bf2a8089 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -5482,7 +5482,13 @@ func addAttributeViewBlock(now int64, avID, dbBlockID, viewID, groupID, previous// 检查是否重复添加相同的块blockValues := attrView.GetBlockKeyValues()+ if nil == blockValues || nil == blockValues.Key {+ return fmt.Errorf("attribute view [%s] has no block key", avID)+ }for _, blockValue := range blockValues.Values {+ if nil == blockValue || nil == blockValue.Block {+ continue+ }if "" != addingBoundBlockID && blockValue.Block.ID == addingBoundBlockID {if !isDetached {// 重复绑定一下,比如剪切数据库块、取消绑定块后再次添加的场景需要@@ -6623,6 +6629,8 @@ func AddAttributeViewKey(avID, keyID, keyName, keyType, keyIcon, previousKeyID skeyTyp := av.KeyType(keyType)switch keyTyp {+ case av.KeyTypeBlock:+ return errors.New("cannot add an attribute view block key")case av.KeyTypeText, av.KeyTypeNumber, av.KeyTypeDate, av.KeyTypeSelect, av.KeyTypeMSelect, av.KeyTypeURL, av.KeyTypeEmail,av.KeyTypePhone, av.KeyTypeMAsset, av.KeyTypeTemplate, av.KeyTypeCreated, av.KeyTypeUpdated, av.KeyTypeCheckbox,av.KeyTypeRelation, av.KeyTypeRollup, av.KeyTypeLineNumber:@@ -6707,6 +6715,8 @@ func AddAttributeViewKey(avID, keyID, keyName, keyType, keyIcon, previousKeyID s}}}+ default:+ return fmt.Errorf("unsupported attribute view key type [%s]", keyType)}err = av.SaveAttributeView(attrView)diff --git a/kernel/model/attribute_view_validation_test.go b/kernel/model/attribute_view_validation_test.gonew file mode 100644index 0000000000..8009076857--- /dev/null+++ b/kernel/model/attribute_view_validation_test.go@@ -0,0 +1,238 @@+// 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 model++import (+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func setupAttributeViewValidationTest(t *testing.T) {+ t.Helper()++ oldDataDir := util.DataDir+ oldConf, oldKernelLangs := Conf, util.Langs+ oldLang, oldAttrViewLangs := util.Lang, util.AttrViewLangs+ util.DataDir = t.TempDir()+ util.Lang = "en"+ util.Langs = map[string]map[int]string{"en": {105: "Database"}}+ util.AttrViewLangs = map[string]map[string]any{+ "en": {+ "key": "Key",+ "select": "Select",+ "table": "Table",+ },+ }+ Conf = NewAppConf()+ Conf.Lang = "en"+ Conf.Sync = conf.NewSync()+ cache.ClearAVCache()+ t.Cleanup(func() {+ cache.ClearAVCache()+ util.DataDir = oldDataDir+ Conf, util.Langs = oldConf, oldKernelLangs+ util.Lang, util.AttrViewLangs = oldLang, oldAttrViewLangs+ })+}++func TestAddAttributeViewBlockRejectsMissingBlockKey(t *testing.T) {+ setupAttributeViewValidationTest(t)++ avID := "20260730130000-missing"+ attrView := av.NewAttributeView(avID)+ attrView.KeyValues = attrView.KeyValues[1:]+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatalf("save attribute view failed: %s", err)+ }++ srcs := []map[string]any{{+ "itemID": ast.NewNodeID(),+ "isDetached": true,+ "content": "",+ }}+ err := AddAttributeViewBlock(nil, srcs, avID, "", "", "", "", false)+ if nil == err || !strings.Contains(err.Error(), "has no block key") {+ t.Fatalf("expected missing block key error, got [%v]", err)+ }+}++func TestAddAttributeViewBlockSkipsInvalidBlockValue(t *testing.T) {+ setupAttributeViewValidationTest(t)++ avID := "20260730130001-invalid"+ attrView := av.NewAttributeView(avID)+ blockValues := attrView.GetBlockKeyValues()+ invalidItemID := ast.NewNodeID()+ blockValues.Values = append(blockValues.Values, &av.Value{+ ID: ast.NewNodeID(),+ KeyID: blockValues.Key.ID,+ BlockID: invalidItemID,+ Type: av.KeyTypeBlock,+ })+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatalf("save attribute view failed: %s", err)+ }++ itemID := ast.NewNodeID()+ srcs := []map[string]any{{+ "itemID": itemID,+ "isDetached": true,+ "content": "Test",+ }}+ if err := AddAttributeViewBlock(nil, srcs, avID, "", "", "", "", false); nil != err {+ t.Fatalf("add detached attribute view item failed: %s", err)+ }++ parsed, err := av.ParseAttributeView(avID)+ if nil != err {+ t.Fatalf("parse attribute view failed: %s", err)+ }+ if invalid := parsed.GetBlockValue(invalidItemID); nil == invalid || nil != invalid.Block {+ t.Fatalf("unexpected invalid block value: %+v", invalid)+ }+ added := parsed.GetBlockValue(itemID)+ if nil == added || nil == added.Block || "Test" != added.Block.Content {+ t.Fatalf("unexpected added block value: %+v", added)+ }+}++func TestAddAttributeViewBlockAcceptsValidDetachedItem(t *testing.T) {+ setupAttributeViewValidationTest(t)++ avID := "20260730130002-validav"+ attrView := av.NewAttributeView(avID)+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatalf("save attribute view failed: %s", err)+ }++ itemID := ast.NewNodeID()+ srcs := []map[string]any{{+ "itemID": itemID,+ "isDetached": true,+ "content": "Test",+ }}+ if err := AddAttributeViewBlock(nil, srcs, avID, "", "", "", "", false); nil != err {+ t.Fatalf("add detached attribute view item failed: %s", err)+ }++ parsed, err := av.ParseAttributeView(avID)+ if nil != err {+ t.Fatalf("parse attribute view failed: %s", err)+ }+ blockValue := parsed.GetBlockValue(itemID)+ if nil == blockValue || nil == blockValue.Block || !blockValue.IsDetached || "Test" != blockValue.Block.Content {+ t.Fatalf("unexpected detached block value: %+v", blockValue)+ }+}++func TestAddAttributeViewBlockAcceptsValidBoundItemWithoutDatabaseBlock(t *testing.T) {+ setupAttributeViewValidationTest(t)++ oldBlockTreeDBPath := util.BlockTreeDBPath+ util.BlockTreeDBPath = filepath.Join(util.DataDir, "blocktree.db")+ treenode.InitBlockTree(true)+ t.Cleanup(func() {+ treenode.CloseDatabase()+ util.BlockTreeDBPath = oldBlockTreeDBPath+ if "" != oldBlockTreeDBPath {+ treenode.InitBlockTree(false)+ }+ })++ avID := "20260730130004-boundav"+ attrView := av.NewAttributeView(avID)+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatalf("save attribute view failed: %s", err)+ }++ tree := treenode.NewTree("20260730130005-box0001", "/20260730130006-doc0001.sy", "/Test", "Test")+ boundBlockID := tree.Root.ID+ t.Cleanup(func() {+ cache.RemoveBlockIALInBox(boundBlockID, tree.Box)+ })+ itemID := ast.NewNodeID()+ src := map[string]any{+ "itemID": itemID,+ "id": boundBlockID,+ "isDetached": false,+ }+ tx := &Transaction{trees: map[string]*parse.Tree{}}+ result := &insertAttrViewBlockResult{}+ err := addAttributeViewBlock(time.Now().UnixMilli(), avID, "", "", "", "", itemID, boundBlockID, "Test", src, false,+ true, tree, tx, result)+ if nil != err {+ t.Fatalf("add bound attribute view item failed: %s", err)+ }++ parsed, err := av.ParseAttributeView(avID)+ if nil != err {+ t.Fatalf("parse attribute view failed: %s", err)+ }+ blockValue := parsed.GetBlockValue(itemID)+ if nil == blockValue || nil == blockValue.Block || blockValue.IsDetached || boundBlockID != blockValue.Block.ID {+ t.Fatalf("unexpected bound block value: %+v", blockValue)+ }+ if !strings.Contains(tree.Root.IALAttr(av.NodeAttrNameAvs), avID) {+ t.Fatalf("bound block does not contain attribute view ID [%s]", avID)+ }+}++func TestAddAttributeViewKeyRejectsUnsupportedTypes(t *testing.T) {+ setupAttributeViewValidationTest(t)++ avID := "20260730130003-keytype"+ attrView := av.NewAttributeView(avID)+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatalf("save attribute view failed: %s", err)+ }+ initialKeyCount := len(attrView.KeyValues)++ tests := []struct {+ name string+ keyType string+ errMessage string+ }{+ {name: "block key", keyType: string(av.KeyTypeBlock), errMessage: "cannot add an attribute view block key"},+ {name: "unknown key", keyType: "unknown", errMessage: "unsupported attribute view key type"},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ err := AddAttributeViewKey(avID, ast.NewNodeID(), "Test", test.keyType, "", "", av.DateDisplayFormatFull)+ if nil == err || !strings.Contains(err.Error(), test.errMessage) {+ t.Fatalf("expected error containing [%s], got [%v]", test.errMessage, err)+ }++ parsed, parseErr := av.ParseAttributeView(avID)+ if nil != parseErr {+ t.Fatalf("parse attribute view failed: %s", parseErr)+ }+ if len(parsed.KeyValues) != initialKeyCount {+ t.Fatalf("unsupported key type changed key count from [%d] to [%d]", initialKeyCount, len(parsed.KeyValues))+ }+ })+ }+}