Skip to main content

Database

Struct Database 

Source
pub struct Database { /* private fields */ }
Expand description

Database struct - 高层 ORM 数据库接口

Implementations§

Source§

impl Database

Source

pub async fn connect(config: ConnectionConfig) -> Result<Self, DbError>

创建新的数据库连接

Source

pub async fn sqlite(path: &str) -> Result<Self, DbError>

创建 SQLite 数据库连接

Examples found in repository?
examples/basic_usage.rs (line 75)
69async fn demonstrate_database_connection() -> std::result::Result<(), Box<dyn std::error::Error>> {
70    println!("SQLite connection:");
71    let dsn = Dsn::new(DBDriver::SQLite, "demo.db");
72    println!("  DSN: {}", dsn.build());
73    
74    // Test actual SQLite connection with pure Rust engine
75    let db = Database::sqlite(":memory:").await?;
76    println!("  ✅ Connected to in-memory SQLite (pure Rust engine)");
77    println!("  DB type: {:?}", db.db_type());
78    println!("  Connected: {}", db.is_connected());
79    db.close().await?;
80    
81    println!();
82    println!("MySQL connection example:");
83    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
84        .with_host("localhost")
85        .with_port(3306)
86        .with_username("user")
87        .with_password("password");
88    println!("  DSN: {}", mysql_dsn.build());
89    
90    println!();
91    println!("PostgreSQL connection example:");
92    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
93        .with_host("localhost")
94        .with_port(5432)
95        .with_username("user")
96        .with_password("password");
97    println!("  DSN: {}", pg_dsn.build());
98
99    Ok(())
100}
101
102fn demonstrate_simplified_uuid() -> std::result::Result<(), Box<dyn std::error::Error>> {
103    println!("Generating UUIDs:");
104    
105    // Generate multiple UUIDs
106    let uuid1 = SimpleUuid::new_v4();
107    let uuid2 = SimpleUuid::new_v4();
108    let uuid3 = SimpleUuid::new_v4();
109    
110    println!("  UUID 1: {}", uuid1);
111    println!("  UUID 2: {}", uuid2);
112    println!("  UUID 3: {}", uuid3);
113    println!("  All unique: {}", uuid1 != uuid2 && uuid2 != uuid3 && uuid1 != uuid3);
114    
115    println!();
116    println!("ID Generator:");
117    let generator = IdGenerator::new();
118    let id1 = generator.generate();
119    let id2 = generator.generate();
120    
121    println!("  ID 1: {}", id1);
122    println!("  ID 2: {}", id2);
123    println!("  ID 3: {}", generator.with_prefix("user_").generate());
124    
125    println!();
126    println!("Simple IDs:");
127    let simple_gen = IdGenerator::new().with_simple_id();
128    println!("  Simple ID: {}", simple_gen.generate());
129    println!("  Prefixed: {}", simple_gen.with_prefix("order_").generate());
130
131    Ok(())
132}
133
134fn demonstrate_simplified_error() -> std::result::Result<(), Box<dyn std::error::Error>> {
135    println!("Error handling without thiserror:");
136    
137    // Create different error types
138    let not_found = SimpleError::NotFound;
139    println!("  NotFound: {}", not_found);
140    
141    let custom = SimpleError::custom("Something went wrong");
142    println!("  Custom: {}", custom);
143    
144    let invalid_query = SimpleError::invalid_query("Invalid WHERE clause");
145    println!("  InvalidQuery: {}", invalid_query);
146    
147    let connection_error = SimpleError::connection_error("Could not connect to database");
148    println!("  ConnectionError: {}", connection_error);
149    
150    println!();
151    println!("Using SimpleResult:");
152    let success: SimpleResult<i32> = Ok(42);
153    println!("  Success: {:?}", success);
154    
155    let failure: SimpleResult<i32> = Err(SimpleError::NotFound);
156    println!("  Failure: {:?}", failure);
157
158    Ok(())
159}
160
161fn demonstrate_simplified_cache() -> std::result::Result<(), Box<dyn std::error::Error>> {
162    println!("LRU cache:");
163    
164    let mut cache: SimpleLruCache<&str, &str> = SimpleLruCache::new(3);
165    
166    // Add items
167    cache.put("key1", "value1");
168    cache.put("key2", "value2");
169    cache.put("key3", "value3");
170    
171    println!("  Initial size: {}", cache.len());
172    println!("  key1: {:?}", cache.get(&"key1"));
173    println!("  key2: {:?}", cache.get(&"key2"));
174    println!("  key3: {:?}", cache.get(&"key3"));
175    
176    // Test LRU eviction
177    println!();
178    println!("  Adding key4 (should evict oldest):");
179    cache.put("key4", "value4");
180    println!("  key1: {:?}", cache.get(&"key1")); // Should be None
181    println!("  key4: {:?}", cache.get(&"key4")); // Should be Some
182    
183    // Test capacity
184    println!();
185    println!("  Current capacity: {}", cache.capacity());
186    println!("  Current size: {}", cache.len());
187    
188    // Resize
189    cache.resize(2);
190    println!("  After resize to 2:");
191    println!("  New size: {}", cache.len());
192    
193    // Cleanup
194    cache.clear();
195    println!("  After clear: {}", cache.is_empty());
196
197    Ok(())
198}
199
200async fn demonstrate_connection_pool() -> std::result::Result<(), Box<dyn std::error::Error>> {
201    println!("Simple connection pool implementation:");
202    
203    // Create a pool with pre-created connections
204    let connections = vec![1, 2, 3, 4, 5];
205    let pool = SimplePool::new(connections);
206    let status = pool.status();
207    
208    println!("  Total connections: {}", status.total_connections);
209    println!("  Idle connections: {}", status.idle_connections);
210    println!("  Active connections: {}", status.active_connections);
211    println!("  Utilization: {:.1}%", status.utilization_rate() * 100.0);
212    
213    // Test getting a connection
214    println!();
215    println!("  Getting a connection from pool:");
216    match pool.get().await {
217        Ok(conn) => {
218            println!("    Got: {}", conn);
219            let status = pool.status();
220            println!("    After get - idle: {}, active: {}", status.idle_connections, status.active_connections);
221            pool.put(conn);
222            let status = pool.status();
223            println!("    After put - idle: {}, active: {}", status.idle_connections, status.active_connections);
224        }
225        Err(e) => println!("    Error: {}", e),
226    }
227    
228    println!();
229    println!("Pool features:");
230    println!("  • Connection reuse");
231    println!("  • Timeout handling");
232    println!("  • No external deadpool dependency");
233
234    Ok(())
235}
236
237async fn demonstrate_sql_engine() -> std::result::Result<(), Box<dyn std::error::Error>> {
238    println!("Pure Rust SQL engine (no rusqlite) + typed model:");
239    
240    let db = Database::sqlite(":memory:").await?;
241    
242    // 依据模型自动建表(零 SqlValue)
243    db.auto_migrate::<Product>().await?;
244    println!("  ✅ Created products table from model schema");
245    
246    // 通过模型 create 插入
247    let mut products = vec![
248        Product { id: 0, name: "Apple".to_string(), price: 5 },
249        Product { id: 0, name: "Banana".to_string(), price: 3 },
250        Product { id: 0, name: "Cherry".to_string(), price: 9 },
251    ];
252    for p in &mut products {
253        db.create(p).await?;
254    }
255    println!("  ✅ Inserted {} products", products.len());
256    
257    // 查询并映射回类型
258    let all: Vec<Product> = db.all::<Product>().await?;
259    println!("  ✅ Query returned {} rows", all.len());
260    for p in &all {
261        println!("    - {} price={}", p.name, p.price);
262    }
263    
264    // 更新(返回影响行数)
265    let affected = db.update(&mut products[0], &[("price", 6)]).await?;
266    println!("  ✅ Updated {} row(s)", affected);
267    
268    // 计数
269    let count = db.all::<Product>().await?.len();
270    println!("  ✅ Count = {}", count);
271    
272    // 删除(使用已回填主键的模型实例)
273    let affected = db.delete(&mut products[2]).await?;
274    println!("  ✅ Deleted {} row(s)", affected);
275    
276    db.close().await?;
277    println!("  ✅ Database closed");
278
279    Ok(())
280}
More examples
Hide additional examples
examples/complete_demo.rs (line 156)
151async fn demonstrate_database_file_connection() -> Result<(), Box<dyn std::error::Error>> {
152    println!("SQLite 连接:");
153    let dsn = Dsn::new(DBDriver::SQLite, "target/demo.db");
154    println!("  DSN: {}", dsn.build());
155    
156    let database = Database::sqlite("target/demo.db").await?;
157    println!("  ✅ 连接成功");
158    println!("  驱动: {:?}", database.db_type());
159    
160    // 测试连接
161    database.ping().await?;
162    println!("  ✅ Ping 成功");
163
164    // 依据模型自动建表并执行 CRUD,触发文件写入(零 SqlValue)
165    database.auto_migrate::<DemoUser>().await?;
166    println!("  ✅ 创建表成功(依据模型 schema)");
167
168    let mut users = vec![
169        DemoUser { id: 0, name: "Alice".into(), age: 25 },
170        DemoUser { id: 0, name: "Bob".into(), age: 30 },
171    ];
172    for u in &mut users {
173        database.create(u).await?;
174    }
175    println!("  ✅ 插入数据成功");
176
177    let all: Vec<DemoUser> = database.all::<DemoUser>().await?;
178    println!("  ✅ 查询返回 {} 行", all.len());
179
180    database.close().await?;
181    println!("  ✅ 数据库已关闭,数据已保存到 demo.db");
182    
183    println!();
184    println!("MySQL 连接示例:");
185    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
186        .with_host("localhost")
187        .with_port(3306)
188        .with_username("user")
189        .with_password("password");
190    println!("  DSN: {}", mysql_dsn.build());
191    
192    println!();
193    println!("PostgreSQL 连接示例:");
194    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
195        .with_host("localhost")
196        .with_port(5432)
197        .with_username("user")
198        .with_password("password");
199    println!("  DSN: {}", pg_dsn.build());
200
201    Ok(())
202}
203
204async fn demonstrate_database_connection() -> Result<(), Box<dyn std::error::Error>> {
205    println!("SQLite 连接:");
206    let dsn = Dsn::new(DBDriver::SQLite, "demo.db");
207    println!("  DSN: {}", dsn.build());
208    
209    let database = Database::sqlite(":memory:").await?;
210    println!("  ✅ 连接成功");
211    println!("  驱动: {:?}", database.db_type());
212    
213    // 测试连接
214    database.ping().await?;
215    println!("  ✅ Ping 成功");
216    database.close().await?;
217    
218    println!();
219    println!("MySQL 连接示例:");
220    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
221        .with_host("localhost")
222        .with_port(3306)
223        .with_username("user")
224        .with_password("password");
225    println!("  DSN: {}", mysql_dsn.build());
226    
227    println!();
228    println!("PostgreSQL 连接示例:");
229    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
230        .with_host("localhost")
231        .with_port(5432)
232        .with_username("user")
233        .with_password("password");
234    println!("  DSN: {}", pg_dsn.build());
235
236    Ok(())
237}
examples/async_concurrency.rs (line 48)
47async fn database_concurrency() -> Result<(), Box<dyn std::error::Error>> {
48    let db = Arc::new(Database::sqlite(":memory:").await?);
49
50    // 依据 Product 模型自动建表。
51    db.auto_migrate::<Product>().await?;
52
53    // 预置数据:通过模型 create,零 SqlValue。
54    for i in 0..100 {
55        let mut p = Product {
56            id: 0,
57            name: format!("product_{}", i),
58            price: i,
59        };
60        db.create(&mut p).await?;
61    }
62
63    // 并发执行多个查询任务(按页读取,映射回模型)。
64    let mut handles = Vec::new();
65    for offset in (0..100).step_by(25) {
66        let db = Arc::clone(&db);
67        handles.push(tokio::spawn(async move {
68            let products: Vec<Product> = Query::new("products")
69                .order_by_asc("id")
70                .limit(25)
71                .offset(offset)
72                .query(&db)
73                .models::<Product>()
74                .await?;
75            Ok::<usize, torm::db::database::DbError>(products.len())
76        }));
77    }
78
79    let mut total = 0usize;
80    for h in handles {
81        total += h.await??;
82    }
83    println!("  4 concurrent queries fetched {} rows in total.", total);
84
85    // 使用 Query builder 并发查询(值类型自动转换,无需手写 SqlValue::I32)
86    let mut handles = Vec::new();
87    for min_price in [10i64, 20, 30, 40] {
88        let db = Arc::clone(&db);
89        handles.push(tokio::spawn(async move {
90            Query::new("products")
91                .where_gt("price", min_price)
92                .query(&db)
93                .count()
94                .await
95        }));
96    }
97    for (i, h) in handles.into_iter().enumerate() {
98        let count = h.await??;
99        let n = count
100            .rows
101            .first()
102            .and_then(|r| r.get("COUNT(*)").or_else(|| r.get("count")))
103            .and_then(|v| v.as_i64())
104            .unwrap_or(0);
105        println!("  price > {}  -> {} products", [10, 20, 30, 40][i], n);
106    }
107
108    Ok(())
109}
examples/dapper_style.rs (line 36)
35async fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let db = Database::sqlite(":memory:").await?;
37
38    // 自动建表(依据模型 schema)
39    db.auto_migrate::<User>().await?;
40    println!("表 users 已自动创建\n");
41
42    // === 1. insert:无需手写 SqlValue,主键自动自增并回填 ===
43    println!("=== 1. Insert (自增主键自动回填) ===");
44    let mut alice = User::new("Alice", "alice@example.com", 25);
45    db.create(&mut alice).await?;
46    let mut bob = User::new("Bob", "bob@example.com", 17);
47    db.create(&mut bob).await?;
48    let mut carol = User::new("Carol", "carol@example.com", 30);
49    db.create(&mut carol).await?;
50    println!(
51        "  id 自动分配: Alice={} Bob={} Carol={}\n",
52        alice.id, bob.id, carol.id
53    );
54
55    // === 2. query:条件查询自动映射回 Vec<User> ===
56    println!("=== 2. Query (自动映射回 User) ===");
57    let adults: Vec<User> = Query::new("users")
58        .where_gte("age", 18)
59        .order_by_desc("age")
60        .query(&db)
61        .models::<User>()
62        .await?;
63    for u in &adults {
64        println!("  id={} name={} email={} age={}", u.id, u.name, u.email, u.age);
65    }
66
67    // 分页 + 条件
68    let first_two: Vec<User> = Query::new("users")
69        .where_gt("age", 0)
70        .order_by_asc("id")
71        .limit(2)
72        .query(&db)
73        .models::<User>()
74        .await?;
75    println!("  前 2 条: {:?}", first_two.iter().map(|u| &u.name).collect::<Vec<_>>());
76    println!();
77
78    // === 3. update:直接执行 SQL,返回影响行数 ===
79    println!("=== 3. Update ===");
80    let affected = db.update(&mut alice, &[("age", 26)]).await?;
81    println!("  更新 age 影响 {} 行", affected);
82
83    // 多列同类型(全为 &str)可直接批量更新
84    db.update(
85        &mut alice,
86        &[("email", "alice_new@example.com"), ("name", "Alice A.")],
87    )
88    .await?;
89
90    // 重新查询验证
91    let refreshed: User = db.first::<User>(&alice.id.to_string()).await?.unwrap();
92    println!(
93        "  更新后: name={} age={} email={}\n",
94        refreshed.name, refreshed.age, refreshed.email
95    );
96
97    // === 4. 条件删除 ===
98    println!("=== 4. Delete ===");
99    let removed = db.delete(&mut bob).await?;
100    println!("  删除 Bob 影响 {} 行", removed);
101    let remaining = db.all::<User>().await?;
102    println!("  剩余 {} 条: {:?}", remaining.len(), remaining.iter().map(|u| &u.name).collect::<Vec<_>>());
103
104    println!("\n✅ insert / query / update / delete 全程零 SqlValue,Dapper 风格完成!");
105    Ok(())
106}
examples/integration_example.rs (line 38)
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}
examples/ergonomic_query.rs (line 16)
15async fn main() -> Result<(), Box<dyn std::error::Error>> {
16    let db = Database::sqlite(":memory:").await?;
17
18    db.execute(
19        "CREATE TABLE IF NOT EXISTS users (
20            id INTEGER PRIMARY KEY AUTOINCREMENT,
21            name TEXT,
22            age INTEGER,
23            score REAL,
24            active INTEGER
25        )",
26        &[],
27    )
28    .await?;
29
30    // 插入示例数据(raw SQL 参数用 .into() 由原生值自动转换)
31    for (name, age, score, active) in [
32        ("Alice", 25i64, 88.5f64, 1),
33        ("Bob", 17, 76.2, 0),
34        ("Carol", 30, 95.0, 1),
35        ("Dave", 22, 63.8, 1),
36        ("Eve", 41, 91.3, 0),
37    ] {
38        db.execute(
39            "INSERT INTO users (name, age, score, active) VALUES (?, ?, ?, ?)",
40            &[name.into(), age.into(), score.into(), active.into()],
41        )
42        .await?;
43    }
44
45    println!("=== 1. 基础链式条件(自动类型转换)===");
46    let result = Query::new("users")
47        .where_gte("age", 18)          // i32 自动转
48        .where_gt("score", 80.0)       // f64 自动转
49        .where_like("name", "A%")      // &str 自动转
50        .query(&db)
51        .select()
52        .await?;
53    for row in &result.rows {
54        println!(
55            "  name={} age={} score={}",
56            row.get("name").and_then(|v| v.as_str()).unwrap_or(""),
57            row.get("age").and_then(|v| v.as_i64()).unwrap_or(0),
58            row.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0),
59        );
60    }
61
62    println!("\n=== 2. 整型 / 浮点 / 字符串全自动 ===");
63    let result = Query::new("users")
64        .where_in("id", vec![1, 3, 5]) // Vec<i32> 自动转
65        .query(&db)
66        .select()
67        .await?;
68    println!("  IN (1,3,5) -> {} 条", result.rows.len());
69
70    let result = Query::new("users")
71        .where_between("score", 70.0, 92.0) // f64 区间自动转
72        .where_eq("active", 1i32)
73        .query(&db)
74        .select()
75        .await?;
76    println!("  score BETWEEN 70 AND 92 AND active -> {} 条", result.rows.len());
77
78    println!("\n=== 3. 排序 + 分页 + 条件 ===");
79    let result = Query::new("users")
80        .where_gt("age", 0)
81        .order_by_desc("score")
82        .limit(2)
83        .query(&db)
84        .select()
85        .await?;
86    for row in &result.rows {
87        println!(
88            "  name={} score={}",
89            row.get("name").and_then(|v| v.as_str()).unwrap_or(""),
90            row.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0),
91        );
92    }
93
94    println!("\n=== 4. AdvancedQuery 聚合 + HAVING ===");
95    let (sql, params) = AdvancedQuery::new("users")
96        .group_by(&["active"])
97        .having(WhereCondition::Gt("COUNT(*)".to_string(), 1i64.into()))
98        .build_select();
99    let result = db.query(&sql, &params).await?;
100    println!("  生成 SQL: {}", sql);
101    for row in &result.rows {
102        println!("  {:?}", row.values);
103    }
104
105    println!("\n✅ 查询 API 无需再写 SqlValue::Type(...),直接书写原生值即可。");
106    Ok(())
107}
Source

pub async fn mysql( host: &str, port: u16, database: &str, username: &str, password: &str, ) -> Result<Self, DbError>

创建 MySQL 数据库连接

Source

pub async fn postgresql( host: &str, port: u16, database: &str, username: &str, password: &str, ) -> Result<Self, DbError>

创建 PostgreSQL 数据库连接

Examples found in repository?
examples/postgresql_example.rs (line 87)
77async fn demonstrate_database_connection() -> std::result::Result<(), Box<dyn std::error::Error>> {
78    println!("PostgreSQL connection (native wire protocol):");
79    let dsn = Dsn::new(DBDriver::PostgreSQL, PG_DB)
80        .with_host(PG_HOST)
81        .with_port(PG_PORT)
82        .with_username(PG_USER)
83        .with_password(PG_PASS);
84    println!("  DSN: {}", dsn.build());
85
86    // Test actual PostgreSQL connection
87    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
88    println!("  ✅ Connected to PostgreSQL (native wire protocol)");
89    println!("  DB type: {:?}", db.db_type());
90    println!("  Connected: {}", db.is_connected());
91    db.ping().await?;
92    println!("  ✅ Ping successful");
93    db.close().await?;
94
95    println!();
96    println!("Connection via ConnectionFactory:");
97    let config = ConnectionConfig::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS)
98        .with_timeout(std::time::Duration::from_secs(30))
99        .with_max_connections(10);
100    let conn = ConnectionFactory::create_connection(config.clone()).await?;
101    println!("  ✅ Connection created (factory)");
102    println!("  DB type: {:?}", conn.db_type());
103    conn.close().await?;
104
105    println!();
106    println!("Direct PostgresConnection:");
107    let pg = PostgresConnection::new(&config).await?;
108    println!("  ✅ PostgresConnection created");
109    println!("  Connected: {}", pg.is_connected());
110    pg.close().await?;
111
112    Ok(())
113}
114
115async fn demonstrate_crud() -> std::result::Result<(), Box<dyn std::error::Error>> {
116    println!("GORM-style model CRUD (create / first / find / update / delete):");
117    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
118
119    // Schema setup (GORM AutoMigrate equivalent — drop + recreate for a clean demo)
120    db.execute("DROP TABLE IF EXISTS users", &[]).await?;
121    db.execute(
122        "CREATE TABLE users (
123            id TEXT PRIMARY KEY,
124            name TEXT NOT NULL,
125            email TEXT,
126            age INTEGER,
127            status TEXT,
128            created_at TIMESTAMPTZ,
129            updated_at TIMESTAMPTZ
130        )",
131        &[],
132    )
133    .await?;
134    println!("  ✅ Schema ready (users table recreated)");
135
136    // Create — GORM `db.Create(&user)` equivalent
137    let mut alice = User::new("Alice", "alice@example.com").with_age(25);
138    db.create(&mut alice).await?;
139    println!(
140        "  ✅ Created: id={} name={} (created_at: {:?})",
141        alice.id,
142        alice.name,
143        alice.created_at()
144    );
145
146    let mut bob = User::new("Bob", "bob@example.com").with_age(30);
147    db.create(&mut bob).await?;
148    println!("  ✅ Created: id={} name={}", bob.id, bob.name);
149
150    // First — GORM `db.First(&user, id)` equivalent
151    let found: Option<User> = db.first(&alice.id).await?;
152    match &found {
153        Some(u) => println!(
154            "  ✅ First: id={} name={} age={:?} status={}",
155            u.id, u.name, u.age, u.status
156        ),
157        None => println!("  ❌ First: not found"),
158    }
159
160    // Find all — GORM `db.Find(&users)` equivalent
161    let users: Vec<User> = db.all().await?;
162    println!("  ✅ Find: {} user(s)", users.len());
163    for u in &users {
164        println!(
165            "    - {} <{}> age={:?} status={}",
166            u.name, u.email, u.age, u.status
167        );
168    }
169
170    // Update — GORM `db.Model(&user).Update("age", 29)` equivalent
171    db.update(&mut alice, &[("age", 29)]).await?;
172    let updated: User = db.first(&alice.id).await?.expect("alice exists");
173    println!("  ✅ Updated: {} age now {:?}", updated.name, updated.age);
174
175    // Delete — GORM `db.Delete(&user)` equivalent
176    db.delete(&mut alice).await?;
177    let gone: Option<User> = db.first(&alice.id).await?;
178    println!(
179        "  ✅ Deleted: {} exists after delete = {}",
180        alice.name,
181        gone.is_some()
182    );
183
184    db.close().await?;
185    println!("  ✅ Database closed");
186
187    Ok(())
188}
189
190async fn demonstrate_transactions() -> std::result::Result<(), Box<dyn std::error::Error>> {
191    println!("PostgreSQL transactions (BEGIN / COMMIT / ROLLBACK):");
192    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
193
194    // Commit
195    let mut tx = db.begin_transaction().await?;
196    tx.execute(
197        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
198        &[
199            SimpleUuid::new_v4().to_string().into(),
200            "Dave".into(),
201            40.into(),
202        ],
203    )
204    .await?;
205    tx.execute(
206        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
207        &[
208            SimpleUuid::new_v4().to_string().into(),
209            "Frank".into(),
210            35.into(),
211        ],
212    )
213    .await?;
214    tx.commit().await?;
215    println!("  ✅ Transaction committed (2 users)");
216
217    // Rollback
218    let mut tx = db.begin_transaction().await?;
219    tx.execute(
220        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
221        &[
222            SimpleUuid::new_v4().to_string().into(),
223            "Eve".into(),
224            45.into(),
225        ],
226    )
227    .await?;
228    tx.rollback().await?;
229    println!("  ✅ Transaction rolled back (Eve not saved)");
230
231    let result = db.query("SELECT COUNT(*) AS count FROM users", &[]).await?;
232    println!("  ✅ Final user count: {:?}", result.rows[0].get("count"));
233
234    db.close().await?;
235    Ok(())
236}
Source

pub async fn query( &self, sql: &str, params: &[SqlValue], ) -> Result<QueryResult, DbError>

执行查询

Examples found in repository?
examples/postgresql_example.rs (line 231)
190async fn demonstrate_transactions() -> std::result::Result<(), Box<dyn std::error::Error>> {
191    println!("PostgreSQL transactions (BEGIN / COMMIT / ROLLBACK):");
192    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
193
194    // Commit
195    let mut tx = db.begin_transaction().await?;
196    tx.execute(
197        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
198        &[
199            SimpleUuid::new_v4().to_string().into(),
200            "Dave".into(),
201            40.into(),
202        ],
203    )
204    .await?;
205    tx.execute(
206        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
207        &[
208            SimpleUuid::new_v4().to_string().into(),
209            "Frank".into(),
210            35.into(),
211        ],
212    )
213    .await?;
214    tx.commit().await?;
215    println!("  ✅ Transaction committed (2 users)");
216
217    // Rollback
218    let mut tx = db.begin_transaction().await?;
219    tx.execute(
220        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
221        &[
222            SimpleUuid::new_v4().to_string().into(),
223            "Eve".into(),
224            45.into(),
225        ],
226    )
227    .await?;
228    tx.rollback().await?;
229    println!("  ✅ Transaction rolled back (Eve not saved)");
230
231    let result = db.query("SELECT COUNT(*) AS count FROM users", &[]).await?;
232    println!("  ✅ Final user count: {:?}", result.rows[0].get("count"));
233
234    db.close().await?;
235    Ok(())
236}
More examples
Hide additional examples
examples/ergonomic_query.rs (line 99)
15async fn main() -> Result<(), Box<dyn std::error::Error>> {
16    let db = Database::sqlite(":memory:").await?;
17
18    db.execute(
19        "CREATE TABLE IF NOT EXISTS users (
20            id INTEGER PRIMARY KEY AUTOINCREMENT,
21            name TEXT,
22            age INTEGER,
23            score REAL,
24            active INTEGER
25        )",
26        &[],
27    )
28    .await?;
29
30    // 插入示例数据(raw SQL 参数用 .into() 由原生值自动转换)
31    for (name, age, score, active) in [
32        ("Alice", 25i64, 88.5f64, 1),
33        ("Bob", 17, 76.2, 0),
34        ("Carol", 30, 95.0, 1),
35        ("Dave", 22, 63.8, 1),
36        ("Eve", 41, 91.3, 0),
37    ] {
38        db.execute(
39            "INSERT INTO users (name, age, score, active) VALUES (?, ?, ?, ?)",
40            &[name.into(), age.into(), score.into(), active.into()],
41        )
42        .await?;
43    }
44
45    println!("=== 1. 基础链式条件(自动类型转换)===");
46    let result = Query::new("users")
47        .where_gte("age", 18)          // i32 自动转
48        .where_gt("score", 80.0)       // f64 自动转
49        .where_like("name", "A%")      // &str 自动转
50        .query(&db)
51        .select()
52        .await?;
53    for row in &result.rows {
54        println!(
55            "  name={} age={} score={}",
56            row.get("name").and_then(|v| v.as_str()).unwrap_or(""),
57            row.get("age").and_then(|v| v.as_i64()).unwrap_or(0),
58            row.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0),
59        );
60    }
61
62    println!("\n=== 2. 整型 / 浮点 / 字符串全自动 ===");
63    let result = Query::new("users")
64        .where_in("id", vec![1, 3, 5]) // Vec<i32> 自动转
65        .query(&db)
66        .select()
67        .await?;
68    println!("  IN (1,3,5) -> {} 条", result.rows.len());
69
70    let result = Query::new("users")
71        .where_between("score", 70.0, 92.0) // f64 区间自动转
72        .where_eq("active", 1i32)
73        .query(&db)
74        .select()
75        .await?;
76    println!("  score BETWEEN 70 AND 92 AND active -> {} 条", result.rows.len());
77
78    println!("\n=== 3. 排序 + 分页 + 条件 ===");
79    let result = Query::new("users")
80        .where_gt("age", 0)
81        .order_by_desc("score")
82        .limit(2)
83        .query(&db)
84        .select()
85        .await?;
86    for row in &result.rows {
87        println!(
88            "  name={} score={}",
89            row.get("name").and_then(|v| v.as_str()).unwrap_or(""),
90            row.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0),
91        );
92    }
93
94    println!("\n=== 4. AdvancedQuery 聚合 + HAVING ===");
95    let (sql, params) = AdvancedQuery::new("users")
96        .group_by(&["active"])
97        .having(WhereCondition::Gt("COUNT(*)".to_string(), 1i64.into()))
98        .build_select();
99    let result = db.query(&sql, &params).await?;
100    println!("  生成 SQL: {}", sql);
101    for row in &result.rows {
102        println!("  {:?}", row.values);
103    }
104
105    println!("\n✅ 查询 API 无需再写 SqlValue::Type(...),直接书写原生值即可。");
106    Ok(())
107}
Source

pub async fn execute( &self, sql: &str, params: &[SqlValue], ) -> Result<u64, DbError>

执行 SQL 语句

Examples found in repository?
examples/postgresql_example.rs (line 120)
115async fn demonstrate_crud() -> std::result::Result<(), Box<dyn std::error::Error>> {
116    println!("GORM-style model CRUD (create / first / find / update / delete):");
117    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
118
119    // Schema setup (GORM AutoMigrate equivalent — drop + recreate for a clean demo)
120    db.execute("DROP TABLE IF EXISTS users", &[]).await?;
121    db.execute(
122        "CREATE TABLE users (
123            id TEXT PRIMARY KEY,
124            name TEXT NOT NULL,
125            email TEXT,
126            age INTEGER,
127            status TEXT,
128            created_at TIMESTAMPTZ,
129            updated_at TIMESTAMPTZ
130        )",
131        &[],
132    )
133    .await?;
134    println!("  ✅ Schema ready (users table recreated)");
135
136    // Create — GORM `db.Create(&user)` equivalent
137    let mut alice = User::new("Alice", "alice@example.com").with_age(25);
138    db.create(&mut alice).await?;
139    println!(
140        "  ✅ Created: id={} name={} (created_at: {:?})",
141        alice.id,
142        alice.name,
143        alice.created_at()
144    );
145
146    let mut bob = User::new("Bob", "bob@example.com").with_age(30);
147    db.create(&mut bob).await?;
148    println!("  ✅ Created: id={} name={}", bob.id, bob.name);
149
150    // First — GORM `db.First(&user, id)` equivalent
151    let found: Option<User> = db.first(&alice.id).await?;
152    match &found {
153        Some(u) => println!(
154            "  ✅ First: id={} name={} age={:?} status={}",
155            u.id, u.name, u.age, u.status
156        ),
157        None => println!("  ❌ First: not found"),
158    }
159
160    // Find all — GORM `db.Find(&users)` equivalent
161    let users: Vec<User> = db.all().await?;
162    println!("  ✅ Find: {} user(s)", users.len());
163    for u in &users {
164        println!(
165            "    - {} <{}> age={:?} status={}",
166            u.name, u.email, u.age, u.status
167        );
168    }
169
170    // Update — GORM `db.Model(&user).Update("age", 29)` equivalent
171    db.update(&mut alice, &[("age", 29)]).await?;
172    let updated: User = db.first(&alice.id).await?.expect("alice exists");
173    println!("  ✅ Updated: {} age now {:?}", updated.name, updated.age);
174
175    // Delete — GORM `db.Delete(&user)` equivalent
176    db.delete(&mut alice).await?;
177    let gone: Option<User> = db.first(&alice.id).await?;
178    println!(
179        "  ✅ Deleted: {} exists after delete = {}",
180        alice.name,
181        gone.is_some()
182    );
183
184    db.close().await?;
185    println!("  ✅ Database closed");
186
187    Ok(())
188}
More examples
Hide additional examples
examples/ergonomic_query.rs (lines 18-27)
15async fn main() -> Result<(), Box<dyn std::error::Error>> {
16    let db = Database::sqlite(":memory:").await?;
17
18    db.execute(
19        "CREATE TABLE IF NOT EXISTS users (
20            id INTEGER PRIMARY KEY AUTOINCREMENT,
21            name TEXT,
22            age INTEGER,
23            score REAL,
24            active INTEGER
25        )",
26        &[],
27    )
28    .await?;
29
30    // 插入示例数据(raw SQL 参数用 .into() 由原生值自动转换)
31    for (name, age, score, active) in [
32        ("Alice", 25i64, 88.5f64, 1),
33        ("Bob", 17, 76.2, 0),
34        ("Carol", 30, 95.0, 1),
35        ("Dave", 22, 63.8, 1),
36        ("Eve", 41, 91.3, 0),
37    ] {
38        db.execute(
39            "INSERT INTO users (name, age, score, active) VALUES (?, ?, ?, ?)",
40            &[name.into(), age.into(), score.into(), active.into()],
41        )
42        .await?;
43    }
44
45    println!("=== 1. 基础链式条件(自动类型转换)===");
46    let result = Query::new("users")
47        .where_gte("age", 18)          // i32 自动转
48        .where_gt("score", 80.0)       // f64 自动转
49        .where_like("name", "A%")      // &str 自动转
50        .query(&db)
51        .select()
52        .await?;
53    for row in &result.rows {
54        println!(
55            "  name={} age={} score={}",
56            row.get("name").and_then(|v| v.as_str()).unwrap_or(""),
57            row.get("age").and_then(|v| v.as_i64()).unwrap_or(0),
58            row.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0),
59        );
60    }
61
62    println!("\n=== 2. 整型 / 浮点 / 字符串全自动 ===");
63    let result = Query::new("users")
64        .where_in("id", vec![1, 3, 5]) // Vec<i32> 自动转
65        .query(&db)
66        .select()
67        .await?;
68    println!("  IN (1,3,5) -> {} 条", result.rows.len());
69
70    let result = Query::new("users")
71        .where_between("score", 70.0, 92.0) // f64 区间自动转
72        .where_eq("active", 1i32)
73        .query(&db)
74        .select()
75        .await?;
76    println!("  score BETWEEN 70 AND 92 AND active -> {} 条", result.rows.len());
77
78    println!("\n=== 3. 排序 + 分页 + 条件 ===");
79    let result = Query::new("users")
80        .where_gt("age", 0)
81        .order_by_desc("score")
82        .limit(2)
83        .query(&db)
84        .select()
85        .await?;
86    for row in &result.rows {
87        println!(
88            "  name={} score={}",
89            row.get("name").and_then(|v| v.as_str()).unwrap_or(""),
90            row.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0),
91        );
92    }
93
94    println!("\n=== 4. AdvancedQuery 聚合 + HAVING ===");
95    let (sql, params) = AdvancedQuery::new("users")
96        .group_by(&["active"])
97        .having(WhereCondition::Gt("COUNT(*)".to_string(), 1i64.into()))
98        .build_select();
99    let result = db.query(&sql, &params).await?;
100    println!("  生成 SQL: {}", sql);
101    for row in &result.rows {
102        println!("  {:?}", row.values);
103    }
104
105    println!("\n✅ 查询 API 无需再写 SqlValue::Type(...),直接书写原生值即可。");
106    Ok(())
107}
Source

pub async fn begin_transaction(&self) -> Result<Transaction, DbError>

开始事务

Examples found in repository?
examples/postgresql_example.rs (line 195)
190async fn demonstrate_transactions() -> std::result::Result<(), Box<dyn std::error::Error>> {
191    println!("PostgreSQL transactions (BEGIN / COMMIT / ROLLBACK):");
192    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
193
194    // Commit
195    let mut tx = db.begin_transaction().await?;
196    tx.execute(
197        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
198        &[
199            SimpleUuid::new_v4().to_string().into(),
200            "Dave".into(),
201            40.into(),
202        ],
203    )
204    .await?;
205    tx.execute(
206        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
207        &[
208            SimpleUuid::new_v4().to_string().into(),
209            "Frank".into(),
210            35.into(),
211        ],
212    )
213    .await?;
214    tx.commit().await?;
215    println!("  ✅ Transaction committed (2 users)");
216
217    // Rollback
218    let mut tx = db.begin_transaction().await?;
219    tx.execute(
220        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
221        &[
222            SimpleUuid::new_v4().to_string().into(),
223            "Eve".into(),
224            45.into(),
225        ],
226    )
227    .await?;
228    tx.rollback().await?;
229    println!("  ✅ Transaction rolled back (Eve not saved)");
230
231    let result = db.query("SELECT COUNT(*) AS count FROM users", &[]).await?;
232    println!("  ✅ Final user count: {:?}", result.rows[0].get("count"));
233
234    db.close().await?;
235    Ok(())
236}
Source

pub async fn ping(&self) -> Result<(), DbError>

Ping 数据库

Examples found in repository?
examples/postgresql_example.rs (line 91)
77async fn demonstrate_database_connection() -> std::result::Result<(), Box<dyn std::error::Error>> {
78    println!("PostgreSQL connection (native wire protocol):");
79    let dsn = Dsn::new(DBDriver::PostgreSQL, PG_DB)
80        .with_host(PG_HOST)
81        .with_port(PG_PORT)
82        .with_username(PG_USER)
83        .with_password(PG_PASS);
84    println!("  DSN: {}", dsn.build());
85
86    // Test actual PostgreSQL connection
87    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
88    println!("  ✅ Connected to PostgreSQL (native wire protocol)");
89    println!("  DB type: {:?}", db.db_type());
90    println!("  Connected: {}", db.is_connected());
91    db.ping().await?;
92    println!("  ✅ Ping successful");
93    db.close().await?;
94
95    println!();
96    println!("Connection via ConnectionFactory:");
97    let config = ConnectionConfig::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS)
98        .with_timeout(std::time::Duration::from_secs(30))
99        .with_max_connections(10);
100    let conn = ConnectionFactory::create_connection(config.clone()).await?;
101    println!("  ✅ Connection created (factory)");
102    println!("  DB type: {:?}", conn.db_type());
103    conn.close().await?;
104
105    println!();
106    println!("Direct PostgresConnection:");
107    let pg = PostgresConnection::new(&config).await?;
108    println!("  ✅ PostgresConnection created");
109    println!("  Connected: {}", pg.is_connected());
110    pg.close().await?;
111
112    Ok(())
113}
More examples
Hide additional examples
examples/complete_demo.rs (line 161)
151async fn demonstrate_database_file_connection() -> Result<(), Box<dyn std::error::Error>> {
152    println!("SQLite 连接:");
153    let dsn = Dsn::new(DBDriver::SQLite, "target/demo.db");
154    println!("  DSN: {}", dsn.build());
155    
156    let database = Database::sqlite("target/demo.db").await?;
157    println!("  ✅ 连接成功");
158    println!("  驱动: {:?}", database.db_type());
159    
160    // 测试连接
161    database.ping().await?;
162    println!("  ✅ Ping 成功");
163
164    // 依据模型自动建表并执行 CRUD,触发文件写入(零 SqlValue)
165    database.auto_migrate::<DemoUser>().await?;
166    println!("  ✅ 创建表成功(依据模型 schema)");
167
168    let mut users = vec![
169        DemoUser { id: 0, name: "Alice".into(), age: 25 },
170        DemoUser { id: 0, name: "Bob".into(), age: 30 },
171    ];
172    for u in &mut users {
173        database.create(u).await?;
174    }
175    println!("  ✅ 插入数据成功");
176
177    let all: Vec<DemoUser> = database.all::<DemoUser>().await?;
178    println!("  ✅ 查询返回 {} 行", all.len());
179
180    database.close().await?;
181    println!("  ✅ 数据库已关闭,数据已保存到 demo.db");
182    
183    println!();
184    println!("MySQL 连接示例:");
185    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
186        .with_host("localhost")
187        .with_port(3306)
188        .with_username("user")
189        .with_password("password");
190    println!("  DSN: {}", mysql_dsn.build());
191    
192    println!();
193    println!("PostgreSQL 连接示例:");
194    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
195        .with_host("localhost")
196        .with_port(5432)
197        .with_username("user")
198        .with_password("password");
199    println!("  DSN: {}", pg_dsn.build());
200
201    Ok(())
202}
203
204async fn demonstrate_database_connection() -> Result<(), Box<dyn std::error::Error>> {
205    println!("SQLite 连接:");
206    let dsn = Dsn::new(DBDriver::SQLite, "demo.db");
207    println!("  DSN: {}", dsn.build());
208    
209    let database = Database::sqlite(":memory:").await?;
210    println!("  ✅ 连接成功");
211    println!("  驱动: {:?}", database.db_type());
212    
213    // 测试连接
214    database.ping().await?;
215    println!("  ✅ Ping 成功");
216    database.close().await?;
217    
218    println!();
219    println!("MySQL 连接示例:");
220    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
221        .with_host("localhost")
222        .with_port(3306)
223        .with_username("user")
224        .with_password("password");
225    println!("  DSN: {}", mysql_dsn.build());
226    
227    println!();
228    println!("PostgreSQL 连接示例:");
229    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
230        .with_host("localhost")
231        .with_port(5432)
232        .with_username("user")
233        .with_password("password");
234    println!("  DSN: {}", pg_dsn.build());
235
236    Ok(())
237}
Source

pub fn db_type(&self) -> DbType

获取数据库类型

Examples found in repository?
examples/basic_usage.rs (line 77)
69async fn demonstrate_database_connection() -> std::result::Result<(), Box<dyn std::error::Error>> {
70    println!("SQLite connection:");
71    let dsn = Dsn::new(DBDriver::SQLite, "demo.db");
72    println!("  DSN: {}", dsn.build());
73    
74    // Test actual SQLite connection with pure Rust engine
75    let db = Database::sqlite(":memory:").await?;
76    println!("  ✅ Connected to in-memory SQLite (pure Rust engine)");
77    println!("  DB type: {:?}", db.db_type());
78    println!("  Connected: {}", db.is_connected());
79    db.close().await?;
80    
81    println!();
82    println!("MySQL connection example:");
83    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
84        .with_host("localhost")
85        .with_port(3306)
86        .with_username("user")
87        .with_password("password");
88    println!("  DSN: {}", mysql_dsn.build());
89    
90    println!();
91    println!("PostgreSQL connection example:");
92    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
93        .with_host("localhost")
94        .with_port(5432)
95        .with_username("user")
96        .with_password("password");
97    println!("  DSN: {}", pg_dsn.build());
98
99    Ok(())
100}
More examples
Hide additional examples
examples/postgresql_example.rs (line 89)
77async fn demonstrate_database_connection() -> std::result::Result<(), Box<dyn std::error::Error>> {
78    println!("PostgreSQL connection (native wire protocol):");
79    let dsn = Dsn::new(DBDriver::PostgreSQL, PG_DB)
80        .with_host(PG_HOST)
81        .with_port(PG_PORT)
82        .with_username(PG_USER)
83        .with_password(PG_PASS);
84    println!("  DSN: {}", dsn.build());
85
86    // Test actual PostgreSQL connection
87    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
88    println!("  ✅ Connected to PostgreSQL (native wire protocol)");
89    println!("  DB type: {:?}", db.db_type());
90    println!("  Connected: {}", db.is_connected());
91    db.ping().await?;
92    println!("  ✅ Ping successful");
93    db.close().await?;
94
95    println!();
96    println!("Connection via ConnectionFactory:");
97    let config = ConnectionConfig::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS)
98        .with_timeout(std::time::Duration::from_secs(30))
99        .with_max_connections(10);
100    let conn = ConnectionFactory::create_connection(config.clone()).await?;
101    println!("  ✅ Connection created (factory)");
102    println!("  DB type: {:?}", conn.db_type());
103    conn.close().await?;
104
105    println!();
106    println!("Direct PostgresConnection:");
107    let pg = PostgresConnection::new(&config).await?;
108    println!("  ✅ PostgresConnection created");
109    println!("  Connected: {}", pg.is_connected());
110    pg.close().await?;
111
112    Ok(())
113}
examples/complete_demo.rs (line 158)
151async fn demonstrate_database_file_connection() -> Result<(), Box<dyn std::error::Error>> {
152    println!("SQLite 连接:");
153    let dsn = Dsn::new(DBDriver::SQLite, "target/demo.db");
154    println!("  DSN: {}", dsn.build());
155    
156    let database = Database::sqlite("target/demo.db").await?;
157    println!("  ✅ 连接成功");
158    println!("  驱动: {:?}", database.db_type());
159    
160    // 测试连接
161    database.ping().await?;
162    println!("  ✅ Ping 成功");
163
164    // 依据模型自动建表并执行 CRUD,触发文件写入(零 SqlValue)
165    database.auto_migrate::<DemoUser>().await?;
166    println!("  ✅ 创建表成功(依据模型 schema)");
167
168    let mut users = vec![
169        DemoUser { id: 0, name: "Alice".into(), age: 25 },
170        DemoUser { id: 0, name: "Bob".into(), age: 30 },
171    ];
172    for u in &mut users {
173        database.create(u).await?;
174    }
175    println!("  ✅ 插入数据成功");
176
177    let all: Vec<DemoUser> = database.all::<DemoUser>().await?;
178    println!("  ✅ 查询返回 {} 行", all.len());
179
180    database.close().await?;
181    println!("  ✅ 数据库已关闭,数据已保存到 demo.db");
182    
183    println!();
184    println!("MySQL 连接示例:");
185    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
186        .with_host("localhost")
187        .with_port(3306)
188        .with_username("user")
189        .with_password("password");
190    println!("  DSN: {}", mysql_dsn.build());
191    
192    println!();
193    println!("PostgreSQL 连接示例:");
194    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
195        .with_host("localhost")
196        .with_port(5432)
197        .with_username("user")
198        .with_password("password");
199    println!("  DSN: {}", pg_dsn.build());
200
201    Ok(())
202}
203
204async fn demonstrate_database_connection() -> Result<(), Box<dyn std::error::Error>> {
205    println!("SQLite 连接:");
206    let dsn = Dsn::new(DBDriver::SQLite, "demo.db");
207    println!("  DSN: {}", dsn.build());
208    
209    let database = Database::sqlite(":memory:").await?;
210    println!("  ✅ 连接成功");
211    println!("  驱动: {:?}", database.db_type());
212    
213    // 测试连接
214    database.ping().await?;
215    println!("  ✅ Ping 成功");
216    database.close().await?;
217    
218    println!();
219    println!("MySQL 连接示例:");
220    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
221        .with_host("localhost")
222        .with_port(3306)
223        .with_username("user")
224        .with_password("password");
225    println!("  DSN: {}", mysql_dsn.build());
226    
227    println!();
228    println!("PostgreSQL 连接示例:");
229    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
230        .with_host("localhost")
231        .with_port(5432)
232        .with_username("user")
233        .with_password("password");
234    println!("  DSN: {}", pg_dsn.build());
235
236    Ok(())
237}
Source

pub fn is_connected(&self) -> bool

检查连接状态

Examples found in repository?
examples/basic_usage.rs (line 78)
69async fn demonstrate_database_connection() -> std::result::Result<(), Box<dyn std::error::Error>> {
70    println!("SQLite connection:");
71    let dsn = Dsn::new(DBDriver::SQLite, "demo.db");
72    println!("  DSN: {}", dsn.build());
73    
74    // Test actual SQLite connection with pure Rust engine
75    let db = Database::sqlite(":memory:").await?;
76    println!("  ✅ Connected to in-memory SQLite (pure Rust engine)");
77    println!("  DB type: {:?}", db.db_type());
78    println!("  Connected: {}", db.is_connected());
79    db.close().await?;
80    
81    println!();
82    println!("MySQL connection example:");
83    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
84        .with_host("localhost")
85        .with_port(3306)
86        .with_username("user")
87        .with_password("password");
88    println!("  DSN: {}", mysql_dsn.build());
89    
90    println!();
91    println!("PostgreSQL connection example:");
92    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
93        .with_host("localhost")
94        .with_port(5432)
95        .with_username("user")
96        .with_password("password");
97    println!("  DSN: {}", pg_dsn.build());
98
99    Ok(())
100}
More examples
Hide additional examples
examples/postgresql_example.rs (line 90)
77async fn demonstrate_database_connection() -> std::result::Result<(), Box<dyn std::error::Error>> {
78    println!("PostgreSQL connection (native wire protocol):");
79    let dsn = Dsn::new(DBDriver::PostgreSQL, PG_DB)
80        .with_host(PG_HOST)
81        .with_port(PG_PORT)
82        .with_username(PG_USER)
83        .with_password(PG_PASS);
84    println!("  DSN: {}", dsn.build());
85
86    // Test actual PostgreSQL connection
87    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
88    println!("  ✅ Connected to PostgreSQL (native wire protocol)");
89    println!("  DB type: {:?}", db.db_type());
90    println!("  Connected: {}", db.is_connected());
91    db.ping().await?;
92    println!("  ✅ Ping successful");
93    db.close().await?;
94
95    println!();
96    println!("Connection via ConnectionFactory:");
97    let config = ConnectionConfig::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS)
98        .with_timeout(std::time::Duration::from_secs(30))
99        .with_max_connections(10);
100    let conn = ConnectionFactory::create_connection(config.clone()).await?;
101    println!("  ✅ Connection created (factory)");
102    println!("  DB type: {:?}", conn.db_type());
103    conn.close().await?;
104
105    println!();
106    println!("Direct PostgresConnection:");
107    let pg = PostgresConnection::new(&config).await?;
108    println!("  ✅ PostgresConnection created");
109    println!("  Connected: {}", pg.is_connected());
110    pg.close().await?;
111
112    Ok(())
113}
Source

pub fn config(&self) -> &ConnectionConfig

获取配置

Examples found in repository?
examples/integration_example.rs (line 39)
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}
Source

pub async fn close(&self) -> Result<(), DbError>

关闭数据库连接

Examples found in repository?
examples/basic_usage.rs (line 79)
69async fn demonstrate_database_connection() -> std::result::Result<(), Box<dyn std::error::Error>> {
70    println!("SQLite connection:");
71    let dsn = Dsn::new(DBDriver::SQLite, "demo.db");
72    println!("  DSN: {}", dsn.build());
73    
74    // Test actual SQLite connection with pure Rust engine
75    let db = Database::sqlite(":memory:").await?;
76    println!("  ✅ Connected to in-memory SQLite (pure Rust engine)");
77    println!("  DB type: {:?}", db.db_type());
78    println!("  Connected: {}", db.is_connected());
79    db.close().await?;
80    
81    println!();
82    println!("MySQL connection example:");
83    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
84        .with_host("localhost")
85        .with_port(3306)
86        .with_username("user")
87        .with_password("password");
88    println!("  DSN: {}", mysql_dsn.build());
89    
90    println!();
91    println!("PostgreSQL connection example:");
92    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
93        .with_host("localhost")
94        .with_port(5432)
95        .with_username("user")
96        .with_password("password");
97    println!("  DSN: {}", pg_dsn.build());
98
99    Ok(())
100}
101
102fn demonstrate_simplified_uuid() -> std::result::Result<(), Box<dyn std::error::Error>> {
103    println!("Generating UUIDs:");
104    
105    // Generate multiple UUIDs
106    let uuid1 = SimpleUuid::new_v4();
107    let uuid2 = SimpleUuid::new_v4();
108    let uuid3 = SimpleUuid::new_v4();
109    
110    println!("  UUID 1: {}", uuid1);
111    println!("  UUID 2: {}", uuid2);
112    println!("  UUID 3: {}", uuid3);
113    println!("  All unique: {}", uuid1 != uuid2 && uuid2 != uuid3 && uuid1 != uuid3);
114    
115    println!();
116    println!("ID Generator:");
117    let generator = IdGenerator::new();
118    let id1 = generator.generate();
119    let id2 = generator.generate();
120    
121    println!("  ID 1: {}", id1);
122    println!("  ID 2: {}", id2);
123    println!("  ID 3: {}", generator.with_prefix("user_").generate());
124    
125    println!();
126    println!("Simple IDs:");
127    let simple_gen = IdGenerator::new().with_simple_id();
128    println!("  Simple ID: {}", simple_gen.generate());
129    println!("  Prefixed: {}", simple_gen.with_prefix("order_").generate());
130
131    Ok(())
132}
133
134fn demonstrate_simplified_error() -> std::result::Result<(), Box<dyn std::error::Error>> {
135    println!("Error handling without thiserror:");
136    
137    // Create different error types
138    let not_found = SimpleError::NotFound;
139    println!("  NotFound: {}", not_found);
140    
141    let custom = SimpleError::custom("Something went wrong");
142    println!("  Custom: {}", custom);
143    
144    let invalid_query = SimpleError::invalid_query("Invalid WHERE clause");
145    println!("  InvalidQuery: {}", invalid_query);
146    
147    let connection_error = SimpleError::connection_error("Could not connect to database");
148    println!("  ConnectionError: {}", connection_error);
149    
150    println!();
151    println!("Using SimpleResult:");
152    let success: SimpleResult<i32> = Ok(42);
153    println!("  Success: {:?}", success);
154    
155    let failure: SimpleResult<i32> = Err(SimpleError::NotFound);
156    println!("  Failure: {:?}", failure);
157
158    Ok(())
159}
160
161fn demonstrate_simplified_cache() -> std::result::Result<(), Box<dyn std::error::Error>> {
162    println!("LRU cache:");
163    
164    let mut cache: SimpleLruCache<&str, &str> = SimpleLruCache::new(3);
165    
166    // Add items
167    cache.put("key1", "value1");
168    cache.put("key2", "value2");
169    cache.put("key3", "value3");
170    
171    println!("  Initial size: {}", cache.len());
172    println!("  key1: {:?}", cache.get(&"key1"));
173    println!("  key2: {:?}", cache.get(&"key2"));
174    println!("  key3: {:?}", cache.get(&"key3"));
175    
176    // Test LRU eviction
177    println!();
178    println!("  Adding key4 (should evict oldest):");
179    cache.put("key4", "value4");
180    println!("  key1: {:?}", cache.get(&"key1")); // Should be None
181    println!("  key4: {:?}", cache.get(&"key4")); // Should be Some
182    
183    // Test capacity
184    println!();
185    println!("  Current capacity: {}", cache.capacity());
186    println!("  Current size: {}", cache.len());
187    
188    // Resize
189    cache.resize(2);
190    println!("  After resize to 2:");
191    println!("  New size: {}", cache.len());
192    
193    // Cleanup
194    cache.clear();
195    println!("  After clear: {}", cache.is_empty());
196
197    Ok(())
198}
199
200async fn demonstrate_connection_pool() -> std::result::Result<(), Box<dyn std::error::Error>> {
201    println!("Simple connection pool implementation:");
202    
203    // Create a pool with pre-created connections
204    let connections = vec![1, 2, 3, 4, 5];
205    let pool = SimplePool::new(connections);
206    let status = pool.status();
207    
208    println!("  Total connections: {}", status.total_connections);
209    println!("  Idle connections: {}", status.idle_connections);
210    println!("  Active connections: {}", status.active_connections);
211    println!("  Utilization: {:.1}%", status.utilization_rate() * 100.0);
212    
213    // Test getting a connection
214    println!();
215    println!("  Getting a connection from pool:");
216    match pool.get().await {
217        Ok(conn) => {
218            println!("    Got: {}", conn);
219            let status = pool.status();
220            println!("    After get - idle: {}, active: {}", status.idle_connections, status.active_connections);
221            pool.put(conn);
222            let status = pool.status();
223            println!("    After put - idle: {}, active: {}", status.idle_connections, status.active_connections);
224        }
225        Err(e) => println!("    Error: {}", e),
226    }
227    
228    println!();
229    println!("Pool features:");
230    println!("  • Connection reuse");
231    println!("  • Timeout handling");
232    println!("  • No external deadpool dependency");
233
234    Ok(())
235}
236
237async fn demonstrate_sql_engine() -> std::result::Result<(), Box<dyn std::error::Error>> {
238    println!("Pure Rust SQL engine (no rusqlite) + typed model:");
239    
240    let db = Database::sqlite(":memory:").await?;
241    
242    // 依据模型自动建表(零 SqlValue)
243    db.auto_migrate::<Product>().await?;
244    println!("  ✅ Created products table from model schema");
245    
246    // 通过模型 create 插入
247    let mut products = vec![
248        Product { id: 0, name: "Apple".to_string(), price: 5 },
249        Product { id: 0, name: "Banana".to_string(), price: 3 },
250        Product { id: 0, name: "Cherry".to_string(), price: 9 },
251    ];
252    for p in &mut products {
253        db.create(p).await?;
254    }
255    println!("  ✅ Inserted {} products", products.len());
256    
257    // 查询并映射回类型
258    let all: Vec<Product> = db.all::<Product>().await?;
259    println!("  ✅ Query returned {} rows", all.len());
260    for p in &all {
261        println!("    - {} price={}", p.name, p.price);
262    }
263    
264    // 更新(返回影响行数)
265    let affected = db.update(&mut products[0], &[("price", 6)]).await?;
266    println!("  ✅ Updated {} row(s)", affected);
267    
268    // 计数
269    let count = db.all::<Product>().await?.len();
270    println!("  ✅ Count = {}", count);
271    
272    // 删除(使用已回填主键的模型实例)
273    let affected = db.delete(&mut products[2]).await?;
274    println!("  ✅ Deleted {} row(s)", affected);
275    
276    db.close().await?;
277    println!("  ✅ Database closed");
278
279    Ok(())
280}
More examples
Hide additional examples
examples/postgresql_example.rs (line 93)
77async fn demonstrate_database_connection() -> std::result::Result<(), Box<dyn std::error::Error>> {
78    println!("PostgreSQL connection (native wire protocol):");
79    let dsn = Dsn::new(DBDriver::PostgreSQL, PG_DB)
80        .with_host(PG_HOST)
81        .with_port(PG_PORT)
82        .with_username(PG_USER)
83        .with_password(PG_PASS);
84    println!("  DSN: {}", dsn.build());
85
86    // Test actual PostgreSQL connection
87    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
88    println!("  ✅ Connected to PostgreSQL (native wire protocol)");
89    println!("  DB type: {:?}", db.db_type());
90    println!("  Connected: {}", db.is_connected());
91    db.ping().await?;
92    println!("  ✅ Ping successful");
93    db.close().await?;
94
95    println!();
96    println!("Connection via ConnectionFactory:");
97    let config = ConnectionConfig::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS)
98        .with_timeout(std::time::Duration::from_secs(30))
99        .with_max_connections(10);
100    let conn = ConnectionFactory::create_connection(config.clone()).await?;
101    println!("  ✅ Connection created (factory)");
102    println!("  DB type: {:?}", conn.db_type());
103    conn.close().await?;
104
105    println!();
106    println!("Direct PostgresConnection:");
107    let pg = PostgresConnection::new(&config).await?;
108    println!("  ✅ PostgresConnection created");
109    println!("  Connected: {}", pg.is_connected());
110    pg.close().await?;
111
112    Ok(())
113}
114
115async fn demonstrate_crud() -> std::result::Result<(), Box<dyn std::error::Error>> {
116    println!("GORM-style model CRUD (create / first / find / update / delete):");
117    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
118
119    // Schema setup (GORM AutoMigrate equivalent — drop + recreate for a clean demo)
120    db.execute("DROP TABLE IF EXISTS users", &[]).await?;
121    db.execute(
122        "CREATE TABLE users (
123            id TEXT PRIMARY KEY,
124            name TEXT NOT NULL,
125            email TEXT,
126            age INTEGER,
127            status TEXT,
128            created_at TIMESTAMPTZ,
129            updated_at TIMESTAMPTZ
130        )",
131        &[],
132    )
133    .await?;
134    println!("  ✅ Schema ready (users table recreated)");
135
136    // Create — GORM `db.Create(&user)` equivalent
137    let mut alice = User::new("Alice", "alice@example.com").with_age(25);
138    db.create(&mut alice).await?;
139    println!(
140        "  ✅ Created: id={} name={} (created_at: {:?})",
141        alice.id,
142        alice.name,
143        alice.created_at()
144    );
145
146    let mut bob = User::new("Bob", "bob@example.com").with_age(30);
147    db.create(&mut bob).await?;
148    println!("  ✅ Created: id={} name={}", bob.id, bob.name);
149
150    // First — GORM `db.First(&user, id)` equivalent
151    let found: Option<User> = db.first(&alice.id).await?;
152    match &found {
153        Some(u) => println!(
154            "  ✅ First: id={} name={} age={:?} status={}",
155            u.id, u.name, u.age, u.status
156        ),
157        None => println!("  ❌ First: not found"),
158    }
159
160    // Find all — GORM `db.Find(&users)` equivalent
161    let users: Vec<User> = db.all().await?;
162    println!("  ✅ Find: {} user(s)", users.len());
163    for u in &users {
164        println!(
165            "    - {} <{}> age={:?} status={}",
166            u.name, u.email, u.age, u.status
167        );
168    }
169
170    // Update — GORM `db.Model(&user).Update("age", 29)` equivalent
171    db.update(&mut alice, &[("age", 29)]).await?;
172    let updated: User = db.first(&alice.id).await?.expect("alice exists");
173    println!("  ✅ Updated: {} age now {:?}", updated.name, updated.age);
174
175    // Delete — GORM `db.Delete(&user)` equivalent
176    db.delete(&mut alice).await?;
177    let gone: Option<User> = db.first(&alice.id).await?;
178    println!(
179        "  ✅ Deleted: {} exists after delete = {}",
180        alice.name,
181        gone.is_some()
182    );
183
184    db.close().await?;
185    println!("  ✅ Database closed");
186
187    Ok(())
188}
189
190async fn demonstrate_transactions() -> std::result::Result<(), Box<dyn std::error::Error>> {
191    println!("PostgreSQL transactions (BEGIN / COMMIT / ROLLBACK):");
192    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
193
194    // Commit
195    let mut tx = db.begin_transaction().await?;
196    tx.execute(
197        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
198        &[
199            SimpleUuid::new_v4().to_string().into(),
200            "Dave".into(),
201            40.into(),
202        ],
203    )
204    .await?;
205    tx.execute(
206        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
207        &[
208            SimpleUuid::new_v4().to_string().into(),
209            "Frank".into(),
210            35.into(),
211        ],
212    )
213    .await?;
214    tx.commit().await?;
215    println!("  ✅ Transaction committed (2 users)");
216
217    // Rollback
218    let mut tx = db.begin_transaction().await?;
219    tx.execute(
220        "INSERT INTO users (id, name, age) VALUES ($1, $2, $3)",
221        &[
222            SimpleUuid::new_v4().to_string().into(),
223            "Eve".into(),
224            45.into(),
225        ],
226    )
227    .await?;
228    tx.rollback().await?;
229    println!("  ✅ Transaction rolled back (Eve not saved)");
230
231    let result = db.query("SELECT COUNT(*) AS count FROM users", &[]).await?;
232    println!("  ✅ Final user count: {:?}", result.rows[0].get("count"));
233
234    db.close().await?;
235    Ok(())
236}
examples/complete_demo.rs (line 180)
151async fn demonstrate_database_file_connection() -> Result<(), Box<dyn std::error::Error>> {
152    println!("SQLite 连接:");
153    let dsn = Dsn::new(DBDriver::SQLite, "target/demo.db");
154    println!("  DSN: {}", dsn.build());
155    
156    let database = Database::sqlite("target/demo.db").await?;
157    println!("  ✅ 连接成功");
158    println!("  驱动: {:?}", database.db_type());
159    
160    // 测试连接
161    database.ping().await?;
162    println!("  ✅ Ping 成功");
163
164    // 依据模型自动建表并执行 CRUD,触发文件写入(零 SqlValue)
165    database.auto_migrate::<DemoUser>().await?;
166    println!("  ✅ 创建表成功(依据模型 schema)");
167
168    let mut users = vec![
169        DemoUser { id: 0, name: "Alice".into(), age: 25 },
170        DemoUser { id: 0, name: "Bob".into(), age: 30 },
171    ];
172    for u in &mut users {
173        database.create(u).await?;
174    }
175    println!("  ✅ 插入数据成功");
176
177    let all: Vec<DemoUser> = database.all::<DemoUser>().await?;
178    println!("  ✅ 查询返回 {} 行", all.len());
179
180    database.close().await?;
181    println!("  ✅ 数据库已关闭,数据已保存到 demo.db");
182    
183    println!();
184    println!("MySQL 连接示例:");
185    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
186        .with_host("localhost")
187        .with_port(3306)
188        .with_username("user")
189        .with_password("password");
190    println!("  DSN: {}", mysql_dsn.build());
191    
192    println!();
193    println!("PostgreSQL 连接示例:");
194    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
195        .with_host("localhost")
196        .with_port(5432)
197        .with_username("user")
198        .with_password("password");
199    println!("  DSN: {}", pg_dsn.build());
200
201    Ok(())
202}
203
204async fn demonstrate_database_connection() -> Result<(), Box<dyn std::error::Error>> {
205    println!("SQLite 连接:");
206    let dsn = Dsn::new(DBDriver::SQLite, "demo.db");
207    println!("  DSN: {}", dsn.build());
208    
209    let database = Database::sqlite(":memory:").await?;
210    println!("  ✅ 连接成功");
211    println!("  驱动: {:?}", database.db_type());
212    
213    // 测试连接
214    database.ping().await?;
215    println!("  ✅ Ping 成功");
216    database.close().await?;
217    
218    println!();
219    println!("MySQL 连接示例:");
220    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
221        .with_host("localhost")
222        .with_port(3306)
223        .with_username("user")
224        .with_password("password");
225    println!("  DSN: {}", mysql_dsn.build());
226    
227    println!();
228    println!("PostgreSQL 连接示例:");
229    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
230        .with_host("localhost")
231        .with_port(5432)
232        .with_username("user")
233        .with_password("password");
234    println!("  DSN: {}", pg_dsn.build());
235
236    Ok(())
237}
examples/integration_example.rs (line 101)
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}
Source

pub async fn create<M: Model>(&self, model: &mut M) -> Result<(), DbError>

GORM-style create: INSERT the model, running the before_create/after_create hooks. Builds the INSERT from Model::columns() plus created_at/updated_at (set by the before_create hook; the table must include those columns). Automatically retrieves the auto-generated primary key and sets it via model.set_id().

Examples found in repository?
examples/basic_usage.rs (line 253)
237async fn demonstrate_sql_engine() -> std::result::Result<(), Box<dyn std::error::Error>> {
238    println!("Pure Rust SQL engine (no rusqlite) + typed model:");
239    
240    let db = Database::sqlite(":memory:").await?;
241    
242    // 依据模型自动建表(零 SqlValue)
243    db.auto_migrate::<Product>().await?;
244    println!("  ✅ Created products table from model schema");
245    
246    // 通过模型 create 插入
247    let mut products = vec![
248        Product { id: 0, name: "Apple".to_string(), price: 5 },
249        Product { id: 0, name: "Banana".to_string(), price: 3 },
250        Product { id: 0, name: "Cherry".to_string(), price: 9 },
251    ];
252    for p in &mut products {
253        db.create(p).await?;
254    }
255    println!("  ✅ Inserted {} products", products.len());
256    
257    // 查询并映射回类型
258    let all: Vec<Product> = db.all::<Product>().await?;
259    println!("  ✅ Query returned {} rows", all.len());
260    for p in &all {
261        println!("    - {} price={}", p.name, p.price);
262    }
263    
264    // 更新(返回影响行数)
265    let affected = db.update(&mut products[0], &[("price", 6)]).await?;
266    println!("  ✅ Updated {} row(s)", affected);
267    
268    // 计数
269    let count = db.all::<Product>().await?.len();
270    println!("  ✅ Count = {}", count);
271    
272    // 删除(使用已回填主键的模型实例)
273    let affected = db.delete(&mut products[2]).await?;
274    println!("  ✅ Deleted {} row(s)", affected);
275    
276    db.close().await?;
277    println!("  ✅ Database closed");
278
279    Ok(())
280}
More examples
Hide additional examples
examples/complete_demo.rs (line 173)
151async fn demonstrate_database_file_connection() -> Result<(), Box<dyn std::error::Error>> {
152    println!("SQLite 连接:");
153    let dsn = Dsn::new(DBDriver::SQLite, "target/demo.db");
154    println!("  DSN: {}", dsn.build());
155    
156    let database = Database::sqlite("target/demo.db").await?;
157    println!("  ✅ 连接成功");
158    println!("  驱动: {:?}", database.db_type());
159    
160    // 测试连接
161    database.ping().await?;
162    println!("  ✅ Ping 成功");
163
164    // 依据模型自动建表并执行 CRUD,触发文件写入(零 SqlValue)
165    database.auto_migrate::<DemoUser>().await?;
166    println!("  ✅ 创建表成功(依据模型 schema)");
167
168    let mut users = vec![
169        DemoUser { id: 0, name: "Alice".into(), age: 25 },
170        DemoUser { id: 0, name: "Bob".into(), age: 30 },
171    ];
172    for u in &mut users {
173        database.create(u).await?;
174    }
175    println!("  ✅ 插入数据成功");
176
177    let all: Vec<DemoUser> = database.all::<DemoUser>().await?;
178    println!("  ✅ 查询返回 {} 行", all.len());
179
180    database.close().await?;
181    println!("  ✅ 数据库已关闭,数据已保存到 demo.db");
182    
183    println!();
184    println!("MySQL 连接示例:");
185    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
186        .with_host("localhost")
187        .with_port(3306)
188        .with_username("user")
189        .with_password("password");
190    println!("  DSN: {}", mysql_dsn.build());
191    
192    println!();
193    println!("PostgreSQL 连接示例:");
194    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
195        .with_host("localhost")
196        .with_port(5432)
197        .with_username("user")
198        .with_password("password");
199    println!("  DSN: {}", pg_dsn.build());
200
201    Ok(())
202}
examples/async_concurrency.rs (line 60)
47async fn database_concurrency() -> Result<(), Box<dyn std::error::Error>> {
48    let db = Arc::new(Database::sqlite(":memory:").await?);
49
50    // 依据 Product 模型自动建表。
51    db.auto_migrate::<Product>().await?;
52
53    // 预置数据:通过模型 create,零 SqlValue。
54    for i in 0..100 {
55        let mut p = Product {
56            id: 0,
57            name: format!("product_{}", i),
58            price: i,
59        };
60        db.create(&mut p).await?;
61    }
62
63    // 并发执行多个查询任务(按页读取,映射回模型)。
64    let mut handles = Vec::new();
65    for offset in (0..100).step_by(25) {
66        let db = Arc::clone(&db);
67        handles.push(tokio::spawn(async move {
68            let products: Vec<Product> = Query::new("products")
69                .order_by_asc("id")
70                .limit(25)
71                .offset(offset)
72                .query(&db)
73                .models::<Product>()
74                .await?;
75            Ok::<usize, torm::db::database::DbError>(products.len())
76        }));
77    }
78
79    let mut total = 0usize;
80    for h in handles {
81        total += h.await??;
82    }
83    println!("  4 concurrent queries fetched {} rows in total.", total);
84
85    // 使用 Query builder 并发查询(值类型自动转换,无需手写 SqlValue::I32)
86    let mut handles = Vec::new();
87    for min_price in [10i64, 20, 30, 40] {
88        let db = Arc::clone(&db);
89        handles.push(tokio::spawn(async move {
90            Query::new("products")
91                .where_gt("price", min_price)
92                .query(&db)
93                .count()
94                .await
95        }));
96    }
97    for (i, h) in handles.into_iter().enumerate() {
98        let count = h.await??;
99        let n = count
100            .rows
101            .first()
102            .and_then(|r| r.get("COUNT(*)").or_else(|| r.get("count")))
103            .and_then(|v| v.as_i64())
104            .unwrap_or(0);
105        println!("  price > {}  -> {} products", [10, 20, 30, 40][i], n);
106    }
107
108    Ok(())
109}
examples/postgresql_example.rs (line 138)
115async fn demonstrate_crud() -> std::result::Result<(), Box<dyn std::error::Error>> {
116    println!("GORM-style model CRUD (create / first / find / update / delete):");
117    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
118
119    // Schema setup (GORM AutoMigrate equivalent — drop + recreate for a clean demo)
120    db.execute("DROP TABLE IF EXISTS users", &[]).await?;
121    db.execute(
122        "CREATE TABLE users (
123            id TEXT PRIMARY KEY,
124            name TEXT NOT NULL,
125            email TEXT,
126            age INTEGER,
127            status TEXT,
128            created_at TIMESTAMPTZ,
129            updated_at TIMESTAMPTZ
130        )",
131        &[],
132    )
133    .await?;
134    println!("  ✅ Schema ready (users table recreated)");
135
136    // Create — GORM `db.Create(&user)` equivalent
137    let mut alice = User::new("Alice", "alice@example.com").with_age(25);
138    db.create(&mut alice).await?;
139    println!(
140        "  ✅ Created: id={} name={} (created_at: {:?})",
141        alice.id,
142        alice.name,
143        alice.created_at()
144    );
145
146    let mut bob = User::new("Bob", "bob@example.com").with_age(30);
147    db.create(&mut bob).await?;
148    println!("  ✅ Created: id={} name={}", bob.id, bob.name);
149
150    // First — GORM `db.First(&user, id)` equivalent
151    let found: Option<User> = db.first(&alice.id).await?;
152    match &found {
153        Some(u) => println!(
154            "  ✅ First: id={} name={} age={:?} status={}",
155            u.id, u.name, u.age, u.status
156        ),
157        None => println!("  ❌ First: not found"),
158    }
159
160    // Find all — GORM `db.Find(&users)` equivalent
161    let users: Vec<User> = db.all().await?;
162    println!("  ✅ Find: {} user(s)", users.len());
163    for u in &users {
164        println!(
165            "    - {} <{}> age={:?} status={}",
166            u.name, u.email, u.age, u.status
167        );
168    }
169
170    // Update — GORM `db.Model(&user).Update("age", 29)` equivalent
171    db.update(&mut alice, &[("age", 29)]).await?;
172    let updated: User = db.first(&alice.id).await?.expect("alice exists");
173    println!("  ✅ Updated: {} age now {:?}", updated.name, updated.age);
174
175    // Delete — GORM `db.Delete(&user)` equivalent
176    db.delete(&mut alice).await?;
177    let gone: Option<User> = db.first(&alice.id).await?;
178    println!(
179        "  ✅ Deleted: {} exists after delete = {}",
180        alice.name,
181        gone.is_some()
182    );
183
184    db.close().await?;
185    println!("  ✅ Database closed");
186
187    Ok(())
188}
examples/dapper_style.rs (line 45)
35async fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let db = Database::sqlite(":memory:").await?;
37
38    // 自动建表(依据模型 schema)
39    db.auto_migrate::<User>().await?;
40    println!("表 users 已自动创建\n");
41
42    // === 1. insert:无需手写 SqlValue,主键自动自增并回填 ===
43    println!("=== 1. Insert (自增主键自动回填) ===");
44    let mut alice = User::new("Alice", "alice@example.com", 25);
45    db.create(&mut alice).await?;
46    let mut bob = User::new("Bob", "bob@example.com", 17);
47    db.create(&mut bob).await?;
48    let mut carol = User::new("Carol", "carol@example.com", 30);
49    db.create(&mut carol).await?;
50    println!(
51        "  id 自动分配: Alice={} Bob={} Carol={}\n",
52        alice.id, bob.id, carol.id
53    );
54
55    // === 2. query:条件查询自动映射回 Vec<User> ===
56    println!("=== 2. Query (自动映射回 User) ===");
57    let adults: Vec<User> = Query::new("users")
58        .where_gte("age", 18)
59        .order_by_desc("age")
60        .query(&db)
61        .models::<User>()
62        .await?;
63    for u in &adults {
64        println!("  id={} name={} email={} age={}", u.id, u.name, u.email, u.age);
65    }
66
67    // 分页 + 条件
68    let first_two: Vec<User> = Query::new("users")
69        .where_gt("age", 0)
70        .order_by_asc("id")
71        .limit(2)
72        .query(&db)
73        .models::<User>()
74        .await?;
75    println!("  前 2 条: {:?}", first_two.iter().map(|u| &u.name).collect::<Vec<_>>());
76    println!();
77
78    // === 3. update:直接执行 SQL,返回影响行数 ===
79    println!("=== 3. Update ===");
80    let affected = db.update(&mut alice, &[("age", 26)]).await?;
81    println!("  更新 age 影响 {} 行", affected);
82
83    // 多列同类型(全为 &str)可直接批量更新
84    db.update(
85        &mut alice,
86        &[("email", "alice_new@example.com"), ("name", "Alice A.")],
87    )
88    .await?;
89
90    // 重新查询验证
91    let refreshed: User = db.first::<User>(&alice.id.to_string()).await?.unwrap();
92    println!(
93        "  更新后: name={} age={} email={}\n",
94        refreshed.name, refreshed.age, refreshed.email
95    );
96
97    // === 4. 条件删除 ===
98    println!("=== 4. Delete ===");
99    let removed = db.delete(&mut bob).await?;
100    println!("  删除 Bob 影响 {} 行", removed);
101    let remaining = db.all::<User>().await?;
102    println!("  剩余 {} 条: {:?}", remaining.len(), remaining.iter().map(|u| &u.name).collect::<Vec<_>>());
103
104    println!("\n✅ insert / query / update / delete 全程零 SqlValue,Dapper 风格完成!");
105    Ok(())
106}
examples/integration_example.rs (line 46)
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}
Source

pub async fn first<M: Model>(&self, id: &str) -> Result<Option<M>, DbError>

GORM-style first: find one model by primary key.

Examples found in repository?
examples/postgresql_example.rs (line 151)
115async fn demonstrate_crud() -> std::result::Result<(), Box<dyn std::error::Error>> {
116    println!("GORM-style model CRUD (create / first / find / update / delete):");
117    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
118
119    // Schema setup (GORM AutoMigrate equivalent — drop + recreate for a clean demo)
120    db.execute("DROP TABLE IF EXISTS users", &[]).await?;
121    db.execute(
122        "CREATE TABLE users (
123            id TEXT PRIMARY KEY,
124            name TEXT NOT NULL,
125            email TEXT,
126            age INTEGER,
127            status TEXT,
128            created_at TIMESTAMPTZ,
129            updated_at TIMESTAMPTZ
130        )",
131        &[],
132    )
133    .await?;
134    println!("  ✅ Schema ready (users table recreated)");
135
136    // Create — GORM `db.Create(&user)` equivalent
137    let mut alice = User::new("Alice", "alice@example.com").with_age(25);
138    db.create(&mut alice).await?;
139    println!(
140        "  ✅ Created: id={} name={} (created_at: {:?})",
141        alice.id,
142        alice.name,
143        alice.created_at()
144    );
145
146    let mut bob = User::new("Bob", "bob@example.com").with_age(30);
147    db.create(&mut bob).await?;
148    println!("  ✅ Created: id={} name={}", bob.id, bob.name);
149
150    // First — GORM `db.First(&user, id)` equivalent
151    let found: Option<User> = db.first(&alice.id).await?;
152    match &found {
153        Some(u) => println!(
154            "  ✅ First: id={} name={} age={:?} status={}",
155            u.id, u.name, u.age, u.status
156        ),
157        None => println!("  ❌ First: not found"),
158    }
159
160    // Find all — GORM `db.Find(&users)` equivalent
161    let users: Vec<User> = db.all().await?;
162    println!("  ✅ Find: {} user(s)", users.len());
163    for u in &users {
164        println!(
165            "    - {} <{}> age={:?} status={}",
166            u.name, u.email, u.age, u.status
167        );
168    }
169
170    // Update — GORM `db.Model(&user).Update("age", 29)` equivalent
171    db.update(&mut alice, &[("age", 29)]).await?;
172    let updated: User = db.first(&alice.id).await?.expect("alice exists");
173    println!("  ✅ Updated: {} age now {:?}", updated.name, updated.age);
174
175    // Delete — GORM `db.Delete(&user)` equivalent
176    db.delete(&mut alice).await?;
177    let gone: Option<User> = db.first(&alice.id).await?;
178    println!(
179        "  ✅ Deleted: {} exists after delete = {}",
180        alice.name,
181        gone.is_some()
182    );
183
184    db.close().await?;
185    println!("  ✅ Database closed");
186
187    Ok(())
188}
More examples
Hide additional examples
examples/dapper_style.rs (line 91)
35async fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let db = Database::sqlite(":memory:").await?;
37
38    // 自动建表(依据模型 schema)
39    db.auto_migrate::<User>().await?;
40    println!("表 users 已自动创建\n");
41
42    // === 1. insert:无需手写 SqlValue,主键自动自增并回填 ===
43    println!("=== 1. Insert (自增主键自动回填) ===");
44    let mut alice = User::new("Alice", "alice@example.com", 25);
45    db.create(&mut alice).await?;
46    let mut bob = User::new("Bob", "bob@example.com", 17);
47    db.create(&mut bob).await?;
48    let mut carol = User::new("Carol", "carol@example.com", 30);
49    db.create(&mut carol).await?;
50    println!(
51        "  id 自动分配: Alice={} Bob={} Carol={}\n",
52        alice.id, bob.id, carol.id
53    );
54
55    // === 2. query:条件查询自动映射回 Vec<User> ===
56    println!("=== 2. Query (自动映射回 User) ===");
57    let adults: Vec<User> = Query::new("users")
58        .where_gte("age", 18)
59        .order_by_desc("age")
60        .query(&db)
61        .models::<User>()
62        .await?;
63    for u in &adults {
64        println!("  id={} name={} email={} age={}", u.id, u.name, u.email, u.age);
65    }
66
67    // 分页 + 条件
68    let first_two: Vec<User> = Query::new("users")
69        .where_gt("age", 0)
70        .order_by_asc("id")
71        .limit(2)
72        .query(&db)
73        .models::<User>()
74        .await?;
75    println!("  前 2 条: {:?}", first_two.iter().map(|u| &u.name).collect::<Vec<_>>());
76    println!();
77
78    // === 3. update:直接执行 SQL,返回影响行数 ===
79    println!("=== 3. Update ===");
80    let affected = db.update(&mut alice, &[("age", 26)]).await?;
81    println!("  更新 age 影响 {} 行", affected);
82
83    // 多列同类型(全为 &str)可直接批量更新
84    db.update(
85        &mut alice,
86        &[("email", "alice_new@example.com"), ("name", "Alice A.")],
87    )
88    .await?;
89
90    // 重新查询验证
91    let refreshed: User = db.first::<User>(&alice.id.to_string()).await?.unwrap();
92    println!(
93        "  更新后: name={} age={} email={}\n",
94        refreshed.name, refreshed.age, refreshed.email
95    );
96
97    // === 4. 条件删除 ===
98    println!("=== 4. Delete ===");
99    let removed = db.delete(&mut bob).await?;
100    println!("  删除 Bob 影响 {} 行", removed);
101    let remaining = db.all::<User>().await?;
102    println!("  剩余 {} 条: {:?}", remaining.len(), remaining.iter().map(|u| &u.name).collect::<Vec<_>>());
103
104    println!("\n✅ insert / query / update / delete 全程零 SqlValue,Dapper 风格完成!");
105    Ok(())
106}
examples/integration_example.rs (line 71)
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}
Source

pub async fn last<M: Model>(&self) -> Result<Option<M>, DbError>

GORM-style last: find the last model by primary key (descending).

Source

pub async fn all<M: Model>(&self) -> Result<Vec<M>, DbError>

GORM-style all: load all rows of the model’s table.

Examples found in repository?
examples/basic_usage.rs (line 258)
237async fn demonstrate_sql_engine() -> std::result::Result<(), Box<dyn std::error::Error>> {
238    println!("Pure Rust SQL engine (no rusqlite) + typed model:");
239    
240    let db = Database::sqlite(":memory:").await?;
241    
242    // 依据模型自动建表(零 SqlValue)
243    db.auto_migrate::<Product>().await?;
244    println!("  ✅ Created products table from model schema");
245    
246    // 通过模型 create 插入
247    let mut products = vec![
248        Product { id: 0, name: "Apple".to_string(), price: 5 },
249        Product { id: 0, name: "Banana".to_string(), price: 3 },
250        Product { id: 0, name: "Cherry".to_string(), price: 9 },
251    ];
252    for p in &mut products {
253        db.create(p).await?;
254    }
255    println!("  ✅ Inserted {} products", products.len());
256    
257    // 查询并映射回类型
258    let all: Vec<Product> = db.all::<Product>().await?;
259    println!("  ✅ Query returned {} rows", all.len());
260    for p in &all {
261        println!("    - {} price={}", p.name, p.price);
262    }
263    
264    // 更新(返回影响行数)
265    let affected = db.update(&mut products[0], &[("price", 6)]).await?;
266    println!("  ✅ Updated {} row(s)", affected);
267    
268    // 计数
269    let count = db.all::<Product>().await?.len();
270    println!("  ✅ Count = {}", count);
271    
272    // 删除(使用已回填主键的模型实例)
273    let affected = db.delete(&mut products[2]).await?;
274    println!("  ✅ Deleted {} row(s)", affected);
275    
276    db.close().await?;
277    println!("  ✅ Database closed");
278
279    Ok(())
280}
More examples
Hide additional examples
examples/complete_demo.rs (line 177)
151async fn demonstrate_database_file_connection() -> Result<(), Box<dyn std::error::Error>> {
152    println!("SQLite 连接:");
153    let dsn = Dsn::new(DBDriver::SQLite, "target/demo.db");
154    println!("  DSN: {}", dsn.build());
155    
156    let database = Database::sqlite("target/demo.db").await?;
157    println!("  ✅ 连接成功");
158    println!("  驱动: {:?}", database.db_type());
159    
160    // 测试连接
161    database.ping().await?;
162    println!("  ✅ Ping 成功");
163
164    // 依据模型自动建表并执行 CRUD,触发文件写入(零 SqlValue)
165    database.auto_migrate::<DemoUser>().await?;
166    println!("  ✅ 创建表成功(依据模型 schema)");
167
168    let mut users = vec![
169        DemoUser { id: 0, name: "Alice".into(), age: 25 },
170        DemoUser { id: 0, name: "Bob".into(), age: 30 },
171    ];
172    for u in &mut users {
173        database.create(u).await?;
174    }
175    println!("  ✅ 插入数据成功");
176
177    let all: Vec<DemoUser> = database.all::<DemoUser>().await?;
178    println!("  ✅ 查询返回 {} 行", all.len());
179
180    database.close().await?;
181    println!("  ✅ 数据库已关闭,数据已保存到 demo.db");
182    
183    println!();
184    println!("MySQL 连接示例:");
185    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
186        .with_host("localhost")
187        .with_port(3306)
188        .with_username("user")
189        .with_password("password");
190    println!("  DSN: {}", mysql_dsn.build());
191    
192    println!();
193    println!("PostgreSQL 连接示例:");
194    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
195        .with_host("localhost")
196        .with_port(5432)
197        .with_username("user")
198        .with_password("password");
199    println!("  DSN: {}", pg_dsn.build());
200
201    Ok(())
202}
examples/postgresql_example.rs (line 161)
115async fn demonstrate_crud() -> std::result::Result<(), Box<dyn std::error::Error>> {
116    println!("GORM-style model CRUD (create / first / find / update / delete):");
117    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
118
119    // Schema setup (GORM AutoMigrate equivalent — drop + recreate for a clean demo)
120    db.execute("DROP TABLE IF EXISTS users", &[]).await?;
121    db.execute(
122        "CREATE TABLE users (
123            id TEXT PRIMARY KEY,
124            name TEXT NOT NULL,
125            email TEXT,
126            age INTEGER,
127            status TEXT,
128            created_at TIMESTAMPTZ,
129            updated_at TIMESTAMPTZ
130        )",
131        &[],
132    )
133    .await?;
134    println!("  ✅ Schema ready (users table recreated)");
135
136    // Create — GORM `db.Create(&user)` equivalent
137    let mut alice = User::new("Alice", "alice@example.com").with_age(25);
138    db.create(&mut alice).await?;
139    println!(
140        "  ✅ Created: id={} name={} (created_at: {:?})",
141        alice.id,
142        alice.name,
143        alice.created_at()
144    );
145
146    let mut bob = User::new("Bob", "bob@example.com").with_age(30);
147    db.create(&mut bob).await?;
148    println!("  ✅ Created: id={} name={}", bob.id, bob.name);
149
150    // First — GORM `db.First(&user, id)` equivalent
151    let found: Option<User> = db.first(&alice.id).await?;
152    match &found {
153        Some(u) => println!(
154            "  ✅ First: id={} name={} age={:?} status={}",
155            u.id, u.name, u.age, u.status
156        ),
157        None => println!("  ❌ First: not found"),
158    }
159
160    // Find all — GORM `db.Find(&users)` equivalent
161    let users: Vec<User> = db.all().await?;
162    println!("  ✅ Find: {} user(s)", users.len());
163    for u in &users {
164        println!(
165            "    - {} <{}> age={:?} status={}",
166            u.name, u.email, u.age, u.status
167        );
168    }
169
170    // Update — GORM `db.Model(&user).Update("age", 29)` equivalent
171    db.update(&mut alice, &[("age", 29)]).await?;
172    let updated: User = db.first(&alice.id).await?.expect("alice exists");
173    println!("  ✅ Updated: {} age now {:?}", updated.name, updated.age);
174
175    // Delete — GORM `db.Delete(&user)` equivalent
176    db.delete(&mut alice).await?;
177    let gone: Option<User> = db.first(&alice.id).await?;
178    println!(
179        "  ✅ Deleted: {} exists after delete = {}",
180        alice.name,
181        gone.is_some()
182    );
183
184    db.close().await?;
185    println!("  ✅ Database closed");
186
187    Ok(())
188}
examples/dapper_style.rs (line 101)
35async fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let db = Database::sqlite(":memory:").await?;
37
38    // 自动建表(依据模型 schema)
39    db.auto_migrate::<User>().await?;
40    println!("表 users 已自动创建\n");
41
42    // === 1. insert:无需手写 SqlValue,主键自动自增并回填 ===
43    println!("=== 1. Insert (自增主键自动回填) ===");
44    let mut alice = User::new("Alice", "alice@example.com", 25);
45    db.create(&mut alice).await?;
46    let mut bob = User::new("Bob", "bob@example.com", 17);
47    db.create(&mut bob).await?;
48    let mut carol = User::new("Carol", "carol@example.com", 30);
49    db.create(&mut carol).await?;
50    println!(
51        "  id 自动分配: Alice={} Bob={} Carol={}\n",
52        alice.id, bob.id, carol.id
53    );
54
55    // === 2. query:条件查询自动映射回 Vec<User> ===
56    println!("=== 2. Query (自动映射回 User) ===");
57    let adults: Vec<User> = Query::new("users")
58        .where_gte("age", 18)
59        .order_by_desc("age")
60        .query(&db)
61        .models::<User>()
62        .await?;
63    for u in &adults {
64        println!("  id={} name={} email={} age={}", u.id, u.name, u.email, u.age);
65    }
66
67    // 分页 + 条件
68    let first_two: Vec<User> = Query::new("users")
69        .where_gt("age", 0)
70        .order_by_asc("id")
71        .limit(2)
72        .query(&db)
73        .models::<User>()
74        .await?;
75    println!("  前 2 条: {:?}", first_two.iter().map(|u| &u.name).collect::<Vec<_>>());
76    println!();
77
78    // === 3. update:直接执行 SQL,返回影响行数 ===
79    println!("=== 3. Update ===");
80    let affected = db.update(&mut alice, &[("age", 26)]).await?;
81    println!("  更新 age 影响 {} 行", affected);
82
83    // 多列同类型(全为 &str)可直接批量更新
84    db.update(
85        &mut alice,
86        &[("email", "alice_new@example.com"), ("name", "Alice A.")],
87    )
88    .await?;
89
90    // 重新查询验证
91    let refreshed: User = db.first::<User>(&alice.id.to_string()).await?.unwrap();
92    println!(
93        "  更新后: name={} age={} email={}\n",
94        refreshed.name, refreshed.age, refreshed.email
95    );
96
97    // === 4. 条件删除 ===
98    println!("=== 4. Delete ===");
99    let removed = db.delete(&mut bob).await?;
100    println!("  删除 Bob 影响 {} 行", removed);
101    let remaining = db.all::<User>().await?;
102    println!("  剩余 {} 条: {:?}", remaining.len(), remaining.iter().map(|u| &u.name).collect::<Vec<_>>());
103
104    println!("\n✅ insert / query / update / delete 全程零 SqlValue,Dapper 风格完成!");
105    Ok(())
106}
examples/integration_example.rs (line 73)
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}
Source

pub async fn update<M: Model, V: Clone + Into<SqlValue>>( &self, model: &mut M, updates: &[(&str, V)], ) -> Result<u64, DbError>

Dapper-style update: UPDATE the given columns of the model, matched by primary key. Executes the SQL directly and returns the number of affected rows. Runs the before_update/after_update hooks and refreshes updated_at.

值参数 V: Into<SqlValue> 接受原生 Rust 值(i32/f64/&str/String/ bool 等),无需手写 SqlValue::*。适用于各列值类型相同的场景 (如全为 &str 或全为整数):

let n = db.update(&mut user, &[("name", "a"), ("email", "b")]).await?;
let n = db.update(&mut user, &[("age", 30)]).await?;

若各列值类型不同(age 为整数、email 为字符串),将值统一为 SqlValue 即可,例如:

let n = db
    .update(&mut user, &[("age", SqlValue::I32(30)), ("email", SqlValue::String("x".into()))])
    .await?;
Examples found in repository?
examples/basic_usage.rs (line 265)
237async fn demonstrate_sql_engine() -> std::result::Result<(), Box<dyn std::error::Error>> {
238    println!("Pure Rust SQL engine (no rusqlite) + typed model:");
239    
240    let db = Database::sqlite(":memory:").await?;
241    
242    // 依据模型自动建表(零 SqlValue)
243    db.auto_migrate::<Product>().await?;
244    println!("  ✅ Created products table from model schema");
245    
246    // 通过模型 create 插入
247    let mut products = vec![
248        Product { id: 0, name: "Apple".to_string(), price: 5 },
249        Product { id: 0, name: "Banana".to_string(), price: 3 },
250        Product { id: 0, name: "Cherry".to_string(), price: 9 },
251    ];
252    for p in &mut products {
253        db.create(p).await?;
254    }
255    println!("  ✅ Inserted {} products", products.len());
256    
257    // 查询并映射回类型
258    let all: Vec<Product> = db.all::<Product>().await?;
259    println!("  ✅ Query returned {} rows", all.len());
260    for p in &all {
261        println!("    - {} price={}", p.name, p.price);
262    }
263    
264    // 更新(返回影响行数)
265    let affected = db.update(&mut products[0], &[("price", 6)]).await?;
266    println!("  ✅ Updated {} row(s)", affected);
267    
268    // 计数
269    let count = db.all::<Product>().await?.len();
270    println!("  ✅ Count = {}", count);
271    
272    // 删除(使用已回填主键的模型实例)
273    let affected = db.delete(&mut products[2]).await?;
274    println!("  ✅ Deleted {} row(s)", affected);
275    
276    db.close().await?;
277    println!("  ✅ Database closed");
278
279    Ok(())
280}
More examples
Hide additional examples
examples/postgresql_example.rs (line 171)
115async fn demonstrate_crud() -> std::result::Result<(), Box<dyn std::error::Error>> {
116    println!("GORM-style model CRUD (create / first / find / update / delete):");
117    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
118
119    // Schema setup (GORM AutoMigrate equivalent — drop + recreate for a clean demo)
120    db.execute("DROP TABLE IF EXISTS users", &[]).await?;
121    db.execute(
122        "CREATE TABLE users (
123            id TEXT PRIMARY KEY,
124            name TEXT NOT NULL,
125            email TEXT,
126            age INTEGER,
127            status TEXT,
128            created_at TIMESTAMPTZ,
129            updated_at TIMESTAMPTZ
130        )",
131        &[],
132    )
133    .await?;
134    println!("  ✅ Schema ready (users table recreated)");
135
136    // Create — GORM `db.Create(&user)` equivalent
137    let mut alice = User::new("Alice", "alice@example.com").with_age(25);
138    db.create(&mut alice).await?;
139    println!(
140        "  ✅ Created: id={} name={} (created_at: {:?})",
141        alice.id,
142        alice.name,
143        alice.created_at()
144    );
145
146    let mut bob = User::new("Bob", "bob@example.com").with_age(30);
147    db.create(&mut bob).await?;
148    println!("  ✅ Created: id={} name={}", bob.id, bob.name);
149
150    // First — GORM `db.First(&user, id)` equivalent
151    let found: Option<User> = db.first(&alice.id).await?;
152    match &found {
153        Some(u) => println!(
154            "  ✅ First: id={} name={} age={:?} status={}",
155            u.id, u.name, u.age, u.status
156        ),
157        None => println!("  ❌ First: not found"),
158    }
159
160    // Find all — GORM `db.Find(&users)` equivalent
161    let users: Vec<User> = db.all().await?;
162    println!("  ✅ Find: {} user(s)", users.len());
163    for u in &users {
164        println!(
165            "    - {} <{}> age={:?} status={}",
166            u.name, u.email, u.age, u.status
167        );
168    }
169
170    // Update — GORM `db.Model(&user).Update("age", 29)` equivalent
171    db.update(&mut alice, &[("age", 29)]).await?;
172    let updated: User = db.first(&alice.id).await?.expect("alice exists");
173    println!("  ✅ Updated: {} age now {:?}", updated.name, updated.age);
174
175    // Delete — GORM `db.Delete(&user)` equivalent
176    db.delete(&mut alice).await?;
177    let gone: Option<User> = db.first(&alice.id).await?;
178    println!(
179        "  ✅ Deleted: {} exists after delete = {}",
180        alice.name,
181        gone.is_some()
182    );
183
184    db.close().await?;
185    println!("  ✅ Database closed");
186
187    Ok(())
188}
examples/dapper_style.rs (line 80)
35async fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let db = Database::sqlite(":memory:").await?;
37
38    // 自动建表(依据模型 schema)
39    db.auto_migrate::<User>().await?;
40    println!("表 users 已自动创建\n");
41
42    // === 1. insert:无需手写 SqlValue,主键自动自增并回填 ===
43    println!("=== 1. Insert (自增主键自动回填) ===");
44    let mut alice = User::new("Alice", "alice@example.com", 25);
45    db.create(&mut alice).await?;
46    let mut bob = User::new("Bob", "bob@example.com", 17);
47    db.create(&mut bob).await?;
48    let mut carol = User::new("Carol", "carol@example.com", 30);
49    db.create(&mut carol).await?;
50    println!(
51        "  id 自动分配: Alice={} Bob={} Carol={}\n",
52        alice.id, bob.id, carol.id
53    );
54
55    // === 2. query:条件查询自动映射回 Vec<User> ===
56    println!("=== 2. Query (自动映射回 User) ===");
57    let adults: Vec<User> = Query::new("users")
58        .where_gte("age", 18)
59        .order_by_desc("age")
60        .query(&db)
61        .models::<User>()
62        .await?;
63    for u in &adults {
64        println!("  id={} name={} email={} age={}", u.id, u.name, u.email, u.age);
65    }
66
67    // 分页 + 条件
68    let first_two: Vec<User> = Query::new("users")
69        .where_gt("age", 0)
70        .order_by_asc("id")
71        .limit(2)
72        .query(&db)
73        .models::<User>()
74        .await?;
75    println!("  前 2 条: {:?}", first_two.iter().map(|u| &u.name).collect::<Vec<_>>());
76    println!();
77
78    // === 3. update:直接执行 SQL,返回影响行数 ===
79    println!("=== 3. Update ===");
80    let affected = db.update(&mut alice, &[("age", 26)]).await?;
81    println!("  更新 age 影响 {} 行", affected);
82
83    // 多列同类型(全为 &str)可直接批量更新
84    db.update(
85        &mut alice,
86        &[("email", "alice_new@example.com"), ("name", "Alice A.")],
87    )
88    .await?;
89
90    // 重新查询验证
91    let refreshed: User = db.first::<User>(&alice.id.to_string()).await?.unwrap();
92    println!(
93        "  更新后: name={} age={} email={}\n",
94        refreshed.name, refreshed.age, refreshed.email
95    );
96
97    // === 4. 条件删除 ===
98    println!("=== 4. Delete ===");
99    let removed = db.delete(&mut bob).await?;
100    println!("  删除 Bob 影响 {} 行", removed);
101    let remaining = db.all::<User>().await?;
102    println!("  剩余 {} 条: {:?}", remaining.len(), remaining.iter().map(|u| &u.name).collect::<Vec<_>>());
103
104    println!("\n✅ insert / query / update / delete 全程零 SqlValue,Dapper 风格完成!");
105    Ok(())
106}
examples/integration_example.rs (line 78)
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}
Source

pub async fn delete<M: Model>(&self, model: &mut M) -> Result<u64, DbError>

GORM-style delete: DELETE the model row matched by primary key. Runs the before_delete/after_delete hooks.

Examples found in repository?
examples/basic_usage.rs (line 273)
237async fn demonstrate_sql_engine() -> std::result::Result<(), Box<dyn std::error::Error>> {
238    println!("Pure Rust SQL engine (no rusqlite) + typed model:");
239    
240    let db = Database::sqlite(":memory:").await?;
241    
242    // 依据模型自动建表(零 SqlValue)
243    db.auto_migrate::<Product>().await?;
244    println!("  ✅ Created products table from model schema");
245    
246    // 通过模型 create 插入
247    let mut products = vec![
248        Product { id: 0, name: "Apple".to_string(), price: 5 },
249        Product { id: 0, name: "Banana".to_string(), price: 3 },
250        Product { id: 0, name: "Cherry".to_string(), price: 9 },
251    ];
252    for p in &mut products {
253        db.create(p).await?;
254    }
255    println!("  ✅ Inserted {} products", products.len());
256    
257    // 查询并映射回类型
258    let all: Vec<Product> = db.all::<Product>().await?;
259    println!("  ✅ Query returned {} rows", all.len());
260    for p in &all {
261        println!("    - {} price={}", p.name, p.price);
262    }
263    
264    // 更新(返回影响行数)
265    let affected = db.update(&mut products[0], &[("price", 6)]).await?;
266    println!("  ✅ Updated {} row(s)", affected);
267    
268    // 计数
269    let count = db.all::<Product>().await?.len();
270    println!("  ✅ Count = {}", count);
271    
272    // 删除(使用已回填主键的模型实例)
273    let affected = db.delete(&mut products[2]).await?;
274    println!("  ✅ Deleted {} row(s)", affected);
275    
276    db.close().await?;
277    println!("  ✅ Database closed");
278
279    Ok(())
280}
More examples
Hide additional examples
examples/postgresql_example.rs (line 176)
115async fn demonstrate_crud() -> std::result::Result<(), Box<dyn std::error::Error>> {
116    println!("GORM-style model CRUD (create / first / find / update / delete):");
117    let db = Database::postgresql(PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASS).await?;
118
119    // Schema setup (GORM AutoMigrate equivalent — drop + recreate for a clean demo)
120    db.execute("DROP TABLE IF EXISTS users", &[]).await?;
121    db.execute(
122        "CREATE TABLE users (
123            id TEXT PRIMARY KEY,
124            name TEXT NOT NULL,
125            email TEXT,
126            age INTEGER,
127            status TEXT,
128            created_at TIMESTAMPTZ,
129            updated_at TIMESTAMPTZ
130        )",
131        &[],
132    )
133    .await?;
134    println!("  ✅ Schema ready (users table recreated)");
135
136    // Create — GORM `db.Create(&user)` equivalent
137    let mut alice = User::new("Alice", "alice@example.com").with_age(25);
138    db.create(&mut alice).await?;
139    println!(
140        "  ✅ Created: id={} name={} (created_at: {:?})",
141        alice.id,
142        alice.name,
143        alice.created_at()
144    );
145
146    let mut bob = User::new("Bob", "bob@example.com").with_age(30);
147    db.create(&mut bob).await?;
148    println!("  ✅ Created: id={} name={}", bob.id, bob.name);
149
150    // First — GORM `db.First(&user, id)` equivalent
151    let found: Option<User> = db.first(&alice.id).await?;
152    match &found {
153        Some(u) => println!(
154            "  ✅ First: id={} name={} age={:?} status={}",
155            u.id, u.name, u.age, u.status
156        ),
157        None => println!("  ❌ First: not found"),
158    }
159
160    // Find all — GORM `db.Find(&users)` equivalent
161    let users: Vec<User> = db.all().await?;
162    println!("  ✅ Find: {} user(s)", users.len());
163    for u in &users {
164        println!(
165            "    - {} <{}> age={:?} status={}",
166            u.name, u.email, u.age, u.status
167        );
168    }
169
170    // Update — GORM `db.Model(&user).Update("age", 29)` equivalent
171    db.update(&mut alice, &[("age", 29)]).await?;
172    let updated: User = db.first(&alice.id).await?.expect("alice exists");
173    println!("  ✅ Updated: {} age now {:?}", updated.name, updated.age);
174
175    // Delete — GORM `db.Delete(&user)` equivalent
176    db.delete(&mut alice).await?;
177    let gone: Option<User> = db.first(&alice.id).await?;
178    println!(
179        "  ✅ Deleted: {} exists after delete = {}",
180        alice.name,
181        gone.is_some()
182    );
183
184    db.close().await?;
185    println!("  ✅ Database closed");
186
187    Ok(())
188}
examples/dapper_style.rs (line 99)
35async fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let db = Database::sqlite(":memory:").await?;
37
38    // 自动建表(依据模型 schema)
39    db.auto_migrate::<User>().await?;
40    println!("表 users 已自动创建\n");
41
42    // === 1. insert:无需手写 SqlValue,主键自动自增并回填 ===
43    println!("=== 1. Insert (自增主键自动回填) ===");
44    let mut alice = User::new("Alice", "alice@example.com", 25);
45    db.create(&mut alice).await?;
46    let mut bob = User::new("Bob", "bob@example.com", 17);
47    db.create(&mut bob).await?;
48    let mut carol = User::new("Carol", "carol@example.com", 30);
49    db.create(&mut carol).await?;
50    println!(
51        "  id 自动分配: Alice={} Bob={} Carol={}\n",
52        alice.id, bob.id, carol.id
53    );
54
55    // === 2. query:条件查询自动映射回 Vec<User> ===
56    println!("=== 2. Query (自动映射回 User) ===");
57    let adults: Vec<User> = Query::new("users")
58        .where_gte("age", 18)
59        .order_by_desc("age")
60        .query(&db)
61        .models::<User>()
62        .await?;
63    for u in &adults {
64        println!("  id={} name={} email={} age={}", u.id, u.name, u.email, u.age);
65    }
66
67    // 分页 + 条件
68    let first_two: Vec<User> = Query::new("users")
69        .where_gt("age", 0)
70        .order_by_asc("id")
71        .limit(2)
72        .query(&db)
73        .models::<User>()
74        .await?;
75    println!("  前 2 条: {:?}", first_two.iter().map(|u| &u.name).collect::<Vec<_>>());
76    println!();
77
78    // === 3. update:直接执行 SQL,返回影响行数 ===
79    println!("=== 3. Update ===");
80    let affected = db.update(&mut alice, &[("age", 26)]).await?;
81    println!("  更新 age 影响 {} 行", affected);
82
83    // 多列同类型(全为 &str)可直接批量更新
84    db.update(
85        &mut alice,
86        &[("email", "alice_new@example.com"), ("name", "Alice A.")],
87    )
88    .await?;
89
90    // 重新查询验证
91    let refreshed: User = db.first::<User>(&alice.id.to_string()).await?.unwrap();
92    println!(
93        "  更新后: name={} age={} email={}\n",
94        refreshed.name, refreshed.age, refreshed.email
95    );
96
97    // === 4. 条件删除 ===
98    println!("=== 4. Delete ===");
99    let removed = db.delete(&mut bob).await?;
100    println!("  删除 Bob 影响 {} 行", removed);
101    let remaining = db.all::<User>().await?;
102    println!("  剩余 {} 条: {:?}", remaining.len(), remaining.iter().map(|u| &u.name).collect::<Vec<_>>());
103
104    println!("\n✅ insert / query / update / delete 全程零 SqlValue,Dapper 风格完成!");
105    Ok(())
106}
examples/integration_example.rs (line 85)
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}
Source

pub async fn auto_migrate<M: Model>(&self) -> Result<(), DbError>

GORM-style auto migration: create the model’s table (if missing) and all of its indexes (primary key, index, uniqueIndex) based on the TableDefinition produced by Model::schema().

Idempotent: uses IF NOT EXISTS so it is safe to call on every startup.

Examples found in repository?
examples/basic_usage.rs (line 243)
237async fn demonstrate_sql_engine() -> std::result::Result<(), Box<dyn std::error::Error>> {
238    println!("Pure Rust SQL engine (no rusqlite) + typed model:");
239    
240    let db = Database::sqlite(":memory:").await?;
241    
242    // 依据模型自动建表(零 SqlValue)
243    db.auto_migrate::<Product>().await?;
244    println!("  ✅ Created products table from model schema");
245    
246    // 通过模型 create 插入
247    let mut products = vec![
248        Product { id: 0, name: "Apple".to_string(), price: 5 },
249        Product { id: 0, name: "Banana".to_string(), price: 3 },
250        Product { id: 0, name: "Cherry".to_string(), price: 9 },
251    ];
252    for p in &mut products {
253        db.create(p).await?;
254    }
255    println!("  ✅ Inserted {} products", products.len());
256    
257    // 查询并映射回类型
258    let all: Vec<Product> = db.all::<Product>().await?;
259    println!("  ✅ Query returned {} rows", all.len());
260    for p in &all {
261        println!("    - {} price={}", p.name, p.price);
262    }
263    
264    // 更新(返回影响行数)
265    let affected = db.update(&mut products[0], &[("price", 6)]).await?;
266    println!("  ✅ Updated {} row(s)", affected);
267    
268    // 计数
269    let count = db.all::<Product>().await?.len();
270    println!("  ✅ Count = {}", count);
271    
272    // 删除(使用已回填主键的模型实例)
273    let affected = db.delete(&mut products[2]).await?;
274    println!("  ✅ Deleted {} row(s)", affected);
275    
276    db.close().await?;
277    println!("  ✅ Database closed");
278
279    Ok(())
280}
More examples
Hide additional examples
examples/complete_demo.rs (line 165)
151async fn demonstrate_database_file_connection() -> Result<(), Box<dyn std::error::Error>> {
152    println!("SQLite 连接:");
153    let dsn = Dsn::new(DBDriver::SQLite, "target/demo.db");
154    println!("  DSN: {}", dsn.build());
155    
156    let database = Database::sqlite("target/demo.db").await?;
157    println!("  ✅ 连接成功");
158    println!("  驱动: {:?}", database.db_type());
159    
160    // 测试连接
161    database.ping().await?;
162    println!("  ✅ Ping 成功");
163
164    // 依据模型自动建表并执行 CRUD,触发文件写入(零 SqlValue)
165    database.auto_migrate::<DemoUser>().await?;
166    println!("  ✅ 创建表成功(依据模型 schema)");
167
168    let mut users = vec![
169        DemoUser { id: 0, name: "Alice".into(), age: 25 },
170        DemoUser { id: 0, name: "Bob".into(), age: 30 },
171    ];
172    for u in &mut users {
173        database.create(u).await?;
174    }
175    println!("  ✅ 插入数据成功");
176
177    let all: Vec<DemoUser> = database.all::<DemoUser>().await?;
178    println!("  ✅ 查询返回 {} 行", all.len());
179
180    database.close().await?;
181    println!("  ✅ 数据库已关闭,数据已保存到 demo.db");
182    
183    println!();
184    println!("MySQL 连接示例:");
185    let mysql_dsn = Dsn::new(DBDriver::MySQL, "mydb")
186        .with_host("localhost")
187        .with_port(3306)
188        .with_username("user")
189        .with_password("password");
190    println!("  DSN: {}", mysql_dsn.build());
191    
192    println!();
193    println!("PostgreSQL 连接示例:");
194    let pg_dsn = Dsn::new(DBDriver::PostgreSQL, "mydb")
195        .with_host("localhost")
196        .with_port(5432)
197        .with_username("user")
198        .with_password("password");
199    println!("  DSN: {}", pg_dsn.build());
200
201    Ok(())
202}
examples/async_concurrency.rs (line 51)
47async fn database_concurrency() -> Result<(), Box<dyn std::error::Error>> {
48    let db = Arc::new(Database::sqlite(":memory:").await?);
49
50    // 依据 Product 模型自动建表。
51    db.auto_migrate::<Product>().await?;
52
53    // 预置数据:通过模型 create,零 SqlValue。
54    for i in 0..100 {
55        let mut p = Product {
56            id: 0,
57            name: format!("product_{}", i),
58            price: i,
59        };
60        db.create(&mut p).await?;
61    }
62
63    // 并发执行多个查询任务(按页读取,映射回模型)。
64    let mut handles = Vec::new();
65    for offset in (0..100).step_by(25) {
66        let db = Arc::clone(&db);
67        handles.push(tokio::spawn(async move {
68            let products: Vec<Product> = Query::new("products")
69                .order_by_asc("id")
70                .limit(25)
71                .offset(offset)
72                .query(&db)
73                .models::<Product>()
74                .await?;
75            Ok::<usize, torm::db::database::DbError>(products.len())
76        }));
77    }
78
79    let mut total = 0usize;
80    for h in handles {
81        total += h.await??;
82    }
83    println!("  4 concurrent queries fetched {} rows in total.", total);
84
85    // 使用 Query builder 并发查询(值类型自动转换,无需手写 SqlValue::I32)
86    let mut handles = Vec::new();
87    for min_price in [10i64, 20, 30, 40] {
88        let db = Arc::clone(&db);
89        handles.push(tokio::spawn(async move {
90            Query::new("products")
91                .where_gt("price", min_price)
92                .query(&db)
93                .count()
94                .await
95        }));
96    }
97    for (i, h) in handles.into_iter().enumerate() {
98        let count = h.await??;
99        let n = count
100            .rows
101            .first()
102            .and_then(|r| r.get("COUNT(*)").or_else(|| r.get("count")))
103            .and_then(|v| v.as_i64())
104            .unwrap_or(0);
105        println!("  price > {}  -> {} products", [10, 20, 30, 40][i], n);
106    }
107
108    Ok(())
109}
examples/dapper_style.rs (line 39)
35async fn main() -> Result<(), Box<dyn std::error::Error>> {
36    let db = Database::sqlite(":memory:").await?;
37
38    // 自动建表(依据模型 schema)
39    db.auto_migrate::<User>().await?;
40    println!("表 users 已自动创建\n");
41
42    // === 1. insert:无需手写 SqlValue,主键自动自增并回填 ===
43    println!("=== 1. Insert (自增主键自动回填) ===");
44    let mut alice = User::new("Alice", "alice@example.com", 25);
45    db.create(&mut alice).await?;
46    let mut bob = User::new("Bob", "bob@example.com", 17);
47    db.create(&mut bob).await?;
48    let mut carol = User::new("Carol", "carol@example.com", 30);
49    db.create(&mut carol).await?;
50    println!(
51        "  id 自动分配: Alice={} Bob={} Carol={}\n",
52        alice.id, bob.id, carol.id
53    );
54
55    // === 2. query:条件查询自动映射回 Vec<User> ===
56    println!("=== 2. Query (自动映射回 User) ===");
57    let adults: Vec<User> = Query::new("users")
58        .where_gte("age", 18)
59        .order_by_desc("age")
60        .query(&db)
61        .models::<User>()
62        .await?;
63    for u in &adults {
64        println!("  id={} name={} email={} age={}", u.id, u.name, u.email, u.age);
65    }
66
67    // 分页 + 条件
68    let first_two: Vec<User> = Query::new("users")
69        .where_gt("age", 0)
70        .order_by_asc("id")
71        .limit(2)
72        .query(&db)
73        .models::<User>()
74        .await?;
75    println!("  前 2 条: {:?}", first_two.iter().map(|u| &u.name).collect::<Vec<_>>());
76    println!();
77
78    // === 3. update:直接执行 SQL,返回影响行数 ===
79    println!("=== 3. Update ===");
80    let affected = db.update(&mut alice, &[("age", 26)]).await?;
81    println!("  更新 age 影响 {} 行", affected);
82
83    // 多列同类型(全为 &str)可直接批量更新
84    db.update(
85        &mut alice,
86        &[("email", "alice_new@example.com"), ("name", "Alice A.")],
87    )
88    .await?;
89
90    // 重新查询验证
91    let refreshed: User = db.first::<User>(&alice.id.to_string()).await?.unwrap();
92    println!(
93        "  更新后: name={} age={} email={}\n",
94        refreshed.name, refreshed.age, refreshed.email
95    );
96
97    // === 4. 条件删除 ===
98    println!("=== 4. Delete ===");
99    let removed = db.delete(&mut bob).await?;
100    println!("  删除 Bob 影响 {} 行", removed);
101    let remaining = db.all::<User>().await?;
102    println!("  剩余 {} 条: {:?}", remaining.len(), remaining.iter().map(|u| &u.name).collect::<Vec<_>>());
103
104    println!("\n✅ insert / query / update / delete 全程零 SqlValue,Dapper 风格完成!");
105    Ok(())
106}
examples/integration_example.rs (line 40)
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}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V