docDB/README.md

100 lines
3.8 KiB
Markdown
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.

# @go/docDB
`docDB` 是一个独立的高级文档存储引擎,基于 `@go/tableDB` 构建,提供全自动版本管理、历史存证、流式大文件处理及生命周期钩子。
## 📦 安装
```bash
go get apigo.cc/go/docDB
```
## 🛠 核心功能
1. **路径驱动**:以 `Path` 作为文档的唯一标识。
2. **版本管控**`SetDoc` 强制提升版本号并自动归档旧版;`SetMeta` 仅更新属性不触碰版本。
3. **重命名支持**:提供 `Move` API 允许修改文档路径,而无需重新上传文件,历史记录自动同步。
4. **历史存证**:即使文档被删除,其所有历史版本(包括被删除前的最后一版)依然可通过 `GetByVersion` 获取。
5. **权限隔离**:完全继承 `tableDB` 的 RLS (Row Level Security) 体系。
6. **流式上传**`BinaryContent` 采用 `io.Reader` 接口,支持低内存处理 GB 级大文件落盘。
7. **事件驱动**:提供标准的 `Hooks` 机制,支持监听文档创建、更新、移除及移动。
8. **智能提取**:自动提取 Markdown 目录结构 (ToC),且能智能跳过代码块内容。
## 🚀 API 指南
### 1. 初始化与授权
```go
import (
"apigo.cc/go/docDB"
"apigo.cc/go/log"
)
// 获取 docDB 引擎 (自动完成系统表与业务表初始化)
// dsn: 数据库连接字符串 (如 sqlite://docs.db)
// logger: 日志对象
// redis: 分布式 ID 用的 Redis 地址 (可选)
// baseDir: 物理文件存储根路径
engine := docDB.GetDB("sqlite://docs.db", log.DefaultLogger, "localhost:6379", "./storage_root")
// 授权并获取操作句柄
db := engine.Auth("user_123")
```
### 2. 文档操作 (DocDB API)
- **`SetDoc(doc *Document) error`**
- 保存文档。通过 `doc.Path` 识别。如果是更新,会自动归档旧版本并递增 `version`
- **`SetMeta(path string, meta map[string]any) error`**
- 通过路径更新文档元数据。**不提升版本号**。
- **`Move(oldPath, newPath string) error`**
- 修改文档路径(重命名)。历史记录将关联至新路径。
- **`Get(path string) (*Document, error)`**
- 获取文档的当前最新版本。
- **`GetByVersion(path string, version uint64) (*Document, error)`**
- 获取指定版本的文档。支持已删除文档的历史回溯。
- **`Remove(path string) error`**
- 删除文档。删除前会自动将当前最后一版归档至历史表。
### 3. 生命周期钩子 (Hooks)
```go
// 监听新文档创建
engine.Hooks.OnCreatedDoc = func(doc *docDB.Document) {
fmt.Println("New doc created:", doc.Path)
}
// 监听内容更新 (SetDoc 触发SetMeta 不触发)
engine.Hooks.OnUpdatedDoc = func(doc *docDB.Document) {
fmt.Println("Doc updated:", doc.Path, "Version:", doc.Version)
}
// 监听文档删除
engine.Hooks.OnRemoved = func(path string) {
fmt.Println("Doc removed:", path)
}
// 监听文档重命名
engine.Hooks.OnMoved = func(oldPath, newPath string) {
fmt.Println("Doc moved from", oldPath, "to", newPath)
}
```
## 📝 数据结构
### Document
| 字段 | 类型 | 说明 |
| :--- | :--- | :--- |
| `Path` | `string` | **核心标识** (如 /docs/readme.md) |
| `BinaryContent` | `io.Reader` | 瞬态流,用于接收上传内容 |
| `TextContent` | `string` | 文档正文 |
| `Version` | `uint64` | 单调递增的版本号 |
| `ToC` | `[]ToCNode` | 自动生成的目录树 |
| `CreateTime` | `int64` | 创建时间 (自动维护) |
| `UpdateTime` | `int64` | 最后更新时间 (自动维护) |
## 💡 注意事项
- **ID 封装**:底层依然使用唯一 ID 维护物理存储,但对 API 调用者完全隐藏。
- **自动初始化**`GetDB` 内部使用 `_system` 权限自动维护系统表及 `_Doc`, `_Doc_History` 的结构。
- **元数据自动维护**`Creator`, `Updater`, `CreateTime`, `UpdateTime` 由底层 `tableDB` 统一管控,无需显式设置。