ormer 0.1.18

A minimalist ORM framework that supports SQLite, PostgreSQL, MySQL, and SqlServer
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
#![cfg(any(feature = "sqlite", feature = "postgresql", feature = "mysql"))]

use ormer::Database;

mod _test_common;

// 使用宏定义测试专用模型(唯一表名)
define_test_user_for_pool!(PoolTestUser, "pool_test_users_1");

#[cfg(any(feature = "sqlite", feature = "postgresql", feature = "mysql"))]
mod connection_pool_tests {
    use super::Database;
    use super::PoolTestUser;
    use crate::_test_common;
    use crate::_test_common::DbConfig;

    // 为 Sqlite 测试创建临时数据库路径

    /// 测试连接池创建和基本配置
    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_pool_creation_turso() -> Result<(), Box<dyn std::error::Error>> {
        // 连接池测试使用 Sqlite 内存数据库的文件版本
        let config: DbConfig = (ormer::DbType::Sqlite, ":memory:");
        let _ = _test_common::create_db_connection(&config).await?;

        // 创建连接池,min=0 表示创建时不建立连接
        // SQLite 建议使用单连接池(max_size=1)以避免并发写入冲突
        // 如需并发支持,可考虑启用 MVCC 模式(PRAGMA journal_mode = 'mvcc')
        let pool = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        // 从池中获取连接(此时才会真正创建连接)
        let conn = pool.get().await?;

        // 验证连接可以使用
        conn.create_table::<PoolTestUser>().execute().await?;

        // 清理测试表
        conn.drop_table::<PoolTestUser>().execute().await?;

        // conn 离开作用域后自动归还
        Ok(())
    }

    /// 测试连接池的插入操作
    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_pool_insert_turso() -> Result<(), Box<dyn std::error::Error>> {
        // SQLite 建议使用单连接池(max_size=1)
        let pool = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        let conn = pool.get().await?;
        conn.create_table::<PoolTestUser>().execute().await?;

        // 插入单条记录
        conn.insert(&PoolTestUser {
            id: 1,
            name: "Alice".to_string(),
            age: 25,
            email: Some("alice@example.com".to_string()),
        })
        .execute()
        .await?;

        // 插入多条记录
        conn.insert(&vec![
            PoolTestUser {
                id: 2,
                name: "Bob".to_string(),
                age: 30,
                email: Some("bob@example.com".to_string()),
            },
            PoolTestUser {
                id: 3,
                name: "Charlie".to_string(),
                age: 35,
                email: None,
            },
        ])
        .execute()
        .await?;

        // 清理测试表
        conn.drop_table::<PoolTestUser>().execute().await?;

        Ok(())
    }

    /// 测试连接池的查询操作
    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_pool_select_turso() -> Result<(), Box<dyn std::error::Error>> {
        // SQLite 建议使用单连接池(max_size=1)
        let pool = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        // 插入测试数据并查询 - 使用同一个连接完成所有操作(SQLite 连接池大小为 1)
        {
            let conn = pool.get().await?;
            conn.create_table::<PoolTestUser>().execute().await?;
            conn.insert(&PoolTestUser {
                id: 1,
                name: "Alice".to_string(),
                age: 25,
                email: Some("alice@example.com".to_string()),
            })
            .execute()
            .await?;
            conn.insert(&PoolTestUser {
                id: 2,
                name: "Bob".to_string(),
                age: 30,
                email: Some("bob@example.com".to_string()),
            })
            .execute()
            .await?;

            let users = conn.select::<PoolTestUser>().collect::<Vec<_>>().await?;

            assert_eq!(users.len(), 2);
            assert_eq!(users[0].name, "Alice");
            assert_eq!(users[1].name, "Bob");

            // 清理测试表
            conn.drop_table::<PoolTestUser>().execute().await?;
        }

        Ok(())
    }

    /// 测试连接池的过滤查询
    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_pool_filter_select_turso() -> Result<(), Box<dyn std::error::Error>> {
        // SQLite 建议使用单连接池(max_size=1)
        let pool = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        // 插入测试数据并进行过滤查询 - 使用同一个连接(SQLite 连接池大小为 1)
        {
            let conn = pool.get().await?;
            conn.create_table::<PoolTestUser>().execute().await?;
            for i in 1..=5 {
                conn.insert(&PoolTestUser {
                    id: i,
                    name: format!("User{}", i),
                    age: 20 + i * 5,
                    email: Some(format!("user{}@example.com", i)),
                })
                .execute()
                .await?;
            }

            // 带过滤条件的查询
            let users = conn
                .select::<PoolTestUser>()
                .filter(|p| p.age.ge(35))
                .collect::<Vec<_>>()
                .await?;

            assert_eq!(users.len(), 3); // age >= 35 的有 3 个

            // 清理测试表
            conn.drop_table::<PoolTestUser>().execute().await?;
        }

        Ok(())
    }

    /// 测试连接池的更新操作
    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_pool_update_turso() -> Result<(), Box<dyn std::error::Error>> {
        // SQLite 建议使用单连接池(max_size=1)
        let pool = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        // 插入、更新和验证 - 使用同一个连接(SQLite 连接池大小为 1)
        {
            let conn = pool.get().await?;
            conn.create_table::<PoolTestUser>().execute().await?;
            conn.insert(&PoolTestUser {
                id: 1,
                name: "Alice".to_string(),
                age: 25,
                email: Some("alice@example.com".to_string()),
            })
            .execute()
            .await?;

            // 更新数据
            let count = conn
                .update::<PoolTestUser>()
                .filter(|p| p.name.eq("Alice".to_string()))
                .set(|p| p.age, 30)
                .execute()
                .await?;

            assert_eq!(count, 1);

            // 验证更新结果
            let users = conn
                .select::<PoolTestUser>()
                .filter(|p| p.name.eq("Alice".to_string()))
                .collect::<Vec<_>>()
                .await?;

            assert_eq!(users.len(), 1);
            assert_eq!(users[0].age, 30);

            // 清理测试表
            conn.drop_table::<PoolTestUser>().execute().await?;
        }

        Ok(())
    }

    /// 测试连接池的删除操作
    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_pool_delete_turso() -> Result<(), Box<dyn std::error::Error>> {
        // SQLite 建议使用单连接池(max_size=1)
        let pool = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        // 插入、删除和验证 - 使用同一个连接(SQLite 连接池大小为 1)
        {
            let conn = pool.get().await?;
            conn.create_table::<PoolTestUser>().execute().await?;
            conn.insert(&PoolTestUser {
                id: 1,
                name: "Alice".to_string(),
                age: 25,
                email: None,
            })
            .execute()
            .await?;
            conn.insert(&PoolTestUser {
                id: 2,
                name: "Bob".to_string(),
                age: 30,
                email: None,
            })
            .execute()
            .await?;

            // 删除数据
            let count = conn
                .delete::<PoolTestUser>()
                .filter(|p| p.age.lt(28))
                .execute()
                .await?;

            assert_eq!(count, 1);

            // 验证删除结果
            let users = conn.select::<PoolTestUser>().collect::<Vec<_>>().await?;
            assert_eq!(users.len(), 1);
            assert_eq!(users[0].name, "Bob");

            // 清理测试表
            conn.drop_table::<PoolTestUser>().execute().await?;
        }

        Ok(())
    }

    /// 测试连接池的事务操作
    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_pool_transaction_turso() -> Result<(), Box<dyn std::error::Error>> {
        // SQLite 建议使用单连接池(max_size=1)
        let pool = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        // 在同一个连接中创建表和执行事务
        let conn = pool.get().await?;
        conn.create_table::<PoolTestUser>().execute().await?;

        // 使用事务插入数据
        let mut txn = conn.begin().await?;

        txn.insert(&PoolTestUser {
            id: 1,
            name: "Alice".to_string(),
            age: 25,
            email: Some("alice@example.com".to_string()),
        })
        .execute()
        .await?;

        txn.insert(&PoolTestUser {
            id: 2,
            name: "Bob".to_string(),
            age: 30,
            email: Some("bob@example.com".to_string()),
        })
        .execute()
        .await?;

        txn.commit().await?;

        // 验证事务提交成功
        let users = conn.select::<PoolTestUser>().collect::<Vec<_>>().await?;
        assert_eq!(users.len(), 2);

        // 清理测试表
        conn.drop_table::<PoolTestUser>().execute().await?;

        Ok(())
    }

    /// 测试连接池的聚合查询
    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_pool_aggregate_turso() -> Result<(), Box<dyn std::error::Error>> {
        // SQLite 建议使用单连接池(max_size=1)
        let pool = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        // 插入测试数据和聚合查询 - 使用同一个连接(SQLite 连接池大小为 1)
        {
            let conn = pool.get().await?;
            conn.create_table::<PoolTestUser>().execute().await?;
            for i in 1..=5 {
                conn.insert(&PoolTestUser {
                    id: i,
                    name: format!("User{}", i),
                    age: 20 + i * 5,
                    email: None,
                })
                .execute()
                .await?;
            }

            // 聚合查询
            let count: usize = conn.select::<PoolTestUser>().count(|p| p.id).await?;
            assert_eq!(count, 5);

            let sum: Option<i32> = conn.select::<PoolTestUser>().sum(|p| p.age).await?;
            assert_eq!(sum, Some(175)); // 25+30+35+40+45 = 175

            let avg: Option<f64> = conn.select::<PoolTestUser>().avg(|p| p.age).await?;
            assert!((avg.unwrap() - 35.0).abs() < 0.01);

            let min: Option<i32> = conn.select::<PoolTestUser>().min(|p| p.age).await?;
            assert_eq!(min, Some(25));

            let max: Option<i32> = conn.select::<PoolTestUser>().max(|p| p.age).await?;
            assert_eq!(max, Some(45));

            // 清理测试表
            conn.drop_table::<PoolTestUser>().execute().await?;
        }

        Ok(())
    }

    /// 测试多次获取和归还连接
    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_pool_multiple_get_return_turso() -> Result<(), Box<dyn std::error::Error>> {
        // SQLite 建议使用单连接池(max_size=1)
        let pool = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        // 多次操作 - 使用同一个连接(SQLite 连接池大小为 1)
        {
            let conn = pool.get().await?;

            // 第一次:创建表
            conn.create_table::<PoolTestUser>().execute().await?;

            // 第二次:插入数据
            conn.insert(&PoolTestUser {
                id: 1,
                name: "Alice".to_string(),
                age: 25,
                email: None,
            })
            .execute()
            .await?;

            // 第三次:查询数据
            let users = conn.select::<PoolTestUser>().collect::<Vec<_>>().await?;
            assert_eq!(users.len(), 1);

            // 第四次:删除表
            conn.drop_table::<PoolTestUser>().execute().await?;
        }

        Ok(())
    }

    /// 测试连接池的原生 SQL 执行
    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_pool_exec_sql_turso() -> Result<(), Box<dyn std::error::Error>> {
        // SQLite 建议使用单连接池(max_size=1)
        let pool = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        let conn = pool.get().await?;

        // 先清理可能存在的旧表
        let _ = conn.drop_table::<PoolTestUser>().execute().await;

        conn.create_table::<PoolTestUser>().execute().await?;

        // 执行原生插入 SQL
        conn.exec_non_query(
            "INSERT INTO pool_test_users_1 (id, name, age, email) VALUES (1, 'Alice', 25, 'alice@example.com')",
        )
        .await?;

        // 执行原生查询 SQL
        let users = conn
            .execute::<PoolTestUser>("SELECT * FROM pool_test_users_1")
            .await?;

        assert_eq!(users.len(), 1);
        assert_eq!(users[0].name, "Alice");

        // 清理测试表
        conn.drop_table::<PoolTestUser>().execute().await?;

        Ok(())
    }

    /// 测试连接池配置的范围参数
    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_pool_range_config_turso() -> Result<(), Box<dyn std::error::Error>> {
        // 测试不同的范围配置(SQLite 建议 max_size=1)
        let pool1 = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        let pool2 = Database::create_pool(ormer::DbType::Sqlite, ":memory:")
            .range(0..1)
            .build()
            .await?;

        // 验证两个池都可以正常工作
        let conn1 = pool1.get().await?;
        conn1.create_table::<PoolTestUser>().execute().await?;

        let conn2 = pool2.get().await?;
        conn2.create_table::<PoolTestUser>().execute().await?;

        // 清理测试表 - 使用各自连接删除表(使用不同表名避免冲突)
        conn1.drop_table::<PoolTestUser>().execute().await?;
        conn2.drop_table::<PoolTestUser>().execute().await?;

        Ok(())
    }
}