Files
AI-Expert-Sidebar/internal/service/knowledge_svc.go
T
2026-04-01 15:29:35 +08:00

59 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package service 提供知识库条目的增删操作。
// 此文件专注于"破坏性"操作(删除、清空),与搜索/导入分开放置,
// 便于代码审计时快速定位所有写入操作。
package service
import (
"fmt"
"AI-Expert-Sidebar/internal/database"
"AI-Expert-Sidebar/internal/models"
)
// DeleteItems 从当前活跃知识库中物理删除指定 ID 的条目。
//
// # 设计决策
//
// - 使用"物理删除"而非"软删除"deleted_at 字段):
// 本项目定位为本地隐私工具,用户期望删除就是彻底删除,
// 不需要回收站或审计日志,软删除只会增加查询复杂度。
//
// - ids 为空时提前返回 nil,避免 GORM 生成 "DELETE ... WHERE id IN ()"
// 这样的非法 SQL 语句。
//
// - 使用 db.Delete(&models.Entry{}, ids) 的原因:
// GORM 会展开 ids 为 "WHERE id IN (?,?,?)",一次网络往返完成批量删除,
// 比循环单条删除效率高出 N 倍。
func DeleteItems(ids []uint) error {
if len(ids) == 0 {
return nil
}
db := database.Get()
if db == nil {
return fmt.Errorf("知识库未初始化,请先选择或创建一个知识库")
}
return db.Delete(&models.Entry{}, ids).Error
}
// ClearDatabase 清空当前活跃知识库的所有条目,但保留 entries 表结构。
//
// # 与"删除知识库"的区别
//
// ClearDatabase 只删除行数据,表和 .db 文件依然存在,
// 用户可以立刻向空库重新导入新的 CSV/Excel 数据。
// 对比 DeleteLibrary(删除整个 .db 文件),此操作更轻量,
// 适合"重置知识库内容但保留库名"的场景。
//
// # WHERE 子句说明
//
// SQLite 的 GORM 驱动需要显式 WHERE 条件才能执行全表删除,
// 否则会因缺少 WHERE 子句而报错(与 MySQL 行为不同)。
// "WHERE id > 0" 是符合 SQL 标准的"全匹配"惯用写法。
func ClearDatabase() error {
db := database.Get()
if db == nil {
return fmt.Errorf("知识库未初始化,请先选择或创建一个知识库")
}
return db.Where("id > 0").Delete(&models.Entry{}).Error
}