dbnexus 0.6.0-rc.4

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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! Pool module implementation details.
//!
//! Contains impl blocks extracted from [`super`].

use super::*;

use crate::foundation::DbResult;
use crate::foundation::{DbConfig, PoolConfig};

#[cfg(any(feature = "cache", feature = "oxcache-integration"))]
use crate::domain::DbCacheProvider;
#[cfg(any(feature = "cache", feature = "oxcache-integration"))]
use std::sync::Arc;

impl DbPoolBuilder {
    /// 创建新的构造器
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置数据库连接 URL
    ///
    /// # Arguments
    ///
    /// * `url` - 数据库连接 URL 字符串
    ///
    /// # Returns
    ///
    /// 返回构造器自身以支持链式调用
    pub fn url(mut self, url: &str) -> Self {
        self.url = Some(url.to_string());
        self
    }

    /// 设置数据库配置
    ///
    /// # Arguments
    ///
    /// * `config` - 数据库配置
    ///
    /// # Returns
    ///
    /// 返回构造器自身以支持链式调用
    pub fn config(mut self, mut config: DbConfig) -> Self {
        // 先前显式设置的 admin_role 优先于 config 自带值(顺序无关语义)
        if let Some(role) = self.admin_role.take() {
            config.admin_role = role;
        }
        self.config = Some(config);
        self
    }

    /// 设置管理员角色名称
    ///
    /// # Arguments
    ///
    /// * `admin_role` - 管理员角色名称
    ///
    /// # Returns
    ///
    /// 返回构造器自身以支持链式调用
    pub fn admin_role(mut self, admin_role: &str) -> Self {
        self.admin_role = Some(admin_role.to_string());
        if let Some(ref mut config) = self.config {
            config.admin_role = admin_role.to_string();
        }
        self
    }

    /// 注入缓存提供者(DI 注入点)
    ///
    /// 允许外部注入 `DbCacheProvider` 实现,覆盖默认的内置缓存。
    /// 仅在 `cache` 特性启用时可用。
    ///
    /// # Arguments
    ///
    /// * `provider` - 缓存提供者实例
    ///
    /// # Returns
    ///
    /// 返回构造器自身以支持链式调用
    #[cfg(any(feature = "cache", feature = "oxcache-integration"))]
    pub fn cache_provider(mut self, provider: Arc<dyn DbCacheProvider + Send + Sync>) -> Self {
        self.cache_provider = Some(provider);
        self
    }

    /// 设置最大连接数
    ///
    /// # Arguments
    ///
    /// * `max_connections` - 最大连接数
    ///
    /// # Returns
    ///
    /// 返回构造器自身以支持链式调用
    pub fn max_connections(mut self, max_connections: u32) -> Self {
        if let Some(ref mut config) = self.config {
            config.pool_config.max_connections = max_connections;
        } else {
            // url/config 之后再就绪:先暂存,build 时统一应用(顺序无关)
            self.pending_max_connections = Some(max_connections);
            if let Some(ref url) = self.url {
                let config = DbConfig {
                    url: url.clone(),
                    pool_config: PoolConfig {
                        max_connections,
                        ..Default::default()
                    },
                    ..Default::default()
                };
                self.config = Some(config);
                self.pending_max_connections = None;
            }
        }
        self
    }

    /// 设置最小连接数
    ///
    /// # Arguments
    ///
    /// * `min_connections` - 最小连接数
    ///
    /// # Returns
    ///
    /// 返回构造器自身以支持链式调用
    pub fn min_connections(mut self, min_connections: u32) -> Self {
        if let Some(ref mut config) = self.config {
            config.pool_config.min_connections = min_connections;
        } else {
            self.pending_min_connections = Some(min_connections);
            if let Some(ref url) = self.url {
                let config = DbConfig {
                    url: url.clone(),
                    pool_config: PoolConfig {
                        min_connections,
                        ..Default::default()
                    },
                    ..Default::default()
                };
                self.config = Some(config);
                self.pending_min_connections = None;
            }
        }
        self
    }

    /// 启用语句级 prepared statement LRU 缓存
    #[cfg(feature = "prepare-cache")]
    pub fn prepare_cache(mut self, capacity: usize) -> Self {
        self.prepare_cache_capacity = Some(capacity);
        self
    }

    /// 注入统一 DDL 守卫策略
    ///
    /// 注入后 `execute_raw_ddl` / DuckDB 安全门等全部 DDL 路径经该策略校验与审计。
    #[cfg(feature = "sql-parser")]
    pub fn ddl_guard(mut self, guard: std::sync::Arc<dyn crate::access::DdlGuardPolicy>) -> Self {
        self.ddl_guard = Some(guard);
        self
    }

    /// 构建 DbPool
    ///
    /// # Errors
    ///
    /// 如果配置无效或无法连接数据库,返回错误
    ///
    /// # Returns
    ///
    /// 返回新创建的 DbPool 实例
    pub async fn build(self) -> DbResult<DbPool> {
        // 确定最终配置
        let mut config = if let Some(config) = self.config {
            config
        } else if let Some(url) = self.url {
            // 从 url 创建默认配置
            DbConfig {
                url,
                pool_config: PoolConfig {
                    max_connections: 20,
                    min_connections: 5,
                    idle_timeout: 300,
                    acquire_timeout: 5000,
                },
                admin_role: self.admin_role.unwrap_or_else(|| "admin".to_string()),
                ..Default::default()
            }
        } else {
            return Err(crate::foundation::DbError::new(sea_orm::DbErr::Custom(
                "Either url or config must be provided".to_string(),
            )));
        };

        // 应用先于 url/config 设置的显式池参数(setter 顺序无关,显式调用优先)
        if let Some(max) = self.pending_max_connections {
            config.pool_config.max_connections = max;
        }
        if let Some(min) = self.pending_min_connections {
            config.pool_config.min_connections = min;
        }

        // 创建 pool
        #[allow(unused_mut)]
        let mut pool = DbPool::with_config(config).await?;

        // 注入缓存提供者(如果设置)
        #[cfg(any(feature = "cache", feature = "oxcache-integration"))]
        if let Some(cache_provider) = self.cache_provider {
            pool.set_cache_provider(cache_provider);
        }

        // 注入统一 DDL 守卫策略(如果设置)
        #[cfg(feature = "sql-parser")]
        if let Some(guard) = self.ddl_guard {
            pool.set_ddl_guard(guard);
        }

        // 启用语句级 prepare 缓存(如果设置)
        #[cfg(feature = "prepare-cache")]
        if let Some(capacity) = self.prepare_cache_capacity {
            pool.enable_prepare_cache(capacity);
        }

        // 注意:以下值已通过 config 设置,不需要额外调用 setter 方法
        // - admin_role: 在 config 创建时已设置(line 327)
        // - metrics_collector: 通过 config 或其他方式设置
        // - permission_config: 在 config 创建时已设置

        Ok(pool)
    }
}

impl std::fmt::Debug for DbPoolBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DbPoolBuilder")
            .field("url", &self.url)
            .field("config", &self.config.is_some())
            .field("admin_role", &self.admin_role)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_new() {
        let builder = DbPoolBuilder::new();
        assert!(builder.url.is_none());
        assert!(builder.config.is_none());
        assert!(builder.admin_role.is_none());
    }

    #[test]
    fn test_builder_url() {
        let builder = DbPoolBuilder::new().url("sqlite::memory:");
        assert_eq!(builder.url.as_deref(), Some("sqlite::memory:"));
    }

    #[test]
    fn test_builder_config() {
        let config = DbConfig {
            url: "sqlite::memory:".to_string(),
            ..Default::default()
        };
        let builder = DbPoolBuilder::new().config(config);
        assert!(builder.config.is_some());
        assert_eq!(builder.config.unwrap().url, "sqlite::memory:");
    }

    #[test]
    fn test_builder_admin_role_with_config() {
        let config = DbConfig {
            url: "sqlite::memory:".to_string(),
            admin_role: "old_admin".to_string(),
            ..Default::default()
        };
        let builder = DbPoolBuilder::new().config(config).admin_role("new_admin");
        assert_eq!(builder.config.unwrap().admin_role, "new_admin");
    }

    #[test]
    fn test_builder_admin_role_without_config() {
        let builder = DbPoolBuilder::new().admin_role("super_admin");
        assert_eq!(builder.admin_role.as_deref(), Some("super_admin"));
    }

    /// admin_role 在 config 之前设置不应丢失(顺序无关)
    #[test]
    fn test_builder_admin_role_before_config() {
        let config = DbConfig {
            url: "sqlite::memory:".to_string(),
            admin_role: "old_admin".to_string(),
            ..Default::default()
        };
        let builder = DbPoolBuilder::new().admin_role("new_admin").config(config);
        assert_eq!(
            builder.config.unwrap().admin_role,
            "new_admin",
            "先设 admin_role 再设 config 应保留显式值"
        );
    }

    /// max_connections 在 url 之前设置不应丢失(经暂存在 build 时应用)
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn test_builder_max_connections_before_url() {
        let pool = DbPoolBuilder::new()
            .max_connections(30)
            .url("sqlite::memory:")
            .build()
            .await
            .expect("should build pool");
        assert_eq!(pool.config().pool_config.max_connections, 30);
    }

    /// max_connections 在 config 之前设置应覆盖 config 自带值
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn test_builder_max_connections_before_config() {
        let config = DbConfig {
            url: "sqlite::memory:".to_string(),
            pool_config: PoolConfig {
                max_connections: 15,
                ..Default::default()
            },
            ..Default::default()
        };
        let pool = DbPoolBuilder::new()
            .max_connections(30)
            .config(config)
            .build()
            .await
            .expect("should build pool");
        assert_eq!(pool.config().pool_config.max_connections, 30);
    }

    #[test]
    fn test_builder_max_connections_with_config() {
        let config = DbConfig {
            url: "sqlite::memory:".to_string(),
            ..Default::default()
        };
        let builder = DbPoolBuilder::new().config(config).max_connections(50);
        assert_eq!(builder.config.unwrap().pool_config.max_connections, 50);
    }

    #[test]
    fn test_builder_max_connections_with_url_only() {
        let builder = DbPoolBuilder::new()
            .url("sqlite::memory:")
            .max_connections(30);
        let config = builder.config.unwrap();
        assert_eq!(config.pool_config.max_connections, 30);
        assert_eq!(config.url, "sqlite::memory:");
    }

    #[test]
    fn test_builder_max_connections_no_config_no_url() {
        // Neither config nor url set -> no-op (self stays same)
        let builder = DbPoolBuilder::new().max_connections(30);
        assert!(builder.config.is_none());
    }

    #[test]
    fn test_builder_min_connections_with_config() {
        let config = DbConfig {
            url: "sqlite::memory:".to_string(),
            ..Default::default()
        };
        let builder = DbPoolBuilder::new().config(config).min_connections(10);
        assert_eq!(builder.config.unwrap().pool_config.min_connections, 10);
    }

    #[test]
    fn test_builder_min_connections_with_url_only() {
        let builder = DbPoolBuilder::new()
            .url("sqlite::memory:")
            .min_connections(5);
        let config = builder.config.unwrap();
        assert_eq!(config.pool_config.min_connections, 5);
    }

    #[test]
    fn test_builder_min_connections_no_config_no_url() {
        let builder = DbPoolBuilder::new().min_connections(5);
        assert!(builder.config.is_none());
    }

    #[test]
    fn test_builder_debug_format() {
        let builder = DbPoolBuilder::new().url("sqlite::memory:");
        let debug = format!("{:?}", builder);
        assert!(debug.contains("DbPoolBuilder"));
        assert!(debug.contains("sqlite::memory:"));
    }

    #[tokio::test]
    async fn test_builder_build_no_url_no_config_fails() {
        let result = DbPoolBuilder::new().build().await;
        assert!(result.is_err());
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn test_builder_build_with_url() {
        let pool = DbPoolBuilder::new()
            .url("sqlite::memory:")
            .build()
            .await
            .expect("should build pool");
        assert_eq!(pool.config().url, "sqlite::memory:");
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn test_builder_build_with_config() {
        let config = DbConfig {
            url: "sqlite::memory:".to_string(),
            pool_config: PoolConfig {
                max_connections: 15,
                ..Default::default()
            },
            ..Default::default()
        };
        let pool = DbPoolBuilder::new()
            .config(config)
            .build()
            .await
            .expect("should build pool");
        assert_eq!(pool.config().pool_config.max_connections, 15);
    }

    #[cfg(any(feature = "cache", feature = "oxcache-integration"))]
    #[test]
    fn test_builder_cache_provider() {
        use crate::foundation::DbError;
        use std::future::Future;
        use std::pin::Pin;

        struct NoopCacheProvider;
        impl DbCacheProvider for NoopCacheProvider {
            fn get<'a>(
                &'a self,
                _key: &'a str,
            ) -> Pin<Box<dyn Future<Output = Result<Option<Vec<u8>>, DbError>> + Send + 'a>>
            {
                Box::pin(async { Ok(None) })
            }
            fn set<'a>(
                &'a self,
                _key: &'a str,
                _value: Vec<u8>,
                _ttl: Option<std::time::Duration>,
            ) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
                Box::pin(async { Ok(()) })
            }
            fn delete<'a>(
                &'a self,
                _key: &'a str,
            ) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
                Box::pin(async { Ok(()) })
            }
        }

        let provider = Arc::new(NoopCacheProvider);
        let builder = DbPoolBuilder::new().cache_provider(provider);
        assert!(builder.cache_provider.is_some());
    }

    #[cfg(all(
        any(feature = "cache", feature = "oxcache-integration"),
        feature = "sqlite"
    ))]
    #[tokio::test]
    async fn test_builder_build_with_cache_provider() {
        use crate::foundation::DbError;
        use std::future::Future;
        use std::pin::Pin;

        struct NoopCacheProvider;
        impl DbCacheProvider for NoopCacheProvider {
            fn get<'a>(
                &'a self,
                _key: &'a str,
            ) -> Pin<Box<dyn Future<Output = Result<Option<Vec<u8>>, DbError>> + Send + 'a>>
            {
                Box::pin(async { Ok(None) })
            }
            fn set<'a>(
                &'a self,
                _key: &'a str,
                _value: Vec<u8>,
                _ttl: Option<std::time::Duration>,
            ) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
                Box::pin(async { Ok(()) })
            }
            fn delete<'a>(
                &'a self,
                _key: &'a str,
            ) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
                Box::pin(async { Ok(()) })
            }
        }

        let provider = Arc::new(NoopCacheProvider);
        let pool = DbPoolBuilder::new()
            .url("sqlite::memory:")
            .cache_provider(provider)
            .build()
            .await
            .expect("should build pool with cache provider");
        assert!(pool.cache_provider().is_some());
    }
}