An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: https://github.com/siyuan-note/siyuan/security/advisories/GHSA-h89q-4j2h-7h88
Danield0f0fe146fb0
diff --git a/kernel/api/search.go b/kernel/api/search.goindex 3f84af55c7..a284cf28f8 100644--- a/kernel/api/search.go+++ b/kernel/api/search.go@@ -449,10 +449,15 @@ func parseSearchBlockArgs(arg map[string]any) (page, pageSize int, query string,for _, p := range pathsArg.([]any) {path := p.(string)box := strings.TrimSpace(strings.Split(path, "/")[0])+ path = strings.TrimSpace(strings.TrimPrefix(path, box))+ // 入口校验:拒绝带 SQL 元字符的非法笔记本 ID 与文档路径,阻止 SQL 注入。+ // 与既有静默去重风格一致,对非法整条丢弃而非中断请求。+ if !model.IsValidSearchBoxPath(box, path) {+ continue+ }if "" != box {boxes = append(boxes, box)}- path = strings.TrimSpace(strings.TrimPrefix(path, box))if "" != path {paths = append(paths, path)}diff --git a/kernel/model/embedding.go b/kernel/model/embedding.goindex 665bd72eef..b0371b2223 100644--- a/kernel/model/embedding.go+++ b/kernel/model/embedding.go@@ -433,8 +433,8 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes ma}queryVec := vectors[0]- boxFilter := buildBoxesFilter(boxes, "be.")- pathFilter := buildPathsFilter(paths, "be.")+ boxFilter, boxArgs := buildBoxesFilter(boxes, "be.")+ pathFilter, pathArgs := buildPathsFilter(paths, "be.")typeFilter := buildTypeFilter(types, subTypes, "b.")hasFilter := 0 < len(boxes) || 0 < len(paths) || 0 < len(types)hasTypeFilter := 0 < len(types)@@ -453,17 +453,20 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes mafor {var q string+ var args []anyif hasFilter {q = fmt.Sprintf("SELECT be.rowid, be.id, be.embedding FROM block_embeddings be JOIN blocks b ON be.id = b.id WHERE be.embedding IS NOT NULL AND length(be.embedding) > 0 AND be.rowid > %d", cursor)if hasTypeFilter {q += " AND " + typeFilter}q += boxFilter + pathFilter+ // box/path 过滤值通过绑定参数传递,避免 SQL 拼接注入+ args = append(append([]any{}, boxArgs...), pathArgs...)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)}- rows, qErr := sql.QueryNoLimit(q)+ rows, qErr := sql.QueryNoLimitArgs(q, args...)if qErr != nil {logging.LogErrorf("query embeddings for search failed: %s", qErr)breakdiff --git a/kernel/model/search.go b/kernel/model/search.goindex 9dabeb5ce8..bf8bdc97cd 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -1182,33 +1182,33 @@ func FullTextSearchBlock(query string, boxes, paths []string, types, subTypes maswitch method {case 1: // 查询语法typeFilter := buildTypeFilter(types, subTypes)- boxFilter := buildBoxesFilter(boxes)- pathFilter := buildPathsFilter(paths)+ boxFilter, boxArgs := buildBoxesFilter(boxes)+ pathFilter, pathArgs := buildPathsFilter(paths)if ast.IsNodeIDPattern(query) {blocks, matchedBlockCount, matchedRootCount = searchBySQL("SELECT * FROM `blocks` WHERE `id` = '"+query+"'", beforeLen, page, pageSize)} else {- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTS(query, boxFilter, pathFilter, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTS(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)}case 2: // SQLblocks, matchedBlockCount, matchedRootCount = searchBySQL(query, beforeLen, page, pageSize)case 3: // 正则表达式typeFilter := buildTypeFilter(types, subTypes)- boxFilter := buildBoxesFilter(boxes)- pathFilter := buildPathsFilter(paths)- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByRegexp(query, boxFilter, pathFilter, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)+ boxFilter, boxArgs := buildBoxesFilter(boxes)+ pathFilter, pathArgs := buildPathsFilter(paths)+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByRegexp(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)default: // 关键字typeFilter := buildTypeFilter(types, subTypes)- boxFilter := buildBoxesFilter(boxes)- pathFilter := buildPathsFilter(paths)+ boxFilter, boxArgs := buildBoxesFilter(boxes)+ pathFilter, pathArgs := buildPathsFilter(paths)if ast.IsNodeIDPattern(query) {blocks, matchedBlockCount, matchedRootCount = searchBySQL("SELECT * FROM `blocks` WHERE `id` = '"+query+"'", beforeLen, page, pageSize)} else {if 2 > len(strings.Split(strings.TrimSpace(query), " ")) {query = stringQuery(query)- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTS(query, boxFilter, pathFilter, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTS(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)} else {docMode = true // 文档全文搜索模式 https://github.com/siyuan-note/siyuan/issues/10584- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)}}}@@ -1332,9 +1332,38 @@ func FullTextSearchBlock(query string, boxes, paths []string, types, subTypes mareturn}-func buildBoxesFilter(boxes []string, alias ...string) string {+// IsValidSearchBoxPath 校验搜索入参中的笔记本 ID 与文档路径,阻止 SQL 元字符进入语句拼接。+// box 必须是合法的节点 ID;docPath 为空表示仅限定笔记本范围;否则须为以 "/" 开头、+// 由节点 ID 段组成的文档路径(如 "/20210808180117-6v0mkxr.sy" 或子树目录 "/20210808180117-6v0mkxr")。+func IsValidSearchBoxPath(box, docPath string) bool {+ if !ast.IsNodeIDPattern(box) {+ return false+ }+ if "" == docPath || "/" == docPath {+ return true+ }+ if !strings.HasPrefix(docPath, "/") {+ return false+ }+ segments := strings.Split(strings.TrimPrefix(docPath, "/"), "/")+ for i, segment := range segments {+ id := segment+ if i == len(segments)-1 {+ // 末段允许带 ".sy" 后缀(具体文档)或不带(子树目录范围)+ id = strings.TrimSuffix(id, ".sy")+ }+ if !ast.IsNodeIDPattern(id) {+ return false+ }+ }+ return true+}++// buildBoxesFilter 构造笔记本过滤子句,box 值通过绑定参数传递,避免 SQL 拼接注入。+// 返回的 args 顺序与 clause 中 "?" 的出现顺序一致。+func buildBoxesFilter(boxes []string, alias ...string) (clause string, args []any) {if 0 == len(boxes) {- return ""+ return}prefix := ""if 0 < len(alias) && "" != alias[0] {@@ -1343,18 +1372,22 @@ func buildBoxesFilter(boxes []string, alias ...string) string {builder := bytes.Buffer{}builder.WriteString(" AND (")for i, box := range boxes {- builder.WriteString(fmt.Sprintf("%sbox = '%s'", prefix, box))+ builder.WriteString(fmt.Sprintf("%sbox = ?", prefix))+ args = append(args, box)if i < len(boxes)-1 {builder.WriteString(" OR ")}}builder.WriteString(")")- return builder.String()+ clause = builder.String()+ return}-func buildPathsFilter(paths []string, alias ...string) string {+// buildPathsFilter 构造文档路径过滤子句,path 前缀通过绑定参数传递,避免 SQL 拼接注入。+// 返回的 args 顺序与 clause 中 "?" 的出现顺序一致。+func buildPathsFilter(paths []string, alias ...string) (clause string, args []any) {if 0 == len(paths) {- return ""+ return}prefix := ""if 0 < len(alias) && "" != alias[0] {@@ -1363,13 +1396,15 @@ func buildPathsFilter(paths []string, alias ...string) string {builder := bytes.Buffer{}builder.WriteString(" AND (")for i, path := range paths {- builder.WriteString(fmt.Sprintf("%spath LIKE '%s%%'", prefix, path))+ builder.WriteString(fmt.Sprintf("%spath LIKE ?", prefix))+ args = append(args, path+"%")if i < len(paths)-1 {builder.WriteString(" OR ")}}builder.WriteString(")")- return builder.String()+ clause = builder.String()+ return}func buildOrderBy(query string, method, orderBy int) string {@@ -1680,7 +1715,7 @@ func extractID(content string) (ret string) {return}-func fullTextSearchByRegexp(exp, boxFilter, pathFilter, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {+func fullTextSearchByRegexp(exp, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {fieldFilter := fieldRegexp(exp)stmt := "SELECT * FROM `blocks` WHERE " + fieldFilter + " AND " + typeFilterstmt += boxFilter + pathFilter + ignoreFilter + " " + orderBy@@ -1690,21 +1725,24 @@ func fullTextSearchByRegexp(exp, boxFilter, pathFilter, typeFilter, ignoreFilterreturn}- blocks := sql.SelectBlocksRegex(stmt, regex, Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo, Conf.Search.IAL, page, pageSize)+ // box/path 过滤值通过绑定参数传递,避免 SQL 拼接注入+ args := append(append([]any{}, boxArgs...), pathArgs...)+ blocks := sql.SelectBlocksRegexArgs(stmt, regex, Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo, Conf.Search.IAL, page, pageSize, args...)ret = fromSQLBlocks(&blocks, "", beforeLen)if 1 > len(ret) {ret = []*Block{}}- matchedBlockCount, matchedRootCount = fullTextSearchCountByRegexp(exp, boxFilter, pathFilter, typeFilter, ignoreFilter)+ matchedBlockCount, matchedRootCount = fullTextSearchCountByRegexp(exp, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter)return}-func fullTextSearchCountByRegexp(exp, boxFilter, pathFilter, typeFilter, ignoreFilter string) (matchedBlockCount, matchedRootCount int) {+func fullTextSearchCountByRegexp(exp, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string) (matchedBlockCount, matchedRootCount int) {fieldFilter := fieldRegexp(exp)stmt := "SELECT COUNT(id) AS `matches`, COUNT(DISTINCT(root_id)) AS `docs` FROM `blocks` WHERE " + fieldFilter + " AND " + typeFilter + ignoreFilterstmt += boxFilter + pathFilter- result, _ := sql.QueryNoLimit(stmt)+ args := append(append([]any{}, boxArgs...), pathArgs...)+ result, _ := sql.QueryNoLimitArgs(stmt, args...)if 1 > len(result) {return}@@ -1713,7 +1751,7 @@ func fullTextSearchCountByRegexp(exp, boxFilter, pathFilter, typeFilter, ignoreFreturn}-func fullTextSearchByFTS(query, boxFilter, pathFilter, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {+func fullTextSearchByFTS(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {table := "blocks_fts"projections := "id, parent_id, root_id, hash, box, path, " +// Search result content snippet returns more text https://github.com/siyuan-note/siyuan/issues/10707@@ -1728,23 +1766,26 @@ func fullTextSearchByFTS(query, boxFilter, pathFilter, typeFilter, ignoreFilter,stmt += ") AND " + typeFilterstmt += boxFilter + pathFilter + ignoreFilter + " " + orderBystmt += " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)- blocks := sql.SelectBlocksRawStmt(stmt, page, pageSize)+ // box/path 过滤值通过绑定参数传递,避免 SQL 拼接注入;绕开 sqlparser 以保留 "?" 占位+ args := append(append([]any{}, boxArgs...), pathArgs...)+ blocks := sql.SelectBlocksRawStmtArgs(stmt, args, pageSize)ret = fromSQLBlocks(&blocks, "", beforeLen)if 1 > len(ret) {ret = []*Block{}}- matchedBlockCount, matchedRootCount = fullTextSearchCountByFTS(query, boxFilter, pathFilter, typeFilter, ignoreFilter)+ matchedBlockCount, matchedRootCount = fullTextSearchCountByFTS(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter)return}-func fullTextSearchCountByFTS(query, boxFilter, pathFilter, typeFilter, ignoreFilter string) (matchedBlockCount, matchedRootCount int) {+func fullTextSearchCountByFTS(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string) (matchedBlockCount, matchedRootCount int) {table := "blocks_fts"stmt := "SELECT COUNT(id) AS `matches`, COUNT(DISTINCT(root_id)) AS `docs` FROM `" + table + "` WHERE (`" + table + "` MATCH '" + columnFilter() + ":(" + query + ")'"stmt += ") AND " + typeFilterstmt += boxFilter + pathFilter + ignoreFilter- result, _ := sql.QueryNoLimit(stmt)+ args := append(append([]any{}, boxArgs...), pathArgs...)+ result, _ := sql.QueryNoLimitArgs(stmt, args...)if 1 > len(result) {return}@@ -1753,7 +1794,7 @@ func fullTextSearchCountByFTS(query, boxFilter, pathFilter, typeFilter, ignoreFireturn}-func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {+func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {query = strings.ReplaceAll(query, "'", "''") // 不需要转义双引号,因为条件都是通过单引号包裹的,只需要转义单引号即可keywords := strings.Split(query, " ")contentField := columnConcat()@@ -1768,6 +1809,9 @@ func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter, typeFilter, igno}}orderByLike += ")"+ // box/path 过滤子句在下方 dMatchStmt 与 selectStmt 中各出现一次,绑定参数需按出现顺序收集两份。+ // 第一份对应 CTE 内的 WHERE+ args := append(append([]any{}, boxArgs...), pathArgs...)dMatchStmt := "SELECT root_id, MAX(CASE WHEN type = 'd' THEN (" + contentField + ") END) AS docContent" +" FROM blocks WHERE " + typeFilter + boxFilter + pathFilter + ignoreFilter +" GROUP BY root_id HAVING " + likeFilter + "ORDER BY " + orderByLike + " DESC, MAX(updated) DESC"@@ -1781,6 +1825,8 @@ func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter, typeFilter, igno" FROM blocks WHERE " + typeFilter + boxFilter + pathFilter + ignoreFilter +" AND (id IN (SELECT root_id FROM docBlocks " + limit + ") OR" +" (root_id IN (SELECT root_id FROM docBlocks" + limit + ") AND (" + likeFilter + ")))"+ // 第二份对应外层 SELECT 的 WHERE+ args = append(args, append(append([]any{}, boxArgs...), pathArgs...)...)if strings.Contains(orderBy, "ORDER BY rank DESC") {orderBy = buildOrderBy(query, 0, 0)selectStmt += " " + strings.Replace(orderBy, "END ASC, ", "END ASC, blockSort ASC, ", 1)@@ -1792,7 +1838,7 @@ func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter, typeFilter, igno} else {selectStmt += " " + orderBy}- result, _ := sql.QueryNoLimit(selectStmt)+ result, _ := sql.QueryNoLimitArgs(selectStmt, args...)resultBlocks := sql.ToBlocks(result)if 0 < len(resultBlocks) {matchedRootCount = int(result[0]["docs"].(int64))diff --git a/kernel/model/search_test.go b/kernel/model/search_test.gonew file mode 100644index 0000000000..1140c2733e--- /dev/null+++ b/kernel/model/search_test.go@@ -0,0 +1,109 @@+// 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 model++import "testing"++// TestIsValidSearchBoxPath 覆盖搜索入参的笔记本 ID 与文档路径校验,阻止 SQL 元字符进入语句拼接。+// 回归用例参考 /api/search/fullTextSearchBlock 的 SQL 注入报告(paths[] 投毒)。+func TestIsValidSearchBoxPath(t *testing.T) {+ validBox := "20210808180117-6v0mkxr"++ validCases := []struct {+ name string+ box string+ path string+ }{+ {"仅笔记本范围", validBox, ""},+ {"仅斜杠", validBox, "/"},+ {"具体文档", validBox, "/20210808180117-6v0mkxr.sy"},+ {"子树目录范围", validBox, "/20210808180117-6v0mkxr"},+ {"子文档完整路径", validBox, "/20210808180117-6v0mkxr/20210808180530-a1b2c3d.sy"},+ }+ for _, tc := range validCases {+ t.Run("valid/"+tc.name, func(t *testing.T) {+ if !IsValidSearchBoxPath(tc.box, tc.path) {+ t.Fatalf("expected valid: box=%q path=%q", tc.box, tc.path)+ }+ })+ }++ invalidCases := []struct {+ name string+ box string+ path string+ }{+ // 报告中的 UNION 投毒 payload+ {+ "SQL注入UNION投影",+ validBox,+ "/x%') UNION SELECT id,parent_id FROM blocks WHERE path='/hidden.sy' -- ",+ },+ {"单引号断字符串", validBox, "/doc'secret.sy"},+ {"百分号前导", validBox, "/%abc"},+ {"注释标记", validBox, "/doc -- "},+ {"非法box短数字", "123", ""},+ {"非法box大写", "20210808180117-6V0MKXR", ""},+ {"非法box空", "", "/20210808180117-6v0mkxr.sy"},+ {"path缺少前导斜杠", validBox, "20210808180117-6v0mkxr.sy"},+ {"path段非法", validBox, "/notanid.sy"},+ {"path中段非法", validBox, "/20210808180117-6v0mkxr/notanid.sy"},+ }+ for _, tc := range invalidCases {+ t.Run("invalid/"+tc.name, func(t *testing.T) {+ if IsValidSearchBoxPath(tc.box, tc.path) {+ t.Fatalf("expected invalid: box=%q path=%q", tc.box, tc.path)+ }+ })+ }+}++// TestBuildBoxesPathFiltersArgCount 验证参数化过滤器产出的 "?" 数量与 args 长度一致。+func TestBuildBoxesPathFiltersArgCount(t *testing.T) {+ boxes := []string{"20210808180117-6v0mkxr", "20210808180117-a1b2c3d"}+ clause, args := buildBoxesFilter(boxes)+ if countPlaceholder(clause) != len(args) {+ t.Fatalf("box filter placeholder/arg mismatch: %q vs %d args", clause, len(args))+ }+ if len(args) != 2 {+ t.Fatalf("expected 2 box args, got %d", len(args))+ }++ paths := []string{"/20210808180117-6v0mkxr", "/20210808180117-a1b2c3d/20210808180530-e5f6g7h.sy"}+ clause, args = buildPathsFilter(paths)+ if countPlaceholder(clause) != len(args) {+ t.Fatalf("path filter placeholder/arg mismatch: %q vs %d args", clause, len(args))+ }+ if len(args) != 2 {+ t.Fatalf("expected 2 path args, got %d", len(args))+ }+ for i, a := range args {+ s, ok := a.(string)+ if !ok || s != paths[i]+"%" {+ t.Fatalf("path arg %d should be %q%%, got %v", i, paths[i], a)+ }+ }+}++func countPlaceholder(s string) (n int) {+ for i := 0; i < len(s); i++ {+ if s[i] == '?' {+ n+++ }+ }+ return+}diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.goindex b714c94047..6ddd979171 100644--- a/kernel/sql/block_query.go+++ b/kernel/sql/block_query.go@@ -591,6 +591,37 @@ func SelectBlocksRawStmtNoParse(stmt string, limit int) (ret []*Block) {return selectBlocksRawStmt(stmt, limit)}+// SelectBlocksRawStmtArgs 与 selectBlocksRawStmt 行为一致,但通过绑定参数执行,+// 绕开 sqlparser 解析(vitess 会把 "?" 改写为 ":vN" 导致占位失效),用于含用户可控参数的搜索语句。+func SelectBlocksRawStmtArgs(stmt string, args []any, limit int) (ret []*Block) {+ rows, err := query(stmt, args...)+ if err != nil {+ if strings.Contains(err.Error(), "syntax error") {+ return+ }+ logging.LogWarnf("sql query [%s] failed: %s", stmt, err)+ return+ }+ defer rows.Close()++ noLimit := !containsLimitClause(stmt)+ var count, errCount int+ for rows.Next() {+ count+++ if block := scanBlockRows(rows); nil != block {+ ret = append(ret, block)+ } else {+ logging.LogWarnf("raw sql query [%s] failed", stmt)+ errCount+++ }++ if (noLimit && limit < count) || 0 < errCount {+ break+ }+ }+ return+}+func SelectBlocksRawStmt(stmt string, page, limit int) (ret []*Block) {parsedStmt, err := sqlparser.Parse(stmt)if err != nil {@@ -738,6 +769,59 @@ func SelectBlocksRegex(stmt string, exp *regexp.Regexp, name, alias, memo, ial breturn}+// SelectBlocksRegexArgs 与 SelectBlocksRegex 行为一致,但通过绑定参数执行,+// 绕开 sqlparser 解析(vitess 会把 "?" 改写为 ":vN" 导致占位失效),用于含用户可控参数的正则搜索。+func SelectBlocksRegexArgs(stmt string, exp *regexp.Regexp, name, alias, memo, ial bool, page, pageSize int, args ...any) (ret []*Block) {+ rows, err := query(stmt, args...)+ if err != nil {+ logging.LogErrorf("sql query [%s] failed: %s", stmt, err)+ return+ }+ defer rows.Close()+ count := 0+ for rows.Next() {+ count+++ if count <= (page-1)*pageSize {+ continue+ }++ var block Block+ if err := rows.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated); err != nil {+ logging.LogErrorf("query scan field failed: %s\n%s", err, logging.ShortStack())+ return+ }++ hitContent := exp.MatchString(block.Content)+ hitName := name && exp.MatchString(block.Name)+ hitAlias := alias && exp.MatchString(block.Alias)+ hitMemo := memo && exp.MatchString(block.Memo)+ hitIAL := ial && exp.MatchString(block.IAL)+ if hitContent || hitName || hitAlias || hitMemo || hitIAL {+ if hitContent {+ block.Content = exp.ReplaceAllString(block.Content, "__@mark__${0}__mark@__")+ }+ if hitName {+ block.Name = exp.ReplaceAllString(block.Name, "__@mark__${0}__mark@__")+ }+ if hitAlias {+ block.Alias = exp.ReplaceAllString(block.Alias, "__@mark__${0}__mark@__")+ }+ if hitMemo {+ block.Memo = exp.ReplaceAllString(block.Memo, "__@mark__${0}__mark@__")+ }+ if hitIAL {+ block.IAL = exp.ReplaceAllString(block.IAL, "__@mark__${0}__mark@__")+ }++ ret = append(ret, &block)+ if len(ret) >= pageSize {+ break+ }+ }+ }+ return+}+func selectBlocksRawStmt(stmt string, limit int) (ret []*Block) {rows, err := query(stmt)if err != nil {