yang-db 0.1.3

个人使用数据库操作
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use crate::error::DbError;
use crate::mysql::condition::{Condition, SqlValue};
use crate::mysql::field::FieldType;
use sqlx::Transaction as SqlxTransaction;
use std::collections::HashMap;

/// 数据库事务
pub struct Transaction {
    tx: Option<SqlxTransaction<'static, sqlx::MySql>>,
    enable_logging: bool,
}

impl Transaction {
    /// 创建新的事务实例
    pub(crate) fn new(tx: SqlxTransaction<'static, sqlx::MySql>, enable_logging: bool) -> Self {
        Self {
            tx: Some(tx),
            enable_logging,
        }
    }

    /// 提交事务
    pub async fn commit(mut self) -> Result<(), DbError> {
        if self.enable_logging {
            log::debug!("提交事务");
        }

        if let Some(tx) = self.tx.take() {
            tx.commit().await?;
        }

        Ok(())
    }

    /// 回滚事务
    pub async fn rollback(mut self) -> Result<(), DbError> {
        if self.enable_logging {
            log::debug!("回滚事务");
        }

        if let Some(tx) = self.tx.take() {
            tx.rollback().await?;
        }

        Ok(())
    }

    /// 执行原生 SQL
    pub async fn execute(&mut self, sql: &str) -> Result<u64, DbError> {
        if self.enable_logging {
            log::debug!("事务中执行: {}", sql);
        }

        if let Some(tx) = &mut self.tx {
            let result = sqlx::query(sql).execute(&mut **tx).await?;
            Ok(result.rows_affected())
        } else {
            Err(DbError::TransactionError("事务已提交或回滚".to_string()))
        }
    }

    /// 执行带参数的原生 SQL(参数化查询,防止 SQL 注入)
    ///
    /// # 参数
    /// - sql: SQL 语句,使用 `?` 作为参数占位符
    /// - params: 参数列表,使用 `serde_json::Value` 类型
    ///
    /// # 返回
    /// - Ok(u64): 受影响的行数
    /// - Err(DbError): 执行失败错误
    ///
    /// # 示例
    ///
    /// ```no_run
    /// use yang_db::Database;
    /// use serde_json::json;
    ///
    /// # async fn example() -> Result<(), yang_db::DbError> {
    /// let db = Database::connect("mysql://root:password@localhost/test").await?;
    /// let mut tx = db.transaction().await?;
    /// let params = vec![json!("张三"), json!("张三@example.com")];
    /// tx.execute_with_params("INSERT INTO users (name, email) VALUES (?, ?)", params).await?;
    /// tx.commit().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn execute_with_params(
        &mut self,
        sql: &str,
        params: Vec<serde_json::Value>,
    ) -> Result<u64, DbError> {
        if self.enable_logging {
            log::debug!("事务中执行参数化语句: {}, 参数数量: {}", sql, params.len());
        }

        if let Some(tx) = &mut self.tx {
            // 构建查询并逐一绑定参数
            let mut query = sqlx::query(sql);
            for param in &params {
                query = bind_json_param_tx(query, param);
            }
            let result = query.execute(&mut **tx).await?;
            Ok(result.rows_affected())
        } else {
            Err(DbError::TransactionError("事务已提交或回滚".to_string()))
        }
    }

    /// 执行带参数的原生 SELECT 查询(参数化查询,防止 SQL 注入)
    ///
    /// # 参数
    /// - sql: SQL 查询语句,使用 `?` 作为参数占位符
    /// - params: 参数列表,使用 `serde_json::Value` 类型
    ///
    /// # 返回
    /// - Ok(Vec<T>): 查询结果列表
    /// - Err(DbError): 查询失败错误
    ///
    /// # 示例
    ///
    /// ```no_run
    /// use yang_db::Database;
    /// use serde_json::json;
    ///
    /// # async fn example() -> Result<(), yang_db::DbError> {
    /// let db = Database::connect("mysql://root:password@localhost/test").await?;
    /// let mut tx = db.transaction().await?;
    /// let params = vec![json!(1i64)];
    /// // let users: Vec<User> = tx.query_with_params("SELECT * FROM users WHERE id = ?", params).await?;
    /// tx.commit().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn query_with_params<T>(
        &mut self,
        sql: &str,
        params: Vec<serde_json::Value>,
    ) -> Result<Vec<T>, DbError>
    where
        T: for<'r> sqlx::FromRow<'r, sqlx::mysql::MySqlRow> + Send + Unpin,
    {
        if self.enable_logging {
            log::debug!("事务中执行参数化查询: {}, 参数数量: {}", sql, params.len());
        }

        if let Some(tx) = &mut self.tx {
            // 构建查询并逐一绑定参数
            let mut query = sqlx::query_as::<_, T>(sql);
            for param in &params {
                query = bind_json_param_as_tx(query, param);
            }
            let rows = query.fetch_all(&mut **tx).await?;
            Ok(rows)
        } else {
            Err(DbError::TransactionError("事务已提交或回滚".to_string()))
        }
    }

    /// 选择表,返回事务中的查询构建器
    ///
    /// # 参数
    /// - table_name: 表名
    ///
    /// # 返回
    /// - TransactionQueryBuilder: 事务查询构建器
    ///
    /// # 示例
    /// ```no_run
    /// use yang_db::Database;
    /// use serde_json::json;
    ///
    /// # async fn example() -> Result<(), yang_db::DbError> {
    /// let db = Database::connect("mysql://root:password@localhost/test").await?;
    /// let mut tx = db.transaction().await?;
    ///
    /// // 在事务中插入数据
    /// let user_data = json!({"name": "张三", "email": "zhangsan@example.com"});
    /// let user_id = tx.table("users").insert(&user_data).await?;
    ///
    /// // 在事务中更新数据
    /// let update_data = json!({"status": 1});
    /// tx.table("users")
    ///     .where_and("id", "=", user_id)
    ///     .update(&update_data)
    ///     .await?;
    ///
    /// // 提交事务
    /// tx.commit().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn table(&mut self, table_name: &str) -> TransactionQueryBuilder<'_> {
        TransactionQueryBuilder::new(self, table_name)
    }
}

/// 事务查询构建器
///
/// 用于在事务上下文中构建和执行查询
pub struct TransactionQueryBuilder<'a> {
    tx: &'a mut Transaction,
    table: String,
    conditions: Vec<Condition>,
    field_types: HashMap<String, FieldType>,
}

impl<'a> TransactionQueryBuilder<'a> {
    /// 创建新的事务查询构建器
    fn new(tx: &'a mut Transaction, table_name: &str) -> Self {
        Self {
            tx,
            table: table_name.to_string(),
            conditions: Vec::new(),
            field_types: HashMap::new(),
        }
    }

    /// 标记字段为 JSON 类型
    pub fn json(mut self, field: &str) -> Self {
        self.field_types.insert(field.to_string(), FieldType::Json);
        self
    }

    /// 标记字段为 DATETIME 类型
    pub fn datetime(mut self, field: &str) -> Self {
        self.field_types
            .insert(field.to_string(), FieldType::DateTime);
        self
    }

    /// 标记字段为 TIMESTAMP 类型
    pub fn timestamp(mut self, field: &str) -> Self {
        self.field_types
            .insert(field.to_string(), FieldType::Timestamp);
        self
    }

    /// 标记字段为 DECIMAL 类型
    pub fn decimal(mut self, field: &str) -> Self {
        self.field_types
            .insert(field.to_string(), FieldType::Decimal);
        self
    }

    /// 标记字段为 BLOB 类型
    pub fn blob(mut self, field: &str) -> Self {
        self.field_types.insert(field.to_string(), FieldType::Blob);
        self
    }

    /// 标记字段为 TEXT 类型
    pub fn text(mut self, field: &str) -> Self {
        self.field_types.insert(field.to_string(), FieldType::Text);
        self
    }

    /// 添加 AND 条件
    pub fn where_and<V>(mut self, field: &str, op: &str, value: V) -> Self
    where
        V: Into<SqlValue>,
    {
        let sql_value = value.into();
        let condition = match op {
            "=" => Condition::Eq(field.to_string(), sql_value),
            "!=" => Condition::Ne(field.to_string(), sql_value),
            ">" => Condition::Gt(field.to_string(), sql_value),
            "<" => Condition::Lt(field.to_string(), sql_value),
            ">=" => Condition::Gte(field.to_string(), sql_value),
            "<=" => Condition::Lte(field.to_string(), sql_value),
            "like" | "LIKE" => {
                if let SqlValue::String(s) = sql_value {
                    Condition::Like(field.to_string(), s)
                } else {
                    Condition::Like(field.to_string(), format!("{:?}", sql_value))
                }
            }
            _ => panic!("不支持的操作符: {}", op),
        };

        self.conditions.push(condition);
        self
    }

    /// 插入数据
    ///
    /// 在事务中执行 INSERT 操作
    ///
    /// # 类型参数
    /// - T: 数据类型,必须实现 Serialize trait
    ///
    /// # 参数
    /// - data: 要插入的数据
    ///
    /// # 返回
    /// - Ok(u64): 插入成功,返回插入记录的 ID(自增主键)
    /// - Err(DbError): 插入失败
    pub async fn insert<T>(self, data: &T) -> Result<u64, DbError>
    where
        T: serde::Serialize,
    {
        // 记录日志
        if self.tx.enable_logging {
            log::debug!("事务中执行 insert() 操作,表: {}", self.table);
        }

        // 将数据序列化为 JSON
        let json_data = serde_json::to_value(data)
            .map_err(|e| DbError::SerializationError(format!("数据序列化失败: {}", e)))?;

        // 生成 INSERT 语句
        let mut generator = crate::mysql::query_builder::SqlGenerator::new();
        generator.build_insert(&self.table, &json_data, &self.field_types)?;

        let sql = generator.get_sql();
        let params = generator.get_params();

        // 记录日志
        if self.tx.enable_logging {
            log::debug!("事务中执行 insert() SQL: {}", sql);
            log::debug!("参数: {:?}", params);
        }

        // 构建查询
        let mut query = sqlx::query(sql);

        // 绑定参数
        for param in params {
            query = bind_execute_param(query, param);
        }

        // 执行插入
        if let Some(tx) = &mut self.tx.tx {
            let result = query.execute(&mut **tx).await?;
            let last_insert_id = result.last_insert_id();

            if self.tx.enable_logging {
                log::debug!("事务中 insert() 成功,插入 ID: {}", last_insert_id);
            }

            Ok(last_insert_id)
        } else {
            Err(DbError::TransactionError("事务已提交或回滚".to_string()))
        }
    }

    /// 更新数据
    ///
    /// 在事务中执行 UPDATE 操作
    /// 为了防止误操作,必须提供 WHERE 条件,否则会返回错误
    ///
    /// # 类型参数
    /// - T: 数据类型,必须实现 Serialize trait
    ///
    /// # 参数
    /// - data: 要更新的数据
    ///
    /// # 返回
    /// - Ok(u64): 更新成功,返回受影响的行数
    /// - Err(DbError): 更新失败
    pub async fn update<T>(self, data: &T) -> Result<u64, DbError>
    where
        T: serde::Serialize,
    {
        // 记录日志
        if self.tx.enable_logging {
            log::debug!("事务中执行 update() 操作,表: {}", self.table);
        }

        // 检查是否有 WHERE 条件
        if self.conditions.is_empty() {
            log::warn!("事务中 update() 操作缺少 WHERE 条件,禁止全表更新");
            return Err(DbError::MissingWhereClause);
        }

        // 将数据序列化为 JSON
        let json_data = serde_json::to_value(data)
            .map_err(|e| DbError::SerializationError(format!("数据序列化失败: {}", e)))?;

        // 生成 UPDATE 语句
        let mut generator = crate::mysql::query_builder::SqlGenerator::new();
        generator.build_update(&self.table, &json_data, &self.field_types, &self.conditions)?;

        let sql = generator.get_sql();
        let params = generator.get_params();

        // 记录日志
        if self.tx.enable_logging {
            log::debug!("事务中执行 update() SQL: {}", sql);
            log::debug!("参数: {:?}", params);
        }

        // 构建查询
        let mut query = sqlx::query(sql);

        // 绑定参数
        for param in params {
            query = bind_execute_param(query, param);
        }

        // 执行更新
        if let Some(tx) = &mut self.tx.tx {
            let result = query.execute(&mut **tx).await?;
            let rows_affected = result.rows_affected();

            if self.tx.enable_logging {
                log::debug!("事务中 update() 成功,影响 {} 行", rows_affected);
            }

            Ok(rows_affected)
        } else {
            Err(DbError::TransactionError("事务已提交或回滚".to_string()))
        }
    }

    /// 删除数据
    ///
    /// 在事务中执行 DELETE 操作
    /// 为了防止误操作,必须提供 WHERE 条件,否则会返回错误
    ///
    /// # 返回
    /// - Ok(u64): 删除成功,返回受影响的行数
    /// - Err(DbError): 删除失败
    pub async fn delete(self) -> Result<u64, DbError> {
        // 记录日志
        if self.tx.enable_logging {
            log::debug!("事务中执行 delete() 操作,表: {}", self.table);
        }

        // 检查是否有 WHERE 条件
        if self.conditions.is_empty() {
            log::warn!("事务中 delete() 操作缺少 WHERE 条件,禁止全表删除");
            return Err(DbError::MissingWhereClause);
        }

        // 生成 DELETE 语句
        let mut generator = crate::mysql::query_builder::SqlGenerator::new();
        generator.build_delete(&self.table, &self.conditions)?;

        let sql = generator.get_sql();
        let params = generator.get_params();

        // 记录日志
        if self.tx.enable_logging {
            log::debug!("事务中执行 delete() SQL: {}", sql);
            log::debug!("参数: {:?}", params);
        }

        // 构建查询
        let mut query = sqlx::query(sql);

        // 绑定参数
        for param in params {
            query = bind_execute_param(query, param);
        }

        // 执行删除
        if let Some(tx) = &mut self.tx.tx {
            let result = query.execute(&mut **tx).await?;
            let rows_affected = result.rows_affected();

            if self.tx.enable_logging {
                log::debug!("事务中 delete() 成功,影响 {} 行", rows_affected);
            }

            Ok(rows_affected)
        } else {
            Err(DbError::TransactionError("事务已提交或回滚".to_string()))
        }
    }
}

/// 绑定参数到执行查询(用于事务中的 INSERT/UPDATE/DELETE)
///
/// # 参数
/// - query: sqlx 查询对象
/// - param: SQL 参数值
///
/// # 返回
/// - 绑定参数后的查询对象
fn bind_execute_param<'q>(
    query: sqlx::query::Query<'q, sqlx::MySql, sqlx::mysql::MySqlArguments>,
    param: &SqlValue,
) -> sqlx::query::Query<'q, sqlx::MySql, sqlx::mysql::MySqlArguments> {
    match param {
        SqlValue::Null => query.bind(Option::<i32>::None),
        SqlValue::Bool(b) => query.bind(*b),
        SqlValue::Int(i) => query.bind(*i),
        SqlValue::Float(f) => query.bind(*f),
        SqlValue::String(s) => query.bind(s.clone()),
        SqlValue::Bytes(b) => query.bind(b.clone()),
        SqlValue::Json(j) => query.bind(j.to_string()),
        SqlValue::DateTime(dt) => query.bind(*dt),
        SqlValue::Timestamp(ts) => query.bind(*ts),
    }
}

/// 将 `serde_json::Value` 参数绑定到事务执行查询(用于参数化 INSERT/UPDATE/DELETE)
///
/// # 参数
/// - query: sqlx 执行查询对象
/// - param: JSON 参数值
///
/// # 返回
/// - 绑定参数后的查询对象
fn bind_json_param_tx<'q>(
    query: sqlx::query::Query<'q, sqlx::MySql, sqlx::mysql::MySqlArguments>,
    param: &serde_json::Value,
) -> sqlx::query::Query<'q, sqlx::MySql, sqlx::mysql::MySqlArguments> {
    match param {
        // 字符串类型直接绑定
        serde_json::Value::String(s) => query.bind(s.clone()),
        // 数字类型转为 i64 绑定
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                query.bind(i)
            } else if let Some(f) = n.as_f64() {
                // 浮点数转为字符串绑定,避免精度丢失
                query.bind(f.to_string())
            } else {
                query.bind(Option::<String>::None)
            }
        }
        // 布尔类型绑定
        serde_json::Value::Bool(b) => query.bind(*b),
        // NULL 类型绑定为 None
        serde_json::Value::Null => query.bind(Option::<String>::None),
        // 数组和对象类型序列化为 JSON 字符串绑定
        other => query.bind(other.to_string()),
    }
}

/// 将 `serde_json::Value` 参数绑定到事务 `query_as` 查询(用于参数化 SELECT)
///
/// # 参数
/// - query: sqlx query_as 查询对象
/// - param: JSON 参数值
///
/// # 返回
/// - 绑定参数后的查询对象
fn bind_json_param_as_tx<'q, T>(
    query: sqlx::query::QueryAs<'q, sqlx::MySql, T, sqlx::mysql::MySqlArguments>,
    param: &serde_json::Value,
) -> sqlx::query::QueryAs<'q, sqlx::MySql, T, sqlx::mysql::MySqlArguments>
where
    T: for<'r> sqlx::FromRow<'r, sqlx::mysql::MySqlRow>,
{
    match param {
        // 字符串类型直接绑定
        serde_json::Value::String(s) => query.bind(s.clone()),
        // 数字类型转为 i64 绑定
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                query.bind(i)
            } else if let Some(f) = n.as_f64() {
                // 浮点数转为字符串绑定,避免精度丢失
                query.bind(f.to_string())
            } else {
                query.bind(Option::<String>::None)
            }
        }
        // 布尔类型绑定
        serde_json::Value::Bool(b) => query.bind(*b),
        // NULL 类型绑定为 None
        serde_json::Value::Null => query.bind(Option::<String>::None),
        // 数组和对象类型序列化为 JSON 字符串绑定
        other => query.bind(other.to_string()),
    }
}