Skip to main content

integration_example/
integration_example.rs

1// TORM Integration Examples
2// 演示基于 `#[derive(Model)]` 结构体的高层数据库操作:
3// create / first / all / update / delete / 条件查询(自动映射回类型)。
4// 全程零 SqlValue。
5
6use torm::db::database::Database;
7use torm::{Model, Query};
8
9/// 用户模型:所有字段自动映射,id 自动自增回填。
10#[derive(Debug, Clone, Model)]
11#[model(table_name = "users")]
12pub struct User {
13    pub id: i64,
14    pub name: String,
15    pub email: String,
16    pub age: i32,
17    pub active: bool,
18}
19
20impl User {
21    fn new(name: &str, email: &str, age: i32, active: bool) -> Self {
22        Self {
23            id: 0,
24            name: name.to_string(),
25            email: email.to_string(),
26            age,
27            active,
28        }
29    }
30}
31
32#[tokio::main]
33async fn main() -> Result<(), Box<dyn std::error::Error>> {
34    println!("TORM Integration Examples\n");
35
36    // Example 1: SQLite 连接 + 依据模型自动建表
37    println!("=== Example 1: Connection & AutoMigrate ===");
38    let db = Database::sqlite(":memory:").await?;
39    println!("Connected to SQLite: {}", db.config().database);
40    db.auto_migrate::<User>().await?;
41    println!("Created users table from model schema");
42
43    // Example 2: 插入(create 自动回填自增 id)
44    println!("\n=== Example 2: Create (Insert) ===");
45    let mut alice = User::new("Alice", "alice@example.com", 25, true);
46    db.create(&mut alice).await?;
47    let mut bob = User::new("Bob", "bob@example.com", 30, true);
48    db.create(&mut bob).await?;
49    let mut carol = User::new("Carol", "carol@example.com", 35, true);
50    db.create(&mut carol).await?;
51    let mut dave = User::new("Dave", "dave@example.com", 17, false);
52    db.create(&mut dave).await?;
53    println!("  Inserted: Alice={} Bob={} Carol={} Dave={}",
54        alice.id, bob.id, carol.id, dave.id);
55
56    // Example 3: 条件查询 + 自动映射回 Vec<User>
57    println!("\n=== Example 3: Typed Query (auto-mapped) ===");
58    let adults: Vec<User> = Query::new("users")
59        .where_gt("age", 18)
60        .order_by_desc("age")
61        .query(&db)
62        .models::<User>()
63        .await?;
64    println!("  Adults (age > 18): {}", adults.len());
65    for u in &adults {
66        println!("    - {} <{}> age={} active={}", u.name, u.email, u.age, u.active);
67    }
68
69    // Example 4: 按主键读取 / 读取全部
70    println!("\n=== Example 4: First & All ===");
71    let one: Option<User> = db.first::<User>(&alice.id.to_string()).await?;
72    println!("  First(id={}): {:?}", alice.id, one.map(|u| u.name));
73    let all: Vec<User> = db.all::<User>().await?;
74    println!("  All: {} users", all.len());
75
76    // Example 5: 更新(直接执行,返回影响行数)
77    println!("\n=== Example 5: Update ===");
78    let affected = db.update(&mut alice, &[("age", 26)]).await?;
79    println!("  Updated Alice age -> affected {} row(s)", affected);
80    let updated: User = db.first(&alice.id.to_string()).await?.expect("exists");
81    println!("  Alice age now = {}", updated.age);
82
83    // Example 6: 删除
84    println!("\n=== Example 6: Delete ===");
85    let removed = db.delete(&mut dave).await?;
86    println!("  Deleted Dave -> {} row(s)", removed);
87    let remaining = db.all::<User>().await?;
88    println!("  Remaining: {} users", remaining.len());
89
90    // Example 7: 计数查询
91    println!("\n=== Example 7: Count ===");
92    let count = Query::new("users").query(&db).count().await?;
93    let n = count
94        .rows
95        .first()
96        .and_then(|r| r.get("COUNT(*)").or_else(|| r.get("count")))
97        .and_then(|v| v.as_i64())
98        .unwrap_or(0);
99    println!("  Total users = {}", n);
100
101    db.close().await?;
102    println!("\n=== Examples Complete ===");
103    Ok(())
104}