Skip to content

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

:zap: Query bookmarks through indexed block attributes https://github.com/siyuan-note/siyuan/issues/20250

Daniel3e4ca3106e00
diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.go
index 865faaa93e..575c6c304e 100644
--- a/kernel/sql/block_query.go
+++ b/kernel/sql/block_query.go
@@ -314,9 +314,11 @@ func queryDocTitles(searchIgnoreLines []string, boxIDs ...string) (ret []string)
return
}
+const bookmarkBlockPredicate = "id IN (SELECT block_id FROM attributes WHERE name = 'bookmark' AND type = 'b')"
+
func QueryBookmarkBlocks() (ret []*Block) {
- sqlStmt := "SELECT * FROM blocks WHERE ial LIKE ?"
- rows, err := query(sqlStmt, "%bookmark=%")
+ sqlStmt := "SELECT * FROM blocks WHERE " + bookmarkBlockPredicate
+ rows, err := query(sqlStmt)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
return
@@ -338,8 +340,8 @@ type BookmarkLabelBlock struct {
func QueryBookmarkLabelBlocks() (ret []*BookmarkLabelBlock) {
ret = []*BookmarkLabelBlock{}
- sqlStmt := "SELECT ial, box, path FROM blocks WHERE ial LIKE ?"
- rows, err := query(sqlStmt, "%bookmark=%")
+ sqlStmt := "SELECT ial, box, path FROM blocks WHERE " + bookmarkBlockPredicate
+ rows, err := query(sqlStmt)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
return
diff --git a/kernel/sql/bookmark_index_fts5_test.go b/kernel/sql/bookmark_index_fts5_test.go
new file mode 100644
index 0000000000..bd9ba4ccda
--- /dev/null
+++ b/kernel/sql/bookmark_index_fts5_test.go
@@ -0,0 +1,37 @@
+//go:build fts5
+
+package sql
+
+import "testing"
+
+func TestBookmarkIndexDatabaseInitialization(t *testing.T) {
+ for _, encrypted := range []bool{false, true} {
+ database := newDeletePathTestDB(t, encrypted)
+ for _, name := range []string{"idx_attributes_bookmark_block_id", "idx_spans_tag_path"} {
+ var count int
+ if err := database.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = ?", name).Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if count != 1 {
+ t.Fatalf("encrypted=%v: index %s missing", encrypted, name)
+ }
+ }
+ if _, err := database.Exec("INSERT INTO attributes VALUES ('bookmark', 'bookmark', '<b>', 'b', 'block', 'root', 'box', '/doc.sy')"); err != nil {
+ t.Fatal(err)
+ }
+ if encrypted {
+ if err := initEncryptedDBTables(database); err != nil {
+ t.Fatal(err)
+ }
+ } else if err := ensureBookmarkAttributesIndex(database); err != nil {
+ t.Fatal(err)
+ }
+ var value string
+ if err := database.QueryRow("SELECT value FROM attributes WHERE id = 'bookmark'").Scan(&value); err != nil {
+ t.Fatal(err)
+ }
+ if value != "<b>" {
+ t.Fatal("index initialization changed stored bookmark data")
+ }
+ }
+}
diff --git a/kernel/sql/bookmark_index_test.go b/kernel/sql/bookmark_index_test.go
new file mode 100644
index 0000000000..c6f4ad6fe7
--- /dev/null
+++ b/kernel/sql/bookmark_index_test.go
@@ -0,0 +1,117 @@
+package sql
+
+import (
+ "html"
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestBookmarkAttributesFollowBlockIAL(t *testing.T) {
+ engine := util.NewLute()
+ for _, typed := range []string{"R&D", "<b>", "&lt;b&gt;", `"quoted"`, ""} {
+ tree := parse.Parse("", []byte("hello"), engine.ParseOptions)
+ tree.Root.ID = "20261008000000-root001"
+ tree.Box, tree.Path = "box", "/doc.sy"
+ node := tree.Root.FirstChild
+ node.ID = "20261008000000-block01"
+ node.SetIALAttr("bookmark", typed)
+ block, attrs := buildBlockFromNode(node, tree)
+ found := false
+ for _, attr := range attrs {
+ if attr.Name == "bookmark" {
+ found = true
+ if attr.Type != "b" || attr.BlockID != block.ID || attr.Value != typed ||
+ html.UnescapeString(ialAttr(block.IAL, "bookmark")) != typed {
+ t.Fatalf("bookmark attribute does not match block IAL: attr=%+v block=%+v", attr, block)
+ }
+ }
+ }
+ if !found {
+ t.Fatalf("bookmark %q missing from block attributes", typed)
+ }
+ }
+}
+
+func TestBookmarkIndexPreservesBlockFieldsAndLabels(t *testing.T) {
+ database := createGraphTestBlocksTable(t)
+ previous := db
+ db = database
+ t.Cleanup(func() { db = previous })
+ for _, stmt := range []string{
+ "CREATE INDEX idx_blocks_id ON blocks(id)",
+ "CREATE TABLE attributes (id, name, value, type, block_id, root_id, box, path)",
+ } {
+ if _, err := database.Exec(stmt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ labels := []string{"R&amp;D", "&amp;lt;b&amp;gt;", "&quot;quoted&quot;", ""}
+ for i, label := range labels {
+ id := string(rune('a' + i))
+ ial := `{: bookmark="` + label + `"}`
+ if _, err := database.Exec("INSERT INTO blocks VALUES (?, '', ?, '', 'box', ?, '/doc', 'name', '', '', '', 'content', '', 'markdown', 8, 'p', '', ?, 0, '2026', '2027')", id, "root-"+id, "/"+id+".sy", ial); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := database.Exec("INSERT INTO attributes VALUES (?, 'bookmark', ?, 'b', ?, ?, 'box', ?)", id, label, id, "root-"+id, "/"+id+".sy"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // 同一块的重复属性不能产生重复书签,行级属性不能被当成块书签。
+ if _, err := database.Exec("INSERT INTO attributes SELECT 'duplicate', name, value, type, block_id, root_id, box, path FROM attributes WHERE block_id = 'a'"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := database.Exec("INSERT INTO attributes VALUES ('span', 'bookmark', 'inline', 's', 'child', 'root', '', '/')"); err != nil {
+ t.Fatal(err)
+ }
+ rows, err := database.Query("SELECT * FROM blocks WHERE ial LIKE '%bookmark=%' ORDER BY id")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var before []*Block
+ for rows.Next() {
+ before = append(before, scanBlockRows(rows))
+ }
+ if err = rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ rows.Close()
+ for i := 0; i < 2; i++ {
+ if err = ensureBookmarkAttributesIndex(database); err != nil {
+ t.Fatal(err)
+ }
+ }
+ blocks := QueryBookmarkBlocks()
+ sort.Slice(blocks, func(i, j int) bool { return blocks[i].ID < blocks[j].ID })
+ if !reflect.DeepEqual(blocks, before) {
+ t.Fatalf("bookmark block fields changed: before=%+v after=%+v", before, blocks)
+ }
+ labelBlocks := QueryBookmarkLabelBlocks()
+ sort.Slice(labelBlocks, func(i, j int) bool { return labelBlocks[i].Path < labelBlocks[j].Path })
+ want := []*BookmarkLabelBlock{{Label: labels[0], Box: "box", Path: "/a.sy"},
+ {Label: labels[1], Box: "box", Path: "/b.sy"}, {Label: labels[2], Box: "box", Path: "/c.sy"}}
+ if !reflect.DeepEqual(labelBlocks, want) {
+ t.Fatalf("bookmark label encoding or paths changed: %+v", labelBlocks)
+ }
+ wantLabels := append([]string(nil), labels[:3]...)
+ sort.Strings(wantLabels)
+ if actual := QueryBookmarkLabels(); !reflect.DeepEqual(actual, wantLabels) {
+ t.Fatalf("labels=%v want=%v", actual, wantLabels)
+ }
+ for _, columns := range []string{"*", "ial, box, path"} {
+ plan := queryPlanDetails(t, database, "SELECT "+columns+" FROM blocks WHERE "+bookmarkBlockPredicate)
+ if !strings.Contains(plan, "idx_attributes_bookmark_block_id") || !strings.Contains(plan, "SEARCH blocks USING INDEX idx_blocks_id") {
+ t.Fatalf("bookmark query does not use indexed attribute lookup: %s", plan)
+ }
+ }
+ if _, err = database.Exec("DELETE FROM attributes WHERE name = 'bookmark' AND type = 'b'"); err != nil {
+ t.Fatal(err)
+ }
+ if len(QueryBookmarkBlocks()) != 0 || len(QueryBookmarkLabels()) != 0 {
+ t.Fatal("removed bookmark attributes still produce bookmarks")
+ }
+}
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index fef35fb64a..798712dfa6 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -131,6 +131,9 @@ func initDatabase(forceRebuild bool) {
if err := ensureTagSpansIndex(db); err != nil {
logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create tag spans index failed: %s", err)
}
+ if err := ensureBookmarkAttributesIndex(db); err != nil {
+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create bookmark attributes index failed: %s", err)
+ }
if err := cleanupInvalidRefs(db); err != nil {
logging.LogErrorf("cleanup invalid refs failed: %s", err)
}
@@ -258,6 +261,9 @@ func initDBTables() {
if err != nil {
logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create index [idx_attributes_root_id] failed: %s", err)
}
+ if err = ensureBookmarkAttributesIndex(db); err != nil {
+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create bookmark attributes index failed: %s", err)
+ }
_, err = db.Exec("DROP TABLE IF EXISTS refs")
if err != nil {
@@ -1443,6 +1449,11 @@ func ensureTagSpansIndex(database *sql.DB) (err error) {
return
}
+func ensureBookmarkAttributesIndex(database *sql.DB) (err error) {
+ _, err = database.Exec("CREATE INDEX IF NOT EXISTS idx_attributes_bookmark_block_id ON attributes(block_id) WHERE name = 'bookmark' AND type = 'b'")
+ return
+}
+
func ensureRefsDefIndexes(database *sql.DB) (err error) {
if _, err = database.Exec("CREATE INDEX IF NOT EXISTS idx_refs_def_block_id ON refs(def_block_id)"); err != nil {
return
@@ -2113,6 +2124,9 @@ func initEncryptedDBTables(boxDB *sql.DB) (err error) {
if err = ensureTagSpansIndex(boxDB); err != nil {
return
}
+ if err = ensureBookmarkAttributesIndex(boxDB); err != nil {
+ return
+ }
if err = cleanupInvalidRefs(boxDB); err != nil {
return
}