docDB/README.md

81 lines
3.1 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/tableDB"
)
// 创建基础数据库连接 (tableDB 层)
unauthorizedDB := tableDB.GetDB("sqlite://docs.db", logger)
// 获取 docDB 引擎 (自动完成表结构初始化)
engine := docDB.GetDB(unauthorizedDB, "./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) { /* ... */ }
engine.Hooks.OnUpdatedDoc = func(doc *docDB.Document) { /* ... */ }
engine.Hooks.OnRemoved = func(path string) { /* ... */ }
engine.Hooks.OnMoved = func(oldPath, newPath string) { /* ... */ }
```
## 📝 数据结构
### Document
| 字段 | 类型 | 说明 |
| :--- | :--- | :--- |
| `Path` | `string` | **核心标识** (如 /docs/readme.md) |
| `BinaryContent` | `io.Reader` | 瞬态流,用于接收上传内容 |
| `TextContent` | `string` | 文档正文 |
| `Version` | `uint64` | 单调递增的版本号 |
| `ToC` | `[]ToCNode` | 自动生成的目录树 |
## 💡 注意事项
- **ID 封装**:底层依然使用唯一 ID 维护物理存储,但对 API 调用者完全隐藏。
- **自动初始化**`GetDB` 会自动维护 `_Doc``_Doc_History` 的表结构。