torm 0.4.0

A Tokio-based async ORM for Rust with GORM-like API, supporting SQLite, MySQL and PostgreSQL via native wire protocols
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
use torm::*;
use chrono::Utc;

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿš€ TORM - Tokio ORM Demo (Simplified Dependencies)\n");

    // 1. Database connection example
    println!("๐Ÿ“ก Database connection example");
    println!("========================");
    demonstrate_database_connection().await?;
    println!();

    // 2. Simplified UUID generation
    println!("๐Ÿ”‘ Simplified UUID generation");
    println!("========================");
    demonstrate_simplified_uuid()?;
    println!();

    // 3. Simplified error handling
    println!("โš ๏ธ  Simplified error handling");
    println!("========================");
    demonstrate_simplified_error()?;
    println!();

    // 4. Simplified LRU cache
    println!("๐Ÿ’พ Simplified LRU cache");
    println!("========================");
    demonstrate_simplified_cache()?;
    println!();

    // 5. Connection pool
    println!("๐ŸŠ Simple connection pool");
    println!("========================");
    demonstrate_connection_pool().await?;
    println!();

    // 6. Query builder example
    println!("๐Ÿ”จ Query builder example");
    println!("========================");
    demonstrate_query_builder();
    println!();

    // 7. Pure Rust SQL engine example
    println!("๐Ÿ—„๏ธ  Pure Rust SQL Engine");
    println!("========================");
    demonstrate_sql_engine().await?;
    println!();

    println!("๐ŸŽ‰ All demos completed successfully!");
    println!();
    println!("๐Ÿ“š Simplified dependencies benefits:");
    println!("  โœ… Reduced external dependencies");
    println!("  โœ… Custom implementations for critical components");
    println!("  โœ… Pure Rust SQL engine (no rusqlite)");
    println!("  โœ… Better control over functionality and performance");
    println!("  โœ… Faster compilation with fewer dependencies");
    println!("  โœ… Smaller binary size");
    println!();
    println!("๐Ÿ“ฆ Remaining dependencies:");
    println!("  โ€ข tokio - Async runtime (essential)");
    println!("  โ€ข serde/serde_json - Serialization (essential)");
    println!("  โ€ข chrono - Time handling (essential)");
    println!("  โ€ข uuid - UUID generation (essential)");

    Ok(())
}

async fn demonstrate_database_connection() -> std::result::Result<(), Box<dyn std::error::Error>> {
    println!("SQLite connection:");
    let dsn = Dsn::new(DBDriver::SQLite, "demo.db");
    println!("  DSN: {}", dsn.build());
    
    // Test actual SQLite connection with pure Rust engine
    let db = Database::sqlite(":memory:").await?;
    println!("  โœ… Connected to in-memory SQLite (pure Rust engine)");
    println!("  DB type: {:?}", db.db_type());
    println!("  Connected: {}", db.is_connected());
    db.close().await?;
    
    println!();
    println!("MySQL connection example:");
    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
        .with_host("localhost")
        .with_port(3306)
        .with_username("user")
        .with_password("password");
    println!("  DSN: {}", mysql_dsn.build());
    
    println!();
    println!("PostgreSQL connection example:");
    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
        .with_host("localhost")
        .with_port(5432)
        .with_username("user")
        .with_password("password");
    println!("  DSN: {}", pg_dsn.build());

    Ok(())
}

fn demonstrate_simplified_uuid() -> std::result::Result<(), Box<dyn std::error::Error>> {
    println!("Generating UUIDs:");
    
    // Generate multiple UUIDs
    let uuid1 = SimpleUuid::new_v4();
    let uuid2 = SimpleUuid::new_v4();
    let uuid3 = SimpleUuid::new_v4();
    
    println!("  UUID 1: {}", uuid1);
    println!("  UUID 2: {}", uuid2);
    println!("  UUID 3: {}", uuid3);
    println!("  All unique: {}", uuid1 != uuid2 && uuid2 != uuid3 && uuid1 != uuid3);
    
    println!();
    println!("ID Generator:");
    let generator = IdGenerator::new();
    let id1 = generator.generate();
    let id2 = generator.generate();
    
    println!("  ID 1: {}", id1);
    println!("  ID 2: {}", id2);
    println!("  ID 3: {}", generator.with_prefix("user_").generate());
    
    println!();
    println!("Simple IDs:");
    let simple_gen = IdGenerator::new().with_simple_id();
    println!("  Simple ID: {}", simple_gen.generate());
    println!("  Prefixed: {}", simple_gen.with_prefix("order_").generate());

    Ok(())
}

fn demonstrate_simplified_error() -> std::result::Result<(), Box<dyn std::error::Error>> {
    println!("Error handling without thiserror:");
    
    // Create different error types
    let not_found = SimpleError::NotFound;
    println!("  NotFound: {}", not_found);
    
    let custom = SimpleError::custom("Something went wrong");
    println!("  Custom: {}", custom);
    
    let invalid_query = SimpleError::invalid_query("Invalid WHERE clause");
    println!("  InvalidQuery: {}", invalid_query);
    
    let connection_error = SimpleError::connection_error("Could not connect to database");
    println!("  ConnectionError: {}", connection_error);
    
    println!();
    println!("Using SimpleResult:");
    let success: SimpleResult<i32> = Ok(42);
    println!("  Success: {:?}", success);
    
    let failure: SimpleResult<i32> = Err(SimpleError::NotFound);
    println!("  Failure: {:?}", failure);

    Ok(())
}

fn demonstrate_simplified_cache() -> std::result::Result<(), Box<dyn std::error::Error>> {
    println!("LRU cache:");
    
    let mut cache: SimpleLruCache<&str, &str> = SimpleLruCache::new(3);
    
    // Add items
    cache.put("key1", "value1");
    cache.put("key2", "value2");
    cache.put("key3", "value3");
    
    println!("  Initial size: {}", cache.len());
    println!("  key1: {:?}", cache.get(&"key1"));
    println!("  key2: {:?}", cache.get(&"key2"));
    println!("  key3: {:?}", cache.get(&"key3"));
    
    // Test LRU eviction
    println!();
    println!("  Adding key4 (should evict oldest):");
    cache.put("key4", "value4");
    println!("  key1: {:?}", cache.get(&"key1")); // Should be None
    println!("  key4: {:?}", cache.get(&"key4")); // Should be Some
    
    // Test capacity
    println!();
    println!("  Current capacity: {}", cache.capacity());
    println!("  Current size: {}", cache.len());
    
    // Resize
    cache.resize(2);
    println!("  After resize to 2:");
    println!("  New size: {}", cache.len());
    
    // Cleanup
    cache.clear();
    println!("  After clear: {}", cache.is_empty());

    Ok(())
}

async fn demonstrate_connection_pool() -> std::result::Result<(), Box<dyn std::error::Error>> {
    println!("Simple connection pool implementation:");
    
    // Create a pool with pre-created connections
    let connections = vec![1, 2, 3, 4, 5];
    let pool = SimplePool::new(connections);
    let status = pool.status();
    
    println!("  Total connections: {}", status.total_connections);
    println!("  Idle connections: {}", status.idle_connections);
    println!("  Active connections: {}", status.active_connections);
    println!("  Utilization: {:.1}%", status.utilization_rate() * 100.0);
    
    // Test getting a connection
    println!();
    println!("  Getting a connection from pool:");
    match pool.get().await {
        Ok(conn) => {
            println!("    Got: {}", conn);
            let status = pool.status();
            println!("    After get - idle: {}, active: {}", status.idle_connections, status.active_connections);
            pool.put(conn);
            let status = pool.status();
            println!("    After put - idle: {}, active: {}", status.idle_connections, status.active_connections);
        }
        Err(e) => println!("    Error: {}", e),
    }
    
    println!();
    println!("Pool features:");
    println!("  โ€ข Connection reuse");
    println!("  โ€ข Timeout handling");
    println!("  โ€ข No external deadpool dependency");

    Ok(())
}

async fn demonstrate_sql_engine() -> std::result::Result<(), Box<dyn std::error::Error>> {
    println!("Pure Rust SQL engine (no rusqlite) + typed model:");
    
    let db = Database::sqlite(":memory:").await?;
    
    // ไพๆฎๆจกๅž‹่‡ชๅŠจๅปบ่กจ๏ผˆ้›ถ SqlValue๏ผ‰
    db.auto_migrate::<Product>().await?;
    println!("  โœ… Created products table from model schema");
    
    // ้€š่ฟ‡ๆจกๅž‹ create ๆ’ๅ…ฅ
    let mut products = vec![
        Product { id: 0, name: "Apple".to_string(), price: 5 },
        Product { id: 0, name: "Banana".to_string(), price: 3 },
        Product { id: 0, name: "Cherry".to_string(), price: 9 },
    ];
    for p in &mut products {
        db.create(p).await?;
    }
    println!("  โœ… Inserted {} products", products.len());
    
    // ๆŸฅ่ฏขๅนถๆ˜ ๅฐ„ๅ›ž็ฑปๅž‹
    let all: Vec<Product> = db.all::<Product>().await?;
    println!("  โœ… Query returned {} rows", all.len());
    for p in &all {
        println!("    - {} price={}", p.name, p.price);
    }
    
    // ๆ›ดๆ–ฐ๏ผˆ่ฟ”ๅ›žๅฝฑๅ“่กŒๆ•ฐ๏ผ‰
    let affected = db.update(&mut products[0], &[("price", 6)]).await?;
    println!("  โœ… Updated {} row(s)", affected);
    
    // ่ฎกๆ•ฐ
    let count = db.all::<Product>().await?.len();
    println!("  โœ… Count = {}", count);
    
    // ๅˆ ้™ค๏ผˆไฝฟ็”จๅทฒๅ›žๅกซไธป้”ฎ็š„ๆจกๅž‹ๅฎžไพ‹๏ผ‰
    let affected = db.delete(&mut products[2]).await?;
    println!("  โœ… Deleted {} row(s)", affected);
    
    db.close().await?;
    println!("  โœ… Database closed");

    Ok(())
}

fn demonstrate_query_builder() {
    println!("Query builder examples:");
    
    // Basic query
    let (sql, bindings) = QueryBuilder::new("users")
        .where_eq("email", "john@example.com")
        .limit(1)
        .build();
    println!("  Basic query:");
    println!("    SQL: {}", sql);
    println!("    Bindings: {:?}", bindings);

    // Complex query
    let (sql, bindings) = QueryBuilder::new("users")
        .where_eq("status", "active")
        .where_gt("age", 18)
        .where_like("name", "John%")
        .order_by("created_at", "DESC")
        .limit(10)
        .build();
    println!();
    println!("  Complex query:");
    println!("    SQL: {}", sql);
    println!("    Bindings: {:?}", bindings);

    // IN query
    let (sql, bindings) = QueryBuilder::new("users")
        .where_in("id", vec![1, 2, 3])
        .build();
    println!();
    println!("  IN query:");
    println!("    SQL: {}", sql);
    println!("    Bindings: {:?}", bindings);

    // BETWEEN query
    let (sql, bindings) = QueryBuilder::new("users")
        .where_between("age", 18, 65)
        .build();
    println!();
    println!("  BETWEEN query:");
    println!("    SQL: {}", sql);
    println!("    Bindings: {:?}", bindings);
}

/// Product ๆจกๅž‹๏ผšไฝฟ็”จ `#[derive(Model)]`๏ผŒ็”ฑๅฎ่‡ชๅŠจ็”Ÿๆˆ schema ไธŽๅญ—ๆฎตๆ˜ ๅฐ„ใ€‚
#[derive(Debug, Clone, Model)]
#[model(table_name = "products")]
pub struct Product {
    pub id: i64,
    pub name: String,
    pub price: i64,
}

// User model with simplified UUID
#[derive(Debug, Clone)]
pub struct User {
    pub id: String,
    pub name: String,
    pub email: String,
    pub age: Option<i32>,
    pub status: String,
    pub timestamps: torm::orm::model::Timestamps,
}

impl User {
    pub fn new(name: &str, email: &str) -> Self {
        let generator = IdGenerator::new().with_prefix("user_");
        Self {
            id: generator.generate(),
            name: name.to_string(),
            email: email.to_string(),
            age: None,
            status: "active".to_string(),
            timestamps: torm::orm::model::Timestamps::new(),
        }
    }

    pub fn with_age(mut self, age: i32) -> Self {
        self.age = Some(age);
        self
    }

    pub fn with_status(mut self, status: &str) -> Self {
        self.status = status.to_string();
        self
    }
}

#[async_trait::async_trait]
impl Model for User {
    fn table_name() -> &'static str {
        "users"
    }

    fn id(&self) -> Option<String> {
        if self.id.is_empty() {
            None
        } else {
            Some(self.id.clone())
        }
    }

    fn set_id(&mut self, id: String) {
        self.id = id;
    }

    fn created_at(&self) -> Option<chrono::DateTime<Utc>> {
        self.timestamps.created_at
    }

    fn updated_at(&self) -> Option<chrono::DateTime<Utc>> {
        self.timestamps.updated_at
    }

    fn deleted_at(&self) -> Option<chrono::DateTime<Utc>> {
        self.timestamps.deleted_at
    }

    fn set_created_at(&mut self, timestamp: chrono::DateTime<Utc>) {
        self.timestamps.created_at = Some(timestamp);
    }

    fn set_updated_at(&mut self, timestamp: chrono::DateTime<Utc>) {
        self.timestamps.updated_at = Some(timestamp);
    }

    fn set_deleted_at(&mut self, timestamp: Option<chrono::DateTime<Utc>>) {
        self.timestamps.deleted_at = timestamp;
    }
}