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: Fix encrypted notebook query regressions https://github.com/siyuan-note/siyuan/issues/18236
Daniel3226a67708e2
diff --git a/app/src/block/util.ts b/app/src/block/util.tsindex 1aea99c058..230f15ece6 100644--- a/app/src/block/util.ts+++ b/app/src/block/util.ts@@ -28,7 +28,10 @@ export const cancelSB = async (protyle: IProtyle, nodeElement: Element, range?:// 缩放和反链需要接口获取if (!previousId && !parentID) {if (protyle.block.showAll || protyle.options.backlinkData) {- const idData = await fetchSyncPost("/api/block/getBlockSiblingID", {id});+ const idData = await fetchSyncPost("/api/block/getBlockSiblingID", {+ id,+ notebook: protyle.notebookId,+ });previousId = idData.data.previous;parentID = idData.data.parent;} else {@@ -178,7 +181,10 @@ export const refreshSbAndPersistWidth = (sbElement: Element,};export const jumpToParent = (protyle: IProtyle, nodeElement: Element, type: "parent" | "next" | "previous") => {- fetchPost("/api/block/getBlockSiblingID", {id: nodeElement.getAttribute("data-node-id")}, (response) => {+ fetchPost("/api/block/getBlockSiblingID", {+ id: nodeElement.getAttribute("data-node-id"),+ notebook: protyle.notebookId,+ }, (response) => {const targetId = response.data[type];if (!targetId) {return;diff --git a/app/src/protyle/header/openTitleMenu.ts b/app/src/protyle/header/openTitleMenu.tsindex 3172e73858..58234d6ede 100644--- a/app/src/protyle/header/openTitleMenu.ts+++ b/app/src/protyle/header/openTitleMenu.ts@@ -53,7 +53,10 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: striaccelerator: undefined,click: async () => {const [responseHTML, responseText] = await Promise.all([- fetchSyncPost("/api/block/getBlockDOM", {id: protyle.block.rootID}),+ fetchSyncPost("/api/block/getBlockDOM", {+ id: protyle.block.rootID,+ notebook: protyle.notebookId,+ }),fetchSyncPost("/api/export/exportMdContent", {id: protyle.block.rootID,refMode: 3,diff --git a/app/src/protyle/wysiwyg/commonHotkey.ts b/app/src/protyle/wysiwyg/commonHotkey.tsindex 0b3430fa8e..d1cabf9c35 100644--- a/app/src/protyle/wysiwyg/commonHotkey.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.ts@@ -289,6 +289,7 @@ export const duplicateBlock = async (nodeElements: Element[], protyle: IProtyle)item.querySelector('[data-type="NodeHeading"][fold="1"]')) {const response = await fetchSyncPost("/api/block/getBlockDOM", {id: item.getAttribute("data-node-id"),+ notebook: protyle.notebookId,});const foldTempElement = document.createElement("template");foldTempElement.innerHTML = response.data.dom;diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 05f6db4ac1..6a60d7c4af 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -344,6 +344,7 @@ export class WYSIWYG {needClipboardWrite = true;const response = await fetchSyncPost("/api/block/getBlockDOM", {id: item.getAttribute("data-node-id"),+ notebook: protyle.notebookId,});itemHTML = response.data.dom;} else {@@ -2155,6 +2156,7 @@ export class WYSIWYG {needClipboardWrite = true;const response = await fetchSyncPost("/api/block/getBlockDOM", {id: item.getAttribute("data-node-id"),+ notebook: protyle.notebookId,});itemHTML = response.data.dom;} else {diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex a4e641f135..ee3041ef8a 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -748,6 +748,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndupdateElements.push(tempEl);fetchPost("/api/block/getBlockDOM", {id: operation.id,+ notebook: protyle.notebookId,}, (response) => {document.querySelectorAll(`.protyle-wysiwyg [data-node-id="${response.data.id}"]`).forEach(item => {if (item.getAttribute("data-protyle-id")) {@@ -1399,7 +1400,10 @@ export const turnsOneInto = async (options: {const oldHTML = options.nodeElement.outerHTML;let previousId = options.nodeElement.previousElementSibling?.getAttribute("data-node-id");if (!options.nodeElement.previousElementSibling && options.protyle.block.showAll) {- const response = await fetchSyncPost("/api/block/getBlockRelevantIDs", {id: options.id});+ const response = await fetchSyncPost("/api/block/getBlockRelevantIDs", {+ id: options.id,+ notebook: options.protyle.notebookId,+ });previousId = response.data.previousID;}const parentId = options.nodeElement.parentElement.getAttribute("data-node-id") || options.protyle.block.parentID;diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.goindex 201afd73dc..1e24223d94 100644--- a/kernel/sql/block_query.go+++ b/kernel/sql/block_query.go@@ -594,10 +594,16 @@ func SelectBlocksRawStmtArgs(stmt string, args []any, limit int) (ret []*Block)return}+type queryRowsFunc func(string, ...any) (*sql.Rows, error)+func SelectBlocksRawStmt(stmt string, page, limit int) (ret []*Block) {+ return selectBlocksRawStmtWithQuery(stmt, page, limit, query)+}++func selectBlocksRawStmtWithQuery(stmt string, page, limit int, queryFn queryRowsFunc) (ret []*Block) {parsedStmt, err := sqlparser.Parse(stmt)if err != nil {- return selectBlocksRawStmt(stmt, limit)+ return selectBlocksRawStmtNoParseWithQuery(stmt, limit, queryFn)}switch parsedStmt.(type) {@@ -673,7 +679,7 @@ func SelectBlocksRawStmt(stmt string, page, limit int) (ret []*Block) {stmt = strings.ReplaceAll(stmt, "\\\"", "\"")stmt = strings.ReplaceAll(stmt, "\\\\*", "\\*")stmt = strings.ReplaceAll(stmt, "from dual", "")- rows, err := query(stmt)+ rows, err := queryFn(stmt)if err != nil {if strings.Contains(err.Error(), "syntax error") {return@@ -795,7 +801,11 @@ func SelectBlocksRegexArgs(stmt string, exp *regexp.Regexp, name, alias, memo, i}func selectBlocksRawStmt(stmt string, limit int) (ret []*Block) {- rows, err := query(stmt)+ return selectBlocksRawStmtNoParseWithQuery(stmt, limit, query)+}++func selectBlocksRawStmtNoParseWithQuery(stmt string, limit int, queryFn queryRowsFunc) (ret []*Block) {+ rows, err := queryFn(stmt)if err != nil {if strings.Contains(err.Error(), "syntax error") {returndiff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.goindex 0ba386c3a7..06674b5f83 100644--- a/kernel/sql/encrypted_query.go+++ b/kernel/sql/encrypted_query.go@@ -51,19 +51,43 @@ func GetBlocksInBox(ids []string, boxID string) (ret []*Block) {if 1 > len(ids) {return}- sqlStmt := "SELECT * FROM blocks WHERE id IN ('" + strings.Join(ids, "','") + "')"- rows, err := queryForBox(boxID, sqlStmt)++ var notHitIDs []string+ cached := map[string]*Block{}+ for _, id := range ids {+ if block := getBlockCacheInBox(id, boxID); nil != block {+ cached[id] = block+ } else {+ notHitIDs = append(notHitIDs, id)+ }+ }++ if 1 > len(notHitIDs) {+ for _, id := range ids {+ ret = append(ret, cached[id])+ }+ return+ }++ sqlStmt := "SELECT * FROM blocks WHERE id IN (" + strings.Repeat("?,", len(notHitIDs)-1) + "?)"+ args := make([]any, len(notHitIDs))+ for i, id := range notHitIDs {+ args[i] = id+ }+ rows, err := queryForBox(boxID, sqlStmt, args...)if err != nil {logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)return}defer rows.Close()for rows.Next() {- b := scanBlockRows(rows)- if b != nil {- ret = append(ret, b)+ if block := scanBlockRows(rows); nil != block {+ cached[block.ID] = block}}+ for _, id := range ids {+ ret = append(ret, cached[id])+ }return}@@ -83,14 +107,22 @@ func GetRefTextInBox(defBlockID, boxID string) (ret string) {}// QueryRefsByDefIDInBox 按 defBlockID 在指定 box 的 db 里查引用列表。-// 注意:加密 content db 里没有 blocktrees 表(在独立的 blocktree db),containChildren 时-// 不能 JOIN blocktrees,改为用 def_block_root_id 查询。+// containChildren 为 true 时递归查询定义块及其所有子块,与 QueryRefsByDefID 保持一致。func QueryRefsByDefIDInBox(defBlockID string, containChildren bool, boxID string) (ret []*Ref) {- sqlStmt := "SELECT * FROM refs WHERE def_block_id = ?"+ var sqlStmt string+ var args []anyif containChildren {- sqlStmt = "SELECT * FROM refs WHERE def_block_root_id = ?"+ blockIDs := queryBlockChildrenIDsForBox(defBlockID, boxID)+ sqlStmt = "SELECT * FROM refs WHERE def_block_id IN (" + strings.Repeat("?,", len(blockIDs)-1) + "?)"+ args = make([]any, len(blockIDs))+ for i, id := range blockIDs {+ args[i] = id+ }+ } else {+ sqlStmt = "SELECT * FROM refs WHERE def_block_id = ?"+ args = []any{defBlockID}}- rows, err := queryForBox(boxID, sqlStmt, defBlockID)+ rows, err := queryForBox(boxID, sqlStmt, args...)if err != nil {logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)return@@ -131,27 +163,10 @@ func QueryRootChildrenRefCountInBox(defRootID, boxID string) (ret map[string]int// SelectBlocksRawStmtInBox 在指定 box 的 db 里执行原始 SQL 查询 blocks。func SelectBlocksRawStmtInBox(stmt string, page, limit int, boxID string) (ret []*Block) {- stmt = strings.TrimSpace(stmt)- if 1 > page {- page = 1+ queryFn := func(stmt string, args ...any) (*sql.Rows, error) {+ return queryForBox(boxID, stmt, args...)}- offset := (page - 1) * limit- if 0 < limit && !strings.Contains(strings.ToLower(stmt), " limit ") {- stmt += " LIMIT " + itoa(limit) + " OFFSET " + itoa(offset)- }- rows, err := queryForBox(boxID, stmt)- if err != nil {- logging.LogErrorf("sql query [%s] failed: %s", stmt, err)- return- }- defer rows.Close()- for rows.Next() {- b := scanBlockRows(rows)- if b != nil {- ret = append(ret, b)- }- }- return+ return selectBlocksRawStmtWithQuery(stmt, page, limit, queryFn)}// QueryRefCountInBox 按 defBlockIDs 在指定 box 的 db 里查引用计数。diff --git a/kernel/sql/encrypted_query_test.go b/kernel/sql/encrypted_query_test.gonew file mode 100644index 0000000000..f97a2dd761--- /dev/null+++ b/kernel/sql/encrypted_query_test.go@@ -0,0 +1,115 @@+// 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++import (+ gosql "database/sql"+ "fmt"+ "testing"+)++func TestGetBlocksInBoxPreservesInputOrder(t *testing.T) {+ testDB, boxID := useEncryptedQueryTestDB(t)+ insertEncryptedQueryTestBlock(t, testDB, "block-1", "", "block-1", "d")+ insertEncryptedQueryTestBlock(t, testDB, "block-2", "", "block-2", "d")+ insertEncryptedQueryTestBlock(t, testDB, "block-3", "", "block-3", "d")++ blocks := GetBlocksInBox([]string{"block-3", "block-1", "block-2"}, boxID)+ if 3 != len(blocks) {+ t.Fatalf("unexpected block count: %d", len(blocks))+ }+ for i, expected := range []string{"block-3", "block-1", "block-2"} {+ if nil == blocks[i] || expected != blocks[i].ID {+ t.Fatalf("unexpected block at %d: %#v", i, blocks[i])+ }+ }+}++func TestQueryRefsByDefIDInBoxContainsChildren(t *testing.T) {+ testDB, boxID := useEncryptedQueryTestDB(t)+ insertEncryptedQueryTestBlock(t, testDB, "root", "", "root", "d")+ insertEncryptedQueryTestBlock(t, testDB, "heading", "root", "root", "h")+ insertEncryptedQueryTestBlock(t, testDB, "paragraph", "heading", "root", "p")+ insertEncryptedQueryTestBlock(t, testDB, "sibling", "root", "root", "p")+ insertEncryptedQueryTestRef(t, testDB, "ref-heading", "heading", "root")+ insertEncryptedQueryTestRef(t, testDB, "ref-paragraph", "paragraph", "root")+ insertEncryptedQueryTestRef(t, testDB, "ref-sibling", "sibling", "root")++ refs := QueryRefsByDefIDInBox("heading", true, boxID)+ actual := map[string]bool{}+ for _, ref := range refs {+ actual[ref.DefBlockID] = true+ }+ if 2 != len(refs) || !actual["heading"] || !actual["paragraph"] || actual["sibling"] {+ t.Fatalf("unexpected refs: %#v", actual)+ }+}++func TestSelectBlocksRawStmtInBoxPaginatesExistingLimit(t *testing.T) {+ testDB, boxID := useEncryptedQueryTestDB(t)+ for i := 1; i <= 6; i++ {+ id := fmt.Sprintf("block-%02d", i)+ insertEncryptedQueryTestBlock(t, testDB, id, "", id, "d")+ }++ blocks := SelectBlocksRawStmtInBox("SELECT * FROM blocks ORDER BY id LIMIT 3", 2, 32, boxID)+ if 3 != len(blocks) {+ t.Fatalf("unexpected block count: %d", len(blocks))+ }+ for i, expected := range []string{"block-04", "block-05", "block-06"} {+ if expected != blocks[i].ID {+ t.Fatalf("unexpected block at %d: %s", i, blocks[i].ID)+ }+ }+}++func useEncryptedQueryTestDB(t *testing.T) (*gosql.DB, string) {+ t.Helper()+ testDB, err := gosql.Open("sqlite3_extended", ":memory:")+ if nil != err {+ t.Fatalf("open test database failed: %s", err)+ }+ testDB.SetMaxOpenConns(1)+ if _, err = testDB.Exec("CREATE TABLE blocks (id TEXT NOT NULL DEFAULT '', parent_id TEXT NOT NULL DEFAULT '', root_id TEXT NOT NULL DEFAULT '', hash TEXT NOT NULL DEFAULT '', box TEXT NOT NULL DEFAULT '', path TEXT NOT NULL DEFAULT '', hpath TEXT NOT NULL DEFAULT '', name TEXT NOT NULL DEFAULT '', alias TEXT NOT NULL DEFAULT '', memo TEXT NOT NULL DEFAULT '', tag TEXT NOT NULL DEFAULT '', content TEXT NOT NULL DEFAULT '', fcontent TEXT NOT NULL DEFAULT '', markdown TEXT NOT NULL DEFAULT '', length INTEGER NOT NULL DEFAULT 0, type TEXT NOT NULL DEFAULT '', subtype TEXT NOT NULL DEFAULT '', ial TEXT NOT NULL DEFAULT '', sort INTEGER NOT NULL DEFAULT 0, created TEXT NOT NULL DEFAULT '', updated TEXT NOT NULL DEFAULT '')"); nil != err {+ t.Fatalf("create blocks table failed: %s", err)+ }+ if _, err = testDB.Exec("CREATE TABLE refs (id TEXT NOT NULL DEFAULT '', def_block_id TEXT NOT NULL DEFAULT '', def_block_parent_id TEXT NOT NULL DEFAULT '', def_block_root_id TEXT NOT NULL DEFAULT '', def_block_path TEXT NOT NULL DEFAULT '', block_id TEXT NOT NULL DEFAULT '', root_id TEXT NOT NULL DEFAULT '', box TEXT NOT NULL DEFAULT '', path TEXT NOT NULL DEFAULT '', content TEXT NOT NULL DEFAULT '', markdown TEXT NOT NULL DEFAULT '', type TEXT NOT NULL DEFAULT '')"); nil != err {+ t.Fatalf("create refs table failed: %s", err)+ }++ boxID := t.Name()+ encryptedDBs.Store(boxID, testDB)+ t.Cleanup(func() {+ encryptedDBs.Delete(boxID)+ testDB.Close()+ })+ return testDB, boxID+}++func insertEncryptedQueryTestBlock(t *testing.T, testDB *gosql.DB, id, parentID, rootID, blockType string) {+ t.Helper()+ if _, err := testDB.Exec("INSERT INTO blocks (id, parent_id, root_id, type) VALUES (?, ?, ?, ?)", id, parentID, rootID, blockType); nil != err {+ t.Fatalf("insert block failed: %s", err)+ }+}++func insertEncryptedQueryTestRef(t *testing.T, testDB *gosql.DB, id, defBlockID, defRootID string) {+ t.Helper()+ if _, err := testDB.Exec("INSERT INTO refs (id, def_block_id, def_block_root_id) VALUES (?, ?, ?)", id, defBlockID, defRootID); nil != err {+ t.Fatalf("insert ref failed: %s", err)+ }+}