Skip to content

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

:bug: Respect block search filters and literal keywords https://github.com/siyuan-note/siyuan/issues/20919

Daniel2ed8a0b0586a
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-l3qg72k.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-l3qg72k.sy
index 60ab04b2a8..727ca5dca1 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-l3qg72k.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-l3qg72k.sy
@@ -7,7 +7,7 @@
"id": "20210808180303-l3qg72k",
"title": "Advanced search",
"type": "doc",
- "updated": "20261024164212"
+ "updated": "20261026182843"
},
"Children": [
{
@@ -44,7 +44,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20261009182324-t1r641c",
- "updated": "20261010113646"
+ "updated": "20261026182843"
},
"Children": [
{
@@ -59,12 +59,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009182324-1ulhib3",
- "updated": "20261009182324"
+ "updated": "20261026182843"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Keyword and query syntax searches support block-type, notebook and document-path filters, including child documents, as well as sorting, grouping and replacement. Content-order sorting is available only when grouping by document."
+ "Data": "Keyword and query syntax searches support block-type, notebook and document-path filters, including child documents, as well as sorting, grouping and replacement. Content-order sorting is available only when grouping by document. An exact block ID follows the same notebook, document-path, block-type, subtype and ignore filters. Multi-keyword searches in keyword mode match %, _ and backslashes literally. Grouping by document organizes only the current page and keeps the pagination unit of the selected search method; with block-based pagination, matches from one document can span several pages."
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-gyngv2x.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-gyngv2x.sy
index 0bf668439f..eb8233b03f 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-gyngv2x.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-gyngv2x.sy
@@ -7,7 +7,7 @@
"id": "20210808180320-gyngv2x",
"title": "搜索进阶",
"type": "doc",
- "updated": "20261024163828"
+ "updated": "20261026182843"
},
"Children": [
{
@@ -44,7 +44,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20261009182324-ljls7op",
- "updated": "20261010113646"
+ "updated": "20261026182843"
},
"Children": [
{
@@ -59,12 +59,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009182324-wscenpu",
- "updated": "20261009182324"
+ "updated": "20261026182843"
},
"Children": [
{
"Type": "NodeText",
- "Data": "关键字与查询语法搜索支持块类型、笔记本和文档路径筛选、包含子文档,以及排序、分组和替换。按内容顺序排序仅在按文档分组时可用。"
+ "Data": "关键字与查询语法搜索支持块类型、笔记本和文档路径筛选、包含子文档,以及排序、分组和替换。按内容顺序排序仅在按文档分组时可用。直接输入块 ID 时,同样遵循笔记本、文档路径、块类型、子类型和忽略条件。关键字模式的多词搜索会按字面量匹配 %、_ 和反斜杠。按文档分组只整理当前页的结果,不改变当前搜索方式的分页单位;按块分页时,同一文档的命中块可能分布在多页。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120933-vnjgwwh.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120933-vnjgwwh.sy
index d70028512b..dd5c71bc6c 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120933-vnjgwwh.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120933-vnjgwwh.sy
@@ -7,7 +7,7 @@
"id": "20211226120933-vnjgwwh",
"title": "搜索進階",
"type": "doc",
- "updated": "20261024163828"
+ "updated": "20261026182843"
},
"Children": [
{
@@ -44,7 +44,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20261009182324-g42svwc",
- "updated": "20261010113646"
+ "updated": "20261026182843"
},
"Children": [
{
@@ -59,12 +59,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009182324-g6i7omp",
- "updated": "20261009182324"
+ "updated": "20261026182843"
},
"Children": [
{
"Type": "NodeText",
- "Data": "關鍵字與查詢語法搜尋支援區塊類型、筆記本和文件路徑篩選、包含子文件,以及排序、分組和取代。依內容順序排序僅在依文件分組時可用。"
+ "Data": "關鍵字與查詢語法搜尋支援區塊類型、筆記本和文件路徑篩選、包含子文件,以及排序、分組和取代。依內容順序排序僅在依文件分組時可用。直接輸入區塊 ID 時,同樣遵循筆記本、文件路徑、區塊類型、子類型和忽略條件。關鍵字模式的多詞搜尋會依字面量比對 %、_ 和反斜線。依文件分組只整理目前頁面的結果,不改變目前搜尋方式的分頁單位;依區塊分頁時,同一文件的命中區塊可能分布在多頁。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-a91lmk2.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-a91lmk2.sy
index 8757b125ef..ac24347588 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-a91lmk2.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-a91lmk2.sy
@@ -8,7 +8,7 @@
"id": "20240530101000-a91lmk2",
"title": "高度な検索",
"type": "doc",
- "updated": "20261024164212"
+ "updated": "20261026182843"
},
"Children": [
{
@@ -45,7 +45,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20261009182324-svc2r56",
- "updated": "20261010113646"
+ "updated": "20261026182843"
},
"Children": [
{
@@ -60,12 +60,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009182324-duyze6a",
- "updated": "20261009182324"
+ "updated": "20261026182843"
},
"Children": [
{
"Type": "NodeText",
- "Data": "キーワード検索とクエリ構文検索では、ブロックタイプ、ノートブック、文書パス、子文書を含めるかどうかの絞り込みと、並べ替え、グループ化、置換を利用できます。本文の順序による並べ替えは、文書ごとにグループ化した場合のみ利用できます。"
+ "Data": "キーワード検索とクエリ構文検索では、ブロックタイプ、ノートブック、文書パス、子文書を含めるかどうかの絞り込みと、並べ替え、グループ化、置換を利用できます。本文の順序による並べ替えは、文書ごとにグループ化した場合のみ利用できます。ブロック ID を直接入力した場合も、ノートブック、文書パス、ブロックタイプ、サブタイプ、除外条件が適用されます。キーワード方式の複数語検索では、%、_、バックスラッシュを文字どおりに照合します。文書ごとのグループ化は現在のページの結果を整理するだけで、検索方式のページ分割単位は変わりません。ブロック単位でページ分割する場合、同じ文書の一致ブロックが複数ページに分かれることがあります。"
}
]
},
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index f094fcc810..f9fc02308d 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -7070,6 +7070,8 @@ export interface APIPOSTRoutes {
};
/**
* SQL 模式保留换行、注释与字面量大小写,支持带别名的完整块投影。
+ * 关键字和查询语法模式下,精确块 ID 仍遵循笔记本、文档路径、类型、子类型和忽略条件。
+ * 关键字模式的多词文档搜索按字面量匹配 %、_ 和反斜杠;按文档分组只整理当前页,不改变分页单位。
*/
"/api/search/fullTextSearchBlock": {
request: FullTextSearchBlockRequestInput;
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index d9e1c6910f..9f3e6135ff 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -848,6 +848,8 @@ var FindReplace = define[FindReplaceRequest, Null]("findReplace", "/api/search/f
var SemanticSearchBlock = define[SearchBlockRequest, SearchBlocksData]("semanticSearchBlock", "/api/search/semanticSearchBlock", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")
// SQL 模式保留换行、注释与字面量大小写,支持带别名的完整块投影。
+// 关键字和查询语法模式下,精确块 ID 仍遵循笔记本、文档路径、类型、子类型和忽略条件。
+// 关键字模式的多词文档搜索按字面量匹配 %、_ 和反斜杠;按文档分组只整理当前页,不改变分页单位。
var FullTextSearchBlock = define[FullTextSearchBlockRequest, *FullTextSearchBlockData]("fullTextSearchBlock", "/api/search/fullTextSearchBlock", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")
// SearchRefBlock 的 exactDocTitle 默认关闭,保留候选搜索行为;启用后仅匹配完整文档标题,
diff --git a/kernel/model/search.go b/kernel/model/search.go
index ee8935b90e..e191bc6fdf 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -1730,7 +1730,6 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlock
return
}
excludeFilter, excludeArgs := buildPublishAccessExclusionFilter(excludeBoxIDs, excludeDocIDs)
- excludeInline := buildPublishAccessExclusionInline(excludeBoxIDs, excludeDocIDs)
var ignoreFilter string
if ignoreLines := getSearchIgnoreLines(); 0 < len(ignoreLines) {
// Support ignore search results https://github.com/siyuan-note/siyuan/issues/10089
@@ -1756,7 +1755,7 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlock
boxArgs = append(boxArgs, excludeArgs...)
pathFilter, pathArgs := buildPathsFilter(paths)
if ast.IsNodeIDPattern(query) {
- blocks, matchedBlockCount, matchedRootCount = searchBySQLInBoxContext(ctx, "SELECT * FROM `blocks` WHERE `id` = '"+query+"'"+excludeInline, beforeLen, page, pageSize, boxID)
+ blocks, matchedBlockCount, matchedRootCount = searchByIDInBoxContext(ctx, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, beforeLen, page, pageSize, boxID)
} else {
blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSInBox(ctx, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
}
@@ -1783,7 +1782,7 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlock
boxArgs = append(boxArgs, excludeArgs...)
pathFilter, pathArgs := buildPathsFilter(paths)
if ast.IsNodeIDPattern(query) {
- blocks, matchedBlockCount, matchedRootCount = searchBySQLInBoxContext(ctx, "SELECT * FROM `blocks` WHERE `id` = '"+query+"'"+excludeInline, beforeLen, page, pageSize, boxID)
+ blocks, matchedBlockCount, matchedRootCount = searchByIDInBoxContext(ctx, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, beforeLen, page, pageSize, boxID)
} else {
if 2 > len(strings.Split(strings.TrimSpace(query), " ")) {
ftsQuery, hPathQuery := buildKeywordSearchQueries(query)
@@ -2059,22 +2058,6 @@ func buildPublishAccessExclusionFilter(boxIDs, docIDs []string, alias ...string)
return
}
-// buildPublishAccessExclusionInline 构造内联的发布访问排除子句,用于无绑定参数的原生 SQL 分支。
-// 排除 ID 均通过节点 ID 模式校验,可直接内联。
-func buildPublishAccessExclusionInline(boxIDs, docIDs []string) string {
- conds := make([]string, 0, len(boxIDs)+len(docIDs))
- for _, boxID := range boxIDs {
- conds = append(conds, "box = '"+boxID+"'")
- }
- for _, docID := range docIDs {
- conds = append(conds, "path LIKE '%"+docID+"%'")
- }
- if 0 == len(conds) {
- return ""
- }
- return " AND NOT (" + strings.Join(conds, " OR ") + ")"
-}
-
func buildOrderBy(query string, method, orderBy int) string {
escapedQuery := strings.ReplaceAll(query, "'", "''")
switch orderBy {
@@ -2298,6 +2281,28 @@ func isTreeExcludedByPublishAccess(tree *parse.Tree, excludeDocIDs []string) boo
return false
}
+func buildSearchByIDStatement(query, boxFilter, pathFilter, typeFilter, ignoreFilter string, boxArgs, pathArgs []any) (string, []any) {
+ statement := "SELECT * FROM blocks WHERE id = ? AND " + typeFilter + boxFilter + pathFilter + ignoreFilter
+ args := append([]any{query}, boxArgs...)
+ args = append(args, pathArgs...)
+ return statement, args
+}
+
+func searchByIDInBoxContext(ctx context.Context, query, boxFilter, pathFilter string, boxArgs, pathArgs []any,
+ typeFilter, ignoreFilter string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+ statement, args := buildSearchByIDStatement(query, boxFilter, pathFilter, typeFilter, ignoreFilter, boxArgs, pathArgs)
+ statement += " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)
+ rows, err := sql.QueryNoLimitArgsInBoxContext(ctx, statement, boxID, args...)
+ if err != nil || ctx.Err() != nil {
+ return
+ }
+ blocks := sql.ToBlocks(rows)
+ ret = fromSQLBlocksContext(ctx, &blocks, "", beforeLen)
+ matchedBlockCount = len(ret)
+ matchedRootCount = matchedBlockCount // 精确块 ID 最多命中一个结果。
+ return
+}
+
// searchBySQLInBox 按 boxID 选择加密或全局数据库,执行分页查询并统计匹配数量。
func searchBySQLInBox(stmt string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
return searchBySQLInBoxContext(context.Background(), stmt, beforeLen, page, pageSize, boxID)
@@ -2999,15 +3004,20 @@ func buildDocumentSearchOrderBy(query string, orderBy int) string {
return ret + ", id ASC"
}
+// 文档查询构造器接收的关键词已经转义 SQL 引号,还原后交由统一的字面量 LIKE 模式构造器处理。
+func documentKeywordLikePattern(keyword string) string {
+ return conf.SearchLikePattern(strings.ReplaceAll(keyword, "''", "'"))
+}
+
func buildDocumentMatchScore(field string, keywords []string) string {
var ret strings.Builder
ret.WriteString("(")
for i, keyword := range keywords {
ret.WriteString("(")
ret.WriteString(field)
- ret.WriteString(" LIKE '%")
- ret.WriteString(keyword)
- ret.WriteString("%')")
+ ret.WriteString(" LIKE ")
+ ret.WriteString(documentKeywordLikePattern(keyword))
+ ret.WriteString(")")
if i < len(keywords)-1 {
ret.WriteString(" + ")
}
@@ -3020,9 +3030,8 @@ func buildSearchDocumentLikeFilter(field string, keywords []string) string {
var ret strings.Builder
for i, keyword := range keywords {
ret.WriteString(field)
- ret.WriteString(" LIKE '%")
- ret.WriteString(keyword)
- ret.WriteString("%'")
+ ret.WriteString(" LIKE ")
+ ret.WriteString(documentKeywordLikePattern(keyword))
if i < len(keywords)-1 {
ret.WriteString(" AND ")
}
@@ -3038,9 +3047,9 @@ func buildSearchDocumentLikeFilterWithHPath(contentField, hPathField string, key
normalizedKeyword := search.NormalizeSearchText(keyword, confSearchSnapshot.CaseSensitive, confSearchSnapshot.HanSensitiveVal())
ret.WriteString("(")
ret.WriteString(contentField)
- ret.WriteString(" LIKE '%")
- ret.WriteString(keyword)
- ret.WriteString("%' OR instr(")
+ ret.WriteString(" LIKE ")
+ ret.WriteString(documentKeywordLikePattern(keyword))
+ ret.WriteString(" OR instr(")
ret.WriteString(hPathField)
ret.WriteString(", '")
ret.WriteString(normalizedKeyword)
diff --git a/kernel/model/search_document_test.go b/kernel/model/search_document_test.go
index 30f3e27663..f7b416f3c6 100644
--- a/kernel/model/search_document_test.go
+++ b/kernel/model/search_document_test.go
@@ -22,6 +22,54 @@ func TestDocumentTypeFilterFromSettings(t *testing.T) {
}
}
+func TestDocumentSearchLiteralSpecialCharacters(t *testing.T) {
+ for _, sensitive := range []bool{false, true} {
+ for _, tc := range []struct{ name, query, other string }{
+ {"percent", "100% efficiency", "100X efficiency"},
+ {"underscore", "snake_case token", "snakeXcase token"},
+ {"backslash", `C:\notes token`, "C:notes token"},
+ {"quote", "reader's choice", "readers choice"},
+ {"consecutive quotes", "reader''s choice", "reader's choice"},
+ } {
+ for _, pathOnly := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/case=%t/path=%t", tc.name, sensitive, pathOnly), func(t *testing.T) {
+ setSearchCaseSensitive(t, sensitive)
+ database := newSearchHPathTestDB(t)
+ setting := "OFF"
+ if sensitive {
+ setting = "ON"
+ }
+ if _, err := database.Exec("PRAGMA case_sensitive_like = " + setting); err != nil {
+ t.Fatal(err)
+ }
+ for _, doc := range []struct{ id, content string }{{"literal", tc.query}, {"wildcard", tc.other}} {
+ content, hpath := doc.content, "/Unrelated"
+ if pathOnly {
+ content, hpath = "Unrelated", "/"+doc.content
+ }
+ insertSearchHPathTestBlock(t, database, doc.id, doc.id, hpath, content, "d")
+ }
+ keywords := strings.Split(strings.ReplaceAll(tc.query, "'", "''"), " ")
+ statement := buildDocumentSearchStatement(tc.query, keywords, "type = 'd'", "", "", "", 0, 1, 32, pathOnly)
+ rows := documentSearchRows(t, database, statement, nil)
+ if len(rows) != 1 || rows[0][0] != "literal" {
+ t.Fatalf("expected only literal match, got %v", rows)
+ }
+ if !pathOnly {
+ var score int
+ if err := database.QueryRow("SELECT " + buildDocumentMatchScore("content", keywords) + " FROM blocks WHERE id = 'wildcard'").Scan(&score); err != nil {
+ t.Fatal(err)
+ }
+ if score != 1 {
+ t.Fatalf("nonliteral keyword affected relevance score: %d", score)
+ }
+ }
+ })
+ }
+ }
+ }
+}
+
func documentSearchRows(t testing.TB, database *gosql.DB, statement string, args []any) [][]any {
t.Helper()
rows, err := database.Query(statement, args...)
diff --git a/kernel/model/search_id_fts5_test.go b/kernel/model/search_id_fts5_test.go
new file mode 100644
index 0000000000..c9dbe5fc8a
--- /dev/null
+++ b/kernel/model/search_id_fts5_test.go
@@ -0,0 +1,67 @@
+//go:build fts5
+
+package model
+
+import (
+ "testing"
+ "time"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+func TestFullTextSearchByIDFilters(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ Conf.Search.Store(conf.NewSearch())
+ tree, err := LoadTreeByBlockID(fixture.sourceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ heading := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 2, ID: ast.NewNodeID()}
+ heading.SetIALAttr("id", heading.ID)
+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("heading")})
+ tree.Root.AppendChild(heading)
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ sql.IndexTreeQueue(tree)
+ sql.FlushQueue()
+ previousIgnore, previousModified := searchIgnore, searchIgnoreLastModified
+ t.Cleanup(func() { searchIgnore, searchIgnoreLastModified = previousIgnore, previousModified })
+ searchIgnore, searchIgnoreLastModified = nil, time.Now().UnixMilli()
+ for _, method := range []int{0, 1} {
+ for _, group := range []int{0, 1} {
+ for _, tc := range []struct {
+ name string
+ change func(*BlockSearchOptions)
+ want int
+ }{
+ {"allowed", func(*BlockSearchOptions) {}, 1},
+ {"notebook", func(o *BlockSearchOptions) { o.Boxes = []string{"20261026000000-other00"} }, 0},
+ {"path", func(o *BlockSearchOptions) { o.Paths = []string{fixture.targetPath} }, 0},
+ {"type", func(o *BlockSearchOptions) { o.Types = map[string]bool{"paragraph": true} }, 0},
+ {"subtype", func(o *BlockSearchOptions) { o.SubTypes = map[string]bool{"h1": true} }, 0},
+ {"excluded notebook", func(o *BlockSearchOptions) { o.ExcludeBoxIDs = []string{fixture.box.ID} }, 0},
+ {"excluded document", func(o *BlockSearchOptions) { o.ExcludeDocIDs = []string{fixture.sourceID} }, 0},
+ {"ignore", func(*BlockSearchOptions) { searchIgnore = []string{"id != '" + heading.ID + "'"} }, 0},
+ {"second page", func(o *BlockSearchOptions) { o.Page = 2 }, 0},
+ } {
+ t.Run(tc.name+string(rune('0'+method))+string(rune('0'+group)), func(t *testing.T) {
+ searchIgnore = nil
+ options := BlockSearchOptions{Query: heading.ID, Method: method, GroupBy: group, Page: 1, PageSize: 32,
+ Boxes: []string{fixture.box.ID}, Paths: []string{fixture.sourcePath}, Types: map[string]bool{"heading": true}, SubTypes: map[string]bool{"h2": true}}
+ tc.change(&options)
+ blocks, matched, roots, pages, docMode := FullTextSearchBlock(options)
+ if len(blocks) != tc.want || matched != tc.want || roots != tc.want || pages != tc.want || docMode {
+ t.Fatalf("results=%d matched=%d roots=%d pages=%d docMode=%v, want %d", len(blocks), matched, roots, pages, docMode, tc.want)
+ }
+ })
+ }
+ }
+ }
+}
diff --git a/kernel/model/search_id_test.go b/kernel/model/search_id_test.go
new file mode 100644
index 0000000000..78677e3a23
--- /dev/null
+++ b/kernel/model/search_id_test.go
@@ -0,0 +1,56 @@
+package model
+
+import "testing"
+
+func TestSearchByIDFilters(t *testing.T) {
+ setSearchCaseSensitive(t, true)
+ database := newSearchHPathTestDB(t)
+ const id = "20261026000000-para001"
+ insertSearchHPathTestBlock(t, database, id, "20261026000000-root001", "/Document", "text", "p")
+ for _, tc := range []struct {
+ name string
+ boxes, paths, excludedBoxes, excludedDocs, hiddenDocs []string
+ types, subTypes map[string]bool
+ ignore string
+ want int
+ }{
+ {name: "unrestricted", types: map[string]bool{"paragraph": true}, want: 1},
+ {name: "matching notebook", boxes: []string{"20260729120000-box000"}, types: map[string]bool{"paragraph": true}, want: 1},
+ {name: "other notebook", boxes: []string{"20260729120000-other00"}, types: map[string]bool{"paragraph": true}},
+ {name: "matching path", paths: []string{"/20261026000000-root001.sy"}, types: map[string]bool{"paragraph": true}, want: 1},
+ {name: "other path", paths: []string{"/20261026000000-other00.sy"}, types: map[string]bool{"paragraph": true}},
+ {name: "wrong type", types: map[string]bool{"heading": true}},
+ {name: "no selected type", types: map[string]bool{}},
+ {name: "ignore expression", types: map[string]bool{"paragraph": true}, ignore: " AND content != 'text'"},
+ {name: "excluded notebook", types: map[string]bool{"paragraph": true}, excludedBoxes: []string{"20260729120000-box000"}},
+ {name: "excluded ancestor", types: map[string]bool{"paragraph": true}, excludedDocs: []string{"20261026000000-root001"}},
+ {name: "hidden notebook document", types: map[string]bool{"paragraph": true}, hiddenDocs: []string{"20261026000000-root001"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ boxFilter, boxArgs := buildBoxesFilter(tc.boxes)
+ hiddenFilter, hiddenArgs := buildRootIDExclusionFilter(tc.hiddenDocs)
+ excludedFilter, excludedArgs := buildPublishAccessExclusionFilter(tc.excludedBoxes, tc.excludedDocs)
+ boxFilter += hiddenFilter + excludedFilter
+ boxArgs = append(boxArgs, hiddenArgs...)
+ boxArgs = append(boxArgs, excludedArgs...)
+ pathFilter, pathArgs := buildPathsFilter(tc.paths)
+ statement, args := buildSearchByIDStatement(id, boxFilter, pathFilter, buildTypeFilter(tc.types, tc.subTypes), tc.ignore, boxArgs, pathArgs)
+ if rows := documentSearchRows(t, database, statement, args); len(rows) != tc.want {
+ t.Fatalf("got %d results, want %d", len(rows), tc.want)
+ }
+ })
+ }
+ if _, err := database.Exec("UPDATE blocks SET type = 'h', subtype = 'h2'"); err != nil {
+ t.Fatal(err)
+ }
+ for _, subtype := range []string{"h1", "h2"} {
+ statement, args := buildSearchByIDStatement(id, "", "", buildTypeFilter(map[string]bool{"heading": true}, map[string]bool{subtype: true}), "", nil, nil)
+ want := 0
+ if subtype == "h2" {
+ want = 1
+ }
+ if rows := documentSearchRows(t, database, statement, args); len(rows) != want {
+ t.Fatalf("subtype %s: got %d, want %d", subtype, len(rows), want)
+ }
+ }
+}