# 依赖优化与 API 现代化实现计划

> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

**Goal:** 优化 Cargo.toml feature 组织，统一错误类型为 DbError，现代化公共 API（Into 转换、语义化命名），新增 ultra-minimal 预设配置。

**Architecture:** 重构 feature 依赖关系，使 sql-parser 独立，permission 不再直接依赖 serde_yaml。统一错误类型入口，简化配置和连接池 API。

**Tech Stack:** Rust 1.85+, Sea-ORM 2.0.0-rc.27, Tokio 1.42, thiserror 2.0

---

## 阶段一：依赖与 Feature 优化

### Task 1: 重构 Cargo.toml feature 依赖关系

**Files:**
- Modify: `Cargo.toml`

**Step 1: 分析当前 feature 依赖关系**

```bash
# 查看当前依赖结构
cargo tree --features permission -p dbnexus -i serde_yaml 2>/dev/null || echo "检查依赖关系"
```

**Step 2: 修改 feature 定义**

修改 `Cargo.toml` 中的 feature 定义：

```toml
# Core features (可选，用于最小化部署)
sql-parser = ["dep:sqlparser", "dep:regex", "dep:once_cell"]

# permission 移除直接的 serde_yaml 依赖，改为可选
permission = [
    "dep:lru",
    "dep:dashmap",
    "sql-parser",  # 间接依赖，使用 sqlparser 的 regex
]

# Config features (配置文件支持)
config-yaml = ["dep:serde_yaml", "dep:regex"]
config-toml = ["dep:toml", "dep:regex"]
config-env = ["dep:regex"]  # 简化：仅需要 regex
```

**Step 3: 添加 ultra-minimal preset**

```toml
# 嵌入式最小配置（真正精简，不包含 permission/sql-parser/macros）
ultra-minimal = [
    "runtime-tokio-rustls",
    "sqlite",
    "config-env",
    "lru",
]
```

**Step 4: 测试 ultra-minimal 构建**

```bash
cargo build --release --features ultra-minimal 2>&1 | tail -10
```

**Step 5: Commit**

```bash
git add Cargo.toml
git commit -m "refactor: optimize feature dependencies and add ultra-minimal preset"
```

---

## 阶段二：统一错误类型

### Task 2: 重构错误模块

**Files:**
- Modify: `src/error/mod.rs`
- Modify: `src/lib.rs` (更新 re-export)

**Step 1: 编写测试**

```rust
// tests/core/integration/error_unification_test.rs
#[cfg(test)]
mod tests {
    use dbnexus::DbResult;

    #[test]
    fn test_db_result_alias_exists() {
        let result: DbResult<String> = Ok("test".to_string());
        assert!(result.is_ok());
    }

    #[test]
    fn test_db_error_from_sea_orm() {
        // 测试 DbError 可以从 sea_orm::DbErr 转换
        use dbnexus::DbError;
        let db_err = sea_orm::DbErr::ConnectionClosed;
        let error: DbError = db_err.into();
        assert!(format!("{:?}", error).contains("ConnectionClosed"));
    }
}
```

**Step 2: 运行测试验证**

```bash
cargo test --features sqlite test_db_result_alias_exists 2>&1 | tail -10
```

**Step 3: 修改错误模块**

```rust
// src/error/mod.rs

/// 统一的数据库错误类型
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct DbError(#[from] sea_orm::DbErr);

impl DbError {
    /// 检查是否为连接错误
    pub fn is_connection_error(&self) -> bool {
        matches!(
            self.0,
            sea_orm::DbErr::ConnectionClosed | sea_orm::DbErr::ConnnectionAcquire
        )
    }

    /// 检查是否为查询错误
    pub fn is_query_error(&self) -> bool {
        matches!(
            self.0,
            sea_orm::DbErr::Query(_) | sea_orm::DbErr::RecordNotFound
        )
    }
}

/// 连接池错误
#[derive(Debug, thiserror::Error)]
pub enum PoolError {
    #[error("Connection pool exhausted")]
    Exhausted,
    #[error("Acquire timeout: {0}ms")]
    Timeout(u64),
    #[error("Invalid configuration: {0}")]
    InvalidConfig(&'static str),
}

/// 权限错误
#[derive(Debug, thiserror::Error)]
#[error("Permission denied: {0}")]
pub struct PermissionError(String);

/// 配置错误
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("Configuration file not found")]
    FileNotFound,
    #[error("Invalid configuration format")]
    InvalidFormat,
    #[error("Missing required field: {0}")]
    MissingField(&'static str),
    #[error("Validation failed: {0}")]
    Validation(&'static str),
}

/// 统一的 Result 类型
pub type DbResult<T> = Result<T, DbError>;
```

**Step 4: 更新 lib.rs 导出**

```rust
// src/lib.rs
pub use error::{ConfigError, DbError, DbResult, PermissionError, PoolError};
```

**Step 5: 运行测试验证**

```bash
cargo test --features sqlite error 2>&1 | tail -20
```

**Step 6: Commit**

```bash
git add src/error/mod.rs src/lib.rs tests/core/integration/error_unification_test.rs
git commit -m "refactor: unify error types with DbResult alias"
```

---

## 阶段三：API 现代化

### Task 3: 优化配置 API

**Files:**
- Modify: `src/config.rs`

**Step 1: 编写测试**

```rust
// tests/core/integration/config_api_test.rs
#[test]
fn test_config_builder_into_api() {
    use dbnexus::config::DbConfigBuilder;

    // 测试 Into<String> API
    let config = DbConfigBuilder::new()
        .url("sqlite::memory:")  // &str 自动转换为 String
        .max_connections(20)
        .build()
        .unwrap();

    assert_eq!(config.max_connections(), 20);
}
```

**Step 2: 运行测试验证**

```bash
cargo test --features sqlite test_config_builder_into_api 2>&1 | tail -10
```

**Step 3: 修改配置 API**

```rust
// src/config.rs - DbConfigBuilder 部分

impl DbConfigBuilder {
    /// 设置数据库 URL（使用 Into<String>）
    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    /// 设置最大连接数
    pub fn max_connections(mut self, n: u32) -> Self {
        self.max_connections = Some(n);
        self
    }

    /// 设置最小连接数
    pub fn min_connections(mut self, n: u32) -> Self {
        self.min_connections = Some(n);
        self
    }

    /// 设置空闲超时（秒）
    pub fn idle_timeout(mut self, timeout: u64) -> Self {
        self.idle_timeout = Some(timeout);
        self
    }

    /// 设置获取超时（毫秒）
    pub fn acquire_timeout(mut self, timeout: u64) -> Self {
        self.acquire_timeout = Some(timeout);
        self
    }

    /// 设置权限配置文件路径
    pub fn permissions_path(mut self, path: impl AsRef<Path>) -> Self {
        self.permissions_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// 设置迁移文件目录
    pub fn migrations_dir(mut self, path: impl AsRef<Path>) -> Self {
        self.migrations_dir = Some(path.as_ref().to_path_buf());
        self
    }

    /// 设置是否自动迁移
    pub fn auto_migrate(mut self, auto: bool) -> Self {
        self.auto_migrate = Some(auto);
        self
    }

    /// 设置迁移超时（秒）
    pub fn migration_timeout(mut self, timeout: u64) -> Self {
        self.migration_timeout = Some(timeout);
        self
    }

    /// 设置管理员角色名称
    pub fn admin_role(mut self, role: impl Into<String>) -> Self {
        self.admin_role = Some(role.into());
        self
    }

    /// 设置预热超时时间（秒）
    pub fn warmup_timeout(mut self, timeout: u64) -> Self {
        self.warmup_timeout = Some(timeout);
        self
    }

    /// 设置预热重试次数
    pub fn warmup_retries(mut self, retries: u32) -> Self {
        self.warmup_retries = Some(retries);
        self
    }
}

// 为 DbConfigBuilder 添加 Default
impl Default for DbConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}
```

**Step 4: 运行测试验证**

```bash
cargo test --features sqlite config_api 2>&1 | tail -15
```

**Step 5: Commit**

```bash
git add src/config.rs tests/core/integration/config_api_test.rs
git commit -m "refactor: modernize config API with Into<String> and Default"
```

---

### Task 4: 优化连接池 API

**Files:**
- Modify: `src/pool/mod.rs`
- Modify: `src/pool/db_pool.rs`
- Modify: `src/pool/session.rs`

**Step 1: 编写测试**

```rust
// tests/core/integration/pool_api_test.rs
#[tokio::test]
async fn test_pool_with_role_api() {
    use dbnexus::{DbPool, DbConfigBuilder};

    let config = DbConfigBuilder::new()
        .url("sqlite::memory:")
        .build()
        .unwrap();

    let pool = DbPool::from_config(&config).await.unwrap();

    // 测试 with_role API
    let session = pool.with_role("admin").await.unwrap();

    // 测试 health_check API
    assert!(pool.health_check().await);

    // 测试 status API
    let status = pool.status();
    assert!(status.max_connections > 0);
}
```

**Step 2: 运行测试验证**

```bash
cargo test --features sqlite test_pool_with_role_api 2>&1 | tail -10
```

**Step 3: 修改连接池 API**

```rust
// src/pool/mod.rs

/// 连接池状态
#[derive(Debug, Clone)]
pub struct PoolStatus {
    /// 最大连接数
    pub max_connections: u32,
    /// 当前活跃连接数
    pub active_connections: u32,
    /// 空闲连接数
    pub idle_connections: u32,
    /// 等待获取连接的任务数
    pub waiters: u32,
}

impl DbPool {
    /// 从配置创建连接池
    pub async fn from_config(config: &DbConfig) -> DbResult<Self> {
        // 实现逻辑
    }

    /// 获取会话（使用语义化命名）
    pub async fn with_role(&self, role: impl Into<String>) -> DbResult<Session> {
        let role = role.into();
        // 实现逻辑
    }

    /// 健康检查
    pub async fn health_check(&self) -> bool {
        // 实现逻辑
    }

    /// 获取池状态
    pub fn status(&self) -> PoolStatus {
        // 实现逻辑
    }
}
```

**Step 4: 简化 Session API**

```rust
// src/pool/session.rs

impl Session {
    /// 开始事务
    pub async fn begin(&mut self) -> DbResult<()> {
        // 实现逻辑
    }

    /// 提交事务
    pub async fn commit(&mut self) -> DbResult<()> {
        // 实现逻辑
    }

    /// 回滚事务
    pub async fn rollback(&mut self) -> DbResult<()> {
        // 实现逻辑
    }

    /// 执行原始 SQL（统一入口）
    pub async fn execute_raw(&self, sql: &str) -> DbResult<ExecResult> {
        // 实现逻辑
    }

    /// 执行 DDL 语句
    pub async fn execute_ddl(&self, sql: &str) -> DbResult<ExecResult> {
        // 实现逻辑
    }
}
```

**Step 5: 运行测试验证**

```bash
cargo test --features sqlite pool_api 2>&1 | tail -20
```

**Step 6: Commit**

```bash
git add src/pool/mod.rs src/pool/db_pool.rs src/pool/session.rs
git commit -m "refactor: modernize pool API with semantic naming"
```

---

### Task 5: 优化宏导出

**Files:**
- Modify: `src/lib.rs`
- Modify: `macros/src/lib.rs` (如需要)

**Step 1: 更新宏导出**

```rust
// src/lib.rs

#[cfg(feature = "macros")]
pub use dbnexus_macros::{
    db_entity,      // 主入口
    db_crud,        // CRUD 宏
    db_permission,  // 权限宏
    db_audit,       // 审计宏
    db_cache,       // 缓存宏
};

// 废弃旧名（保持向后兼容）
#[cfg(feature = "macros")]
#[deprecated(since = "0.2.0", note = "Use db_entity instead")]
pub use dbnexus_macros::DbEntity as Entity;
```

**Step 2: 测试编译**

```bash
cargo build --features "sqlite,macros" 2>&1 | tail -10
```

**Step 3: Commit**

```bash
git add src/lib.rs
git commit -m "refactor: simplify macro exports with semantic naming"
```

---

## 阶段四：测试验证

### Task 6: 完整测试验证

**Files:**
- 运行现有测试

**Step 1: 测试 ultra-minimal 构建**

```bash
# 测试 ultra-minimal
cargo build --release --features ultra-minimal 2>&1 | tail -10
cargo test --features ultra-minimal 2>&1 | tail -15
```

**Step 2: 测试默认配置构建**

```bash
# 测试默认配置
cargo build --release --features sqlite 2>&1 | tail -10
cargo test --features sqlite 2>&1 | tail -15
```

**Step 3: 测试完整特性构建**

```bash
# 测试所有特性
cargo build --all-features 2>&1 | tail -10
cargo test --all-features 2>&1 | tail -15
```

**Step 4: 验证二进制大小变化**

```bash
# 比较不同配置的大小
echo "=== ultra-minimal ==="
ls -lh target/release/libdbnexus.rlib 2>/dev/null || echo "library built"

echo "=== default ==="
ls -lh target/release/libdbnexus.rlib 2>/dev/null || echo "library built"
```

**Step 5: Commit**

```bash
git commit -a -m "chore: verify all configurations build and pass tests"
```

---

## 执行摘要

**变更文件清单：**
- `Cargo.toml` - feature 依赖优化，新增 ultra-minimal preset
- `src/error/mod.rs` - 统一错误类型
- `src/config.rs` - API 现代化（Into 转换）
- `src/pool/mod.rs` - 连接池 API 优化
- `src/pool/db_pool.rs` - 实现更新
- `src/pool/session.rs` - Session API 简化
- `src/lib.rs` - 导出更新
- `tests/core/integration/error_unification_test.rs` - 新增测试
- `tests/core/integration/config_api_test.rs` - 新增测试
- `tests/core/integration/pool_api_test.rs` - 新增测试

**预期结果：**
- feature 依赖关系更清晰
- ultra-minimal 配置可正常构建
- API 更现代化（Into 转换、语义化命名）
- 向后兼容性保持

---

**Plan complete and saved to `docs/plans/2026-01-21-dependencies-api-optimization.md`.**

**Two execution options:**

**1. Subagent-Driven (this session)** - I dispatch fresh subagent per task, review between tasks, fast iteration

**2. Parallel Session (separate)** - Open new session with executing-plans, batch execution with checkpoints

**Which approach?**
