An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support configuring database fields through the agent https://github.com/siyuan-note/siyuan/issues/19256
Daniel81807ded6d3a
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 0667320918..11a5cf5792 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -74,7 +74,7 @@ second paragraph- Modify: block.update replaces ONE block's content with new markdown — it does NOT create or append new blocks. To both modify and add, call block.update first, then block.append/prepend/insert as separate calls.- Organize: document.move (full document), document.rename (title), block.move (single content block), document.delete.- Inbox (cloud-synced clippings, messages, and audio/video/file attachments; requires subscription): inbox.list (paged, summaries only) → inbox.get (read full content to judge how to file it) → inbox.convert (move one or many into local documents under a notebook, auto-deleting the cloud originals on success). Failed conversions are left in the inbox for retry. If a request fails with an auth/subscription error, report it honestly — do not retry.-- Attributes: attr.get/set on any block. Database/attribute views: database.create (database block with ordered fields), database.item_add (rows), database.key_add (columns), database.render (view). Create database blocks via database.create, never via the file tool or generic block insertion.+- Attributes: attr.get/set on any block. Database/attribute views: database.create (database block with ordered fields), database.item_add (rows), database.key_add (columns), database.key_update (field configuration: name/type/icon/description, number/date format, display template, date defaults, select options, relation and rollup settings; inspect keys first, send exactly one config setting per call, and render to verify), database.key_set_template (existing template field formulas; use .action{add .Number 1} for a number field plus one, then render to verify; do not write computed template cells with item_update), database.render (view). Create database blocks via database.create, never via the file tool or generic block insertion.- Icons: attr.set only changes a document BLOCK's icon — it cannot set a NOTEBOOK's icon. For notebooks use notebook.set_icon (a specific emoji) or notebook.random_icon (random emoji, optionally scoped by id; omit id to randomize ALL notebooks).- Document images: image.list finds local images referenced by a document; call image.analyze on a returned asset path to attach it to the current model for understanding. image.generate creates a reusable image asset for insertion or other document operations.- HTML components: asset.create_html writes HTML content as an asset and inserts a sandboxed IFrame block in one operation. Prefer self-contained HTML; only use remote resources when the user requests them.diff --git a/kernel/mcp/tools/database.go b/kernel/mcp/tools/database.goindex a118aec84c..ca04a26d47 100644--- a/kernel/mcp/tools/database.go+++ b/kernel/mcp/tools/database.go@@ -28,7 +28,7 @@ import ()var databaseActions = []string{- "create", "search", "get", "render", "keys", "key_add", "key_remove", "item_add", "item_remove", "item_update", "unused", "clean",+ "create", "search", "get", "render", "keys", "key_add", "key_update", "key_set_template", "key_remove", "item_add", "item_remove", "item_update", "unused", "clean",}var databaseKeyTypes = []string{@@ -43,21 +43,23 @@ type databaseToolOutput struct {var DatabaseTool = &Tool{Name: "database",- Description: "Attribute view (database) operations. Every successful call returns {action, data}. Actions: create(parentID, name?, primaryKeyName?, layout=table, keys?, previousID?, nextID?), search(keyword), get(id), render(id, viewID?, query?, page=1, pageSize=50), keys(id), key_add(id, name, type, icon?, prev?), key_remove(id, keyID, removeRelationDest?), item_add(id, blockID?, content?, viewID?, groupID?, previousID?, detached?, ignoreDefaultFill?), item_remove(id, itemIDs), item_update(id, keyID, itemID, value), unused(), clean(id?). key_add appends to the current view when prev is omitted.",+ Description: "Attribute view (database) operations. Every successful call returns {action, data}. Actions: create(parentID, name?, primaryKeyName?, layout=table, keys?, previousID?, nextID?), search(keyword), get(id), render(id, viewID?, query?, page=1, pageSize=50), keys(id), key_add(id, name, type, icon?, prev?), key_update(id, keyID, config), key_set_template(id, keyID, template), key_remove(id, keyID, removeRelationDest?), item_add(id, blockID?, content?, viewID?, groupID?, previousID?, detached?, ignoreDefaultFill?), item_remove(id, itemIDs), item_update(id, keyID, itemID, value), unused(), clean(id?). key_add appends to the current view when prev is omitted.",EffectScope: EffectScopeLocal,ActionEffects: map[string]ToolEffects{- "create": {LocalWrite: true},- "search": {LocalRead: true},- "get": {LocalRead: true},- "render": {LocalRead: true},- "keys": {LocalRead: true},- "key_add": {LocalWrite: true},- "key_remove": {LocalWrite: true},- "item_add": {LocalWrite: true},- "item_remove": {LocalWrite: true},- "item_update": {LocalWrite: true},- "unused": {LocalRead: true},- "clean": {LocalWrite: true},+ "create": {LocalWrite: true},+ "search": {LocalRead: true},+ "get": {LocalRead: true},+ "render": {LocalRead: true},+ "keys": {LocalRead: true},+ "key_add": {LocalWrite: true},+ "key_update": {LocalWrite: true},+ "key_set_template": {LocalWrite: true},+ "key_remove": {LocalWrite: true},+ "item_add": {LocalWrite: true},+ "item_remove": {LocalWrite: true},+ "item_update": {LocalWrite: true},+ "unused": {LocalRead: true},+ "clean": {LocalWrite: true},},InputSchema: ToolSchema{Type: "object",@@ -65,7 +67,7 @@ var DatabaseTool = &Tool{"action": {Type: "string", Description: "Operation", Enum: databaseActions},"notebook": {Type: "string", Description: "Notebook ID that owns the new database; required for encrypted notebooks"},"keyword": {Type: "string", Description: "Search keyword (for search)"},- "id": {Type: "string", Description: "Attribute view ID (for get, render, keys, key_add, key_remove, item_add, item_remove, item_update, clean)"},+ "id": {Type: "string", Description: "Attribute view ID (for get, render, keys, key_add, key_update, key_set_template, key_remove, item_add, item_remove, item_update, clean)"},"parentID": {Type: "string", Description: "Parent block ID for the new database (for create)"},"nextID": {Type: "string", Description: "Next sibling block ID for positioning the new database (for create, optional)"},"viewID": {Type: "string", Description: "View ID (for render, item_add)"},@@ -90,7 +92,9 @@ var DatabaseTool = &Tool{"type": {Type: "string", Description: "Key type (for key_add)", Enum: databaseKeyTypes},"icon": {Type: "string", Description: "Key icon (for key_add, optional)"},"prev": {Type: "string", Description: "Previous key ID for ordering (for key_add; omit to append)"},- "keyID": {Type: "string", Description: "Key ID (for key_remove, item_update)"},+ "keyID": {Type: "string", Description: "Key ID (for key_update, key_set_template, key_remove, item_update)"},+ "template": {Type: "string", Description: "Formula for key_set_template on an existing template field, e.g. .action{add .Number 1}; empty string clears it. Use keys to inspect field names and IDs, then render to verify results. Do not write calculated template cells with item_update"},+ "config": databaseKeyConfigProperty,"removeRelationDest": {Type: "boolean", Description: "Also remove related data in linked databases (for key_remove, optional)"},"blockID": {Type: "string", Description: "Block ID to bind (for item_add, optional)"},"content": {Type: "string", Description: "Block column text content (for item_add, optional)"},@@ -134,6 +138,10 @@ func databaseHandler(args map[string]any) (CallToolResult, error) {return databaseKeys(args)case "key_add":return databaseKeyAdd(args)+ case "key_set_template":+ return databaseKeySetTemplate(args)+ case "key_update":+ return databaseKeyUpdate(args)case "key_remove":return databaseKeyRemove(args)case "item_add":@@ -353,6 +361,20 @@ func databasePreviousKeyID(attrView *av.AttributeView, args map[string]any) (retreturn "", nil}+func databaseKeySetTemplate(args map[string]any) (CallToolResult, error) {+ id, _ := args["id"].(string)+ keyID, _ := args["keyID"].(string)+ templateContent, ok := args["template"].(string)+ if "" == id || "" == keyID || !ok {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id, keyID and template (string, may be empty) are required"}}, IsError: true}, nil+ }+ if err := model.SetAttributeViewKeyTemplate(id, keyID, templateContent); nil != err {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "set key template failed: " + err.Error()}}, IsError: true}, nil+ }+ model.ReloadAttrView(id)+ return databaseSuccess("key_set_template", map[string]any{"id": id, "keyID": keyID, "template": templateContent})+}+func databaseViewFieldIDs(view *av.View) (ret []string) {if nil == view {returndiff --git a/kernel/mcp/tools/database_key.go b/kernel/mcp/tools/database_key.gonew file mode 100644index 0000000000..25551ef11d--- /dev/null+++ b/kernel/mcp/tools/database_key.go@@ -0,0 +1,74 @@+// SiYuan - From thought to insight, with agents+// 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.++package tools++import "github.com/siyuan-note/siyuan/kernel/model"++var databaseKeyConfigProperty = Property{+ Type: "object",+ Description: "For key_update: exactly ONE setting per call. Inspect keys first; omitted settings are preserved. Type conversion follows the UI and can change how existing values are interpreted; primary key type is immutable. Render after updating to verify.",+ Properties: map[string]Property{+ "name": {Type: "string", Description: "Nonempty field name"},+ "type": {Type: "string", Enum: databaseKeyTypes, Description: "New field type"},+ "icon": {Type: "string", Description: "Field icon, empty string clears it"},+ "desc": {Type: "string", Description: "Field description, empty string clears it"},+ "numberFormat": {Type: "string", Enum: model.AttributeViewKeyNumberFormats},+ "dateFormat": {Type: "string", Enum: []string{"", "full", "month-day-year", "day-month-year", "year-month-day"}, Description: "Display format for date, created or updated fields"},+ "template": {Type: "string", Description: "Template field formula, e.g. .action{add .Number 1}; empty string clears it"},+ "renderTemplate": {Type: "string", Description: "Display template for non-template fields; empty string clears it"},+ "autoFillNow": {Type: "boolean", Description: "Date field: fill the current time by default"},+ "fillSpecificTime": {Type: "boolean", Description: "Date field: include a specific time by default"},+ "includeTime": {Type: "boolean", Description: "Created or updated field: include time"},+ "options": {+ Type: "array", Description: "Add/update and order select/mSelect options. Existing unlisted options are retained. Color and desc default to empty. Use optionUpdate to rename and optionRemove to delete.",+ Items: &Property{Type: "object", Properties: map[string]Property{+ "name": {Type: "string"}, "color": {Type: "string", Description: "Empty, palette index 1-14, or an existing custom color ID"}, "desc": {Type: "string"},+ }, Required: []string{"name"}},+ },+ "optionUpdate": {+ Type: "object", Description: "Update an existing option, preserving omitted properties and synchronizing row selections and filters",+ Properties: map[string]Property{+ "name": {Type: "string", Description: "Existing option name"}, "newName": {Type: "string"}, "color": {Type: "string"}, "desc": {Type: "string"},+ }, Required: []string{"name"},+ },+ "optionRemove": {Type: "string", Description: "Existing option name to delete, also removing its selections and filter references"},+ "relation": {+ Type: "object", Description: "Configure a relation field. A two-way back field is created automatically or reused for the same target; changing targets maintains backlinks using the UI operation.",+ Properties: map[string]Property{+ "avID": {Type: "string", Description: "Target database ID"}, "isTwoWay": {Type: "boolean"}, "backKeyName": {Type: "string", Description: "Optional back field name"},+ }, Required: []string{"avID", "isTwoWay"},+ },+ "rollup": {+ Type: "object", Description: "Configure a rollup field using an existing relation and a field in its target database",+ Properties: map[string]Property{+ "relationKeyID": {Type: "string"}, "keyID": {Type: "string"}, "operator": {Type: "string", Enum: model.AttributeViewKeyRollupOperators},+ }, Required: []string{"relationKeyID", "keyID", "operator"},+ },+ "relationFilters": {Type: "array", Items: &Property{Type: "object"}, Description: "Relation candidate filters in native ViewFilter format using target field IDs; [] clears them"},+ "rollupFilters": {Type: "array", Items: &Property{Type: "object"}, Description: "Rollup filters in native ViewFilter format using target field IDs; [] clears them"},+ },+}++func databaseKeyUpdate(args map[string]any) (CallToolResult, error) {+ id, _ := args["id"].(string)+ keyID, _ := args["keyID"].(string)+ config, ok := args["config"].(map[string]any)+ if "" == id || "" == keyID || !ok {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id, keyID and config object are required"}}, IsError: true}, nil+ }+ if err := model.UpdateAttributeViewKeyConfig(id, keyID, config); nil != err {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "update key failed: " + err.Error()}}, IsError: true}, nil+ }+ model.ReloadAttrView(id)+ keys := model.GetAttributeViewKeysByID(id, keyID)+ if 1 != len(keys) {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "field configuration was saved but could not be read back; inspect keys before retrying"}}, IsError: true}, nil+ }+ return databaseSuccess("key_update", map[string]any{"id": id, "key": keys[0]})+}diff --git a/kernel/mcp/tools/database_key_test.go b/kernel/mcp/tools/database_key_test.gonew file mode 100644index 0000000000..4a2f1e3246--- /dev/null+++ b/kernel/mcp/tools/database_key_test.go@@ -0,0 +1,256 @@+// SiYuan - From thought to insight, with agents+// 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.++package tools++import (+ "encoding/json"+ "os"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func databaseKeyTestWorkspace(t *testing.T) {+ t.Helper()+ originalDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() { util.DataDir = originalDataDir })+}++func databaseKeyTestFixture(t *testing.T, keys ...*av.KeyValues) *av.AttributeView {+ t.Helper()+ attrView := &av.AttributeView{ID: ast.NewNodeID(), Name: "Test", KeyValues: keys}+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatal(err)+ }+ return attrView+}++func databaseKeyTestUpdate(t *testing.T, id, keyID string, config map[string]any) *av.Key {+ t.Helper()+ args := map[string]any{"action": "key_update", "id": id, "keyID": keyID, "config": config}+ validator, err := CompileToolValidator(DatabaseTool)+ if nil != err {+ t.Fatal(err)+ }+ if err = validator.ValidateInput(args); nil != err {+ t.Fatal(err)+ }+ result, err := databaseHandler(args)+ if nil != err || result.IsError {+ t.Fatalf("update %+v failed: %+v, %v", config, result, err)+ }+ if err = validator.ValidateOutput(result); nil != err {+ t.Fatal(err)+ }+ stored, err := av.ParseAttributeView(id)+ if nil != err {+ t.Fatal(err)+ }+ key, err := stored.GetKey(keyID)+ if nil != err {+ t.Fatal(err)+ }+ return key+}++func TestDatabaseKeyUpdateScalarSettings(t *testing.T) {+ databaseKeyTestWorkspace(t)+ for _, test := range []struct {+ setting string+ typ av.KeyType+ value any+ storedSetting string+ }{+ {"name", av.KeyTypeBlock, "主键名称", "name"},+ {"type", av.KeyTypeText, "number", "type"},+ {"icon", av.KeyTypeText, "1f600", "icon"},+ {"desc", av.KeyTypeText, "字段说明", "desc"},+ {"numberFormat", av.KeyTypeNumber, "percent", "numberFormat"},+ {"dateFormat", av.KeyTypeDate, "year-month-day", "dateFormat"},+ {"dateFormat", av.KeyTypeCreated, "full", "dateFormat"},+ {"dateFormat", av.KeyTypeUpdated, "month-day-year", "dateFormat"},+ {"template", av.KeyTypeTemplate, ".action{add .数字 1}", "template"},+ {"renderTemplate", av.KeyTypeText, ".action{.text}", "renderTemplate"},+ } {+ t.Run(test.setting+string(test.typ), func(t *testing.T) {+ attrView := databaseKeyTestFixture(t, &av.KeyValues{Key: &av.Key{ID: "field", Name: "Before", Type: test.typ}})+ key := databaseKeyTestUpdate(t, attrView.ID, "field", map[string]any{test.setting: test.value})+ data, _ := json.Marshal(key)+ var fields map[string]any+ if err := json.Unmarshal(data, &fields); nil != err {+ t.Fatal(err)+ }+ if test.value != fields[test.storedSetting] {+ t.Fatalf("setting not persisted: %s", data)+ }+ if "name" != test.setting && "Before" != key.Name {+ t.Fatal("unrelated field name changed")+ }+ })+ }+ for _, typ := range []av.KeyType{av.KeyTypeDate, av.KeyTypeCreated, av.KeyTypeUpdated} {+ attrView := databaseKeyTestFixture(t, &av.KeyValues{Key: &av.Key{ID: "field", Type: typ}})+ for _, flag := range []bool{true, false} {+ if av.KeyTypeDate == typ {+ key := databaseKeyTestUpdate(t, attrView.ID, "field", map[string]any{"autoFillNow": flag})+ if nil == key.Date || flag != key.Date.AutoFillNow {+ t.Fatal("autoFillNow not persisted")+ }+ key = databaseKeyTestUpdate(t, attrView.ID, "field", map[string]any{"fillSpecificTime": flag})+ if flag != key.Date.FillSpecificTime {+ t.Fatal("fillSpecificTime not persisted")+ }+ } else {+ key := databaseKeyTestUpdate(t, attrView.ID, "field", map[string]any{"includeTime": flag})+ if av.KeyTypeCreated == typ && (nil == key.Created || flag != key.Created.IncludeTime) ||+ av.KeyTypeUpdated == typ && (nil == key.Updated || flag != key.Updated.IncludeTime) {+ t.Fatal("includeTime not persisted")+ }+ }+ }+ }+}++func TestDatabaseKeyUpdateOptionsMaintainsSelections(t *testing.T) {+ databaseKeyTestWorkspace(t)+ attrView := databaseKeyTestFixture(t, &av.KeyValues{+ Key: &av.Key{ID: "field", Type: av.KeyTypeMSelect, Options: []*av.SelectOption{{Name: "旧选项", Color: "1", Desc: "说明"}}},+ Values: []*av.Value{{ID: ast.NewNodeID(), KeyID: "field", BlockID: ast.NewNodeID(), Type: av.KeyTypeMSelect, MSelect: []*av.ValueSelect{{Content: "旧选项", Color: "1"}}}},+ })+ key := databaseKeyTestUpdate(t, attrView.ID, "field", map[string]any{"options": []any{map[string]any{"name": "新选项", "color": "2"}}})+ if 2 != len(key.Options) || nil == key.GetOption("旧选项") {+ t.Fatal("adding options should retain existing options")+ }+ key = databaseKeyTestUpdate(t, attrView.ID, "field", map[string]any{"optionUpdate": map[string]any{"name": "旧选项", "newName": "已改名", "color": "3"}})+ if nil == key.GetOption("已改名") || "说明" != key.GetOption("已改名").Desc {+ t.Fatal("rename should preserve the option description")+ }+ stored, _ := av.ParseAttributeView(attrView.ID)+ selection := stored.KeyValues[0].Values[0].MSelect[0]+ if "已改名" != selection.Content || "3" != selection.Color {+ t.Fatalf("row selection not updated: %+v", selection)+ }+ databaseKeyTestUpdate(t, attrView.ID, "field", map[string]any{"optionRemove": "已改名"})+ stored, _ = av.ParseAttributeView(attrView.ID)+ if 0 != len(stored.KeyValues[0].Values[0].MSelect) {+ t.Fatal("removed option remains in row selection")+ }+}++func TestDatabaseKeyUpdateRelationAndRollup(t *testing.T) {+ databaseKeyTestWorkspace(t)+ dest := databaseKeyTestFixture(t, &av.KeyValues{Key: &av.Key{ID: "number", Name: "数字", Type: av.KeyTypeNumber}})+ source := databaseKeyTestFixture(t,+ &av.KeyValues{Key: &av.Key{ID: "relation", Name: "关联", Type: av.KeyTypeRelation}},+ &av.KeyValues{Key: &av.Key{ID: "rollup", Name: "汇总", Type: av.KeyTypeRollup}},+ )+ key := databaseKeyTestUpdate(t, source.ID, "relation", map[string]any{"relation": map[string]any{"avID": dest.ID, "isTwoWay": true, "backKeyName": "回链"}})+ backKeyID := key.Relation.BackKeyID+ if "" == backKeyID || !key.Relation.IsTwoWay {+ t.Fatal("two-way relation not configured")+ }+ storedDest, _ := av.ParseAttributeView(dest.ID)+ back, err := storedDest.GetKey(backKeyID)+ if nil != err || nil == back.Relation || back.Relation.AvID != source.ID || back.Relation.BackKeyID != "relation" {+ t.Fatalf("back relation not configured: %+v, %v", back, err)+ }+ key = databaseKeyTestUpdate(t, source.ID, "relation", map[string]any{"relation": map[string]any{"avID": dest.ID, "isTwoWay": true}})+ if backKeyID != key.Relation.BackKeyID {+ t.Fatal("reconfiguring the same relation created another back field")+ }+ storedDest, _ = av.ParseAttributeView(dest.ID)+ back, _ = storedDest.GetKey(backKeyID)+ if "回链" != back.Name {+ t.Fatal("omitting the back field name changed its existing name")+ }+ key = databaseKeyTestUpdate(t, source.ID, "rollup", map[string]any{"rollup": map[string]any{"relationKeyID": "relation", "keyID": "number", "operator": "Sum"}})+ if nil == key.Rollup || nil == key.Rollup.Calc || av.CalcOperatorSum != key.Rollup.Calc.Operator {+ t.Fatal("rollup was not configured")+ }+ for _, setting := range []string{"relationFilters", "rollupFilters"} {+ field := "relation"+ if "rollupFilters" == setting {+ field = "rollup"+ }+ key = databaseKeyTestUpdate(t, source.ID, field, map[string]any{setting: []any{map[string]any{"column": "number", "operator": "Is not empty"}}})+ if "relation" == field && 0 == len(key.Relation.CandidateFilters) || "rollup" == field && 0 == len(key.Rollup.Filters) {+ t.Fatal("filters were not saved")+ }+ result, callErr := databaseHandler(map[string]any{"action": "key_update", "id": source.ID, "keyID": field,+ "config": map[string]any{setting: []any{map[string]any{"column": "missing", "operator": "Is not empty"}}}})+ if nil != callErr || !result.IsError {+ t.Fatal("invalid target filter field should be rejected")+ }+ key = databaseKeyTestUpdate(t, source.ID, field, map[string]any{setting: []any{}})+ if "relation" == field && 0 != len(key.Relation.CandidateFilters) || "rollup" == field && 0 != len(key.Rollup.Filters) {+ t.Fatal("filters were not cleared")+ }+ }+ databaseKeyTestUpdate(t, source.ID, "relation", map[string]any{"relation": map[string]any{"avID": dest.ID, "isTwoWay": false}})+ storedDest, _ = av.ParseAttributeView(dest.ID)+ back, _ = storedDest.GetKey(backKeyID)+ if back.Relation.IsTwoWay || "" != back.Relation.BackKeyID {+ t.Fatal("disabling two-way relation left an active backlink")+ }+}++func TestDatabaseKeyUpdateRejectsInvalidConfigWithoutWriting(t *testing.T) {+ databaseKeyTestWorkspace(t)+ attrView := databaseKeyTestFixture(t,+ &av.KeyValues{Key: &av.Key{ID: "text", Name: "Text", Type: av.KeyTypeText}},+ &av.KeyValues{Key: &av.Key{ID: "primary", Name: "Primary", Type: av.KeyTypeBlock}},+ &av.KeyValues{Key: &av.Key{ID: "select", Type: av.KeyTypeSelect}},+ &av.KeyValues{Key: &av.Key{ID: "relation", Type: av.KeyTypeRelation}},+ &av.KeyValues{Key: &av.Key{ID: "rollup", Type: av.KeyTypeRollup}},+ )+ path := av.GetAttributeViewDataPath(attrView.ID)+ before, err := os.ReadFile(path)+ if nil != err {+ t.Fatal(err)+ }+ for _, test := range []struct {+ key string+ config map[string]any+ }{+ {"missing", map[string]any{"name": "Name"}},+ {"text", map[string]any{}},+ {"text", map[string]any{"name": "Name", "type": "number"}},+ {"text", map[string]any{"unknown": true}},+ {"text", map[string]any{"name": " "}},+ {"text", map[string]any{"name": nil}},+ {"text", map[string]any{"type": "invalid"}},+ {"text", map[string]any{"type": "block"}},+ {"primary", map[string]any{"type": "text"}},+ {"text", map[string]any{"numberFormat": "percent"}},+ {"text", map[string]any{"dateFormat": "invalid"}},+ {"text", map[string]any{"template": "formula"}},+ {"text", map[string]any{"includeTime": true}},+ {"text", map[string]any{"autoFillNow": true}},+ {"text", map[string]any{"options": []any{}}},+ {"select", map[string]any{"options": []any{nil}}},+ {"select", map[string]any{"options": []any{map[string]any{"name": "One", "color": "999"}}}},+ {"select", map[string]any{"optionUpdate": map[string]any{"name": "missing"}}},+ {"select", map[string]any{"optionRemove": "missing"}},+ {"relation", map[string]any{"relation": map[string]any{"avID": attrView.ID}}},+ {"relation", map[string]any{"relation": map[string]any{"avID": "missing", "isTwoWay": true}}},+ {"rollup", map[string]any{"rollup": map[string]any{"relationKeyID": "text", "keyID": "text", "operator": "Sum"}}},+ } {+ result, callErr := databaseHandler(map[string]any{"action": "key_update", "id": attrView.ID, "keyID": test.key, "config": test.config})+ if nil != callErr || !result.IsError {+ t.Fatalf("expected invalid config to fail: %+v, %+v, %v", test, result, callErr)+ }+ after, readErr := os.ReadFile(path)+ if nil != readErr || string(before) != string(after) {+ t.Fatalf("invalid config changed persisted data: %+v, %v", test, readErr)+ }+ }+}diff --git a/kernel/mcp/tools/database_test.go b/kernel/mcp/tools/database_test.goindex 00b26ab66a..08b6342455 100644--- a/kernel/mcp/tools/database_test.go+++ b/kernel/mcp/tools/database_test.go@@ -12,8 +12,10 @@ import ("encoding/json""testing"+ "github.com/88250/lute/ast""github.com/siyuan-note/siyuan/kernel/av""github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util")func TestDatabaseStructuredRenderOutput(t *testing.T) {@@ -188,7 +190,7 @@ func TestDatabaseViewFieldIDsSupportsLayouts(t *testing.T) {}func TestDatabaseActionEffects(t *testing.T) {- for _, action := range []string{"create", "key_add", "key_remove", "item_add", "item_remove", "item_update", "clean"} {+ for _, action := range []string{"create", "key_add", "key_update", "key_set_template", "key_remove", "item_add", "item_remove", "item_update", "clean"} {effects, ok := DatabaseTool.EffectsFor(action)if !ok || !effects.LocalWrite {t.Fatalf("database action [%s] should declare a local write", action)@@ -208,3 +210,74 @@ func TestDatabaseStringArray(t *testing.T) {t.Fatalf("unexpected database string array: %+v", values)}}++func TestDatabaseKeySetTemplateArguments(t *testing.T) {+ validator, err := CompileToolValidator(DatabaseTool)+ if nil != err {+ t.Fatal(err)+ }+ for _, templateContent := range []string{".action{add .数字 1}", ""} {+ args := map[string]any{"action": "key_set_template", "id": "database", "keyID": "field", "template": templateContent}+ if err = validator.ValidateInput(args); nil != err {+ t.Fatal(err)+ }+ result, resultErr := databaseSuccess("key_set_template", map[string]any{"id": "database", "keyID": "field", "template": templateContent})+ if nil != resultErr {+ t.Fatal(resultErr)+ }+ if err = validator.ValidateOutput(result); nil != err {+ t.Fatal(err)+ }+ }+ for _, args := range []map[string]any{+ {"action": "key_set_template", "id": "database", "keyID": "field"},+ {"action": "key_set_template", "id": "database", "keyID": "field", "template": 1},+ {"action": "key_set_template", "keyID": "field", "template": ""},+ {"action": "key_set_template", "id": "database", "template": ""},+ } {+ result, callErr := databaseHandler(args)+ if nil != callErr || !result.IsError {+ t.Fatalf("invalid arguments should fail before accessing a database: %+v, %v", result, callErr)+ }+ }+}++func TestDatabaseKeyTemplatePersistence(t *testing.T) {+ originalDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() { util.DataDir = originalDataDir })+ attrView := &av.AttributeView{ID: ast.NewNodeID(), KeyValues: []*av.KeyValues{+ {Key: &av.Key{ID: "number", Name: "数字", Type: av.KeyTypeNumber}},+ {Key: &av.Key{ID: "template", Name: "模板", Type: av.KeyTypeTemplate}},+ }}+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatal(err)+ }+ for _, formula := range []string{".action{add .数字 1}", ""} {+ if err := model.SetAttributeViewKeyTemplate(attrView.ID, "template", formula); nil != err {+ t.Fatal(err)+ }+ stored, err := av.ParseAttributeView(attrView.ID)+ if nil != err {+ t.Fatal(err)+ }+ key, err := stored.GetKey("template")+ if nil != err || formula != key.Template {+ t.Fatalf("template was not persisted: %+v, %v", key, err)+ }+ for _, keyID := range []string{"number", "missing"} {+ if err = model.SetAttributeViewKeyTemplate(attrView.ID, keyID, "invalid"); nil == err {+ t.Fatalf("expected invalid target %q to be rejected", keyID)+ }+ }+ stored, err = av.ParseAttributeView(attrView.ID)+ if nil != err {+ t.Fatal(err)+ }+ key, _ = stored.GetKey("template")+ numberKey, _ := stored.GetKey("number")+ if formula != key.Template || "" != numberKey.RenderTemplate || "" != numberKey.Template {+ t.Fatal("rejected updates changed field configuration")+ }+ }+}diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex f10f266153..911a9d8570 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -7529,6 +7529,24 @@ func updateAttributeViewColTemplate(operation *Operation) (err error) {return}+// SetAttributeViewKeyTemplate 设置模板字段公式,复用字段模板保存和分组更新逻辑。+func SetAttributeViewKeyTemplate(avID, keyID, templateContent string) (err error) {+ attrView, err := av.ParseAttributeView(avID)+ if nil != err {+ return err+ }+ key, err := attrView.GetKey(keyID)+ if nil != err {+ return err+ }+ if av.KeyTypeTemplate != key.Type {+ return errors.New("key must be a template field")+ }+ return updateAttributeViewColTemplate(&Operation{+ AvID: avID, ID: keyID, Typ: string(av.KeyTypeTemplate), Data: templateContent,+ })+}+func (tx *Transaction) doUpdateAttrViewColNumberFormat(operation *Operation) (ret *TxErr) {err := updateAttributeViewColNumberFormat(operation)if err != nil {diff --git a/kernel/model/attribute_view_key_config.go b/kernel/model/attribute_view_key_config.gonew file mode 100644index 0000000000..ab7d3bb7e9--- /dev/null+++ b/kernel/model/attribute_view_key_config.go@@ -0,0 +1,347 @@+// SiYuan - From thought to insight, with agents+// 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.++package model++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+ "slices"+ "strings"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/av"+)++var AttributeViewKeyNumberFormats = []string{"", "commas", "percent", "USD", "CNY", "EUR", "GBP", "JPY", "RUB", "INR", "KRW", "TRY", "CAD", "CHF", "THB", "AUD", "HKD", "TWD", "MOP", "SGD", "NZD", "ILS", "SKK"}++var AttributeViewKeyRollupOperators = []string{"", "Unique values", "Count all", "Count values", "Count unique values", "Count empty", "Count not empty", "Percent empty", "Percent not empty", "Percent unique values", "Sum", "Average", "Median", "Min", "Max", "Range", "Earliest", "Latest", "Checked", "Unchecked", "Percent checked", "Percent unchecked"}++// UpdateAttributeViewKeyConfig 每次修改一个字段配置,先校验参数,再复用界面操作维护关联数据。+func UpdateAttributeViewKeyConfig(avID, keyID string, config map[string]any) (err error) {+ if 1 != len(config) {+ return errors.New("config must contain exactly one setting; use separate calls for multiple settings")+ }+ attrView, err := av.ParseAttributeView(avID)+ if nil != err {+ return err+ }+ key, err := attrView.GetKey(keyID)+ if nil != err {+ return err+ }+ op := &Operation{AvID: avID, ID: keyID, Typ: string(key.Type), Name: key.Name}+ for setting, value := range config {+ switch setting {+ case "name", "type", "icon", "desc", "numberFormat", "dateFormat", "template", "renderTemplate":+ text, ok := value.(string)+ if !ok {+ return fmt.Errorf("%s must be a string", setting)+ }+ op.Data, op.Format = text, text+ switch setting {+ case "name":+ if "" == strings.TrimSpace(text) {+ return errors.New("field name must not be empty")+ }+ op.Name = text+ return updateAttributeViewColumn(op)+ case "type":+ if _, err = newAttributeViewKey(keyID, key.Name, text, key.Icon, key.DateFormat); nil != err {+ return err+ }+ op.Typ = text+ return updateAttributeViewColumn(op)+ case "icon":+ return setAttributeViewColIcon(op)+ case "desc":+ return setAttributeViewColDesc(op)+ case "numberFormat":+ if av.KeyTypeNumber != key.Type || !slices.Contains(AttributeViewKeyNumberFormats, text) {+ return errors.New("numberFormat requires a number field and a supported format")+ }+ return updateAttributeViewColNumberFormat(op)+ case "dateFormat":+ return setAttributeViewColDateFormat(op)+ case "template":+ if av.KeyTypeTemplate != key.Type {+ return errors.New("template requires a template field; use renderTemplate for other fields")+ }+ return updateAttributeViewColTemplate(op)+ case "renderTemplate":+ if av.KeyTypeTemplate == key.Type {+ return errors.New("use template for a template field")+ }+ return updateAttributeViewColTemplate(op)+ }+ case "autoFillNow", "fillSpecificTime", "includeTime":+ flag, ok := value.(bool)+ if !ok {+ return fmt.Errorf("%s must be a boolean", setting)+ }+ op.Data = flag+ if "includeTime" == setting {+ switch key.Type {+ case av.KeyTypeCreated:+ return setAttrViewCreatedIncludeTime(op)+ case av.KeyTypeUpdated:+ return setAttrViewUpdatedIncludeTime(op)+ }+ return errors.New("includeTime requires a created or updated field")+ }+ if av.KeyTypeDate != key.Type {+ return fmt.Errorf("%s requires a date field", setting)+ }+ if "autoFillNow" == setting {+ return setAttributeViewColDateFillCreated(op)+ }+ return setAttrViewColDateFillSpecificTime(op)+ case "options", "optionUpdate", "optionRemove":+ if av.KeyTypeSelect != key.Type && av.KeyTypeMSelect != key.Type {+ return errors.New("option settings require a select or mSelect field")+ }+ return updateAttributeViewKeyOptions(attrView, key, op, setting, value)+ case "relation":+ return updateAttributeViewKeyRelation(key, op, value)+ case "rollup":+ return updateAttributeViewKeyRollup(attrView, key, op, value)+ case "relationFilters", "rollupFilters":+ filters, ok := value.([]any)+ if !ok {+ return errors.New("filters must be an array")+ }+ if err = validateAttributeViewKeyFilters(attrView, key, setting, filters); nil != err {+ return err+ }+ return setAttrViewColFilters(avID, "", keyID, filters, "relationFilters" == setting)+ default:+ return fmt.Errorf("unknown field setting: %s", setting)+ }+ }+ return+}++func validateAttributeViewKeyFilters(attrView *av.AttributeView, key *av.Key, setting string, value []any) error {+ relationKey := key+ if "rollupFilters" == setting {+ if av.KeyTypeRollup != key.Type || nil == key.Rollup {+ return errors.New("rollupFilters requires a configured rollup field")+ }+ var err error+ relationKey, err = attrView.GetKey(key.Rollup.RelationKeyID)+ if nil != err {+ return err+ }+ }+ if av.KeyTypeRelation != relationKey.Type || nil == relationKey.Relation {+ return errors.New("filters require a configured relation field")+ }+ dest, err := av.ParseAttributeView(relationKey.Relation.AvID)+ if nil != err {+ return err+ }+ var filters []*av.ViewFilter+ if err = decodeAttributeViewKeyConfig(value, &filters); nil != err {+ return err+ }+ if err = av.ValidateFilterDepth(filters); nil != err {+ return err+ }+ var validate func([]*av.ViewFilter) error+ validate = func(items []*av.ViewFilter) error {+ for _, filter := range items {+ if nil == filter {+ return errors.New("filter must not be null")+ }+ if filter.IsGroup() {+ if av.FilterCombinationAnd != filter.Combination && av.FilterCombinationOr != filter.Combination {+ return errors.New("filter group requires and/or combination")+ }+ if err := validate(filter.Filters); nil != err {+ return err+ }+ } else if _, err := dest.GetKey(filter.Column); nil != err {+ return fmt.Errorf("invalid filter target field: %s", filter.Column)+ }+ }+ return nil+ }+ return validate(filters)+}++// decodeAttributeViewKeyConfig 拒绝未知字段及空值,防止拼写错误被当作成功更新。+func decodeAttributeViewKeyConfig(value, dest any) error {+ if nil == value {+ return errors.New("configuration must not be null")+ }+ data, err := json.Marshal(value)+ if nil != err {+ return err+ }+ decoder := json.NewDecoder(bytes.NewReader(data))+ decoder.DisallowUnknownFields()+ return decoder.Decode(dest)+}++func updateAttributeViewKeyOptions(attrView *av.AttributeView, key *av.Key, op *Operation, setting string, value any) error {+ if "options" == setting {+ var options []*av.SelectOption+ if err := decodeAttributeViewKeyConfig(value, &options); nil != err {+ return err+ }+ if 0 == len(options) {+ return errors.New("options must not be empty; use optionRemove to delete existing options")+ }+ names := map[string]bool{}+ for _, option := range options {+ if nil == option || "" == strings.TrimSpace(option.Name) {+ return errors.New("each option requires a nonempty name")+ }+ if names[option.Name] {+ return errors.New("duplicate option name")+ }+ if attrView.FilterColorValue(option.Color) != option.Color {+ return errors.New("invalid option color")+ }+ names[option.Name] = true+ }+ op.Data = options+ return updateAttributeViewColumnOptions(op)+ }+ if "optionRemove" == setting {+ name, ok := value.(string)+ if !ok || nil == key.GetOption(name) {+ return errors.New("optionRemove must name an existing option")+ }+ op.Data = name+ return removeAttributeViewColumnOption(op)+ }+ var config struct {+ Name string `json:"name"`+ NewName *string `json:"newName"`+ Color *string `json:"color"`+ Desc *string `json:"desc"`+ }+ if err := decodeAttributeViewKeyConfig(value, &config); nil != err {+ return err+ }+ option := key.GetOption(config.Name)+ if nil == option {+ return errors.New("optionUpdate must name an existing option")+ }+ name, color, desc := option.Name, option.Color, option.Desc+ if nil != config.NewName {+ name = strings.TrimSpace(*config.NewName)+ if "" == name {+ return errors.New("new option name must not be empty")+ }+ if name != option.Name && nil != key.GetOption(name) {+ return errors.New("new option name already exists")+ }+ }+ if nil != config.Color {+ color = *config.Color+ if attrView.FilterColorValue(color) != color {+ return errors.New("invalid option color")+ }+ }+ if nil != config.Desc {+ desc = *config.Desc+ }+ if name == option.Name {+ op.Data = []*av.SelectOption{{Name: name, Color: color, Desc: desc}}+ return updateAttributeViewColumnOptions(op)+ }+ op.Data = map[string]any{"oldName": option.Name, "newName": name, "newColor": color, "newDesc": desc}+ return updateAttributeViewColumnOption(op)+}++func updateAttributeViewKeyRelation(key *av.Key, op *Operation, value any) error {+ if av.KeyTypeRelation != key.Type {+ return errors.New("relation requires a relation field")+ }+ var config struct {+ AvID string `json:"avID"`+ IsTwoWay *bool `json:"isTwoWay"`+ BackKeyName string `json:"backKeyName"`+ }+ if err := decodeAttributeViewKeyConfig(value, &config); nil != err {+ return err+ }+ if nil == config.IsTwoWay || "" == config.AvID {+ return errors.New("relation requires avID and isTwoWay")+ }+ dest, err := av.ParseAttributeView(config.AvID)+ if nil != err {+ return err+ }+ // 先认证已有目标,避免无法读取旧关联时静默跳过回链清理。+ if nil != key.Relation && "" != key.Relation.AvID {+ if _, err := av.ParseAttributeView(key.Relation.AvID); nil != err {+ return err+ }+ }+ op.ID, op.KeyID, op.Format = config.AvID, key.ID, key.Name+ op.IsTwoWay, op.Name = *config.IsTwoWay, config.BackKeyName+ if op.IsTwoWay {+ op.BackRelationKeyID = ast.NewNodeID()+ if nil != key.Relation && key.Relation.IsTwoWay && key.Relation.AvID == config.AvID {+ op.BackRelationKeyID = key.Relation.BackKeyID+ backKey, getErr := dest.GetKey(op.BackRelationKeyID)+ if nil != getErr || av.KeyTypeRelation != backKey.Type || nil == backKey.Relation ||+ backKey.Relation.AvID != op.AvID || backKey.Relation.BackKeyID != key.ID {+ return errors.New("existing back relation is invalid")+ }+ if "" == config.BackKeyName {+ op.Name = backKey.Name+ }+ }+ }+ err = updateAttributeViewColRelation(op)+ if nil == err {+ ReloadAttrView(config.AvID)+ if nil != key.Relation && key.Relation.AvID != config.AvID {+ ReloadAttrView(key.Relation.AvID)+ }+ }+ return err+}++func updateAttributeViewKeyRollup(attrView *av.AttributeView, key *av.Key, op *Operation, value any) error {+ if av.KeyTypeRollup != key.Type {+ return errors.New("rollup requires a rollup field")+ }+ var config struct {+ RelationKeyID string `json:"relationKeyID"`+ KeyID string `json:"keyID"`+ Operator *string `json:"operator"`+ }+ if err := decodeAttributeViewKeyConfig(value, &config); nil != err {+ return err+ }+ if nil == config.Operator || !slices.Contains(AttributeViewKeyRollupOperators, *config.Operator) {+ return errors.New("rollup requires a supported operator")+ }+ relationKey, err := attrView.GetKey(config.RelationKeyID)+ if nil != err || av.KeyTypeRelation != relationKey.Type || nil == relationKey.Relation {+ return errors.New("rollup requires a configured relation field")+ }+ dest, err := av.ParseAttributeView(relationKey.Relation.AvID)+ if nil != err {+ return err+ }+ if _, err = dest.GetKey(config.KeyID); nil != err {+ return err+ }+ calc := &av.RollupCalc{Operator: av.CalcOperator(*config.Operator)}+ op.ParentID, op.KeyID = config.RelationKeyID, config.KeyID+ op.Data = map[string]any{"calc": calc}+ return updateAttributeViewColRollup(op)+}