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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
# API 参考

DBNexus 的完整 API 文档。

## 目录

- [核心类型]#核心类型
- [连接池 API]#连接池-api
- [会话 API]#会话-api
- [配置 API]#配置-api
- [权限 API]#权限-api
- [过程宏]#过程宏
- [错误类型]#错误类型

---

## 核心类型

### `DbPool`

数据库连接的主连接池管理器。

```rust
pub struct DbPool {
    // 字段是私有的
}
```

#### 方法

##### `new`

使用默认配置创建新的连接池。

```rust
pub async fn new(url: &str) -> DbResult<Self>
```

**参数:**
- `url: &str` - 数据库连接 URL

**返回值:**
- `DbResult<DbPool>` - 连接池实例

**示例:**
```rust
let pool = DbPool::new("sqlite::memory:").await?;
```

##### `try_from_config`

从显式配置创建连接池。

```rust
pub async fn try_from_config(config: DbConfig) -> DbResult<Self>
```

**参数:**
- `config: DbConfig` - 数据库配置

**返回值:**
- `DbResult<DbPool>` - 连接池实例

**示例:**
```rust
let config = DbConfigBuilder::new()
    .url("postgresql://localhost/db")
    .max_connections(20)
    .build()?;

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

##### `with_config`

从显式配置创建连接池(带自动修正)。

```rust
pub async fn with_config(config: DbConfig) -> DbResult<Self>
```

**参数:**
- `config: DbConfig` - 数据库配置

**返回值:**
- `DbResult<DbPool>` - 连接池实例

**示例:**
```rust
let config = DbConfigBuilder::new()
    .url("postgresql://localhost/db")
    .max_connections(20)
    .build()?;

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

##### `try_from`

同步创建未初始化的连接池。

```rust
pub fn try_from(config: &DbConfig) -> Result<Self, ConfigError>
```

##### `get_session`

获取具有基于角色的访问控制的数据库会话。

```rust
pub async fn get_session(&self, role: &str) -> DbResult<Session>
```

**参数:**
- `role: &str` - 用于权限检查的用户角色

**返回值:**
- `DbResult<Session>` - 数据库会话

**错误:**
- `DbError::Permission` - 角色不在权限配置中
- `DbError::ConnectionPool` - 获取连接失败

**示例:**
```rust
let session = pool.get_session("admin").await?;
```

##### `with_role`

`get_session()` 的语义化别名,用于基于角色的访问。

```rust
pub async fn with_role(&self, role: impl Into<String>) -> DbResult<Session>
```

**参数:**
- `role: impl Into<String>` - 角色名称,必须与权限配置中定义的角色匹配

**返回值:**
- `DbResult<Session>` - 数据库会话

**错误:**
- `DbError::Permission` - 角色不在权限配置中
- `DbError::ConnectionPool` - 获取连接失败

**示例:**
```rust
let session = pool.with_role("admin").await?;
// 或者使用其他可以转换为 String 的类型
let session = pool.with_role(String::from("manager")).await?;
```

##### `health_check`

检查连接池的健康状态,返回是否有可用容量。

```rust
pub async fn health_check(&self) -> bool
```

**返回值:**
- `bool` - 如果池有可用容量返回 `true`,否则返回 `false`

**示例:**
```rust
if pool.health_check().await {
    println!("连接池健康且有可用容量");
} else {
    println!("连接池已满或不可用");
}
```

##### `status`

返回当前池状态。

```rust
pub fn status(&self) -> PoolStatus
```

**返回值:**
- `PoolStatus` - 池状态信息

**示例:**
```rust
let status = pool.status();
println!("活跃: {}, 空闲: {}", status.active, status.idle);
```

##### `clean_invalid_connections`

手动触发连接健康检查和清理。

```rust
pub async fn clean_invalid_connections(&self) -> u32
```

**返回值:**
- `u32` - 移除的无效连接数

---

### `Session`

基于 RAII 的数据库会话,用于执行查询。

```rust
pub struct Session {
    // 字段是私有的
}
```

#### 方法

##### `execute`

执行带权限检查的 SQL 语句。

```rust
pub async fn execute(&mut self, sql: &str) -> DbResult<ExecResult>
```

**参数:**
- `sql: &str` - 要执行的 SQL 语句

**返回值:**
- `DbResult<ExecResult>` - 执行结果

**错误:**
- `DbError::Permission` - 权限被拒绝
- `DbError::SqlParse` - 无效的 SQL 语法
- `DbError::Database` - 数据库错误

**示例:**
```rust
let result = session.execute("SELECT * FROM users").await?;
```

##### `execute_raw`

执行不带权限检查的 SQL(用于管理员操作)。

```rust
pub async fn execute_raw(&self, sql: &str) -> DbResult<ExecResult>
```

##### `begin_transaction`

开始数据库事务。

```rust
pub async fn begin_transaction(&mut self) -> DbResult<()>
```

**错误:**
- `DbError::Transaction` - 已在事务中

**示例:**
```rust
session.begin_transaction().await?;
User::insert(&session, user1).await?;
User::insert(&session, user2).await?;
session.commit().await?;
```

##### `commit`

提交当前事务。

```rust
pub async fn commit(&mut self) -> DbResult<()>
```

##### `rollback`

回滚当前事务。

```rust
pub async fn rollback(&mut self) -> DbResult<()>
```

##### `is_in_transaction`

检查当前是否在事务中。

```rust
pub fn is_in_transaction(&self) -> bool
```

##### `role`

返回当前会话的角色。

```rust
pub fn role(&self) -> &str
```

---

### `PoolStatus`

连接池状态信息。

```rust
pub struct PoolStatus {
    pub total: u32,      // 池中的总连接数
    pub active: u32,     // 当前活跃连接数
    pub idle: u32,       // 空闲连接数(总数 - 活跃)
    pub wait_count: u32,  // 等待连接的次数
    pub borrow_count: u64, // 总借用次数
    pub max_active: u32, // 观察到的最大活跃连接数
}
```

---

## 配置 API

### `DbConfig`

数据库配置结构(所有字段均为私有,请使用 DbConfigBuilder 构建)。

```rust
pub struct DbConfig {
    url: String,
    max_connections: u32,
    min_connections: u32,
    idle_timeout: u64,
    acquire_timeout: u64,
    permissions_path: Option<String>,
    migrations_dir: Option<PathBuf>,
    auto_migrate: bool,
    migration_timeout: u64,
    admin_role: String,
    warmup_timeout: u64,
    warmup_retries: u32,
}
```

**注意:** 所有字段都是私有的,请使用 `DbConfigBuilder` 来构建配置实例。

**默认值:**

| 字段 | 默认值 |
|-------|----------|
| `max_connections` | 20 |
| `min_connections` | 5 |
| `idle_timeout` | 300 (秒) |
| `acquire_timeout` | 5000 (毫秒) |
| `auto_migrate` | `false` |
| `migration_timeout` | 60 (秒) |
| `admin_role` | `"admin"` |
| `warmup_timeout` | 30 (秒) |
| `warmup_retries` | 3 |

**默认值:**

| 字段 | 默认值 |
|-------|----------|
| `max_connections` | 20 |
| `min_connections` | 5 |
| `idle_timeout` | 300 (秒) |
| `acquire_timeout` | 5000 (毫秒) |
| `auto_migrate` | `false` |
| `migration_timeout` | 60 (秒) |
| `admin_role` | `"admin"` |
| `warmup_timeout` | 30 (秒) |
| `warmup_retries` | 3 |

### `DbConfigBuilder`

用于创建 `DbConfig` 实例的构建器。

```rust
pub struct DbConfigBuilder {
    // 内部状态
}
```

#### 方法

##### `new`

创建带默认值的新构建器。

```rust
pub fn new() -> Self
```

##### `url`

设置数据库连接 URL。

```rust
pub fn url(self, url: &str) -> Self
```

##### `max_connections`

设置最大池大小。

```rust
pub fn max_connections(self, max: u32) -> Self
```

##### `min_connections`

设置最小池大小。

```rust
pub fn min_connections(self, min: u32) -> Self
```

##### `idle_timeout`

设置空闲连接超时(秒)。

```rust
pub fn idle_timeout(self, timeout: u64) -> Self
```

##### `acquire_timeout`

设置连接获取超时(毫秒)。

```rust
pub fn acquire_timeout(self, timeout: u64) -> Self
```

##### `permissions_path`

设置权限配置文件的路径。

```rust
pub fn permissions_path(self, path: &str) -> Self
```

##### `auto_migrate`

启用自动数据库迁移。

```rust
pub fn auto_migrate(self, enabled: bool) -> Self
```

##### `admin_role`

设置管理员角色名称。

```rust
pub fn admin_role(self, role: &str) -> Self
```

##### `build`

构建 `DbConfig` 实例。

```rust
pub fn build(self) -> Result<DbConfig, ConfigError>
```

**示例:**
```rust
let config = DbConfigBuilder::new()
    .url("postgresql://localhost/db")
    .max_connections(20)
    .min_connections(5)
    .idle_timeout(300)
    .acquire_timeout(5000)
    .permissions_path("/etc/dbnexus/permissions.yaml")
    .auto_migrate(true)
    .admin_role("superuser")
    .build()?;
```

### `DbConfig` 配置加载方法

#### `from_env`

从环境变量加载配置。

```rust
pub fn from_env() -> Result<DbConfig, ConfigError>
```

**环境变量:**

| 变量 | 类型 | 默认值 | 描述 |
|-----------|-------|----------|-------------|
| `DATABASE_URL` | String | - | **必需**,数据库连接 URL |
| `DB_MAX_CONNECTIONS` | u32 | 20 | 最大池大小 |
| `DB_MIN_CONNECTIONS` | u32 | 5 | 最小池大小 |
| `DB_IDLE_TIMEOUT` | u64 | 300 | 空闲超时(秒) |
| `DB_ACQUIRE_TIMEOUT` | u64 | 5000 | 获取超时(毫秒) |
| `DB_PERMISSIONS_PATH` | String | - | 权限配置路径 |
| `DB_MIGRATIONS_DIR` | String | - | 迁移目录 |
| `DB_AUTO_MIGRATE` | bool | false | 启用自动迁移 |
| `DB_ADMIN_ROLE` | String | "admin" | 管理员角色名称 |

**示例:**
```bash
export DATABASE_URL="postgresql://localhost/db"
export DB_MAX_CONNECTIONS=20
export DB_ADMIN_ROLE=admin
```

```rust
let config = DbConfig::from_env()?;
```

#### `from_yaml_file`

从 YAML 文件加载配置。

```rust
#[cfg(feature = "config-yaml")]
pub fn from_yaml_file(path: impl AsRef<Path>) -> Result<DbConfig, ConfigError>
```

**YAML 格式:**
```yaml
url: "postgresql://localhost/db"
max_connections: 20
min_connections: 5
idle_timeout: 300
acquire_timeout: 5000
auto_migrate: true
admin_role: admin
```

#### `from_toml_file`

从 TOML 文件加载配置。

```rust
#[cfg(feature = "config-toml")]
pub fn from_toml_file(path: impl AsRef<Path>) -> Result<DbConfig, ConfigError>
```

**TOML 格式:**
```toml
url = "postgresql://localhost/db"
max_connections = 20
min_connections = 5
idle_timeout = 300
acquire_timeout = 5000
auto_migrate = true
admin_role = "admin"
```

#### `from_config_files`

自动检测并从标准路径加载配置。

```rust
pub fn from_config_files() -> Result<DbConfig, ConfigError>
```

**搜索顺序:**
1. `./dbnexus.yaml`
2. `./dbnexus.toml`
3. `./config/dbnexus.yaml`
4. `./config/dbnexus.toml`
5. `~/.config/dbnexus/config.yaml`
6. `~/.dbnexus/config.toml`

---

## 权限 API

### `PermissionAction`

用于权限检查的数据库操作类型。

```rust
pub enum PermissionAction {
    Select,  // SELECT 查询
    Insert,  // INSERT 语句
    Update,  // UPDATE 语句
    Delete,  // DELETE 语句
}
```

### `PermissionContext`

具有缓存和速率限制的权限检查上下文。

```rust
pub struct PermissionContext {
    // 私有字段
}
```

#### 方法

##### `new`

创建新的权限上下文。

```rust
pub fn new(role: String, cache: Arc<AsyncMutex<LruCache<String, RolePolicy>>>) -> Self
```

##### `with_rate_limiter`

创建启用速率限制的上下文。

```rust
pub fn with_rate_limiter(
    role: String,
    cache: Arc<AsyncMutex<LruCache<String, RolePolicy>>>,
    limiter: Arc<RateLimiter>,
) -> Self
```

##### `check_table_access`

检查当前角色是否可以对表执行操作。

```rust
pub async fn check_table_access(&self, table: &str, action: &PermissionAction) -> bool
```

**返回值:**
- `bool` - 如果允许返回 `true`,如果拒绝返回 `false`

##### `load_policy`

从 YAML 字符串加载权限配置。

```rust
pub async fn load_policy(&self, yaml: &str) -> DbResult<()>
```

### `PermissionConfig`

权限配置结构。

```rust
pub struct PermissionConfig {
    pub roles: HashMap<String, RolePolicy>,
}
```

**YAML 格式:**
```yaml
roles:
  admin:
    tables:
      - name: "*"
        operations:
          - select
          - insert
          - update
          - delete

  manager:
    tables:
      - name: "users"
        operations:
          - select
          - insert
          - update

  user:
    tables:
      - name: "users"
        operations:
          - select
```

#### 方法

##### `from_yaml`

从 YAML 字符串解析权限配置。

```rust
pub fn from_yaml(yaml: &str) -> Result<Self, serde_yaml::Error>
```

##### `deny_all`

创建拒绝所有访问的权限配置。

```rust
pub fn deny_all() -> Self
```

---

## 过程宏

### `#[derive(DbEntity)]`

将结构体标记为数据库实体的派生宏。

**必需属性:**

| 属性 | 描述 | 必需 |
|-----------|-------------|-----------|
| `#[derive(DbEntity, DeriveEntityModel, DeriveModel, DeriveActiveModel)]` | 启用 DBNexus 和 Sea-ORM 实体特性 ||
| `#[sea_orm(table_name = "...")]` | 数据库表名 ||
| `#[sea_orm(primary_key)]` | 标记主键字段 ||

**可选属性:**

| 属性 | 描述 | 必需 |
|-----------|-------------|-----------|
| `#[db_crud]` | 生成 CRUD 方法 ||
| `#[db_permission(...)]` | 添加权限控制 ||
| `#[db_cache]` | 启用缓存(需要 `cache` 特性) ||
| `#[db_audit]` | 启用审计日志(需要 `audit` 特性) ||

### `#[db_crud]`

自动为实体生成 CRUD 方法。

**生成的方法:**

```rust
impl MyEntity {
    // 插入记录
    pub async fn insert(session: &Session, value: MyEntity) -> DbResult<MyEntity>;

    // 按主键查找
    pub async fn find_by_id(session: &Session, id: i64) -> DbResult<Option<MyEntity>>;

    // 查找所有记录
    pub async fn find_all(session: &Session) -> DbResult<Vec<MyEntity>>;

    // 按条件查找
    pub async fn find_by_condition(
        session: &Session,
        condition: Condition
    ) -> DbResult<Vec<MyEntity>>;

    // 更新记录
    pub async fn update(session: &Session, value: MyEntity) -> DbResult<MyEntity>;

    // 按主键删除
    pub async fn delete(session: &Session, id: i64) -> DbResult<()>;

    // 按条件删除
    pub async fn delete_many(session: &Session, condition: Condition) -> DbResult<u64>;

    // 记录计数
    pub async fn count(session: &Session) -> DbResult<u64>;
}
```

**示例:**
```rust
use dbnexus::{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,
}

// 使用
let user = User {
    id: 1,
    name: "Alice".to_string(),
    email: "alice@example.com".to_string(),
};

let inserted = User::insert(&session, user).await?;
let found = User::find_by_id(&session, 1).await?;
```

### `#[db_permission]`

声明实体的基于角色的访问控制。

**属性:**

```rust
#[db_permission(
    roles = ["admin", "manager"],
    operations = ["SELECT", "INSERT", "UPDATE"],
    config = "permissions.yaml"
)]
```

**参数:**

| 参数 | 类型 | 必需 | 描述 |
|-----------|-------|-----------|-------------|
| `roles` | `Vec<&str>` || 允许访问此实体的角色列表 |
| `operations` | `Vec<&str>` || 允许的操作列表(SELECT, INSERT, UPDATE, DELETE) |
| `config` | `&str` || 用于编译时验证的权限配置文件路径 |

**生成的方法:**

```rust
impl MyEntity {
    pub const ALLOWED_ROLES: &[&str] = &["admin", "manager"];
    pub const ALLOWED_OPERATIONS: &[&str] = &["SELECT", "INSERT", "UPDATE"];

    pub fn check_permission(ctx: &PermissionContext) -> DbResult<()>;
    pub fn check_operation(ctx: &PermissionContext, op: &PermissionAction) -> DbResult<()>;
}

// 使用
let session = pool.get_session("admin").await?;
User::find_all(&session).await?; // OK
let session = pool.get_session("guest").await?;
User::find_all(&session).await?; // 错误:权限被拒绝
```

### `#[db_cache]`

启用实体查询的缓存(需要 `cache` 特性)。

**生成的方法:**

```rust
impl MyEntity {
    pub async fn find_cached(session: &Session, id: i64) -> DbResult<Option<MyEntity>>;
    pub async fn invalidate_cache(session: &Session, id: i64) -> DbResult<()>;
}
```

### `#[db_audit]`

启用实体操作的审计日志(需要 `audit` 特性)。

**效果:**
- 所有 CRUD 操作都记录到审计跟踪中
- 包括操作类型、时间戳、用户角色和结果

---

## 错误类型

### `DbError`

数据库操作错误。

```rust
#[derive(Debug, Error, PartialEq)]
pub enum DbError {
    /// 连接错误
    #[error("Connection error: {0}")]
    Connection(#[from] DbErr),

    /// 配置错误
    #[error("Configuration error: {0}")]
    Config(String),

    /// 权限错误
    #[error("Permission denied: {0}")]
    Permission(String),

    /// 事务错误
    #[error("Transaction error: {0}")]
    Transaction(String),

    /// 迁移错误
    #[error("Migration error: {0}")]
    Migration(String),
}
```

### `ConfigError`

配置相关错误。

```rust
pub enum ConfigError {
    /// 文件未找到
    #[error("Configuration file not found")]
    FileNotFound,

    /// 格式无效
    #[error("Invalid configuration format")]
    InvalidFormat,

    /// 缺少必填字段
    #[error("Missing required configuration field")]
    MissingField,

    /// 环境变量错误
    #[error("Environment variable error")]
    EnvVarError,

    /// IO错误
    #[error("Configuration file I/O error")]
    IoError,

    /// URL格式错误(带详细错误信息)
    #[error("Invalid database URL format: {0}")]
    InvalidUrl(String),

    /// 不支持的数据库协议
    #[error("Unsupported database protocol")]
    UnsupportedProtocol,

    /// 验证失败
    #[error("Configuration validation failed")]
    ValidationFailed,
}
```

### `SqlParseError`

SQL 解析错误。

```rust
pub enum SqlParseError {
    /// SQL parsing failed due to syntax errors or invalid structure
    #[error("Failed to parse SQL: {0}")]
    ParseError(String),

    /// SQL statement type is not supported for permission checking
    #[error("Unsupported SQL statement type: {0}")]
    UnsupportedStatement(String),

    /// Empty SQL statement was provided
    #[error("Empty SQL statement")]
    EmptyStatement,

    /// Multiple SQL statements detected (only single statements are allowed)
    #[error("Multiple statements not allowed")]
    MultipleStatements,

    /// SQL statement contains variables that could indicate dynamic SQL injection
    #[error("SQL statement contains variables: {0}")]
    ContainsVariables(String),
}
```

---

## 工具类型

### `ExecResult`

SQL 执行的结果。

```rust
pub struct ExecResult {
    pub rows_affected: u64,
    pub last_insert_id: Option<i64>,
}
```

---

## 类型别名

```rust
pub type DbResult<T> = Result<T, DbError>;
pub type Operation = PermissionAction;
```

---

## 特性门控 API

### 指标(需要 `metrics` 特性)

```rust
use dbnexus::metrics::MetricsCollector;

let collector = MetricsCollector::new(&pool);
println!("{}", collector.export_prometheus());
```

### 审计(需要 `audit` 特性)

```rust
use dbnexus::audit::AuditLogger;

let logger = AuditLogger::new("/var/log/dbnexus/audit.log");
logger.log_event(audit_event).await?;
```

### 迁移(需要 `migration` 特性)

```rust
use dbnexus::migration::MigrationExecutor;

let executor = MigrationExecutor::new(&pool);
executor.run_migrations().await?;
```

---

更多详细文档,请参见:
- [用户指南]USER_GUIDE.md
- [架构]ARCHITECTURE.md
- [Rust 文档]https://docs.rs/dbnexus