bootrust 0.1.0

An elegant macroless data access layer abstraction, simple and easy-use object-relational mapping powered by the Serde serialization framework. 一个优雅的无宏的数据访问层抽象, 由serde序列化框架提供支持的简单易用的对象关系映射
Documentation
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
use bootrust::asyncdao::Dao;
use bootrust::asyncdatabase::{
    postgres::PostgresDatabase, DatabaseConfig, DbError, RelationalDatabase, Row, Value,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serial_test::serial;
use std::marker::PhantomData;
use std::sync::Arc;

// 商品实体
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Product {
    id: i64,
    name: String,
    description: String,
    price: f64,
    stock: i64,
    #[serde(with = "chrono::serde::ts_seconds")]
    created_at: DateTime<Utc>,
}

// 购物车实体
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct CartItem {
    id: i64,
    user_id: i64,
    product_id: i64,
    quantity: i64,
    #[serde(with = "chrono::serde::ts_seconds")]
    added_at: DateTime<Utc>,
}

// 支付信息实体
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Payment {
    id: i64,
    order_id: i64,
    amount: f64,
    payment_method: String,
    transaction_id: String,
    #[serde(with = "chrono::serde::ts_seconds")]
    paid_at: DateTime<Utc>,
}

// ECommerceDo实现
struct ECommerceDo<T: Sized, D: RelationalDatabase> {
    database: D,
    _table: PhantomData<T>,
}

impl<D: RelationalDatabase> Dao<Product> for ECommerceDo<Product, D> {
    type Database = D;

    fn new(database: Self::Database) -> Self {
        ECommerceDo {
            database,
            _table: PhantomData,
        }
    }

    fn database(&self) -> &Self::Database {
        &self.database
    }

    fn row_to_entity(row: Row) -> Result<Product, DbError> {
        if row.values.len() != 6 {
            return Err(DbError::ConversionError(
                "Invalid number of columns".to_string(),
            ));
        }

        Ok(Product {
            id: match &row.values[0] {
                Value::Bigint(i) => *i,
                _ => return Err(DbError::ConversionError("Invalid id type".to_string())),
            },
            name: match &row.values[1] {
                Value::Text(s) => s.clone(),
                _ => return Err(DbError::ConversionError("Invalid name type".to_string())),
            },
            description: match &row.values[2] {
                Value::Text(s) => s.clone(),
                _ => {
                    return Err(DbError::ConversionError(
                        "Invalid description type".to_string(),
                    ))
                }
            },
            price: match &row.values[3] {
                Value::Double(f) => *f,
                _ => return Err(DbError::ConversionError("Invalid price type".to_string())),
            },
            stock: match &row.values[4] {
                Value::Bigint(i) => *i,
                _ => return Err(DbError::ConversionError("Invalid stock type".to_string())),
            },
            created_at: match &row.values[5] {
                Value::DateTime(dt) => *dt,
                _ => {
                    return Err(DbError::ConversionError(
                        "Invalid created_at type".to_string(),
                    ))
                }
            },
        })
    }

    fn entity_to_map(entity: &Product) -> Vec<(String, Value)> {
        let mut map = Vec::new();
        map.push(("id".to_string(), Value::Bigint(entity.id)));
        map.push(("name".to_string(), Value::Text(entity.name.clone())));
        map.push((
            "description".to_string(),
            Value::Text(entity.description.clone()),
        ));
        map.push(("price".to_string(), Value::Double(entity.price)));
        map.push(("stock".to_string(), Value::Bigint(entity.stock)));
        map.push(("created_at".to_string(), Value::DateTime(entity.created_at)));
        map
    }

    fn table_name() -> String {
        "products".to_string()
    }

    fn primary_key_column() -> String {
        "id".to_string()
    }
}

impl<D: RelationalDatabase> Dao<CartItem> for ECommerceDo<CartItem, D> {
    type Database = D;

    fn new(database: Self::Database) -> Self {
        ECommerceDo {
            database,
            _table: PhantomData,
        }
    }

    fn database(&self) -> &Self::Database {
        &self.database
    }

    fn row_to_entity(row: Row) -> Result<CartItem, DbError> {
        if row.values.len() != 5 {
            return Err(DbError::ConversionError(
                "Invalid number of columns".to_string(),
            ));
        }

        Ok(CartItem {
            id: match &row.values[0] {
                Value::Bigint(i) => *i,
                _ => return Err(DbError::ConversionError("Invalid id type".to_string())),
            },
            user_id: match &row.values[1] {
                Value::Bigint(i) => *i,
                _ => return Err(DbError::ConversionError("Invalid user_id type".to_string())),
            },
            product_id: match &row.values[2] {
                Value::Bigint(i) => *i,
                _ => {
                    return Err(DbError::ConversionError(
                        "Invalid product_id type".to_string(),
                    ))
                }
            },
            quantity: match &row.values[3] {
                Value::Bigint(i) => *i,
                _ => {
                    return Err(DbError::ConversionError(
                        "Invalid quantity type".to_string(),
                    ))
                }
            },
            added_at: match &row.values[4] {
                Value::DateTime(dt) => *dt,
                _ => {
                    return Err(DbError::ConversionError(
                        "Invalid added_at type".to_string(),
                    ))
                }
            },
        })
    }

    fn entity_to_map(entity: &CartItem) -> Vec<(String, Value)> {
        let mut map = Vec::new();
        map.push(("id".to_string(), Value::Bigint(entity.id)));
        map.push(("user_id".to_string(), Value::Bigint(entity.user_id)));
        map.push(("product_id".to_string(), Value::Bigint(entity.product_id)));
        map.push(("quantity".to_string(), Value::Bigint(entity.quantity)));
        map.push(("added_at".to_string(), Value::DateTime(entity.added_at)));
        map
    }

    fn table_name() -> String {
        "cart_items".to_string()
    }

    fn primary_key_column() -> String {
        "id".to_string()
    }
}

impl<D: RelationalDatabase> Dao<Payment> for ECommerceDo<Payment, D> {
    type Database = D;

    fn new(database: Self::Database) -> Self {
        ECommerceDo {
            database,
            _table: PhantomData,
        }
    }

    fn database(&self) -> &Self::Database {
        &self.database
    }

    fn row_to_entity(row: Row) -> Result<Payment, DbError> {
        if row.values.len() != 6 {
            return Err(DbError::ConversionError(
                "Invalid number of columns".to_string(),
            ));
        }

        Ok(Payment {
            id: match &row.values[0] {
                Value::Bigint(i) => *i,
                _ => return Err(DbError::ConversionError("Invalid id type".to_string())),
            },
            order_id: match &row.values[1] {
                Value::Bigint(i) => *i,
                _ => {
                    return Err(DbError::ConversionError(
                        "Invalid order_id type".to_string(),
                    ))
                }
            },
            amount: match &row.values[2] {
                Value::Double(f) => *f,
                _ => return Err(DbError::ConversionError("Invalid amount type".to_string())),
            },
            payment_method: match &row.values[3] {
                Value::Text(s) => s.clone(),
                _ => {
                    return Err(DbError::ConversionError(
                        "Invalid payment_method type".to_string(),
                    ))
                }
            },
            transaction_id: match &row.values[4] {
                Value::Text(s) => s.clone(),
                _ => {
                    return Err(DbError::ConversionError(
                        "Invalid transaction_id type".to_string(),
                    ))
                }
            },
            paid_at: match &row.values[5] {
                Value::DateTime(dt) => *dt,
                _ => return Err(DbError::ConversionError("Invalid paid_at type".to_string())),
            },
        })
    }

    fn entity_to_map(entity: &Payment) -> Vec<(String, Value)> {
        let mut map = Vec::new();
        map.push(("id".to_string(), Value::Bigint(entity.id)));
        map.push(("order_id".to_string(), Value::Bigint(entity.order_id)));
        map.push(("amount".to_string(), Value::Double(entity.amount)));
        map.push((
            "payment_method".to_string(),
            Value::Text(entity.payment_method.clone()),
        ));
        map.push((
            "transaction_id".to_string(),
            Value::Text(entity.transaction_id.clone()),
        ));
        map.push(("paid_at".to_string(), Value::DateTime(entity.paid_at)));
        map
    }

    fn table_name() -> String {
        "payments".to_string()
    }

    fn primary_key_column() -> String {
        "id".to_string()
    }
}

// 设置测试数据库
async fn setup_ecommerce_test_db() -> PostgresDatabase {
    let config = DatabaseConfig {
        host: "localhost".to_string(),
        port: 5432,
        username: "root".to_string(),
        password: "root".to_string(),
        database_name: "test".to_string(),
        max_size: 10,
    };
    let db = PostgresDatabase::connect(config).await.unwrap();

    // 创建商品表
    db.execute("DROP TABLE IF EXISTS products", vec![])
        .await
        .unwrap();
    db.execute(
        "CREATE TABLE products (
            id BIGSERIAL PRIMARY KEY,
            name TEXT NOT NULL,
            description TEXT,
            price FLOAT8 NOT NULL,
            stock INT8 NOT NULL,
            created_at TIMESTAMPTZ
        )",
        vec![],
    )
    .await
    .unwrap();

    // 创建购物车表
    db.execute("DROP TABLE IF EXISTS cart_items", vec![])
        .await
        .unwrap();
    db.execute(
        "CREATE TABLE cart_items (
            id BIGSERIAL   PRIMARY KEY,
            user_id INT8 NOT NULL,
            product_id INT8 NOT NULL,
            quantity INT8 NOT NULL,
            added_at TIMESTAMPTZ NOT NULL
        )",
        vec![],
    )
    .await
    .unwrap();

    // 创建支付信息表
    db.execute("DROP TABLE IF EXISTS payments", vec![])
        .await
        .unwrap();
    db.execute(
        "CREATE TABLE payments (
            id BIGSERIAL  PRIMARY KEY,
            order_id INT8 NOT NULL,
            amount FLOAT8 NOT NULL,
            payment_method TEXT NOT NULL,
            transaction_id TEXT NOT NULL,
            paid_at TIMESTAMP WITH TIME ZONE   NOT NULL
        )",
        vec![],
    )
    .await
    .unwrap();

    db
}

// 创建测试商品
fn create_test_product() -> Product {
    Product {
        id: 1,
        name: "Test Product".to_string(),
        description: "This is a test product.".to_string(),
        price: 99.99,
        stock: 100,
        created_at: Utc::now(),
    }
}

// 创建测试购物车项
fn create_test_cart_item() -> CartItem {
    CartItem {
        id: 1,
        user_id: 1,
        product_id: 1,
        quantity: 2,
        added_at: Utc::now(),
    }
}

// 创建测试支付信息
fn create_test_payment() -> Payment {
    Payment {
        id: 1,
        order_id: 1,
        amount: 199.98,
        payment_method: "Credit Card".to_string(),
        transaction_id: "tx12345".to_string(),
        paid_at: Utc::now(),
    }
}

// 测试添加商品到购物车
#[tokio::test]
#[serial]
async fn test_add_product_to_cart() {
    let db = setup_ecommerce_test_db().await;
    let product_dao = ECommerceDo::new(db.clone());
    let cart_dao = ECommerceDo::new(db.clone());

    // 创建测试商品
    let product = create_test_product();
    product_dao.create(&product).await.unwrap();

    // 添加商品到购物车
    let mut cart_item = create_test_cart_item();
    cart_item.product_id = product.id;
    let result = cart_dao.create(&cart_item).await;
    assert!(result.is_ok());

    // 验证购物车项是否添加成功
    let added_item = cart_dao
        .find_by_id(Value::Bigint(cart_item.id))
        .await
        .unwrap();
    assert!(added_item.is_some());
    assert_eq!(added_item.unwrap().product_id, product.id);
}

// 测试从购物车移除商品
#[tokio::test]
#[serial]
async fn test_remove_product_from_cart() {
    let db = setup_ecommerce_test_db().await;
    let cart_dao = ECommerceDo::new(db.clone());

    // 添加商品到购物车
    let cart_item = create_test_cart_item();
    cart_dao.create(&cart_item).await.unwrap();

    // 从购物车移除商品
    let result = cart_dao.delete(Value::Bigint(cart_item.id)).await;
    dbg!(&result);
    assert!(result.is_ok());

    // 验证购物车项是否已移除
    let removed_item = cart_dao
        .find_by_id(Value::Bigint(cart_item.id))
        .await
        .unwrap();
    assert!(removed_item.is_none());
}

// 测试更新购物车商品数量
#[tokio::test]
#[serial]
async fn test_update_cart_item_quantity() {
    let db = setup_ecommerce_test_db().await;
    let cart_dao = ECommerceDo::new(db.clone());

    // 添加商品到购物车
    let mut cart_item = create_test_cart_item();
    cart_dao.create(&cart_item).await.unwrap();

    // 更新购物车商品数量
    cart_item.quantity = 3;
    let result = cart_dao.update(&cart_item).await;
    assert!(result.is_ok());

    // 验证购物车商品数量是否更新
    let updated_item = cart_dao
        .find_by_id(Value::Bigint(cart_item.id))
        .await
        .unwrap();
    assert_eq!(updated_item.unwrap().quantity, 3);
}

// 测试支付流程
#[tokio::test]
#[serial]
async fn test_payment_process() {
    let db = setup_ecommerce_test_db().await;
    let payment_dao = ECommerceDo::new(db.clone());

    // 创建测试订单
    let order_id = 1;

    // 进行支付
    let mut payment = create_test_payment();
    payment.order_id = order_id;
    let result = payment_dao.create(&payment).await;
    assert!(result.is_ok());

    // 验证支付信息是否保存成功
    let saved_payment = payment_dao
        .find_by_id(Value::Bigint(payment.id))
        .await
        .unwrap();
    assert!(saved_payment.is_some());
    assert_eq!(saved_payment.unwrap().order_id, order_id);
}

// 测试库存更新
#[tokio::test]
#[serial]
async fn test_stock_update() {
    let db = setup_ecommerce_test_db().await;
    let product_dao = ECommerceDo::new(db.clone());

    // 创建测试商品
    let mut product = create_test_product();
    product_dao.create(&product).await.unwrap();

    // 更新商品库存
    product.stock = 50;
    let result = product_dao.update(&product).await;
    assert!(result.is_ok());

    // 验证商品库存是否更新
    let updated_product = product_dao
        .find_by_id(Value::Bigint(product.id))
        .await
        .unwrap();
    assert_eq!(updated_product.unwrap().stock, 50);
}

// 测试事务处理
#[tokio::test]
#[serial]
async fn test_transaction() {
    let db = setup_ecommerce_test_db().await;
    let product_dao = ECommerceDo::new(db.clone());
    let cart_dao = ECommerceDo::new(db.clone());
    let payment_dao = ECommerceDo::new(db.clone());

    // 开始事务
    let result = product_dao.begin_transaction().await;
    assert!(result.is_ok());

    // 创建商品
    let product = create_test_product();
    let result = product_dao.create(&product).await;
    assert!(result.is_ok());

    // 添加商品到购物车
    let mut cart_item = create_test_cart_item();
    cart_item.product_id = product.id;
    let result = cart_dao.create(&cart_item).await;
    assert!(result.is_ok());

    // 进行支付
    let payment = create_test_payment();
    let result = payment_dao.create(&payment).await;
    assert!(result.is_ok());

    // 提交事务
    let result = product_dao.commit().await;
    assert!(result.is_ok());

    // 验证商品、购物车项和支付信息是否已创建
    let found_product = product_dao
        .find_by_id(Value::Bigint(product.id))
        .await
        .unwrap();
    assert!(found_product.is_some());

    let found_cart_item = cart_dao
        .find_by_id(Value::Bigint(cart_item.id))
        .await
        .unwrap();
    assert!(found_cart_item.is_some());

    let found_payment = payment_dao
        .find_by_id(Value::Bigint(payment.id))
        .await
        .unwrap();
    assert!(found_payment.is_some());
}

// 测试事务回滚
#[tokio::test]
#[serial]
async fn test_transaction_rollback() {
    let db = setup_ecommerce_test_db().await;
    let arc_db = Arc::new(db);
    let product_dao = ECommerceDo::new(Arc::clone(&arc_db));
    let cart_dao = ECommerceDo::new(Arc::clone(&arc_db));
    // let product_dao = ECommerceDo::new(db.clone());
    // let cart_dao = ECommerceDo::new(db.clone());

    // 开始事务
    let result = product_dao.begin_transaction().await;
    assert!(result.is_ok());

    // 创建商品
    let product = create_test_product();
    let result = product_dao.create(&product).await;
    assert!(result.is_ok());

    // 添加商品到购物车 (故意制造错误, 例如商品ID不存在)
    let mut cart_item = create_test_cart_item();
    cart_item.product_id = 999; // 不存在的商品ID
    let _result = cart_dao.create(&cart_item);
    // assert!(result.is_err()); // 应该返回错误

    // 回滚事务
    let result = product_dao.rollback().await;
    assert!(result.is_ok());

    // 验证商品和购物车项是否未创建
    let found_product = product_dao
        .find_by_id(Value::Bigint(product.id))
        .await
        .unwrap();
    assert!(found_product.is_none());

    let found_cart_item = cart_dao
        .find_by_id(Value::Bigint(cart_item.id))
        .await
        .unwrap();
    assert!(found_cart_item.is_none());
}

#[tokio::test]
#[serial]
async fn test_arc_db() {
    let db = setup_ecommerce_test_db().await;
    let arc_db = Arc::new(db);
    let product_dao = ECommerceDo::<Product, _>::new(Arc::clone(&arc_db));

    let product = create_test_product();
    product_dao.create(&product).await.unwrap();

    let added_item = product_dao
        .find_by_id(Value::Bigint(product.id))
        .await
        .unwrap();
    assert!(added_item.is_some());
    assert_eq!(added_item.unwrap().id, product.id);
}