dbnexus 0.1.2

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
<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 Status" 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="Version" style="display:inline;margin:0 4px;">
  </a>
  <!-- 文档 -->
  <a href="https://docs.rs/dbnexus">
    <img src="https://docs.rs/dbnexus/badge.svg" alt="Documentation" 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="Downloads" 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="License" 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>Enterprise-grade Database Abstraction Layer for Rust</strong>
</p>

<p align="center">
  <a href="#features" style="color:#3B82F6;">✨ Features</a><a href="#quick-start" style="color:#3B82F6;">🚀 Quick Start</a><a href="#documentation" style="color:#3B82F6;">📚 Documentation</a><a href="#examples" style="color:#3B82F6;">💻 Examples</a><a href="#contributing" style="color:#3B82F6;">🤝 Contributing</a>
</p>

</div>

---

### 🎯 A high-performance, secure, and feature-rich database access layer built on Sea-ORM

DBNexus provides a **declarative** database access approach:

| ✨ Type Safe | 🔒 Permission Control | 🏊 Smart Pooling | 📊 Enterprise Monitoring |
|:---------:|:----------:|:--------------:|:--------:|
| Compile-time checks | Table-level RBAC | RAII auto-management | Prometheus metrics |

```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(())
}
```

---

## 📋 Table of Contents

<details open style="border-radius:8px; padding:16px; border:1px solid #E2E8F0;">
<summary style="cursor:pointer; font-weight:600; color:#1E293B;">📑 Table of Contents (Click to expand)</summary>

- [✨ Features]#features
- [🚀 Quick Start]#quick-start
  - [📦 Installation]#installation
  - [💡 Basic Usage]#basic-usage
  - [🔒 Permission Control]#permission-control
- [🎨 Feature Flags]#feature-flags
- [📚 Documentation]#documentation
- [💻 Examples]#examples
- [🏗️ Architecture]#architecture
- [🔒 Security]#security
- [🧪 Testing]#testing
- [🤝 Contributing]#contributing
- [📄 License]#license
- [🙏 Acknowledgments]#acknowledgments

</details>

---

## <span id="features">✨ Features</span>

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

| 🎯 Core Features | ⚡ Enterprise Features |
|:----------:|:----------:|
| Always Available | Optional |

</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;">

### 🎯 Core Features (Always Available)

| Status | Feature | Description |
|:----:|------|------|
|| **Connection Pooling** | RAII-style automatic connection lifecycle management |
|| **Permission Control** | Role-based table-level access control (RBAC) |
|| **Procedural Macros** | Auto-generate CRUD methods and permission checks |
|| **SQL Parser** | Extract operation type and target table |
|| **Transaction Support** | Complete transaction management |
|| **Multi-Database Support** | SQLite, PostgreSQL, MySQL |

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

### ⚡ Enterprise Features

| Status | Feature | Description |
|:----:|------|------|
| 🔍 | **Metrics Monitoring** | Prometheus metrics export (`metrics` feature) |
| 📊 | **Distributed Tracing** | OpenTelemetry integration (`tracing` feature) |
| 📝 | **Audit Logging** | Automatic audit for all operations (`audit` feature) |
| 🗄️ | **Database Migration** | Automatic migration execution (`migration` feature) |
| 🔀 | **Data Sharding** | Support for sharding strategies (`sharding` feature) |
| 🌐 | **Global Index** | Cross-shard queries (`global-index` feature) |
| 💾 | **Caching** | LRU cache support (`cache` feature) |
| 🔐 | **Permission Engine** | Advanced permission system (`permission-engine` feature) |

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

### 📦 Feature Presets

| Preset | Features | Use Case |
|------|------|----------|
| <span style="color:#166534; padding:4px 8px; border-radius:4px;">minimal</span> | `runtime-tokio-rustls`, `sqlite`, `config-env`, `lru`, `regex`, `sql-parser` | Minimal for embedded devices |
| <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` | Microservice setup |
| <span style="color:#991B1B; padding:4px 8px; border-radius:4px;">all-optional</span> | All enterprise features except database drivers | Full enterprise features |

---

## <span id="quick-start">🚀 Quick Start</span>

### <span id="installation">📦 Installation</span>

Add this to your `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">💡 Basic Usage</span>

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

#### 🎬 5-Minute Quick Start

</div>

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

**Step 1: Define Entity**

```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;">

**Step 2: Create Connection Pool**

```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;">

**Step 3: Insert Data**

```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;">

**Step 4: Query Data**

```rust
let users = User::find_all(&session).await?;
println!("Found {} users", users.len());
```

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

### <span id="permission-control">🔒 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,
}

// Admin can access
let session = pool.get_session("admin").await?;
User::find_all(&session).await?;

// Regular user will be denied
let session = pool.get_session("guest").await?;
User::find_all(&session).await?; // Error: Permission denied
```

---

## <span id="feature-flags">🎨 Feature Flags</span>

### Database Drivers (choose one)

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

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

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

### Runtime

```toml
# Tokio with RustLS (default)
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"] }
```

### Optional Features

```toml
# Core features
dbnexus = { version = "0.1.1", features = [
    "permission",      # Permission control
    "sql-parser",      # SQL parsing
    "macros",          # Procedural macros
] }

# Enterprise features
dbnexus = { version = "0.1.1", features = [
    "metrics",         # Prometheus metrics
    "tracing",         # Distributed tracing
    "audit",           # Audit logging
    "migration",       # Database migration
    "sharding",        # Data sharding
    "permission-engine" # Advanced permission engine
] }

# Configuration
dbnexus = { version = "0.1.1", features = [
    "config-yaml",     # YAML config support
    "config-toml",     # TOML config support
    "config-env",      # Environment variables (default)
] }
```

---

## <span id="documentation">📚 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;">📖 User Guide</b>
</div>
</a>
<br><span style="color:#64748B;">Comprehensive guide</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 Reference</b>
</div>
</a>
<br><span style="color:#64748B;">Complete API docs</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;">💻 Examples</b>
</div>
</a>
<br><span style="color:#64748B;">Code examples</span>
</td>
</tr>
</table>

</div>

### 📖 Additional Resources

| Resource | Description |
|----------|-------------|
| 📖 [User Guide]USER_GUIDE.md | Comprehensive guide for using DBNexus |
| 📘 [API Reference]API_REFERENCE.md | Complete API documentation |
| 🏗️ [Architecture]ARCHITECTURE.md | System architecture and design decisions |
| 📦 [Examples]examples/ | Working code examples |

---

## <span id="examples">💻 Examples</span>

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

### 💡 Real-world Examples

</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;">

#### 📝 Advanced Configuration

```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;">

#### 🔧 Environment Variables

```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;">

#### 🔄 Transactions

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

// Begin transaction
session.begin_transaction().await?;

// Multiple operations
User::insert(&session, user1).await?;
User::insert(&session, user2).await?;

// Commit
session.commit_transaction().await?;
```

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

#### 📊 Monitoring

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

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

// Get pool status
let status = pool.status();
println!("Active: {}, Idle: {}", status.active, status.idle);

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

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

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

**[📂 View all examples →](examples/)**

</div>

---

## <span id="architecture">🏗️ Architecture</span>

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

### 🏗️ System Architecture

</div>

<div align="center">

</div>

```mermaid
graph TD
    A[Application Layer<br/>Your code using DbPool and Session] --> B[DBNexus API Layer<br/>DbPool, Session<br/>Permission checking<br/>Transaction management]
    B --> C[Feature Modules<br/>Config, Permission, Metrics<br/>Migration, Sharding, Audit]
    C --> D[Connection Pool<br/>Connection lifecycle management<br/>Health checking<br/>RAII guarantees]
    D --> E[Sea-ORM / SQLx<br/>Database drivers<br/>Query builder]
```

See [ARCHITECTURE.md](ARCHITECTURE.md) for detailed architecture documentation.

---

## <span id="security">🔒 Security</span>

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

### 🛡️ Security Features

</div>

DBNexus is built with security in mind:

- **No unsafe code** - `#![forbid(unsafe_code)]` in all library code
- **Permission enforcement** - Table-level access control with compile-time verification
- **SQL injection prevention** - Parameterized queries by default
- **Config path validation** - Protection against path traversal attacks
- **Rate limiting** - Permission check rate limiting to prevent abuse

---

## <span id="testing">🧪 Testing</span>

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

### 🎯 Run Tests

</div>

```bash
# SQLite tests
cargo test --features sqlite

# PostgreSQL tests
cargo test --features postgres

# MySQL tests
cargo test --features mysql

# All tests (requires Docker)
make test-all
```

### Using Docker

```bash
# Start databases
make docker-up

# Run all tests
make test-all

# Stop databases
make docker-down
```

---

## <span id="contributing">🤝 Contributing</span>

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

Contributions are welcome! Please check the repository for contribution guidelines.

</div>

### Development Setup

```bash
# Clone repository
git clone https://github.com/Kirky-X/dbnexus.git
cd dbnexus

# Install pre-commit hooks
./scripts/install-pre-commit.sh

# Run tests
cargo test --all-features

# Run linter
cargo clippy --all-features
```

---

## <span id="license">📄 License</span>

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

This project is licensed under **MIT**:

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

</div>

---

## <span id="acknowledgments">🙏 Acknowledgments</span>

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

### 🌟 Built on Excellent Tools

</div>

- [Sea-ORM]https://www.sea-ql.org/SeaORM/ - The excellent ORM framework DBNexus is built on
- [SQLx]https://github.com/launchbadge/sqlx - Async SQL toolkit
- The Rust community for amazing tools and libraries

---

## 📞 Support

<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;">Report bugs and issues</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;">Ask questions and share ideas</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;">View source code</span>
</td>
</tr>
</table>

</div>

---

## ⭐ Star History

<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;">

### 💝 Support This Project

If you find this project useful, please consider giving it a ⭐️!

**Built with ❤️ by Kirky.X**

---

**[⬆ Back to Top](#dbnexus)**

---

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

</div>