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: Improve top-level notebook document behavior https://github.com/siyuan-note/siyuan/issues/18266
Daniel4fc07cc59406
diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.tsindex 38fc4b5aec..f610cde5bd 100644--- a/app/src/util/pathName.ts+++ b/app/src/util/pathName.ts@@ -764,6 +764,7 @@ export const setNoteBook = (cb?: (notebook: INotebook[]) => void, flashcard = fa}, (response) => {if (!flashcard) {window.siyuan.notebooks = response.data.notebooks;+ window.siyuan.config.fileTree.boxDocEnabled = response.data.boxDocEnabled;}if (cb) {cb(response.data.notebooks);diff --git a/kernel/api/notebook.go b/kernel/api/notebook.goindex 8bd4b392d1..2964cbc2e6 100644--- a/kernel/api/notebook.go+++ b/kernel/api/notebook.go@@ -462,7 +462,8 @@ func lsNotebooks(c *gin.Context) {}ret.Data = map[string]any{- "notebooks": notebooks,+ "notebooks": notebooks,+ "boxDocEnabled": model.IsBoxDocEnabled(),}}diff --git a/kernel/model/box_doc.go b/kernel/model/box_doc.goindex 8807059657..180086b7c6 100644--- a/kernel/model/box_doc.go+++ b/kernel/model/box_doc.go@@ -113,6 +113,31 @@ func IsBoxDocEnabled() bool {return nil != Conf && nil != Conf.FileTree && nil != Conf.FileTree.BoxDocEnabled && *Conf.FileTree.BoxDocEnabled}+func hiddenBoxDocRootIDs() (ret []string) {+ if IsBoxDocEnabled() || nil == Conf {+ return+ }+ for _, box := range Conf.GetOpenedBoxes() {+ if "" != box.BoxDocID {+ ret = append(ret, box.BoxDocID)+ }+ }+ return+}++func isHiddenBoxDocBlock(id, boxID string) bool {+ if IsBoxDocEnabled() {+ return false+ }+ var bt *treenode.BlockTree+ if "" == boxID {+ bt = treenode.GetBlockTree(id)+ } else {+ bt = treenode.GetBlockTreeInBox(id, boxID)+ }+ return nil != bt && IsBoxDoc(bt.BoxID, bt.RootID)+}+func EnsureBoxDoc(boxID string) (boxDocID string, err error) {createDocLock.Lock()defer createDocLock.Unlock()@@ -125,7 +150,7 @@ func ensureBoxDoc0(boxID string) (boxDocID string, err error) {return}- box := Conf.Box(boxID)+ box := Conf.GetBox(boxID)if nil == box {return "", ErrBoxNotFound}@@ -186,28 +211,16 @@ func RefreshBoxDocFeature() {}func findBoxDocByMarker(box *Box) (ret string, err error) {- files, _, err := box.Ls("/")+ boxDocID := deterministicBoxDocID(box.ID)+ if "" == boxDocID || !box.Exist(boxDocPath(boxDocID)) {+ return+ }+ tree, err := filesys.LoadTree(box.ID, boxDocPath(boxDocID), util.NewLute())if err != nil {return "", err}-- luteEngine := util.NewLute()- for _, file := range files {- if file.isdir || !strings.HasSuffix(file.path, ".sy") {- continue- }- id := util.GetTreeID(file.path)- if !ast.IsNodeIDPattern(id) {- continue- }- tree, loadErr := filesys.LoadTree(box.ID, file.path, luteEngine)- if loadErr != nil || box.ID != tree.Root.IALAttr(BoxDocAttr) {- continue- }- if "" != ret && ret != id {- return "", fmt.Errorf("multiple box documents found in notebook [%s]", box.ID)- }- ret = id+ if box.ID == tree.Root.IALAttr(BoxDocAttr) {+ ret = boxDocID}return}diff --git a/kernel/model/embedding.go b/kernel/model/embedding.goindex a985ea0288..bbc301e925 100644--- a/kernel/model/embedding.go+++ b/kernel/model/embedding.go@@ -440,8 +440,9 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes maboxFilter, boxArgs := buildBoxesFilter(boxes, "be.")pathFilter, pathArgs := buildPathsFilter(paths, "be.")+ boxDocFilter, boxDocArgs := buildRootIDExclusionFilter(hiddenBoxDocRootIDs(), "b.")typeFilter := buildTypeFilter(types, subTypes, "b.")- hasFilter := 0 < len(boxes) || 0 < len(paths) || 0 < len(types)+ hasFilter := 0 < len(boxes) || 0 < len(paths) || 0 < len(types) || "" != boxDocFilterhasTypeFilter := 0 < len(types)numWorkers := max(runtime.GOMAXPROCS(0), 1)@@ -465,9 +466,9 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes maif hasTypeFilter {q += " AND " + typeFilter}- q += boxFilter + pathFilter- // box/path 过滤值通过绑定参数传递,避免 SQL 拼接注入- args = append(append([]any{}, boxArgs...), pathArgs...)+ q += boxFilter + pathFilter + boxDocFilter+ // 过滤值通过绑定参数传递,避免 SQL 拼接注入+ args = append(append(append([]any{}, boxArgs...), pathArgs...), boxDocArgs...)q += fmt.Sprintf(" ORDER BY be.rowid LIMIT %d", scanSize)} else {q = fmt.Sprintf("SELECT rowid, id, embedding FROM block_embeddings WHERE embedding IS NOT NULL AND length(embedding) > 0 AND rowid > %d ORDER BY rowid LIMIT %d", cursor, scanSize)diff --git a/kernel/model/file.go b/kernel/model/file.goindex 06ffe9b3af..4df1d159ae 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -230,6 +230,9 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[if nil == b {continue}+ if !IsBoxDocEnabled() && IsBoxDoc(rootBlock.Box, rootBlock.RootID) {+ continue+ }hPath := b.Name + rootBlock.HPathif flashcard {newFlashcardCount, dueFlashcardCount, flashcardCount := countTreeFlashcard(rootBlock.ID, deck, deckBlockIDs)@@ -1374,7 +1377,7 @@ func GetFullHPathByID(id string) (hPath string, err error) {func GetIDsByHPath(hpath, boxID string) (ret []string, err error) {ret = []string{}- if "/" == hpath {+ if IsBoxDocEnabled() && "/" == hpath {if box := Conf.Box(boxID); nil != box && "" != box.BoxDocID {return []string{box.BoxDocID}, nil}diff --git a/kernel/model/mount.go b/kernel/model/mount.goindex f25b1c4ae5..3e497a488d 100644--- a/kernel/model/mount.go+++ b/kernel/model/mount.go@@ -48,16 +48,12 @@ func GetBoxByName(name string) (ret *Box) {}func CreateBox(name string) (id string, err error) {- name = util.RemoveInvalid(name)+ name = normalizeBoxName(name)if 512 < utf8.RuneCountInString(name) {// 限制笔记本名和文档名最大长度为 `512` https://github.com/siyuan-note/siyuan/issues/6299err = errors.New(Conf.Language(106))return}- if "" == name {- name = Conf.language(105)- }-FlushTxQueue()createDocLock.Lock()@@ -104,16 +100,13 @@ func RenameBox(boxID, name string) (err error) {return errors.New(Conf.Language(0))}+ name = normalizeBoxName(name)if 512 < utf8.RuneCountInString(name) {// 限制笔记本名和文档名最大长度为 `512` https://github.com/siyuan-note/siyuan/issues/6299err = errors.New(Conf.Language(106))return}- if "" == name {- name = Conf.language(105)- }-boxConf := box.GetConf()boxConf.Name = namebox.Name = name@@ -130,6 +123,14 @@ func RenameBox(boxID, name string) (err error) {return}+func normalizeBoxName(name string) string {+ name = normalizeDocTitle(name)+ if "" == name {+ name = normalizeDocTitle(Conf.language(105))+ }+ return name+}+var boxLock = sync.Map{}func RemoveBox(boxID string) (err error) {diff --git a/kernel/model/search.go b/kernel/model/search.goindex 7185d524e0..0f5d05cefd 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -1198,6 +1198,9 @@ func FullTextSearchBlockInBox(query string, boxes, paths []string, types, subTyp}query = filterQueryInvisibleChars(query)+ if 2 != method && 3 != method && ast.IsNodeIDPattern(query) && isHiddenBoxDocBlock(query, boxID) {+ return+ }var ignoreFilter stringif ignoreLines := getSearchIgnoreLines(); 0 < len(ignoreLines) {// Support ignore search results https://github.com/siyuan-note/siyuan/issues/10089@@ -1216,6 +1219,9 @@ func FullTextSearchBlockInBox(query string, boxes, paths []string, types, subTypcase 1: // 查询语法typeFilter := buildTypeFilter(types, subTypes)boxFilter, boxArgs := buildBoxesFilter(boxes)+ boxDocFilter, boxDocArgs := buildRootIDExclusionFilter(hiddenBoxDocRootIDs())+ boxFilter += boxDocFilter+ boxArgs = append(boxArgs, boxDocArgs...)pathFilter, pathArgs := buildPathsFilter(paths)if ast.IsNodeIDPattern(query) {blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+query+"'", beforeLen, page, pageSize, boxID)@@ -1227,11 +1233,17 @@ func FullTextSearchBlockInBox(query string, boxes, paths []string, types, subTypcase 3: // 正则表达式typeFilter := buildTypeFilter(types, subTypes)boxFilter, boxArgs := buildBoxesFilter(boxes)+ boxDocFilter, boxDocArgs := buildRootIDExclusionFilter(hiddenBoxDocRootIDs())+ boxFilter += boxDocFilter+ boxArgs = append(boxArgs, boxDocArgs...)pathFilter, pathArgs := buildPathsFilter(paths)blocks, matchedBlockCount, matchedRootCount = fullTextSearchByRegexpInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)default: // 关键字typeFilter := buildTypeFilter(types, subTypes)boxFilter, boxArgs := buildBoxesFilter(boxes)+ boxDocFilter, boxDocArgs := buildRootIDExclusionFilter(hiddenBoxDocRootIDs())+ boxFilter += boxDocFilter+ boxArgs = append(boxArgs, boxDocArgs...)pathFilter, pathArgs := buildPathsFilter(paths)if ast.IsNodeIDPattern(query) {blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+query+"'", beforeLen, page, pageSize, boxID)@@ -1440,6 +1452,29 @@ func buildPathsFilter(paths []string, alias ...string) (clause string, args []anreturn}+// buildRootIDExclusionFilter 构造根文档 ID 排除子句,ID 通过绑定参数传递。+func buildRootIDExclusionFilter(rootIDs []string, alias ...string) (clause string, args []any) {+ if 0 == len(rootIDs) {+ return+ }+ prefix := ""+ if 0 < len(alias) && "" != alias[0] {+ prefix = alias[0]+ }+ builder := bytes.Buffer{}+ builder.WriteString(fmt.Sprintf(" AND %sroot_id NOT IN (", prefix))+ for i, rootID := range rootIDs {+ if 0 < i {+ builder.WriteString(", ")+ }+ builder.WriteString("?")+ args = append(args, rootID)+ }+ builder.WriteString(")")+ clause = builder.String()+ return+}+func buildOrderBy(query string, method, orderBy int) string {switch orderBy {case 1:diff --git a/kernel/model/search_test.go b/kernel/model/search_test.goindex f9b927ecb0..a11f131cac 100644--- a/kernel/model/search_test.go+++ b/kernel/model/search_test.go@@ -102,6 +102,34 @@ func TestBuildBoxesPathFiltersArgCount(t *testing.T) {}}+func TestBuildRootIDExclusionFilter(t *testing.T) {+ rootIDs := []string{"20260716120000-abcdefg", "20260716120001-hijklmn"}+ clause, args := buildRootIDExclusionFilter(rootIDs, "b.")+ if " AND b.root_id NOT IN (?, ?)" != clause {+ t.Fatalf("unexpected root ID exclusion filter: %q", clause)+ }+ if countPlaceholder(clause) != len(args) || len(rootIDs) != len(args) {+ t.Fatalf("root ID filter placeholder/arg mismatch: %q vs %d args", clause, len(args))+ }+ for i, arg := range args {+ if rootIDs[i] != arg {+ t.Fatalf("root ID arg %d should be %q, got %v", i, rootIDs[i], arg)+ }+ }++ clause, args = buildRootIDExclusionFilter(nil)+ if "" != clause || 0 != len(args) {+ t.Fatalf("empty root IDs should not generate a filter: %q, %v", clause, args)+ }+}++func TestNormalizeBoxName(t *testing.T) {+ name := " notebook/name\x00 "+ if normalized := normalizeBoxName(name); "notebookname" != normalized {+ t.Fatalf("unexpected normalized notebook name: %q", normalized)+ }+}+func countPlaceholder(s string) (n int) {for i := 0; i < len(s); i++ {if s[i] == '?' {diff --git a/kernel/model/storage.go b/kernel/model/storage.goindex 26178bbec6..15125180a2 100644--- a/kernel/model/storage.go+++ b/kernel/model/storage.go@@ -480,7 +480,6 @@ func getRecentDocs(sortBy string) (ret []*RecentDoc, err error) {changed = truecontinue}-// 文档块可能已经转换成标题块 https://github.com/siyuan-note/siyuan/pull/16727#issuecomment-3810081850if doc.RootID != bt.RootID {changed = true@@ -521,12 +520,30 @@ func getRecentDocs(sortBy string) (ret []*RecentDoc, err error) {logging.LogErrorf("update storage [recent-doc] failed in getRecentDocs: %s", errSet)}}+ if !IsBoxDocEnabled() {+ filtered := make([]*RecentDoc, 0, len(ret))+ for _, doc := range ret {+ bt := bts[doc.RootID]+ if nil == bt || !IsBoxDoc(bt.BoxID, bt.RootID) {+ filtered = append(filtered, doc)+ }+ }+ ret = filtered+ }// 根据排序参数进行排序switch sortBy {case "updated": // 按更新时间排序// 从数据库查询最近修改的文档- sqlBlocks := sql.SelectBlocksRawStmt("SELECT * FROM blocks WHERE type = 'd' ORDER BY updated DESC", 1, Conf.FileTree.RecentDocsMaxListCount)+ boxDocFilter, boxDocArgs := buildRootIDExclusionFilter(hiddenBoxDocRootIDs())+ var sqlBlocks []*sql.Block+ if "" == boxDocFilter {+ sqlBlocks = sql.SelectBlocksRawStmt("SELECT * FROM blocks WHERE type = 'd' ORDER BY updated DESC", 1, Conf.FileTree.RecentDocsMaxListCount)+ } else {+ stmt := "SELECT * FROM blocks WHERE type = 'd'" + boxDocFilter + " ORDER BY updated DESC" ++ fmt.Sprintf(" LIMIT %d", Conf.FileTree.RecentDocsMaxListCount)+ sqlBlocks = sql.SelectBlocksRawStmtArgs(stmt, boxDocArgs, Conf.FileTree.RecentDocsMaxListCount)+ }ret = []*RecentDoc{}if 1 > len(sqlBlocks) {returndiff --git a/kernel/sql/fts_bench_test.go b/kernel/sql/fts_bench_test.godeleted file mode 100644index 064a1eae01..0000000000--- a/kernel/sql/fts_bench_test.go+++ /dev/null@@ -1,452 +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 sql--// 本文件为 blocks_fts 改造为 FTS5 external-content 模式后的性能基准测试,量化写入/查询/重建开销。-// https://github.com/siyuan-note/siyuan/issues/17540-//-// 运行(需 fts5 build tag,FTS5 是可选编译):-//-// cd kernel-// go test -vet=off -tags=fts5 -run=^$ -bench=BenchmarkFTS -benchmem -benchtime=5x ./sql/-// go test -vet=off -tags=fts5 -run=TestFTSBenchStorage -v ./sql/-//-// 调整 genBlock 中正文段落的重复次数可在大小内容场景间切换。-vet=off 用于跳过 queue*.go 里-// 既有的、与本测试无关的 vet 警告。测试在临时数据库上执行,结束自动清理,不影响真实数据。--import (- "database/sql"- "fmt"- "os"- "path/filepath"- "strconv"- "strings"- "testing"-- _ "github.com/mattn/go-sqlite3"-)--// ftsBenchDB 封装一次基准测试的数据库句柄与 DDL 模式。-type ftsBenchDB struct {- db *sql.DB- path string- mode string // "standard" 或 "external"-}--// newFTSBenchDB 在临时路径创建数据库,并按指定模式建表。-func newFTSBenchDB(mode string) (*ftsBenchDB, error) {- tmpDir, err := os.MkdirTemp("", "fts-bench-*")- if err != nil {- return nil, err- }- dbPath := filepath.Join(tmpDir, "bench.db")- dsn := dbPath + "?_journal_mode=WAL&_synchronous=OFF&_cache_size=-128000&_page_size=32768&_busy_timeout=7000"- // 使用内核注册的 sqlite3_extended 驱动(带 regexp 函数,且 fork 的 amalgamation 内置 FTS5 + siyuan 分词器)- db, err := sql.Open("sqlite3_extended", dsn)- if err != nil {- os.RemoveAll(tmpDir)- return nil, err- }- db.SetMaxOpenConns(1)-- b := &ftsBenchDB{db: db, path: tmpDir, mode: mode}- if err = b.createTables(mode); err != nil {- db.Close()- os.RemoveAll(tmpDir)- return nil, err- }- return b, nil-}--func (b *ftsBenchDB) close() {- if b.db != nil {- b.db.Close()- }- if b.path != "" {- os.RemoveAll(b.path)- }-}--// createTables 按指定模式创建 blocks 与 blocks_fts。-func (b *ftsBenchDB) createTables(mode string) error {- _, err := b.db.Exec("CREATE TABLE blocks (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated)")- if err != nil {- return err- }- _, err = b.db.Exec("CREATE INDEX idx_blocks_id ON blocks(id)")- if err != nil {- return err- }- _, err = b.db.Exec("CREATE INDEX idx_blocks_root_id ON blocks(root_id)")- if err != nil {- return err- }-- cols := "id UNINDEXED, parent_id UNINDEXED, root_id UNINDEXED, hash UNINDEXED, box UNINDEXED, path UNINDEXED, hpath UNINDEXED, name, alias, memo, tag, content, fcontent, markdown UNINDEXED, length UNINDEXED, type UNINDEXED, subtype UNINDEXED, ial, sort UNINDEXED, created UNINDEXED, updated UNINDEXED"- var ddl string- switch mode {- case "standard":- ddl = "CREATE VIRTUAL TABLE blocks_fts USING fts5(" + cols + ", tokenize=\"siyuan case_insensitive\")"- case "external":- ddl = "CREATE VIRTUAL TABLE blocks_fts USING fts5(" + cols + ", content='blocks', content_rowid='rowid', tokenize=\"siyuan case_insensitive\")"- default:- return fmt.Errorf("unknown mode: %s", mode)- }- _, err = b.db.Exec(ddl)- return err-}--// createFTSTable 只重建 FTS 虚表(不动 blocks),用于 rebuild 基准测试。-func (b *ftsBenchDB) createFTSTable(mode string) error {- if _, err := b.db.Exec("DROP TABLE IF EXISTS blocks_fts"); err != nil {- return err- }- cols := "id UNINDEXED, parent_id UNINDEXED, root_id UNINDEXED, hash UNINDEXED, box UNINDEXED, path UNINDEXED, hpath UNINDEXED, name, alias, memo, tag, content, fcontent, markdown UNINDEXED, length UNINDEXED, type UNINDEXED, subtype UNINDEXED, ial, sort UNINDEXED, created UNINDEXED, updated UNINDEXED"- var ddl string- switch mode {- case "standard":- ddl = "CREATE VIRTUAL TABLE blocks_fts USING fts5(" + cols + ", tokenize=\"siyuan case_insensitive\")"- case "external":- ddl = "CREATE VIRTUAL TABLE blocks_fts USING fts5(" + cols + ", content='blocks', content_rowid='rowid', tokenize=\"siyuan case_insensitive\")"- default:- return fmt.Errorf("unknown mode: %s", mode)- }- _, err := b.db.Exec(ddl)- return err-}--// genBlock 生成一个用于基准测试的 block(content 含中英文长正文,模拟真实笔记段落)。-// 正文体量约 2KB,贴近真实长笔记,放大 external-content 省影子表写的收益。-func genBlock(i, root int) []any {- para := "这是一段用于基准测试的中英文混排正文。SiYuan 是一款本地优先的个人知识管理系统,支持块级引用、双链、全文搜索与闪卡复习。" +- "The quick brown fox jumps over the lazy dog. 代码示例:func main() { println(\"hello world\"); for i := 0; i < 10; i++ { go work(i) } }。" +- "思源笔记使用 SQLite FTS5 提供全文检索能力,配合自定义的 siyuan 分词器处理中英文及 CJK 字符的逐字切分。"- // 重复约 10 次凑到 ~2KB- var bld strings.Builder- for range 10 {- bld.WriteString(para)- }- content := bld.String()- return []any{- fmt.Sprintf("%020d", i), // id- fmt.Sprintf("%020d", root), // parent_id- fmt.Sprintf("%020d", root), // root_id- fmt.Sprintf("hash%d", i), // hash- "20230201000", // box- fmt.Sprintf("/p/%020d.sy", root), // path- fmt.Sprintf("/文档%d", root), // hpath- fmt.Sprintf("块名%d", i), // name- "alias", // alias- "memo", // memo- "tag", // tag- content, // content- content, // fcontent- fmt.Sprintf("markdown %d", i), // markdown- len(content), // length- "p", // type- "", // subtype- "{: id=\"ial\"}", // ial- i, // sort- "20230101000000", // created- "20230101000000", // updated- }-}--// insertBlocksStandard 标准模式:成对写 blocks 与 blocks_fts(原 insertBlocks0 逻辑)。-func (b *ftsBenchDB) insertBlocksStandard(bulk [][]any) error {- if len(bulk) == 0 {- return nil- }- ph := "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"- placeholderRows := make([]string, len(bulk))- for i := range placeholderRows {- placeholderRows[i] = ph- }- args := make([]any, 0, len(bulk)*21)- for _, blk := range bulk {- args = append(args, blk...)- }- joined := strings.Join(placeholderRows, ",")- if _, err := b.db.Exec("INSERT INTO blocks (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated) VALUES "+joined, args...); err != nil {- return err- }- if _, err := b.db.Exec("INSERT INTO blocks_fts (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated) VALUES "+joined, args...); err != nil {- return err- }- return nil-}--// insertBlocksExternal external-content 模式:插 blocks 后反查 rowid 再带 rowid 插 FTS。-func (b *ftsBenchDB) insertBlocksExternal(bulk [][]any) error {- if len(bulk) == 0 {- return nil- }- ph := "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"- placeholderRows := make([]string, len(bulk))- for i := range placeholderRows {- placeholderRows[i] = ph- }- args := make([]any, 0, len(bulk)*21)- for _, blk := range bulk {- args = append(args, blk...)- }- joined := strings.Join(placeholderRows, ",")- if _, err := b.db.Exec("INSERT INTO blocks (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated) VALUES "+joined, args...); err != nil {- return err- }-- // 反查 rowid(按 id 用 map 对齐)- idList := make([]string, len(bulk))- for i, blk := range bulk {- idList[i] = "\"" + blk[0].(string) + "\""- }- rows, err := b.db.Query("SELECT id, ROWID FROM blocks WHERE id IN (" + strings.Join(idList, ",") + ")")- if err != nil {- return err- }- rowIDMap := map[string]int64{}- for rows.Next() {- var id string- var rid int64- if err = rows.Scan(&id, &rid); err != nil {- rows.Close()- return err- }- rowIDMap[id] = rid- }- rows.Close()-- // 拼 FTS 写入参数(首列 rowid)- ftsPH := "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"- ftsRows := make([]string, len(bulk))- for i := range ftsRows {- ftsRows[i] = ftsPH- }- ftsArgs := make([]any, 0, len(bulk)*22)- for _, blk := range bulk {- id := blk[0].(string)- rid, ok := rowIDMap[id]- if !ok {- return fmt.Errorf("rowid not found for %s", id)- }- ftsArgs = append(ftsArgs, rid)- ftsArgs = append(ftsArgs, blk...)- }- if _, err := b.db.Exec("INSERT INTO blocks_fts (rowid, id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated) VALUES "+strings.Join(ftsRows, ","), ftsArgs...); err != nil {- return err- }- return nil-}--// insertBatch 按模式分派插入。-func (b *ftsBenchDB) insertBatch(bulk [][]any) error {- if b.mode == "external" {- return b.insertBlocksExternal(bulk)- }- return b.insertBlocksStandard(bulk)-}--// rebuild 重建 FTS 索引(标准模式用 INSERT...SELECT,external 用 'rebuild')。-func (b *ftsBenchDB) rebuild() error {- if b.mode == "external" {- _, err := b.db.Exec("INSERT INTO blocks_fts(blocks_fts) VALUES('rebuild')")- return err- }- _, err := b.db.Exec("INSERT INTO blocks_fts (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated) SELECT id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated FROM blocks")- return err-}--// queryFTS 执行一次带 snippet 的 FTS 搜索,返回命中行数,模拟 fullTextSearchByFTS。-func (b *ftsBenchDB) queryFTS(keyword string, limit int) (int, error) {- stmt := "SELECT id, snippet(blocks_fts, 11, '__@mark__', '__mark@__', '...', 512) AS content, fcontent, markdown, type FROM blocks_fts WHERE blocks_fts MATCH '{content name tag}:(\"" + keyword + "\")' LIMIT " + strconv.Itoa(limit)- rows, err := b.db.Query(stmt)- if err != nil {- return 0, err- }- count := 0- for rows.Next() {- count++- var id, content, fcontent, markdown, typ string- rows.Scan(&id, &content, &fcontent, &markdown, &typ)- }- return count, rows.Err()-}--// seedData 在指定模式下填充 nRoots × nBlocksPerRoot 个块。-func (b *ftsBenchDB) seedData(nRoots, nBlocksPerRoot int, batch int) error {- var bulk [][]any- idx := 0- for r := range nRoots {- for range nBlocksPerRoot {- bulk = append(bulk, genBlock(idx, r))- idx++- if len(bulk) >= batch {- if err := b.insertBatch(bulk); err != nil {- return err- }- bulk = bulk[:0]- }- }- }- if len(bulk) > 0 {- if err := b.insertBatch(bulk); err != nil {- return err- }- }- return nil-}--// dbFileSize 返回数据库文件大小(字节)。-func (b *ftsBenchDB) dbFileSize() (int64, error) {- entries, err := os.ReadDir(b.path)- if err != nil {- return 0, err- }- var total int64- for _, e := range entries {- info, err := e.Info()- if err != nil {- continue- }- total += info.Size()- }- return total, nil-}--// benchSize 控制基准测试的数据规模:可在编译时用 -ldflags 调整,这里给一个默认值。-const benchRoots = 50-const benchBlocksPerRoot = 100 // 共 5000 块--// BenchmarkFTSInsert 对比两种模式的批量 INSERT 性能。-func BenchmarkFTSInsertStandard(b *testing.B) {- for i := 0; i < b.N; i++ {- b.StopTimer()- db, err := newFTSBenchDB("standard")- if err != nil {- b.Fatal(err)- }- b.StartTimer()- if err := db.seedData(benchRoots, benchBlocksPerRoot, 512); err != nil {- db.close()- b.Fatal(err)- }- b.StopTimer()- db.close()- b.StartTimer()- }-}--func BenchmarkFTSInsertExternal(b *testing.B) {- for i := 0; i < b.N; i++ {- b.StopTimer()- db, err := newFTSBenchDB("external")- if err != nil {- b.Fatal(err)- }- b.StartTimer()- if err := db.seedData(benchRoots, benchBlocksPerRoot, 512); err != nil {- db.close()- b.Fatal(err)- }- b.StopTimer()- db.close()- b.StartTimer()- }-}--// BenchmarkFTSRebuild 对比两种模式的 FTS 索引重建性能。-func BenchmarkFTSRebuildStandard(b *testing.B) {- db, err := newFTSBenchDB("standard")- if err != nil {- b.Fatal(err)- }- defer db.close()- if err := db.seedData(benchRoots, benchBlocksPerRoot, 512); err != nil {- b.Fatal(err)- }- // 先 DROP FTS 再重建,模拟 RebuildFTSIndex(blocks 表保留不动)- b.ResetTimer()- for i := 0; i < b.N; i++ {- if err := db.createFTSTable("standard"); err != nil {- b.Fatal(err)- }- if err := db.rebuild(); err != nil {- b.Fatal(err)- }- }-}--func BenchmarkFTSRebuildExternal(b *testing.B) {- db, err := newFTSBenchDB("external")- if err != nil {- b.Fatal(err)- }- defer db.close()- if err := db.seedData(benchRoots, benchBlocksPerRoot, 512); err != nil {- b.Fatal(err)- }- b.ResetTimer()- for i := 0; i < b.N; i++ {- if err := db.createFTSTable("external"); err != nil {- b.Fatal(err)- }- if err := db.rebuild(); err != nil {- b.Fatal(err)- }- }-}--// BenchmarkFTSQuery 对比两种模式的搜索查询性能(含 snippet 回表开销)。-// 数据预填充,只测查询本身。-func benchFTSQuery(b *testing.B, mode, keyword string) {- db, err := newFTSBenchDB(mode)- if err != nil {- b.Fatal(err)- }- defer db.close()- if err := db.seedData(benchRoots, benchBlocksPerRoot, 512); err != nil {- b.Fatal(err)- }- b.ResetTimer()- for i := 0; i < b.N; i++ {- if _, err := db.queryFTS(keyword, 50); err != nil {- b.Fatal(err)- }- }-}--func BenchmarkFTSQueryChineseStandard(b *testing.B) { benchFTSQuery(b, "standard", "中文") }-func BenchmarkFTSQueryChineseExternal(b *testing.B) { benchFTSQuery(b, "external", "中文") }-func BenchmarkFTSQueryEnglishStandard(b *testing.B) { benchFTSQuery(b, "standard", "code") }-func BenchmarkFTSQueryEnglishExternal(b *testing.B) { benchFTSQuery(b, "external", "code") }--// TestFTSBenchStorage 是普通测试(非 benchmark),打印两种模式下的数据库文件大小对比。-func TestFTSBenchStorage(t *testing.T) {- for _, mode := range []string{"standard", "external"} {- db, err := newFTSBenchDB(mode)- if err != nil {- t.Fatal(err)- }- if err := db.seedData(benchRoots, benchBlocksPerRoot, 512); err != nil {- db.close()- t.Fatal(err)- }- size, _ := db.dbFileSize()- t.Logf("[%s] 数据库文件总大小: %d 字节 (%.2f MB),共 %d 块", mode, size, float64(size)/1024/1024, benchRoots*benchBlocksPerRoot)- db.close()- }-}