Skip to content

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

:sparkles: split blocktree + content-db box-scoped read routing (stage 8 part 1) #18034

Danielbd143ece21d5
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 4c274070db..08a8796e45 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -28,6 +28,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -127,6 +128,10 @@ func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) error
if err = sql.OpenEncryptedDB(boxID, dek); err != nil {
return err
}
+ if err = treenode.OpenEncryptedBlockTreeDB(boxID, dek); err != nil {
+ sql.CloseEncryptedDB(boxID)
+ return err
+ }
cachedDEKs[boxID] = dek
return nil
}
@@ -149,6 +154,7 @@ func LockBox(boxID string) {
}
cachedDEKsLock.Unlock()
sql.CloseEncryptedDB(boxID)
+ treenode.CloseEncryptedBlockTreeDB(boxID)
cache.ClearTreeCache()
}
@@ -162,6 +168,7 @@ func LockAllBoxes() {
cachedDEKsLock.Unlock()
// 关闭所有已打开的加密 db 连接,清空树缓存避免明文残留
sql.CloseAllEncryptedDBs()
+ treenode.CloseAllEncryptedBlockTreeDBs()
cache.ClearTreeCache()
}
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index a7a86924a9..cc97b1d16e 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -33,6 +33,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/task"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -165,6 +166,7 @@ func RemoveBox(boxID string) (err error) {
// 加密笔记本删除时清理其独立加密 db 文件(含 WAL/SHM),避免残留
if IsEncryptedBox(boxID) {
sql.RemoveEncryptedDBFile(boxID)
+ treenode.RemoveEncryptedBlockTreeDBFile(boxID)
}
if isUserGuide {
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index 97375f55e4..8cbe9118d8 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -1423,6 +1423,37 @@ func query(query string, args ...any) (*sql.Rows, error) {
return db.Query(query, args...)
}
+// queryRowForBox 按 box 路由查询单行。加密 box 用独立 db,否则用全局 db。boxID 为空走全局。
+func queryRowForBox(boxID, query string, args ...any) *sql.Row {
+ query = strings.TrimSpace(query)
+ if "" == query {
+ logging.LogErrorf("statement is empty")
+ return nil
+ }
+ if boxDB := GetEncryptedDB(boxID); boxDB != nil {
+ return boxDB.QueryRow(query, args...)
+ }
+ if nil == db {
+ return nil
+ }
+ return db.QueryRow(query, args...)
+}
+
+// queryForBox 按 box 路由查询多行。加密 box 用独立 db,否则用全局 db。boxID 为空走全局。
+func queryForBox(boxID, query string, args ...any) (*sql.Rows, error) {
+ query = strings.TrimSpace(query)
+ if "" == query {
+ return nil, errors.New("statement is empty")
+ }
+ if boxDB := GetEncryptedDB(boxID); boxDB != nil {
+ return boxDB.Query(query, args...)
+ }
+ if nil == db {
+ return nil, errors.New("database is nil")
+ }
+ return db.Query(query, args...)
+}
+
func Exec(stmt string, args ...any) error {
stmt = strings.TrimSpace(stmt)
if "" == stmt {
diff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.go
new file mode 100644
index 0000000000..285c725d80
--- /dev/null
+++ b/kernel/sql/encrypted_query.go
@@ -0,0 +1,217 @@
+// 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 (
+ "database/sql"
+ "strings"
+
+ "github.com/siyuan-note/logging"
+)
+
+// 本文件提供加密笔记本的 box-scoped 读查询。每个函数接收 boxID,路由到加密 db(已打开)或全局 db。
+// 调用方(model 层)在加密 box 上下文里改用这些 InBox 版;全局功能继续用原函数。
+
+// GetBlockInBox 按 id 在指定 box 的 db 里查 block。boxID 为空则查全局 db。
+func GetBlockInBox(id, boxID string) (ret *Block) {
+ ret = getBlockCache(id)
+ if nil != ret {
+ return
+ }
+ row := queryRowForBox(boxID, "SELECT * FROM blocks WHERE id = ?", id)
+ if row == nil {
+ return
+ }
+ ret = scanBlockRow(row)
+ if nil != ret {
+ putBlockCache(ret)
+ }
+ return
+}
+
+// GetBlocksInBox 按 ids 在指定 box 的 db 里批量查 block。
+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)
+ 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)
+ }
+ }
+ return
+}
+
+// GetRefTextInBox 按 defBlockID 在指定 box 的 db 里查引用文本。
+func GetRefTextInBox(defBlockID, boxID string) (ret string) {
+ row := queryRowForBox(boxID, "SELECT content FROM blocks WHERE id = ?", defBlockID)
+ if row == nil {
+ return
+ }
+ if err := row.Scan(&ret); err != nil {
+ if err != sql.ErrNoRows {
+ logging.LogErrorf("sql query failed: %s", err)
+ }
+ ret = ""
+ }
+ return
+}
+
+// QueryRefsByDefIDInBox 按 defBlockID 在指定 box 的 db 里查引用列表。
+func QueryRefsByDefIDInBox(defBlockID string, containChildren bool, boxID string) (ret []*Ref) {
+ sqlStmt := "SELECT * FROM refs WHERE def_block_id = ?"
+ if containChildren {
+ sqlStmt = "SELECT r.* FROM refs r JOIN blocktrees b ON r.def_block_root_id = b.root_id WHERE r.def_block_id = ?"
+ }
+ rows, err := queryForBox(boxID, sqlStmt, defBlockID)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var ref Ref
+ if err = rows.Scan(&ref.ID, &ref.DefBlockID, &ref.DefBlockParentID, &ref.DefBlockRootID, &ref.DefBlockPath, &ref.BlockID, &ref.RootID, &ref.Box, &ref.Path, &ref.Content, &ref.Markdown, &ref.Type); err != nil {
+ logging.LogErrorf("query scan field failed: %s", err)
+ return
+ }
+ ret = append(ret, &ref)
+ }
+ return
+}
+
+// QueryRootChildrenRefCountInBox 按 defRootID 在指定 box 的 db 里查子文档引用计数。
+func QueryRootChildrenRefCountInBox(defRootID, boxID string) (ret map[string]int) {
+ ret = map[string]int{}
+ sqlStmt := "SELECT r.def_block_root_id, COUNT(*) FROM refs r WHERE r.def_block_root_id IN (SELECT id FROM blocks WHERE root_id = ? AND type = 'd') GROUP BY r.def_block_root_id"
+ rows, err := queryForBox(boxID, sqlStmt, defRootID)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id string
+ var count int
+ if err = rows.Scan(&id, &count); err != nil {
+ logging.LogErrorf("query scan field failed: %s", err)
+ return
+ }
+ ret[id] = count
+ }
+ return
+}
+
+// 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
+ }
+ 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
+}
+
+// QueryTagSpansByLabelInBox 按 label 在指定 box 的 db 里查标签。
+func QueryTagSpansByLabelInBox(label, boxID string) (ret []*Span) {
+ sqlStmt := "SELECT * FROM spans WHERE type LIKE '%tag%' AND content LIKE ?"
+ rows, err := queryForBox(boxID, sqlStmt, "%#"+label+"#%")
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var span Span
+ if err = rows.Scan(&span.ID, &span.BlockID, &span.RootID, &span.Box, &span.Path, &span.Content, &span.Markdown, &span.Type, &span.IAL); err != nil {
+ logging.LogErrorf("query scan field failed: %s", err)
+ return
+ }
+ ret = append(ret, &span)
+ }
+ return
+}
+
+// QueryBookmarkBlocksInBox 在指定 box 的 db 里查书签块。
+func QueryBookmarkBlocksInBox(boxID string) (ret []*Block) {
+ sqlStmt := "SELECT * FROM blocks WHERE ial LIKE '%bookmark=%'"
+ rows, err := queryForBox(boxID, sqlStmt)
+ 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)
+ }
+ }
+ return
+}
+
+// itoa 是 strconv.Itoa 的简写别名,避免重复 import。
+func itoa(i int) string {
+ return intToStr(i)
+}
+
+// intToStr 把 int 转字符串(避免 import strconv 的循环)。
+func intToStr(i int) string {
+ if i == 0 {
+ return "0"
+ }
+ neg := false
+ if i < 0 {
+ neg = true
+ i = -i
+ }
+ var buf [20]byte
+ pos := len(buf)
+ for i > 0 {
+ pos--
+ buf[pos] = byte('0' + i%10)
+ i /= 10
+ }
+ if neg {
+ pos--
+ buf[pos] = '-'
+ }
+ return string(buf[pos:])
+}
diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.go
index 5f0458d599..87805eb199 100644
--- a/kernel/treenode/blocktree.go
+++ b/kernel/treenode/blocktree.go
@@ -19,8 +19,10 @@ package treenode
import (
"bytes"
"database/sql"
+ "encoding/hex"
"errors"
"fmt"
+ "os"
"runtime"
"runtime/debug"
"strings"
@@ -165,7 +167,7 @@ func GetBlockTreesByType(typ string) (ret []*BlockTree) {
func GetBlockTreeByBoxPath(boxID, path string) (ret *BlockTree) {
ret = &BlockTree{}
sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND path = ?"
- err := queryRow(sqlStmt, boxID, path).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
+ err := queryRowForBox(boxID, sqlStmt, boxID, path).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
if err != nil {
ret = nil
if errors.Is(err, sql.ErrNoRows) {
@@ -204,7 +206,7 @@ func CountBlocks() (ret int) {
func GetBlockTreeRootByPath(boxID, path string) (ret *BlockTree) {
ret = &BlockTree{}
sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND path = ? AND type = 'd'"
- err := queryRow(sqlStmt, boxID, path).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
+ err := queryRowForBox(boxID, sqlStmt, boxID, path).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
if err != nil {
ret = nil
if errors.Is(err, sql.ErrNoRows) {
@@ -220,7 +222,7 @@ func GetBlockTreeRootByHPath(boxID, hPath string) (ret *BlockTree) {
ret = &BlockTree{}
hPath = gulu.Str.RemoveInvisible(hPath)
sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND hpath = ? AND type = 'd'"
- err := queryRow(sqlStmt, boxID, hPath).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
+ err := queryRowForBox(boxID, sqlStmt, boxID, hPath).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
if err != nil {
ret = nil
if errors.Is(err, sql.ErrNoRows) {
@@ -235,7 +237,7 @@ func GetBlockTreeRootByHPath(boxID, hPath string) (ret *BlockTree) {
func GetBlockTreeRootsByHPath(boxID, hPath string) (ret []*BlockTree) {
hPath = gulu.Str.RemoveInvisible(hPath)
sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND hpath = ? AND type = 'd'"
- rows, err := query(sqlStmt, boxID, hPath)
+ rows, err := queryForBox(boxID, sqlStmt, boxID, hPath)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
return
@@ -256,7 +258,7 @@ func GetBlockTreeByHPathPreferredParentID(boxID, hPath, preferredParentID string
hPath = gulu.Str.RemoveInvisible(hPath)
var roots []*BlockTree
sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND hpath = ? AND parent_id = ? LIMIT 1"
- rows, err := query(sqlStmt, boxID, hPath, preferredParentID)
+ rows, err := queryForBox(boxID, sqlStmt, boxID, hPath, preferredParentID)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
return
@@ -508,7 +510,7 @@ func RemoveBlockTreesByPathPrefix(pathPrefix string) {
func GetBlockTreesByBoxID(boxID string) (ret []*BlockTree) {
sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ?"
- rows, err := query(sqlStmt, boxID)
+ rows, err := queryForBox(boxID, sqlStmt, boxID)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
return
@@ -527,7 +529,7 @@ func GetBlockTreesByBoxID(boxID string) (ret []*BlockTree) {
func RemoveBlockTreesByBoxID(boxID string) (ids []string) {
sqlStmt := "SELECT id FROM blocktrees WHERE box_id = ?"
- rows, err := query(sqlStmt, boxID)
+ rows, err := queryForBox(boxID, sqlStmt, boxID)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
return
@@ -543,7 +545,7 @@ func RemoveBlockTreesByBoxID(boxID string) (ids []string) {
}
sqlStmt = "DELETE FROM blocktrees WHERE box_id = ?"
- _, err = exec(sqlStmt, boxID)
+ _, err = execForBox(boxID, sqlStmt, boxID)
if err != nil {
logging.LogErrorf("sql exec [%s] failed: %s", sqlStmt, err)
return
@@ -593,13 +595,13 @@ func IndexBlockTree(tree *parse.Tree) {
indexBlockTreeLock.Lock()
defer indexBlockTreeLock.Unlock()
- if nil == db {
- // 数据库可能在重建过程中被置空,此时直接返回避免空指针解引用
+ // 加密 box 用独立 blocktree db;非加密 box 用全局 db(两者都可能为 nil——重建过程中)
+ if nil == db && getEncryptedBlockTreeDB(tree.Box) == nil {
logging.LogErrorf("database is nil")
return
}
- tx, err := db.Begin()
+ tx, err := beginTxForBox(tree.Box)
if err != nil {
logging.LogErrorf("begin transaction failed: %s", err)
return
@@ -614,7 +616,7 @@ func IndexBlockTree(tree *parse.Tree) {
func UpsertBlockTree(tree *parse.Tree) {
oldBts := map[string]*BlockTree{}
- bts := GetBlockTreesByRootID(tree.ID)
+ bts := GetBlockTreesByRootIDInBox(tree.ID, tree.Box)
for _, bt := range bts {
oldBts[bt.ID] = bt
}
@@ -654,13 +656,12 @@ func UpsertBlockTree(tree *parse.Tree) {
indexBlockTreeLock.Lock()
defer indexBlockTreeLock.Unlock()
- if nil == db {
- // 数据库可能在重建过程中被置空,此时直接返回避免空指针解引用
+ if nil == db && getEncryptedBlockTreeDB(tree.Box) == nil {
logging.LogErrorf("database is nil")
return
}
- tx, err := db.Begin()
+ tx, err := beginTxForBox(tree.Box)
if err != nil {
logging.LogErrorf("begin transaction failed: %s", err)
return
@@ -792,3 +793,193 @@ func vacuum() {
}
}
}
+
+// 加密笔记本的独立 blocktree db 注册表。boxID -> *sql.DB。
+var encryptedBlockTreeDBs = &sync.Map{}
+
+// OpenEncryptedBlockTreeDB 打开加密笔记本的独立 SQLCipher blocktree db。
+// 与 sql.OpenEncryptedDB 配对,UnlockBox 时调用。dek 为该 box 的 32 字节 DEK。
+func OpenEncryptedBlockTreeDB(boxID string, dek []byte) (err error) {
+ if _, loaded := encryptedBlockTreeDBs.Load(boxID); loaded {
+ return nil
+ }
+ dbPath := util.EncryptedBlockTreeDBPath(boxID)
+ dsn := dbPath + "?_journal_mode=WAL&_synchronous=OFF&_mmap_size=4294967296&_secure_delete=OFF" +
+ "&_cache_size=-128000&_page_size=32768&_busy_timeout=7000&_ignore_check_constraints=ON" +
+ "&_temp_store=MEMORY&_case_sensitive_like=OFF&_key=x'" + hex.EncodeToString(dek) + "'"
+ boxDB, err := sql.Open("sqlite3_extended", dsn)
+ if err != nil {
+ return err
+ }
+ boxDB.SetMaxOpenConns(7)
+ boxDB.SetMaxIdleConns(3)
+ boxDB.SetConnMaxLifetime(365 * 24 * time.Hour)
+ if err = initEncryptedBlockTreeTables(boxDB); err != nil {
+ boxDB.Close()
+ return err
+ }
+ encryptedBlockTreeDBs.Store(boxID, boxDB)
+ return nil
+}
+
+// CloseEncryptedBlockTreeDB 关闭并移除加密 blocktree db 连接。LockBox/Unmount 时调用。
+func CloseEncryptedBlockTreeDB(boxID string) {
+ if v, ok := encryptedBlockTreeDBs.LoadAndDelete(boxID); ok {
+ if boxDB, ok := v.(*sql.DB); ok {
+ boxDB.Close()
+ }
+ }
+}
+
+// CloseAllEncryptedBlockTreeDBs 关闭所有加密 blocktree db。LockAllBoxes 时调用。
+func CloseAllEncryptedBlockTreeDBs() {
+ encryptedBlockTreeDBs.Range(func(key, value any) bool {
+ encryptedBlockTreeDBs.Delete(key)
+ if boxDB, ok := value.(*sql.DB); ok {
+ boxDB.Close()
+ }
+ return true
+ })
+}
+
+// RemoveEncryptedBlockTreeDBFile 关闭连接并删除加密 blocktree db 文件。删笔记本时调用。
+func RemoveEncryptedBlockTreeDBFile(boxID string) {
+ CloseEncryptedBlockTreeDB(boxID)
+ dbPath := util.EncryptedBlockTreeDBPath(boxID)
+ for _, suffix := range []string{"", "-wal", "-shm"} {
+ if err := os.Remove(dbPath + suffix); err != nil && !os.IsNotExist(err) {
+ logging.LogErrorf("remove encrypted blocktree db file [%s] failed: %s", dbPath+suffix, err)
+ }
+ }
+}
+
+// getEncryptedBlockTreeDB 返回加密 box 的 blocktree db 句柄;未打开返回 nil。
+func getEncryptedBlockTreeDB(boxID string) *sql.DB {
+ if v, ok := encryptedBlockTreeDBs.Load(boxID); ok {
+ if boxDB, ok := v.(*sql.DB); ok {
+ return boxDB
+ }
+ }
+ return nil
+}
+
+// initEncryptedBlockTreeTables 在加密 blocktree db 上建表(幂等)。
+func initEncryptedBlockTreeTables(boxDB *sql.DB) (err error) {
+ stmts := []string{
+ "CREATE TABLE IF NOT EXISTS blocktrees (id, root_id, parent_id, box_id, path, hpath, updated, type)",
+ "CREATE INDEX IF NOT EXISTS idx_blocktrees_id ON blocktrees(id)",
+ "CREATE INDEX IF NOT EXISTS idx_blocktrees_root_id ON blocktrees(root_id)",
+ }
+ for _, s := range stmts {
+ if _, err = boxDB.Exec(s); err != nil {
+ return
+ }
+ }
+ return
+}
+
+// --- box-scoped wrapper(加密 box 用独立 db,否则用全局 db)---
+
+func queryForBox(box, stmt string, args ...any) (*sql.Rows, error) {
+ if boxDB := getEncryptedBlockTreeDB(box); boxDB != nil {
+ return boxDB.Query(stmt, args...)
+ }
+ return query(stmt, args...)
+}
+
+func queryRowForBox(box, stmt string, args ...any) *sql.Row {
+ if boxDB := getEncryptedBlockTreeDB(box); boxDB != nil {
+ return boxDB.QueryRow(stmt, args...)
+ }
+ return queryRow(stmt, args...)
+}
+
+func execForBox(box, stmt string, args ...any) (sql.Result, error) {
+ if boxDB := getEncryptedBlockTreeDB(box); boxDB != nil {
+ return boxDB.Exec(stmt, args...)
+ }
+ return exec(stmt, args...)
+}
+
+func beginTxForBox(box string) (tx *sql.Tx, err error) {
+ if boxDB := getEncryptedBlockTreeDB(box); boxDB != nil {
+ return boxDB.Begin()
+ }
+ return db.Begin()
+}
+
+// --- InBox 读函数(加密 box 内浏览时调用方传 boxID,路由到加密 db) ---
+
+// GetBlockTreeInBox 按 id 在指定 box 的 db 里查块树。boxID 为空则查全局 db。
+func GetBlockTreeInBox(id, boxID string) (ret *BlockTree) {
+ if boxID == "" {
+ return GetBlockTree(id)
+ }
+ ret = &BlockTree{}
+ sqlStmt := "SELECT * FROM blocktrees WHERE id = ?"
+ err := queryRowForBox(boxID, sqlStmt, id).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
+ if err != nil {
+ ret = nil
+ if !errors.Is(err, sql.ErrNoRows) {
+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
+ }
+ return
+ }
+ return
+}
+
+// GetBlockTreesInBox 按 ids 在指定 box 的 db 里批量查块树。
+func GetBlockTreesInBox(ids []string, boxID string) (ret map[string]*BlockTree) {
+ ret = map[string]*BlockTree{}
+ if 1 > len(ids) {
+ return
+ }
+ sqlStmt := "SELECT * FROM blocktrees WHERE id IN (" + strings.Repeat("?,", len(ids)-1) + "?)"
+ args := make([]any, len(ids))
+ for i, id := range ids {
+ 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() {
+ var block BlockTree
+ if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); err != nil {
+ logging.LogErrorf("query scan field failed: %s", err)
+ return
+ }
+ ret[block.ID] = &block
+ }
+ return
+}
+
+// ExistBlockTreeInBox 判断指定 box 的 db 里是否存在该 id 的块树。
+func ExistBlockTreeInBox(id, boxID string) bool {
+ sqlStmt := "SELECT 1 FROM blocktrees WHERE id = ? LIMIT 1"
+ row := queryRowForBox(boxID, sqlStmt, id)
+ var tmp any
+ return row.Scan(&tmp) == nil
+}
+
+// GetBlockTreesByRootIDInBox 按 rootID 在指定 box 的 db 里查块树。
+func GetBlockTreesByRootIDInBox(rootID, boxID string) (ret []*BlockTree) {
+ sqlStmt := "SELECT * FROM blocktrees WHERE root_id = ?"
+ rows, err := queryForBox(boxID, sqlStmt, rootID)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var block BlockTree
+ if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); err != nil {
+ logging.LogErrorf("query scan field failed: %s", err)
+ return
+ }
+ ret = append(ret, &block)
+ }
+ return
+}
diff --git a/kernel/util/working.go b/kernel/util/working.go
index 51880380ed..5d8f9f99f6 100644
--- a/kernel/util/working.go
+++ b/kernel/util/working.go
@@ -605,6 +605,11 @@ func EncryptedDBPath(boxID string) string {
return filepath.Join(TempDir, "siyuan-encrypted-"+boxID+".db")
}
+// EncryptedBlockTreeDBPath 返回加密笔记本的独立 SQLCipher blocktree db 文件路径。
+func EncryptedBlockTreeDBPath(boxID string) string {
+ return filepath.Join(TempDir, "siyuan-encrypted-"+boxID+"-blocktree.db")
+}
+
func tryLockWorkspace() {
WorkspaceLock = flock.New(filepath.Join(WorkspaceDir, ".lock"))
ok, err := WorkspaceLock.TryLock()