dbnexus 0.1.3

An enterprise-grade database abstraction layer for Rust with built-in permission control and connection pooling
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
<div align="center">

<a name="dbnexus"></a>

<img src="docs/image/logo/logo.png" alt="DBNexus Logo" width="200" style="margin-bottom: 16px;">

<p>
  <!-- CI/CD 状态 -->
  <a href="https://github.com/Kirky-X/dbnexus/actions/workflows/ci.yml">
    <img src="https://github.com/Kirky-X/dbnexus/actions/workflows/ci.yml/badge.svg" alt="CI 状态" style="display:inline;margin:0 4px;">
  </a>
  <!-- 版本 -->
  <a href="https://crates.io/crates/dbnexus">
    <img src="https://img.shields.io/crates/v/dbnexus.svg" alt="版本" style="display:inline;margin:0 4px;">
  </a>
  <!-- 文档 -->
  <a href="https://docs.rs/dbnexus">
    <img src="https://docs.rs/dbnexus/badge.svg" alt="文档" style="display:inline;margin:0 4px;">
  </a>
  <!-- 下载量 -->
  <a href="https://crates.io/crates/dbnexus">
    <img src="https://img.shields.io/crates/d/dbnexus.svg" alt="下载量" style="display:inline;margin:0 4px;">
  </a>
  <!-- 许可证 -->
  <a href="https://github.com/Kirky-X/dbnexus/blob/main/LICENSE">
    <img src="https://img.shields.io/crates/l/dbnexus.svg" alt="许可证" style="display:inline;margin:0 4px;">
  </a>
  <!-- Rust 版本 -->
  <a href="https://www.rust-lang.org/">
    <img src="https://img.shields.io/badge/rust-1.85+-orange.svg" alt="Rust 1.85+" style="display:inline;margin:0 4px;">
  </a>
</p>

<p align="center">
  <strong>企业级 Rust 数据库抽象层</strong>
</p>

<p align="center">
  <a href="#features" style="color:#3B82F6;">✨ 功能特性</a><a href="#quick-start" style="color:#3B82F6;">🚀 快速开始</a><a href="#documentation" style="color:#3B82F6;">📚 文档</a><a href="#examples" style="color:#3B82F6;">💻 示例</a><a href="#contributing" style="color:#3B82F6;">🤝 贡献</a>
</p>

</div>

---

### 🎯 基于 Sea-ORM 构建的高性能、高安全性、功能丰富的数据库访问层

DBNexus 提供了一种**声明式**的数据库访问方法:

| ✨ 类型安全 | 🔒 权限控制 | 🏊 智能连接池 | 📊 企业级监控 |
|:---------:|:----------:|:--------------:|:--------:|
| 编译时检查 | 表级 RBAC | RAII 自动管理 | Prometheus 指标 |

```rust
use dbnexus::{DbPool, DbEntity, db_crud, db_permission};
use sea_orm::entity::prelude::*;

#[derive(DbEntity, DeriveEntityModel, DeriveModel, DeriveActiveModel)]
#[sea_orm(table_name = "users")]
#[db_crud]
#[db_permission(roles = ["admin", "manager"], operations = ["SELECT", "INSERT"])]
pub struct User {
    #[sea_orm(primary_key)]
    pub id: i64,
    pub name: String,
    pub email: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = DbPool::new("sqlite::memory:").await?;
    let session = pool.get_session("admin").await?;
    let user = User { id: 1, name: "Alice".to_string(), email: "alice@example.com".to_string() };
    User::insert(&session, user).await?;
    Ok(())
}
```

---

## 📋 目录

<details open style="border-radius:8px; padding:16px; border:1px solid #E2E8F0;">
<summary style="cursor:pointer; font-weight:600; color:#1E293B;">📑 目录(点击展开)</summary>

- [✨ 功能特性]#features
- [🚀 快速开始]#quick-start
  - [📦 安装]#installation
  - [💡 基本用法]#basic-usage
  - [🔒 权限控制]#permission-control
- [🎨 特性标志]#feature-flags
- [📚 文档]#documentation
- [💻 示例]#examples
- [🏗️ 架构]#architecture
- [🔒 安全性]#security
- [🧪 测试]#testing
- [🤝 贡献]#contributing
- [📄 许可证]#license
- [🙏 致谢]#acknowledgments

</details>

---

## <span id="features">✨ 功能特性</span>

<div align="center" style="margin: 24px 0;">

| 🎯 核心功能 | ⚡ 企业级功能 |
|:----------:|:----------:|
| 始终可用 | 按需启用 |

</div>

<table style="width:100%; border-collapse: collapse;">
<tr>
<td width="50%" style="vertical-align:top; padding: 16px; border-radius:8px; border:1px solid #E2E8F0;">

### 🎯 核心功能(始终可用)

| 状态 | 功能 | 描述 |
|:----:|------|------|
|| **连接池管理** | RAII 风格的自动连接生命周期管理 |
|| **权限控制** | 基于角色的表级访问控制(RBAC) |
|| **过程宏** | 自动生成 CRUD 方法和权限检查 |
|| **SQL 解析器** | 提取操作类型和目标表 |
|| **事务支持** | 完整的事务管理 |
|| **多数据库支持** | SQLite、PostgreSQL、MySQL |

</td>
<td width="50%" style="vertical-align:top; padding: 16px; border-radius:8px; border:1px solid #E2E8F0;">

### ⚡ 企业级功能

| 状态 | 功能 | 描述 |
|:----:|------|------|
| 🔍 | **指标监控** | Prometheus 指标导出(`metrics` 特性) |
| 📊 | **分布式追踪** | OpenTelemetry 集成(`tracing` 特性) |
| 📝 | **审计日志** | 所有操作的自动审计(`audit` 特性) |
| 🗄️ | **数据库迁移** | 自动迁移执行(`migration` 特性) |
| 🔀 | **数据分片** | 支持分片策略(`sharding` 特性) |
| 🌐 | **全局索引** | 跨分片查询(`global-index` 特性) |
| 💾 | **缓存** | LRU 缓存支持(`cache` 特性) |
| 🔐 | **权限引擎** | 高级权限系统(`permission-engine` 特性) |

</td>
</tr>
</table>

### 📦 特性预设

| 预设 | 特性 | 使用场景 |
|------|------|----------|
| <span style="color:#166534; padding:4px 8px; border-radius:4px;">minimal</span> | `runtime-tokio-rustls`, `sqlite`, `config-env`, `lru`, `regex`, `sql-parser` | 嵌入式设备最小配置 |
| <span style="color:#1E40AF; padding:4px 8px; border-radius:4px;">microservice</span> | `runtime-tokio-rustls`, `postgres`, `permission`, `sql-parser`, `config-env`, `pool-health-check`, `config-yaml`, `regex`, `lru` | 微服务配置 |
| <span style="color:#991B1B; padding:4px 8px; border-radius:4px;">all-optional</span> | 除数据库驱动外的所有企业级特性 | 完整企业功能 |

---

## <span id="quick-start">🚀 快速开始</span>

### <span id="installation">📦 安装</span>

在你的 `Cargo.toml` 中添加:

```toml
[dependencies]
dbnexus = "0.1.1"
tokio = { version = "1.42", features = ["rt-multi-thread", "macros"] }
sea-orm = { version = "2.0.0-rc.27", features = ["macros"] }
```

### <span id="basic-usage">💡 基本用法</span>

<div align="center" style="margin: 24px 0;">

#### 🎬 5 分钟快速开始

</div>

<table style="width:100%; border-collapse: collapse;">
<tr>
<td width="50%" style="padding: 16px; vertical-align:top;">

**步骤 1:定义实体**

```rust
use dbnexus::{DbPool, DbEntity, db_crud};
use sea_orm::entity::prelude::*;

#[derive(DbEntity, DeriveEntityModel, DeriveModel, DeriveActiveModel)]
#[sea_orm(table_name = "users")]
#[db_crud]
pub struct User {
    #[sea_orm(primary_key)]
    pub id: i64,
    pub name: String,
    pub email: String,
}
```

</td>
<td width="50%" style="padding: 16px; vertical-align:top;">

**步骤 2:创建连接池**

```rust
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = DbPool::new("sqlite::memory:").await?;
    let session = pool.get_session("admin").await?;
    Ok(())
}
```

</td>
</tr>
<tr>
<td width="50%" style="padding: 16px; vertical-align:top;">

**步骤 3:插入数据**

```rust
let user = User {
    id: 1,
    name: "Alice".to_string(),
    email: "alice@example.com".to_string(),
};
User::insert(&session, user).await?;
```

</td>
<td width="50%" style="padding: 16px; vertical-align:top;">

**步骤 4:查询数据**

```rust
let users = User::find_all(&session).await?;
println!("找到 {} 个用户", users.len());
```

</td>
</tr>
</table>

### <span id="permission-control">🔒 权限控制</span>

```rust
use dbnexus::{DbPool, DbEntity, db_crud, db_permission};
use sea_orm::entity::prelude::*;

#[derive(DbEntity, DeriveEntityModel, DeriveModel, DeriveActiveModel)]
#[sea_orm(table_name = "users")]
#[db_crud]
#[db_permission(roles = ["admin", "manager"], operations = ["SELECT", "INSERT"])]
pub struct User {
    #[sea_orm(primary_key)]
    pub id: i64,
    pub name: String,
}

// 管理员可以访问
let session = pool.get_session("admin").await?;
User::find_all(&session).await?;

// 普通用户会被拒绝
let session = pool.get_session("guest").await?;
User::find_all(&session).await?; // 错误:权限被拒绝
```

---

## <span id="feature-flags">🎨 特性标志</span>

### 数据库驱动(选择一个)

```toml
# SQLite(默认)
dbnexus = { version = "0.1.1", features = ["sqlite"] }

# PostgreSQL
dbnexus = { version = "0.1.1", features = ["postgres"] }

# MySQL
dbnexus = { version = "0.1.1", features = ["mysql"] }
```

### 运行时

```toml
# Tokio with RustLS(默认)
dbnexus = { version = "0.1.1", features = ["runtime-tokio-rustls"] }

# Tokio with Native TLS
dbnexus = { version = "0.1.1", features = ["runtime-tokio-native-tls"] }

# AsyncStd
dbnexus = { version = "0.1.1", features = ["runtime-async-std"] }
```

### 可选功能

```toml
# 核心功能
dbnexus = { version = "0.1.1", features = [
    "permission",      # 权限控制
    "sql-parser",      # SQL 解析
    "macros",          # 过程宏
] }

# 企业级功能
dbnexus = { version = "0.1.1", features = [
    "metrics",         # Prometheus 指标
    "tracing",         # 分布式追踪
    "audit",           # 审计日志
    "migration",       # 数据库迁移
    "sharding",        # 数据分片
    "permission-engine" # 高级权限引擎
] }

# 配置
dbnexus = { version = "0.1.1", features = [
    "config-yaml",     # YAML 配置支持
    "config-toml",     # TOML 配置支持
    "config-env",      # 环境变量(默认)
] }
```

---

## <span id="documentation">📚 文档</span>

<div align="center" style="margin: 24px 0;">

<table style="width:100%; max-width: 800px;">
<tr>
<td align="center" width="33%" style="padding: 16px;">
<a href="USER_GUIDE.md" style="text-decoration:none;">
<div style="padding: 24px; border-radius:12px; transition: transform 0.2s;">
<b style="color:#1E293B;">📖 用户指南</b>
</div>
</a>
<br><span style="color:#64748B;">完整使用指南</span>
</td>
<td align="center" width="33%" style="padding: 16px;">
<a href="https://docs.rs/dbnexus" style="text-decoration:none;">
<div style="padding: 24px; border-radius:12px; transition: transform 0.2s;">
<b style="color:#1E293B;">📘 API 参考</b>
</div>
</a>
<br><span style="color:#64748B;">完整 API 文档</span>
</td>
<td align="center" width="33%" style="padding: 16px;">
<a href="examples/" style="text-decoration:none;">
<div style="padding: 24px; border-radius:12px; transition: transform 0.2s;">
<b style="color:#1E293B;">💻 示例代码</b>
</div>
</a>
<br><span style="color:#64748B;">代码示例</span>
</td>
</tr>
</table>

</div>

### 📖 补充资源

| 资源 | 描述 |
|------|------|
| 📖 [用户指南]USER_GUIDE.md | 使用 DBNexus 的全面指南 |
| 📘 [API 参考]API_REFERENCE.md | 完整 API 文档 |
| 🏗️ [架构文档]ARCHITECTURE.md | 系统架构和设计决策 |
| 📦 [示例]examples/ | 可运行的代码示例 |

---

## <span id="examples">💻 示例</span>

<div align="center" style="margin: 24px 0;">

### 💡 真实示例

</div>

<table style="width:100%; border-collapse: collapse;">
<tr>
<td width="50%" style="padding: 16px; border-radius:8px; border:1px solid #E2E8F0; vertical-align:top;">

#### 📝 高级配置

```rust
use dbnexus::{DbPool, config::DbConfigBuilder};

let config = DbConfigBuilder::new()
    .url("postgresql://user:pass@localhost/db")
    .max_connections(20)
    .min_connections(5)
    .idle_timeout(300)
    .acquire_timeout(5000)
    .build()?;

let pool = DbPool::with_config(config).await?;
```

</td>
<td width="50%" style="padding: 16px; border-radius:8px; border:1px solid #E2E8F0; vertical-align:top;">

#### 🔧 环境变量

```bash
export DATABASE_URL="postgresql://user:pass@localhost/db"
export DB_MAX_CONNECTIONS=20
export DB_MIN_CONNECTIONS=5
export DB_ADMIN_ROLE=admin
```

```rust
let pool = DbPool::new().await?;
```

</td>
</tr>
<tr>
<td width="50%" style="padding: 16px; border-radius:8px; border:1px solid #E2E8F0; vertical-align:top;">

#### 🔄 事务处理

```rust
let mut session = pool.get_session("admin").await?;

// 开始事务
session.begin_transaction().await?;

// 多个操作
User::insert(&session, user1).await?;
User::insert(&session, user2).await?;

// 提交
session.commit_transaction().await?;
```

</td>
<td width="50%" style="padding: 16px; border-radius:8px; border:1px solid #E2E8F0; vertical-align:top;">

#### 📊 监控

```rust
use dbnexus::{DbPool, metrics::MetricsCollector};

let pool = DbPool::new("postgresql://localhost/db").await?;

// 获取连接池状态
let status = pool.status();
println!("活跃: {}, 空闲: {}", status.active, status.idle);

// 导出 Prometheus 指标
let metrics = MetricsCollector::new(&pool);
println!("{}", metrics.export_prometheus());
```

</td>
</tr>
</table>

<div align="center" style="margin: 24px 0;">

**[📂 查看所有示例 →](examples/)**

</div>

---

## <span id="architecture">🏗️ 架构</span>

<div align="center" style="margin: 24px 0;">

### 🏗️ 系统架构

</div>

<div align="center">

</div>

```mermaid
graph TD
    A[应用层<br/>使用 DbPool 和 Session 的代码] --> B[DBNexus API 层<br/>DbPool, Session<br/>权限检查<br/>事务管理]
    B --> C[功能模块<br/>Config, Permission, Metrics<br/>Migration, Sharding, Audit]
    C --> D[连接池层<br/>连接生命周期管理<br/>健康检查<br/>RAII 保证]
    D --> E[Sea-ORM / SQLx<br/>数据库驱动<br/>查询构建器]
```

查看 [ARCHITECTURE.md](ARCHITECTURE.md) 获取详细的架构文档。

---

## <span id="security">🔒 安全性</span>

<div align="center" style="margin: 24px 0;">

### 🛡️ 安全特性

</div>

DBNexus 在设计时就考虑了安全性:

- **无 unsafe 代码** - 所有库代码都使用 `#![forbid(unsafe_code)]`
- **权限强制执行** - 具有编译时验证的表级访问控制
- **SQL 注入防护** - 默认使用参数化查询
- **配置路径验证** - 防止路径遍历攻击
- **速率限制** - 权限检查速率限制以防止滥用

---

## <span id="testing">🧪 测试</span>

<div align="center" style="margin: 24px 0;">

### 🎯 运行测试

</div>

```bash
# 数据库特定测试
make test-sqlite       # SQLite
make test-postgres     # PostgreSQL(需要 Docker)
make test-mysql        # MySQL(需要 Docker)
make test-all          # 所有数据库

# 预设配置测试
make test-minimal      # minimal 预设(仅核心功能)
make test-microservice # microservice 预设(完整功能)
make test-ultra-minimal # ultra-minimal 预设(嵌入式设备)

# 运行所有测试
cargo test --all-features
```

### 使用 Docker

```bash
# 启动数据库
make docker-up

# 运行所有测试
make test-all

# 停止数据库
make docker-down
```

---

## <span id="contributing">🤝 贡献</span>

<div align="center" style="margin: 24px 0;">

欢迎贡献!请查看仓库获取贡献指南。

</div>

### 开发设置

```bash
# 克隆仓库
git clone https://github.com/Kirky-X/dbnexus.git
cd dbnexus

# 安装 pre-commit 钩子
./scripts/install-pre-commit.sh

# 运行测试
cargo test --all-features

# 运行 linter
cargo clippy --all-features
```

---

## <span id="license">📄 许可证</span>

<div align="center" style="margin: 24px 0;">

本项目采用 **MIT** 许可证:

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

</div>

---

## <span id="acknowledgments">🙏 致谢</span>

<div align="center" style="margin: 24px 0;">

### 🌟 基于优秀工具构建

</div>

- [Sea-ORM]https://www.sea-ql.org/SeaORM/ - 优秀的 ORM 框架,DBNexus 建立在其上
- [SQLx]https://github.com/launchbadge/sqlx - 异步 SQL 工具包
- Rust 社区提供的优秀工具和库

---

## 📞 支持

<div align="center" style="margin: 24px 0;">

<table style="width:100%; max-width: 600px;">
<tr>
<td align="center" width="33%">
<a href="https://github.com/Kirky-X/dbnexus/issues">
<div style="padding: 16px; border-radius:8px;">
<b style="color:#991B1B;">📋 Issues</b>
</div>
</a>
<br><span style="color:#64748B;">报告 Bug 和问题</span>
</td>
<td align="center" width="33%">
<a href="https://github.com/Kirky-X/dbnexus/discussions">
<div style="padding: 16px; border-radius:8px;">
<b style="color:#1E40AF;">💬 Discussions</b>
</div>
</a>
<br><span style="color:#64748B;">提问和分享想法</span>
</td>
<td align="center" width="33%">
<a href="https://github.com/Kirky-X/dbnexus">
<div style="padding: 16px; border-radius:8px;">
<b style="color:#1E293B;">🐙 GitHub</b>
</div>
</a>
<br><span style="color:#64748B;">查看源代码</span>
</td>
</tr>
</table>

</div>

---

## ⭐ Star 历史

<div align="center">

[![Star History Chart](https://api.star-history.com/svg?repos=Kirky-X/dbnexus&type=Date)](https://star-history.com/#Kirky-X/dbnexus&Date)

</div>

---

<div align="center" style="margin: 32px 0; padding: 24px; border-radius: 12px;">

### 💝 支持本项目

如果您觉得这个项目有用,请考虑给它一个 ⭐️!

**由 Kirky.X 用 ❤️ 构建**

---

**[⬆ 返回顶部](#dbnexus)**

---

<sub>© 2026 Kirky.X. All rights reserved.</sub>

</div>