dbnexus 0.5.0

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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! PostgreSQL testcontainers 集成测试
//!
//! 使用 testcontainers 启动真实的 PostgreSQL 容器,验证 dbnexus 在真实数据库环境下的
//! 连接、CRUD、事务等核心功能。需要 Docker 环境,且本地需有 `postgres:16-alpine` 镜像。
//!
//! # 运行方式
//!
//! ```bash
//! cargo test --test postgres_testcontainers --features postgres
//! ```

#![cfg(feature = "postgres")]

use dbnexus::{DbConfig, DbPool};
use testcontainers::GenericImage;
use testcontainers::core::{ContainerAsync, ImageExt, WaitFor};
use testcontainers::runners::AsyncRunner;

/// 启动一个 PostgreSQL 容器并返回 (容器, 连接 URL)。
///
/// 使用本地 `postgres:16-alpine` 镜像(需预先 `docker pull postgres:16-alpine`)。
/// 容器必须在测试期间保持存活,否则 Docker 会回收它。
async fn setup_postgres() -> (ContainerAsync<GenericImage>, String) {
    let container = GenericImage::new("postgres", "16-alpine")
        .with_wait_for(WaitFor::message_on_stderr(
            "database system is ready to accept connections",
        ))
        .with_wait_for(WaitFor::seconds(2))
        .with_env_var("POSTGRES_USER", "dbnexus")
        .with_env_var("POSTGRES_PASSWORD", "dbnexus")
        .with_env_var("POSTGRES_DB", "dbnexus_test")
        .start()
        .await
        .expect("Failed to start PostgreSQL container");

    let host = container.get_host().await.expect("Failed to get host");
    let port = container
        .get_host_port_ipv4(5432)
        .await
        .expect("Failed to get host port");

    let url = format!("postgres://dbnexus:dbnexus@{}:{}/dbnexus_test", host, port);

    (container, url)
}

/// 创建测试用的 DbConfig
fn make_config(url: String) -> DbConfig {
    DbConfig {
        url,
        admin_role: "admin".to_string(),
        pool_config: dbnexus::foundation::PoolConfig {
            max_connections: 5,
            min_connections: 1,
            idle_timeout: 300,
            acquire_timeout: 5000,
        },
        ..Default::default()
    }
}

#[tokio::test]
async fn test_postgres_connection() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");

    let session = pool.get_session("admin").await.expect("Failed to get session");
    assert_eq!(session.role(), "admin");

    let status = pool.status();
    assert!(
        status.total >= 1,
        "Pool should have at least one connection, got total={}",
        status.total
    );
    assert_eq!(
        status.total,
        status.active + status.idle,
        "Total should equal active + idle"
    );
}

#[tokio::test]
async fn test_postgres_crud_insert() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");

    let session = pool.get_session("admin").await.expect("Failed to get session");

    session
        .execute_raw_ddl(
            "CREATE TABLE users (
                id SERIAL PRIMARY KEY,
                name VARCHAR(100) NOT NULL,
                email VARCHAR(200) NOT NULL UNIQUE
            )",
        )
        .await
        .expect("Failed to create table");

    let result = session
        .execute_raw("INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')")
        .await
        .expect("Failed to insert");

    assert_eq!(result.rows_affected(), 1, "Should insert 1 row");
}

#[tokio::test]
async fn test_postgres_crud_update_delete() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");

    let session = pool.get_session("admin").await.expect("Failed to get session");

    session
        .execute_raw_ddl(
            "CREATE TABLE products (
                id SERIAL PRIMARY KEY,
                name VARCHAR(100) NOT NULL,
                stock INTEGER NOT NULL DEFAULT 0
            )",
        )
        .await
        .expect("Failed to create table");

    session
        .execute_raw("INSERT INTO products (name, stock) VALUES ('Widget', 10)")
        .await
        .expect("Failed to insert");

    let update_result = session
        .execute_raw("UPDATE products SET stock = 5 WHERE name = 'Widget'")
        .await
        .expect("Failed to update");
    assert_eq!(update_result.rows_affected(), 1, "Should update 1 row");

    let delete_result = session
        .execute_raw("DELETE FROM products WHERE name = 'Widget'")
        .await
        .expect("Failed to delete");
    assert_eq!(delete_result.rows_affected(), 1, "Should delete 1 row");
}

#[tokio::test]
async fn test_postgres_transaction_rollback() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");

    let session = pool.get_session("admin").await.expect("Failed to get session");

    session
        .execute_raw_ddl(
            "CREATE TABLE accounts (
                id SERIAL PRIMARY KEY,
                email VARCHAR(200) NOT NULL UNIQUE
            )",
        )
        .await
        .expect("Failed to create table");

    session.begin_transaction().await.expect("Failed to begin transaction");

    session
        .execute_raw("INSERT INTO accounts (email) VALUES ('bob@example.com')")
        .await
        .expect("Failed to insert in transaction");

    session.rollback().await.expect("Failed to rollback");

    assert!(
        !session.is_in_transaction().await,
        "Should not be in transaction after rollback"
    );

    let result = session
        .execute_raw("INSERT INTO accounts (email) VALUES ('bob@example.com')")
        .await
        .expect("Failed to insert after rollback");
    assert_eq!(
        result.rows_affected(),
        1,
        "Insert should succeed after rollback (data was not committed)"
    );
}

#[tokio::test]
async fn test_postgres_transaction_commit() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");

    let session = pool.get_session("admin").await.expect("Failed to get session");

    session
        .execute_raw_ddl(
            "CREATE TABLE orders (
                id SERIAL PRIMARY KEY,
                order_no VARCHAR(100) NOT NULL UNIQUE
            )",
        )
        .await
        .expect("Failed to create table");

    session.begin_transaction().await.expect("Failed to begin transaction");

    session
        .execute_raw("INSERT INTO orders (order_no) VALUES ('ORD-001')")
        .await
        .expect("Failed to insert in transaction");

    session.commit().await.expect("Failed to commit");

    assert!(
        !session.is_in_transaction().await,
        "Should not be in transaction after commit"
    );

    let conflict_result = session
        .execute_raw("INSERT INTO orders (order_no) VALUES ('ORD-001') ON CONFLICT (order_no) DO NOTHING")
        .await
        .expect("Failed to execute conflict insert");
    assert_eq!(
        conflict_result.rows_affected(),
        0,
        "Insert should conflict with committed data (rows_affected=0)"
    );
}

// ============================================================================
// 数据类型测试
// ============================================================================

#[tokio::test]
async fn test_postgres_data_types() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");
    let session = pool.get_session("admin").await.expect("Failed to get session");

    // PostgreSQL 特有数据类型
    session
        .execute_raw_ddl(
            "CREATE TABLE type_test (
                id SERIAL PRIMARY KEY,
                bool_col BOOLEAN,
                int_col INTEGER,
                bigint_col BIGINT,
                float_col REAL,
                double_col DOUBLE PRECISION,
                text_col TEXT,
                varchar_col VARCHAR(100),
                uuid_col UUID,
                json_col JSONB,
                array_col INTEGER[]
            )",
        )
        .await
        .expect("Failed to create table");

    session
        .execute_raw(
            "INSERT INTO type_test (bool_col, int_col, bigint_col, float_col, double_col,
             text_col, varchar_col, uuid_col, json_col, array_col)
             VALUES (true, 42, 9223372036854775807, 3.14, 2.718281828,
             'text value', 'varchar value', 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11',
             '{\"key\": \"value\"}', '{1,2,3}')",
        )
        .await
        .expect("Failed to insert");

    let result = session
        .execute_raw("SELECT * FROM type_test WHERE id = 1")
        .await
        .expect("Failed to query");
    assert_eq!(result.rows_affected(), 1, "Should return 1 row");
}

#[tokio::test]
async fn test_postgres_null_handling() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");
    let session = pool.get_session("admin").await.expect("Failed to get session");

    session
        .execute_raw_ddl("CREATE TABLE null_test (id SERIAL PRIMARY KEY, nullable_col VARCHAR(100))")
        .await
        .expect("Failed to create table");

    session
        .execute_raw("INSERT INTO null_test (nullable_col) VALUES (NULL)")
        .await
        .expect("Failed to insert NULL");

    let result = session
        .execute_raw("SELECT nullable_col FROM null_test WHERE id = 1")
        .await
        .expect("Failed to query");
    assert_eq!(result.rows_affected(), 1, "Should return 1 row");
}

// ============================================================================
// 错误路径测试
// ============================================================================

#[tokio::test]
async fn test_postgres_syntax_error_returns_error() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");
    let session = pool.get_session("admin").await.expect("Failed to get session");

    let result = session.execute_raw("SELEC * FORM nonexistent").await;
    assert!(result.is_err(), "Syntax error should return error");
}

#[tokio::test]
async fn test_postgres_table_not_exists_returns_error() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");
    let session = pool.get_session("admin").await.expect("Failed to get session");

    let result = session.execute_raw("SELECT * FROM nonexistent_table").await;
    assert!(result.is_err(), "Query on nonexistent table should return error");
}

#[tokio::test]
async fn test_postgres_duplicate_key_returns_error() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");
    let session = pool.get_session("admin").await.expect("Failed to get session");

    session
        .execute_raw_ddl("CREATE TABLE pk_test (id INTEGER PRIMARY KEY, value VARCHAR(50))")
        .await
        .expect("Failed to create table");

    session
        .execute_raw("INSERT INTO pk_test (id, value) VALUES (1, 'first')")
        .await
        .expect("First insert should succeed");

    let result = session
        .execute_raw("INSERT INTO pk_test (id, value) VALUES (1, 'duplicate')")
        .await;
    assert!(result.is_err(), "Duplicate primary key should return error");
}

// ============================================================================
// 聚合与 JOIN 测试
// ============================================================================

#[tokio::test]
async fn test_postgres_aggregate_query() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");
    let session = pool.get_session("admin").await.expect("Failed to get session");

    session
        .execute_raw_ddl("CREATE TABLE sales (id SERIAL PRIMARY KEY, product VARCHAR(50), amount DECIMAL(10,2))")
        .await
        .expect("Failed to create table");

    session
        .execute_raw("INSERT INTO sales (product, amount) VALUES ('A', 100.50), ('A', 200.00), ('B', 50.00)")
        .await
        .expect("Failed to insert");

    let result = session
        .execute_raw(
            "SELECT product, COUNT(*) as cnt, SUM(amount) as total FROM sales GROUP BY product ORDER BY product",
        )
        .await
        .expect("Aggregate query should succeed");
    assert_eq!(result.rows_affected(), 2, "Should return 2 groups");
}

#[tokio::test]
async fn test_postgres_join_query() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");
    let session = pool.get_session("admin").await.expect("Failed to get session");

    session
        .execute_raw_ddl("CREATE TABLE customers (id SERIAL PRIMARY KEY, name VARCHAR(100))")
        .await
        .expect("Failed to create customers table");

    session
        .execute_raw_ddl("CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INTEGER REFERENCES customers(id), total DECIMAL(10,2))")
        .await
        .expect("Failed to create orders table");

    session
        .execute_raw("INSERT INTO customers (name) VALUES ('Alice'), ('Bob')")
        .await
        .expect("Failed to insert customers");

    session
        .execute_raw("INSERT INTO orders (customer_id, total) VALUES (1, 100.00), (1, 200.00), (2, 50.00)")
        .await
        .expect("Failed to insert orders");

    let result = session
        .execute_raw(
            "SELECT c.name, COUNT(o.id) as order_count, SUM(o.total) as total_spent
             FROM customers c LEFT JOIN orders o ON c.id = o.customer_id
             GROUP BY c.name ORDER BY c.name",
        )
        .await
        .expect("JOIN query should succeed");
    assert_eq!(result.rows_affected(), 2, "Should return 2 customers");
}

// ============================================================================
// 健康检查与并发测试
// ============================================================================

#[tokio::test]
async fn test_postgres_health_check() {
    let (_container, url) = setup_postgres().await;
    let pool = DbPool::with_config(make_config(url))
        .await
        .expect("Failed to create pool");

    // 通过成功获取 session 并执行查询来验证连接健康
    let session = pool.get_session("admin").await;
    assert!(session.is_ok(), "get_session should succeed with healthy connection");

    let session = session.unwrap();
    let result = session.execute_raw("SELECT 1").await;
    assert!(result.is_ok(), "Health check query should succeed");
}

#[tokio::test(flavor = "multi_thread")]
async fn test_postgres_concurrent_access() {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    let (_container, url) = setup_postgres().await;
    let config = make_config(url);
    let pool = Arc::new(DbPool::with_config(config).await.expect("Failed to create pool"));

    // 创建测试表
    {
        let session = pool.get_session("admin").await.expect("Failed to get setup session");
        session
            .execute_raw_ddl("CREATE TABLE concurrent_test (id INTEGER, value INTEGER)")
            .await
            .expect("CREATE TABLE should succeed");
    }

    let success_count = Arc::new(AtomicUsize::new(0));
    let mut handles = Vec::new();

    for i in 0..4 {
        let pool_clone = pool.clone();
        let success_clone = success_count.clone();
        handles.push(tokio::spawn(async move {
            let session = match pool_clone.get_session("admin").await {
                Ok(s) => s,
                Err(_) => return,
            };
            let sql = format!("INSERT INTO concurrent_test VALUES ({}, {})", i, i * 10);
            if session.execute_raw(&sql).await.is_ok() {
                success_clone.fetch_add(1, Ordering::SeqCst);
            }
        }));
    }

    for handle in handles {
        handle.await.expect("Task panicked");
    }

    assert_eq!(
        success_count.load(Ordering::SeqCst),
        4,
        "All concurrent inserts should succeed"
    );

    // 验证数据
    let session = pool
        .get_session("admin")
        .await
        .expect("Failed to get verification session");
    let result = session
        .execute_raw("SELECT COUNT(*) as cnt FROM concurrent_test")
        .await
        .expect("COUNT query should succeed");
    assert_eq!(result.rows_affected(), 1, "Should return 1 row");
}