Skip to content

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

:zap: Index annotation references while preserving legacy suffixes https://github.com/siyuan-note/siyuan/issues/20260

Daniel8c98c994ff95
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index 498f6a3bfb..5f9d9d39f9 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -137,6 +137,9 @@ func initDatabase(forceRebuild bool) {
if err := ensureDailyNoteAttributesIndex(db); err != nil {
logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create daily note attributes index failed: %s", err)
}
+ if err := ensureFileAnnotationRefIndex(db); err != nil {
+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create file annotation reference index failed: %s", err)
+ }
if err := ensureRecentUpdatedBlocksIndexes(db); err != nil {
logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create recent updated block indexes failed: %s", err)
}
@@ -297,6 +300,9 @@ func initDBTables() {
if err != nil {
logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create table [refs] failed: %s", err)
}
+ if err = ensureFileAnnotationRefIndex(db); err != nil {
+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create file annotation reference index failed: %s", err)
+ }
_, err = db.Exec("DROP TABLE IF EXISTS block_embeddings")
if err != nil {
@@ -1480,6 +1486,11 @@ func ensureDailyNoteAttributesIndex(database *sql.DB) (err error) {
return
}
+func ensureFileAnnotationRefIndex(database *sql.DB) (err error) {
+ _, err = database.Exec("CREATE INDEX IF NOT EXISTS idx_file_annotation_refs_annotation_id ON file_annotation_refs(annotation_id)")
+ 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
@@ -2159,6 +2170,9 @@ func initEncryptedDBTables(boxDB *sql.DB) (err error) {
if err = ensureDailyNoteAttributesIndex(boxDB); err != nil {
return
}
+ if err = ensureFileAnnotationRefIndex(boxDB); err != nil {
+ return
+ }
if err = cleanupInvalidRefs(boxDB); err != nil {
return
}
diff --git a/kernel/sql/file_annotation_ref.go b/kernel/sql/file_annotation_ref.go
index 5f36c0b1e6..75adfd5bee 100644
--- a/kernel/sql/file_annotation_ref.go
+++ b/kernel/sql/file_annotation_ref.go
@@ -17,9 +17,14 @@
package sql
import (
+ "unicode/utf8"
+
"github.com/siyuan-note/logging"
)
+const fileAnnotationRefQuery = "SELECT block_id FROM file_annotation_refs WHERE annotation_id = ? " +
+ "OR (annotation_id >= ? AND annotation_id < ?) OR (annotation_id >= ? AND annotation_id < ?)"
+
type FileAnnotationRef struct {
ID string
FilePath string
@@ -39,8 +44,14 @@ func QueryRefIDsByAnnotationID(annotationID string) (refIDs []string) {
func QueryRefIDsByAnnotationIDInBox(annotationID, boxID string) (refIDs []string) {
refIDs = []string{}
// 兼容已持久化的带查询参数或片段的标注索引,新建索引只保存纯标注 ID。
- rows, err := queryForBox(boxID, "SELECT block_id FROM file_annotation_refs WHERE annotation_id = ? "+
- "OR substr(annotation_id, 1, ?) IN (?, ?)", annotationID, len(annotationID)+1, annotationID+"?", annotationID+"#")
+ stmt := fileAnnotationRefQuery
+ args := []any{annotationID, annotationID + "?", annotationID + "@", annotationID + "#", annotationID + "$"}
+ // 非 ASCII 参数保留按字节长度截取的既有查询语义,标准标注 ID 使用可索引的范围条件。
+ if len(annotationID) != utf8.RuneCountInString(annotationID) {
+ stmt = "SELECT block_id FROM file_annotation_refs WHERE annotation_id = ? OR substr(annotation_id, 1, ?) IN (?, ?)"
+ args = []any{annotationID, len(annotationID) + 1, annotationID + "?", annotationID + "#"}
+ }
+ rows, err := queryForBox(boxID, stmt, args...)
if err != nil {
logging.LogErrorf("sql query failed: %s", err)
return
diff --git a/kernel/sql/file_annotation_ref_index_fts5_test.go b/kernel/sql/file_annotation_ref_index_fts5_test.go
new file mode 100644
index 0000000000..d6752595c9
--- /dev/null
+++ b/kernel/sql/file_annotation_ref_index_fts5_test.go
@@ -0,0 +1,18 @@
+//go:build fts5
+
+package sql
+
+import "testing"
+
+func TestFileAnnotationRefIndexDatabaseInitialization(t *testing.T) {
+ for _, encrypted := range []bool{false, true} {
+ database := newDeletePathTestDB(t, encrypted)
+ var count int
+ if err := database.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'idx_file_annotation_refs_annotation_id'").Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if count != 1 {
+ t.Fatalf("encrypted=%v: annotation reference index missing", encrypted)
+ }
+ }
+}
diff --git a/kernel/sql/file_annotation_ref_test.go b/kernel/sql/file_annotation_ref_test.go
index 266788696e..10f772b460 100644
--- a/kernel/sql/file_annotation_ref_test.go
+++ b/kernel/sql/file_annotation_ref_test.go
@@ -7,6 +7,8 @@ package sql
import (
stdsql "database/sql"
"reflect"
+ "sort"
+ "strings"
"testing"
"github.com/88250/lute/ast"
@@ -14,6 +16,60 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+func TestAnnotationRefRangeQueryPreservesExistingMatches(t *testing.T) {
+ previousDB := db
+ testDB, err := stdsql.Open("sqlite3", ":memory:")
+ if err != nil {
+ t.Fatal(err)
+ }
+ db = testDB
+ t.Cleanup(func() { db = previousDB; testDB.Close() })
+ if _, err = db.Exec("CREATE TABLE file_annotation_refs (block_id, annotation_id)"); err != nil {
+ t.Fatal(err)
+ }
+ for range 2 {
+ if err = ensureFileAnnotationRefIndex(db); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, id := range []string{"20261008000000-abcdefg", "", "a%_'\\", "标注"} {
+ if _, err = db.Exec("DELETE FROM file_annotation_refs"); err != nil {
+ t.Fatal(err)
+ }
+ for _, stored := range []string{id, id, id + "?", id + "?box=notebook", id + "#", id + "#view", id + "?中文", id + "@", id + "$", id + "x", "x" + id} {
+ if _, err = db.Exec("INSERT INTO file_annotation_refs VALUES (?, ?)", stored, stored); err != nil {
+ t.Fatal(err)
+ }
+ }
+ rows, err := db.Query("SELECT block_id FROM file_annotation_refs WHERE annotation_id = ? OR substr(annotation_id, 1, ?) IN (?, ?)", id, len(id)+1, id+"?", id+"#")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var before []string
+ for rows.Next() {
+ var blockID string
+ if err = rows.Scan(&blockID); err != nil {
+ t.Fatal(err)
+ }
+ before = append(before, blockID)
+ }
+ if err = rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ rows.Close()
+ after := QueryRefIDsByAnnotationID(id)
+ sort.Strings(before)
+ sort.Strings(after)
+ if !reflect.DeepEqual(before, after) {
+ t.Fatalf("annotation %q changed matches: before=%v after=%v", id, before, after)
+ }
+ }
+ plan := queryPlanDetails(t, db, fileAnnotationRefQuery, "id", "id?", "id@", "id#", "id$")
+ if strings.Count(plan, "SEARCH file_annotation_refs USING INDEX idx_file_annotation_refs_annotation_id") != 3 || strings.Contains(plan, "SCAN file_annotation_refs") {
+ t.Fatalf("annotation reference query still scans the table: %s", plan)
+ }
+}
+
func TestFileAnnotationRefsFromTree(t *testing.T) {
const id = "20260912000000-abcdefg"
for _, asset := range []string{"assets/a.pdf", "assets/a-20260912000001-abcdefg.pdf", "assets/folder/文档.PDF"} {