yang-db 0.3.1

个人使用数据库操作
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
#![allow(deprecated)]

use chrono::NaiveDateTime;
use serde_json::Value as JsonValue;

use crate::error::DbError;

/// 受控列比较操作符。
#[derive(Debug, Clone, Copy)]
pub enum ComparisonOperator {
    /// 等于。
    Eq,
    /// 不等于。
    Ne,
    /// 大于。
    Gt,
    /// 小于。
    Lt,
    /// 大于等于。
    Gte,
    /// 小于等于。
    Lte,
}

impl ComparisonOperator {
    fn parse(op: &str) -> Result<Self, DbError> {
        match op {
            "=" => Ok(Self::Eq),
            "!=" => Ok(Self::Ne),
            ">" => Ok(Self::Gt),
            "<" => Ok(Self::Lt),
            ">=" => Ok(Self::Gte),
            "<=" => Ok(Self::Lte),
            _ => Err(DbError::UnsupportedOperator(op.to_string())),
        }
    }

    fn as_sql(self) -> &'static str {
        match self {
            Self::Eq => "=",
            Self::Ne => "!=",
            Self::Gt => ">",
            Self::Lt => "<",
            Self::Gte => ">=",
            Self::Lte => "<=",
        }
    }
}

/// 只能由安全标识符和绑定条件构造的 SELECT 子查询。
#[derive(Debug, Clone)]
pub struct Subquery {
    table: String,
    field: String,
    conditions: Vec<Condition>,
}

impl Subquery {
    /// 创建只投影一个字段的受控子查询。
    pub fn new(table: &str, field: &str) -> Result<Self, DbError> {
        super::identifier::quote_identifier(table)?;
        super::identifier::quote_qualified(field)?;
        Ok(Self {
            table: table.to_string(),
            field: field.to_string(),
            conditions: Vec::new(),
        })
    }

    /// 添加字段与绑定值的 AND 条件。
    pub fn where_value<V>(mut self, field: &str, op: &str, value: V) -> Result<Self, DbError>
    where
        V: Into<SqlValue>,
    {
        super::identifier::quote_qualified(field)?;
        let value = value.into();
        let condition = match op {
            "=" => Condition::Eq(field.to_string(), value),
            "!=" => Condition::Ne(field.to_string(), value),
            ">" => Condition::Gt(field.to_string(), value),
            "<" => Condition::Lt(field.to_string(), value),
            ">=" => Condition::Gte(field.to_string(), value),
            "<=" => Condition::Lte(field.to_string(), value),
            _ => return Err(DbError::UnsupportedOperator(op.to_string())),
        };
        self.conditions.push(condition);
        Ok(self)
    }

    /// 添加两个已校验列之间的 AND 比较,用于关联子查询。
    pub fn where_column(mut self, left: &str, op: &str, right: &str) -> Result<Self, DbError> {
        super::identifier::quote_qualified(left)?;
        super::identifier::quote_qualified(right)?;
        self.conditions.push(Condition::ColumnComparison(
            left.to_string(),
            ComparisonOperator::parse(op)?,
            right.to_string(),
        ));
        Ok(self)
    }
}

/// SQL 值类型
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum SqlValue {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    String(String),
    Bytes(Vec<u8>),
    Json(JsonValue),
    DateTime(NaiveDateTime),
    Timestamp(i64),
}

/// 查询条件
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Condition {
    /// 相等
    Eq(String, SqlValue),
    /// 不等
    Ne(String, SqlValue),
    /// 大于
    Gt(String, SqlValue),
    /// 小于
    Lt(String, SqlValue),
    /// 大于等于
    Gte(String, SqlValue),
    /// 小于等于
    Lte(String, SqlValue),
    /// IN 条件
    In(String, Vec<SqlValue>),
    /// NOT IN 条件
    NotIn(String, Vec<SqlValue>),
    /// BETWEEN 条件
    Between(String, SqlValue, SqlValue),
    /// LIKE 条件
    Like(String, String),
    /// 大小写不敏感 LIKE(MySQL 无 ILIKE,退化为 `LIKE`)。
    ILike(String, String),
    /// 大小写不敏感 LIKE 取反(MySQL 无 ILIKE,退化为 `NOT LIKE`)。
    NotILike(String, String),
    /// 正则匹配(`REGEXP`)。
    RegexMatch(String, String),
    /// 大小写不敏感正则匹配(`REGEXP`,大小写敏感性由 collation 决定)。
    RegexIMatch(String, String),
    /// 正则不匹配(`NOT REGEXP`)。
    NotRegexMatch(String, String),
    /// 大小写不敏感正则不匹配(`NOT REGEXP`)。
    NotRegexIMatch(String, String),
    /// IS NULL 条件
    IsNull(String),
    /// IS NOT NULL 条件
    IsNotNull(String),
    /// 两个标识符之间的受控比较。
    ColumnComparison(String, ComparisonOperator, String),
    /// 字段与受控服务端表达式的比较(如 `expires_at > UNIX_TIMESTAMP()`)。
    ColumnExprComparison(String, ComparisonOperator, crate::SqlExpr),
    /// EXISTS 子查询。
    Exists(Box<Subquery>),
    /// NOT EXISTS 子查询。
    NotExists(Box<Subquery>),
    /// IN 子查询。
    InSubquery(String, Box<Subquery>),
    /// AND 组合
    And(Vec<Condition>),
    /// OR 组合
    Or(Vec<Condition>),
}

// 实现 From trait 支持自动转换
impl From<i32> for SqlValue {
    fn from(v: i32) -> Self {
        SqlValue::Int(v as i64)
    }
}

impl From<i64> for SqlValue {
    fn from(v: i64) -> Self {
        SqlValue::Int(v)
    }
}

impl From<u64> for SqlValue {
    fn from(v: u64) -> Self {
        // u64 顶半区(> i64::MAX,如 BIGINT UNSIGNED / 无符号雪花 ID)若强转 i64 会
        // 静默环绕成负数(NEW-11)。超出 i64 范围时走十进制字符串,MySQL 对数值列会
        // 隐式转换,避免数据被悄悄改写。SqlValue 未标 non_exhaustive,不新增 UInt 变体
        // 以免破坏全 crate 的 match。
        if v > i64::MAX as u64 {
            SqlValue::String(v.to_string())
        } else {
            SqlValue::Int(v as i64)
        }
    }
}

impl From<f64> for SqlValue {
    fn from(v: f64) -> Self {
        SqlValue::Float(v)
    }
}

impl From<f32> for SqlValue {
    fn from(v: f32) -> Self {
        SqlValue::Float(v as f64)
    }
}

impl From<String> for SqlValue {
    fn from(v: String) -> Self {
        SqlValue::String(v)
    }
}

impl From<&str> for SqlValue {
    fn from(v: &str) -> Self {
        SqlValue::String(v.to_string())
    }
}

impl From<bool> for SqlValue {
    fn from(v: bool) -> Self {
        SqlValue::Bool(v)
    }
}

impl From<Vec<u8>> for SqlValue {
    fn from(v: Vec<u8>) -> Self {
        SqlValue::Bytes(v)
    }
}

impl From<JsonValue> for SqlValue {
    fn from(v: JsonValue) -> Self {
        SqlValue::Json(v)
    }
}

impl From<NaiveDateTime> for SqlValue {
    fn from(v: NaiveDateTime) -> Self {
        SqlValue::DateTime(v)
    }
}

impl<T> From<Option<T>> for SqlValue
where
    T: Into<SqlValue>,
{
    fn from(v: Option<T>) -> Self {
        match v {
            Some(val) => val.into(),
            None => SqlValue::Null,
        }
    }
}

/// 将条件转换为 SQL 字符串和参数列表
///
/// # 参数
/// - condition: 要转换的条件
/// - params: 用于收集参数的可变向量
///
/// # 返回
/// - SQL 字符串片段
#[deprecated(
    since = "0.1.3",
    note = "使用 condition_to_sql_owned_checked 获取结构化错误"
)]
pub fn condition_to_sql(condition: &Condition, params: &mut Vec<SqlValue>) -> String {
    condition_to_sql_owned(condition.clone(), params)
}

/// 借用签名的兼容层,内部对整棵树 clone 一次后委托 `condition_to_sql_owned`
///
/// 签名虽为借用,实现仍会对整棵条件树做一次 `clone()`(含 `Vec<SqlValue>` 与子查询),
/// 不要指望它避免克隆。
///
/// # 参数
/// - `cond`: 要转换的条件引用
/// - `out`: 输出 SQL 的可变字符串(追加模式,不清空已有内容)
/// - `params`: 用于收集参数的可变向量
#[deprecated(
    since = "0.1.3",
    note = "使用 condition_to_sql_owned_checked 获取结构化错误"
)]
pub fn write_condition_to_sql(cond: &Condition, out: &mut String, params: &mut Vec<SqlValue>) {
    out.push_str(&condition_to_sql_owned(cond.clone(), params));
}

/// 消费版本的兼容条件渲染入口。
///
/// 内部只委托 checked renderer;校验失败时返回固定 fail-closed 条件,且不会修改参数。
///
/// # 参数
/// - `condition`: 要消费的条件(owned)
/// - `params`: 用于收集参数的可变向量
///
/// # 返回
/// - SQL 字符串片段
///
const FAIL_CLOSED_CONDITION: &str = "/* invalid condition */ 1 = 0";

/// 兼容的 infallible 入口只委托 checked renderer;失败时返回固定不可执行条件。
#[deprecated(
    since = "0.1.3",
    note = "使用 condition_to_sql_owned_checked 获取结构化错误"
)]
pub fn condition_to_sql_owned(condition: Condition, params: &mut Vec<SqlValue>) -> String {
    condition_to_sql_owned_checked(condition, params)
        .unwrap_or_else(|_| FAIL_CLOSED_CONDITION.to_string())
}

/// 严格版条件转 SQL:非法标识符返回 [`DbError::InvalidArgument`] 而非 RAW 回退。
///
/// 字段标识符校验失败时立即返回错误;只接受单段或两段限定标识符,不接受表达式。
///
/// # 返回
///
/// - `Ok(String)`: SQL 片段
/// - `Err(DbError::InvalidArgument)`: 包含非法标识符
pub fn condition_to_sql_owned_checked(
    condition: Condition,
    params: &mut Vec<SqlValue>,
) -> Result<String, DbError> {
    let rendered = render_condition_checked(condition)?;
    params.extend(rendered.params);
    Ok(rendered.sql)
}

pub(crate) fn render_condition_checked(
    condition: Condition,
) -> Result<crate::sql_types::RenderedCondition<SqlValue>, DbError> {
    // 渲染逻辑按方言共享于 crate::dialect;这里只做公开条件树 → 内部树的转换。
    crate::dialect::render_condition(crate::dialect::MYSQL, into_node(condition)?, 0)
}

/// 将公开条件树转换为方言无关的内部渲染树(值原样移动,不复制)。
///
/// 受控表达式在转换期预渲染;MySQL 不支持的表达式(如 `to_char`)在此返回
/// [`DbError::UnsupportedOperator`]。
fn into_node(condition: Condition) -> Result<crate::dialect::CondNode<SqlValue>, DbError> {
    use crate::dialect::CondNode as Node;
    Ok(match condition {
        Condition::Eq(field, value) => Node::Eq(field, value),
        Condition::Ne(field, value) => Node::Ne(field, value),
        Condition::Gt(field, value) => Node::Gt(field, value),
        Condition::Lt(field, value) => Node::Lt(field, value),
        Condition::Gte(field, value) => Node::Gte(field, value),
        Condition::Lte(field, value) => Node::Lte(field, value),
        Condition::In(field, values) => Node::In(field, values),
        Condition::NotIn(field, values) => Node::NotIn(field, values),
        Condition::Between(field, start, end) => Node::Between(field, start, end),
        Condition::Like(field, pattern) => Node::Like(field, SqlValue::String(pattern)),
        Condition::ILike(field, pattern) => {
            Node::PatternMatch(field, "LIKE", SqlValue::String(pattern))
        }
        Condition::NotILike(field, pattern) => {
            Node::PatternMatch(field, "NOT LIKE", SqlValue::String(pattern))
        }
        Condition::RegexMatch(field, pattern) | Condition::RegexIMatch(field, pattern) => {
            Node::PatternMatch(field, "REGEXP", SqlValue::String(pattern))
        }
        Condition::NotRegexMatch(field, pattern) | Condition::NotRegexIMatch(field, pattern) => {
            Node::PatternMatch(field, "NOT REGEXP", SqlValue::String(pattern))
        }
        Condition::IsNull(field) => Node::IsNull(field),
        Condition::IsNotNull(field) => Node::IsNotNull(field),
        Condition::ColumnComparison(left, op, right) => {
            Node::ColumnComparison(left, op.as_sql(), right)
        }
        Condition::ColumnExprComparison(field, op, expression) => {
            // 预渲染 SqlExpr 白名单片段:固定文本 + 按占位符顺序的绑定参数。
            let rendered = expression.mysql_render()?;
            Node::ColumnExpr(
                field,
                op.as_sql(),
                rendered.sql,
                rendered.params.into_iter().map(Into::into).collect(),
            )
        }
        Condition::Exists(subquery) => Node::Exists(Box::new(into_subquery_node(*subquery)?)),
        Condition::NotExists(subquery) => Node::NotExists(Box::new(into_subquery_node(*subquery)?)),
        Condition::InSubquery(field, subquery) => {
            Node::InSubquery(field, Box::new(into_subquery_node(*subquery)?))
        }
        Condition::And(conditions) => Node::And(
            conditions
                .into_iter()
                .map(into_node)
                .collect::<Result<_, _>>()?,
        ),
        Condition::Or(conditions) => Node::Or(
            conditions
                .into_iter()
                .map(into_node)
                .collect::<Result<_, _>>()?,
        ),
    })
}

/// 将受控子查询转换为内部渲染节点。
fn into_subquery_node(
    subquery: Subquery,
) -> Result<crate::dialect::SubqueryNode<SqlValue>, DbError> {
    Ok(crate::dialect::SubqueryNode {
        table: subquery.table,
        field: subquery.field,
        conditions: subquery
            .conditions
            .into_iter()
            .map(into_node)
            .collect::<Result<_, _>>()?,
    })
}

#[cfg(test)]
#[allow(deprecated, clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use chrono::NaiveDate;

    #[test]
    fn test_checked_rejects_empty_in_condition() {
        let mut params = Vec::new();
        let result =
            condition_to_sql_owned_checked(Condition::In("id".to_string(), vec![]), &mut params);

        assert!(matches!(result, Err(crate::DbError::InvalidArgument(_))));
        assert!(params.is_empty());
    }

    #[test]
    fn test_checked_rejects_empty_boolean_condition() {
        let mut params = Vec::new();
        let result = condition_to_sql_owned_checked(Condition::And(vec![]), &mut params);

        assert!(matches!(result, Err(crate::DbError::InvalidArgument(_))));
        assert!(params.is_empty());
    }

    #[test]
    fn test_checked_failure_does_not_partially_mutate_caller_params() {
        let mut params = vec![SqlValue::Int(99)];
        let condition = Condition::And(vec![
            Condition::Eq("users.id".to_string(), SqlValue::Int(1)),
            Condition::Eq("users.id --".to_string(), SqlValue::Int(2)),
        ]);

        assert!(condition_to_sql_owned_checked(condition, &mut params).is_err());
        assert_eq!(params.len(), 1);
        assert!(matches!(params[0], SqlValue::Int(99)));
    }

    #[test]
    fn test_legacy_renderer_fails_closed_without_raw_payload_or_params() {
        let mut params = Vec::new();
        let sql = condition_to_sql_owned(
            Condition::Eq("id; DROP TABLE users".to_string(), SqlValue::Int(1)),
            &mut params,
        );

        assert_eq!(sql, FAIL_CLOSED_CONDITION);
        assert!(!sql.contains("DROP TABLE"));
        assert!(params.is_empty());
    }

    #[test]
    fn test_from_i32() {
        let value: SqlValue = 42i32.into();
        match value {
            SqlValue::Int(v) => assert_eq!(v, 42),
            _ => panic!("期望 SqlValue::Int"),
        }
    }

    #[test]
    fn test_from_i64() {
        let value: SqlValue = 9223372036854775807i64.into();
        match value {
            SqlValue::Int(v) => assert_eq!(v, 9223372036854775807),
            _ => panic!("期望 SqlValue::Int"),
        }
    }

    #[test]
    fn test_from_f32() {
        let value: SqlValue = 3.5f32.into();
        match value {
            SqlValue::Float(v) => assert!((v - 3.5).abs() < 0.01),
            _ => panic!("期望 SqlValue::Float"),
        }
    }

    #[test]
    fn test_from_f64() {
        let value: SqlValue = 2.5f64.into();
        match value {
            SqlValue::Float(v) => assert!((v - 2.5).abs() < 0.000001),
            _ => panic!("期望 SqlValue::Float"),
        }
    }

    #[test]
    fn test_from_string() {
        let value: SqlValue = String::from("测试字符串").into();
        match value {
            SqlValue::String(s) => assert_eq!(s, "测试字符串"),
            _ => panic!("期望 SqlValue::String"),
        }
    }

    #[test]
    fn test_from_str() {
        let value: SqlValue = "hello world".into();
        match value {
            SqlValue::String(s) => assert_eq!(s, "hello world"),
            _ => panic!("期望 SqlValue::String"),
        }
    }

    #[test]
    fn test_from_bool_true() {
        let value: SqlValue = true.into();
        match value {
            SqlValue::Bool(b) => assert!(b),
            _ => panic!("期望 SqlValue::Bool"),
        }
    }

    #[test]
    fn test_from_bool_false() {
        let value: SqlValue = false.into();
        match value {
            SqlValue::Bool(b) => assert!(!b),
            _ => panic!("期望 SqlValue::Bool"),
        }
    }

    #[test]
    fn test_from_vec_u8() {
        let bytes = vec![0x48, 0x65, 0x6c, 0x6c, 0x6f]; // "Hello"
        let value: SqlValue = bytes.clone().into();
        match value {
            SqlValue::Bytes(b) => assert_eq!(b, bytes),
            _ => panic!("期望 SqlValue::Bytes"),
        }
    }

    #[test]
    fn test_from_json_value() {
        let json = serde_json::json!({
            "name": "测试",
            "age": 25,
            "active": true
        });
        let value: SqlValue = json.clone().into();
        match value {
            SqlValue::Json(j) => assert_eq!(j, json),
            _ => panic!("期望 SqlValue::Json"),
        }
    }

    #[test]
    fn test_from_naive_datetime() {
        let dt = NaiveDate::from_ymd_opt(2024, 1, 15)
            .unwrap()
            .and_hms_opt(10, 30, 45)
            .unwrap();
        let value: SqlValue = dt.into();
        match value {
            SqlValue::DateTime(d) => assert_eq!(d, dt),
            _ => panic!("期望 SqlValue::DateTime"),
        }
    }

    #[test]
    fn test_from_option_some() {
        let value: SqlValue = Some(42i32).into();
        match value {
            SqlValue::Int(v) => assert_eq!(v, 42),
            _ => panic!("期望 SqlValue::Int"),
        }
    }

    #[test]
    fn test_from_option_none() {
        let value: SqlValue = None::<i32>.into();
        match value {
            SqlValue::Null => (),
            _ => panic!("期望 SqlValue::Null"),
        }
    }

    #[test]
    fn test_from_option_string_some() {
        let value: SqlValue = Some(String::from("测试")).into();
        match value {
            SqlValue::String(s) => assert_eq!(s, "测试"),
            _ => panic!("期望 SqlValue::String"),
        }
    }

    #[test]
    fn test_from_option_string_none() {
        let value: SqlValue = None::<String>.into();
        match value {
            SqlValue::Null => (),
            _ => panic!("期望 SqlValue::Null"),
        }
    }

    #[test]
    fn test_negative_integers() {
        let value: SqlValue = (-100i32).into();
        match value {
            SqlValue::Int(v) => assert_eq!(v, -100),
            _ => panic!("期望 SqlValue::Int"),
        }
    }

    #[test]
    fn test_negative_floats() {
        let value: SqlValue = (-3.5f64).into();
        match value {
            SqlValue::Float(v) => assert!((v + 3.5).abs() < 0.01),
            _ => panic!("期望 SqlValue::Float"),
        }
    }

    #[test]
    fn test_empty_string() {
        let value: SqlValue = "".into();
        match value {
            SqlValue::String(s) => assert_eq!(s, ""),
            _ => panic!("期望 SqlValue::String"),
        }
    }

    #[test]
    fn test_empty_bytes() {
        let value: SqlValue = Vec::<u8>::new().into();
        match value {
            SqlValue::Bytes(b) => assert!(b.is_empty()),
            _ => panic!("期望 SqlValue::Bytes"),
        }
    }

    #[test]
    fn test_json_null() {
        let json = serde_json::Value::Null;
        let value: SqlValue = json.into();
        match value {
            SqlValue::Json(j) => assert!(j.is_null()),
            _ => panic!("期望 SqlValue::Json"),
        }
    }

    #[test]
    fn test_json_array() {
        let json = serde_json::json!([1, 2, 3, 4, 5]);
        let value: SqlValue = json.clone().into();
        match value {
            SqlValue::Json(j) => assert_eq!(j, json),
            _ => panic!("期望 SqlValue::Json"),
        }
    }

    #[test]
    fn test_unicode_string() {
        let value: SqlValue = "你好世界 🌍".into();
        match value {
            SqlValue::String(s) => assert_eq!(s, "你好世界 🌍"),
            _ => panic!("期望 SqlValue::String"),
        }
    }

    #[test]
    fn test_zero_values() {
        let int_value: SqlValue = 0i32.into();
        match int_value {
            SqlValue::Int(v) => assert_eq!(v, 0),
            _ => panic!("期望 SqlValue::Int"),
        }

        let float_value: SqlValue = 0.0f64.into();
        match float_value {
            SqlValue::Float(v) => assert_eq!(v, 0.0),
            _ => panic!("期望 SqlValue::Float"),
        }
    }

    // 测试 condition_to_sql 函数
    #[test]
    fn test_condition_column_expr_comparison_renders_fixed_fragment_with_bound_param() {
        // 无参表达式:不产出绑定参数
        let mut params = Vec::new();
        let sql = condition_to_sql_owned_checked(
            Condition::ColumnExprComparison(
                "expires_at".to_string(),
                ComparisonOperator::Gt,
                crate::SqlExpr::unix_timestamp(),
            ),
            &mut params,
        )
        .expect("合法表达式条件应渲染成功");
        assert_eq!(sql, "`expires_at` > UNIX_TIMESTAMP()");
        assert!(params.is_empty());

        // 带参表达式:偏移秒数只进参数列表,不进 SQL 文本
        let mut params = Vec::new();
        let sql = condition_to_sql_owned_checked(
            Condition::ColumnExprComparison(
                "expires_at".to_string(),
                ComparisonOperator::Lte,
                crate::SqlExpr::unix_timestamp_add(600),
            ),
            &mut params,
        )
        .expect("合法表达式条件应渲染成功");
        assert_eq!(sql, "`expires_at` <= UNIX_TIMESTAMP() + ?");
        assert_eq!(params.len(), 1);
        assert!(matches!(params[0], SqlValue::Int(600)));
    }

    #[test]
    fn test_condition_eq() {
        let mut params = Vec::new();
        let cond = Condition::Eq("name".to_string(), SqlValue::String("test".to_string()));
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "`name` = ?");
        assert_eq!(params.len(), 1);
    }

    #[test]
    fn test_condition_ne() {
        let mut params = Vec::new();
        let cond = Condition::Ne("status".to_string(), SqlValue::Int(1));
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "`status` != ?");
        assert_eq!(params.len(), 1);
    }

    #[test]
    fn test_condition_gt() {
        let mut params = Vec::new();
        let cond = Condition::Gt("age".to_string(), SqlValue::Int(18));
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "`age` > ?");
        assert_eq!(params.len(), 1);
    }

    #[test]
    fn test_condition_lt() {
        let mut params = Vec::new();
        let cond = Condition::Lt("price".to_string(), SqlValue::Float(100.0));
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "`price` < ?");
        assert_eq!(params.len(), 1);
    }

    #[test]
    fn test_condition_gte() {
        let mut params = Vec::new();
        let cond = Condition::Gte("score".to_string(), SqlValue::Int(60));
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "`score` >= ?");
        assert_eq!(params.len(), 1);
    }

    #[test]
    fn test_condition_lte() {
        let mut params = Vec::new();
        let cond = Condition::Lte("count".to_string(), SqlValue::Int(10));
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "`count` <= ?");
        assert_eq!(params.len(), 1);
    }

    #[test]
    fn test_condition_in() {
        let mut params = Vec::new();
        let cond = Condition::In(
            "id".to_string(),
            vec![SqlValue::Int(1), SqlValue::Int(2), SqlValue::Int(3)],
        );
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "`id` IN (?, ?, ?)");
        assert_eq!(params.len(), 3);
    }

    #[test]
    fn test_condition_in_empty() {
        let mut params = Vec::new();
        let cond = Condition::In("id".to_string(), vec![]);
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, FAIL_CLOSED_CONDITION);
        assert_eq!(params.len(), 0);
    }

    #[test]
    fn test_condition_between() {
        let mut params = Vec::new();
        let cond = Condition::Between("age".to_string(), SqlValue::Int(18), SqlValue::Int(65));
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "`age` BETWEEN ? AND ?");
        assert_eq!(params.len(), 2);
    }

    #[test]
    fn test_condition_like() {
        let mut params = Vec::new();
        let cond = Condition::Like("name".to_string(), "%test%".to_string());
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "`name` LIKE ?");
        assert_eq!(params.len(), 1);
    }

    #[test]
    fn test_condition_and() {
        let mut params = Vec::new();
        let cond = Condition::And(vec![
            Condition::Eq("name".to_string(), SqlValue::String("test".to_string())),
            Condition::Gt("age".to_string(), SqlValue::Int(18)),
        ]);
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "(`name` = ? AND `age` > ?)");
        assert_eq!(params.len(), 2);
    }

    #[test]
    fn test_condition_or() {
        let mut params = Vec::new();
        let cond = Condition::Or(vec![
            Condition::Eq("status".to_string(), SqlValue::Int(1)),
            Condition::Eq("status".to_string(), SqlValue::Int(2)),
        ]);
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "(`status` = ? OR `status` = ?)");
        assert_eq!(params.len(), 2);
    }

    #[test]
    fn test_condition_and_or_priority() {
        let mut params = Vec::new();
        // (name = 'test' OR name = 'demo') AND age > 18
        let cond = Condition::And(vec![
            Condition::Or(vec![
                Condition::Eq("name".to_string(), SqlValue::String("test".to_string())),
                Condition::Eq("name".to_string(), SqlValue::String("demo".to_string())),
            ]),
            Condition::Gt("age".to_string(), SqlValue::Int(18)),
        ]);
        let sql = super::condition_to_sql(&cond, &mut params);
        // OR 条件应该被括号包围
        assert_eq!(sql, "((`name` = ? OR `name` = ?) AND `age` > ?)");
        assert_eq!(params.len(), 3);
    }

    #[test]
    fn test_condition_empty_and() {
        let mut params = Vec::new();
        let cond = Condition::And(vec![]);
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, FAIL_CLOSED_CONDITION);
        assert_eq!(params.len(), 0);
    }

    #[test]
    fn test_condition_empty_or() {
        let mut params = Vec::new();
        let cond = Condition::Or(vec![]);
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, FAIL_CLOSED_CONDITION);
        assert_eq!(params.len(), 0);
    }

    #[test]
    fn test_condition_single_and() {
        let mut params = Vec::new();
        let cond = Condition::And(vec![Condition::Eq("id".to_string(), SqlValue::Int(1))]);
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "`id` = ?");
        assert_eq!(params.len(), 1);
    }

    #[test]
    fn test_condition_single_or() {
        let mut params = Vec::new();
        let cond = Condition::Or(vec![Condition::Eq("id".to_string(), SqlValue::Int(1))]);
        let sql = super::condition_to_sql(&cond, &mut params);
        assert_eq!(sql, "`id` = ?");
        assert_eq!(params.len(), 1);
    }

    /// NULL 归一:`= NULL`/`!= NULL` 改写成 IS NULL / IS NOT NULL,不产生绑定参数。
    #[test]
    fn test_null_comparison_normalization() {
        let mut params = Vec::new();
        let sql = super::condition_to_sql(
            &Condition::Eq("name".to_string(), SqlValue::Null),
            &mut params,
        );
        assert_eq!(sql, "`name` IS NULL");
        assert!(params.is_empty());

        let mut params = Vec::new();
        let sql = super::condition_to_sql(
            &Condition::Ne("name".to_string(), SqlValue::Null),
            &mut params,
        );
        assert_eq!(sql, "`name` IS NOT NULL");
        assert!(params.is_empty());

        // 大小比较与 NULL 恒为 UNKNOWN:渲染为 SQL NULL 字面量,NOT 也不会反转成 TRUE。
        for cond in [
            Condition::Gt("n".to_string(), SqlValue::Null),
            Condition::Lt("n".to_string(), SqlValue::Null),
            Condition::Gte("n".to_string(), SqlValue::Null),
            Condition::Lte("n".to_string(), SqlValue::Null),
            Condition::Between("n".to_string(), SqlValue::Null, SqlValue::Int(1)),
        ] {
            let mut params = Vec::new();
            assert_eq!(super::condition_to_sql(&cond, &mut params), "NULL");
            assert!(params.is_empty());
        }
    }

    /// IN 按 SQL 三值逻辑处理 NULL:丢弃 NULL 项;NOT IN 含 NULL 时恒不为 TRUE。
    #[test]
    fn test_in_with_null_follows_sql_three_valued_logic() {
        let mut params = Vec::new();
        let sql = super::condition_to_sql(
            &Condition::In(
                "id".to_string(),
                vec![SqlValue::Int(1), SqlValue::Null, SqlValue::Int(2)],
            ),
            &mut params,
        );
        assert_eq!(sql, "`id` IN (?, ?)");
        assert_eq!(params.len(), 2);

        let mut params = Vec::new();
        let sql = super::condition_to_sql(
            &Condition::NotIn("id".to_string(), vec![SqlValue::Null, SqlValue::Int(2)]),
            &mut params,
        );
        assert_eq!(sql, "NULL");
        assert!(params.is_empty());

        let mut params = Vec::new();
        assert_eq!(
            super::condition_to_sql(
                &Condition::In("id".to_string(), vec![SqlValue::Null]),
                &mut params
            ),
            "NULL"
        );
        assert!(params.is_empty());
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod property_tests {
    use super::*;
    use proptest::prelude::*;

    // 生成有效的字段名(字母开头,后跟字母数字下划线)
    fn field_name_strategy() -> impl Strategy<Value = String> {
        "[a-z][a-z0-9_]{0,30}"
    }

    // 生成 SqlValue 策略(不含 NULL:NULL 会被归一为 IS NULL/IS NOT NULL/FALSE,
    // 不再产生绑定占位符,由下方 test_null_* 专项覆盖)
    fn sql_value_strategy() -> impl Strategy<Value = SqlValue> {
        prop_oneof![
            any::<bool>().prop_map(SqlValue::Bool),
            any::<i64>().prop_map(SqlValue::Int),
            any::<f64>().prop_map(|f| {
                if f.is_finite() {
                    SqlValue::Float(f)
                } else {
                    SqlValue::Float(0.0)
                }
            }),
            "[a-zA-Z0-9_\\s]{0,50}".prop_map(SqlValue::String),
        ]
    }

    // **Feature: mysql-query-builder, Property 5: 操作符支持**
    // **验证需求:3.3**
    //
    // 属性:对于任意支持的操作符(=, !=, >, <, >=, <=, in, between, like),
    // 生成的 SQL 应该包含正确的操作符语法
    //
    // 此测试验证所有支持的操作符都能正确生成 SQL 语句,
    // 确保参数化查询的正确性和 SQL 注入防护。
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_operator_eq_support(
            field in field_name_strategy(),
            value in sql_value_strategy()
        ) {
            let mut params = Vec::new();
            let cond = Condition::Eq(field.clone(), value);
            let sql = condition_to_sql(&cond, &mut params);

            // 验证 SQL 包含正确的操作符(字段名会被反引号转义)
            let expected = format!("`{}` = {{placeholder}}", field).replace("{placeholder}", "?");
            prop_assert!(sql.contains(&expected));
            prop_assert_eq!(params.len(), 1);
        }

        #[test]
        fn prop_operator_ne_support(
            field in field_name_strategy(),
            value in sql_value_strategy()
        ) {
            let mut params = Vec::new();
            let cond = Condition::Ne(field.clone(), value);
            let sql = condition_to_sql(&cond, &mut params);

            let expected = format!("`{}` != {{placeholder}}", field).replace("{placeholder}", "?");
            prop_assert!(sql.contains(&expected));
            prop_assert_eq!(params.len(), 1);
        }

        #[test]
        fn prop_operator_gt_support(
            field in field_name_strategy(),
            value in sql_value_strategy()
        ) {
            let mut params = Vec::new();
            let cond = Condition::Gt(field.clone(), value);
            let sql = condition_to_sql(&cond, &mut params);

            let expected = format!("`{}` > {{placeholder}}", field).replace("{placeholder}", "?");
            prop_assert!(sql.contains(&expected));
            prop_assert_eq!(params.len(), 1);
        }

        #[test]
        fn prop_operator_lt_support(
            field in field_name_strategy(),
            value in sql_value_strategy()
        ) {
            let mut params = Vec::new();
            let cond = Condition::Lt(field.clone(), value);
            let sql = condition_to_sql(&cond, &mut params);

            let expected = format!("`{}` < {{placeholder}}", field).replace("{placeholder}", "?");
            prop_assert!(sql.contains(&expected));
            prop_assert_eq!(params.len(), 1);
        }

        #[test]
        fn prop_operator_gte_support(
            field in field_name_strategy(),
            value in sql_value_strategy()
        ) {
            let mut params = Vec::new();
            let cond = Condition::Gte(field.clone(), value);
            let sql = condition_to_sql(&cond, &mut params);

            let expected = format!("`{}` >= {{placeholder}}", field).replace("{placeholder}", "?");
            prop_assert!(sql.contains(&expected));
            prop_assert_eq!(params.len(), 1);
        }

        #[test]
        fn prop_operator_lte_support(
            field in field_name_strategy(),
            value in sql_value_strategy()
        ) {
            let mut params = Vec::new();
            let cond = Condition::Lte(field.clone(), value);
            let sql = condition_to_sql(&cond, &mut params);

            let expected = format!("`{}` <= {{placeholder}}", field).replace("{placeholder}", "?");
            prop_assert!(sql.contains(&expected));
            prop_assert_eq!(params.len(), 1);
        }

        #[test]
        fn prop_operator_in_support(
            field in field_name_strategy(),
            values in prop::collection::vec(sql_value_strategy(), 1..10)
        ) {
            let mut params = Vec::new();
            let values_len = values.len();
            let cond = Condition::In(field.clone(), values);
            let sql = condition_to_sql(&cond, &mut params);

            let expected = format!("`{}` IN", field);
            prop_assert!(sql.contains(&expected));
            prop_assert_eq!(params.len(), values_len);
        }

        #[test]
        fn prop_operator_between_support(
            field in field_name_strategy(),
            start in sql_value_strategy(),
            end in sql_value_strategy()
        ) {
            let mut params = Vec::new();
            let cond = Condition::Between(field.clone(), start, end);
            let sql = condition_to_sql(&cond, &mut params);

            let expected = format!("`{}` BETWEEN {{p1}} AND {{p2}}", field)
                .replace("{p1}", "?")
                .replace("{p2}", "?");
            prop_assert!(sql.contains(&expected));
            prop_assert_eq!(params.len(), 2);
        }

        #[test]
        fn prop_operator_like_support(
            field in field_name_strategy(),
            pattern in "[a-zA-Z0-9_%]{1,20}"
        ) {
            let mut params = Vec::new();
            let cond = Condition::Like(field.clone(), pattern);
            let sql = condition_to_sql(&cond, &mut params);

            let expected = format!("`{}` LIKE {{placeholder}}", field).replace("{placeholder}", "?");
            prop_assert!(sql.contains(&expected));
            prop_assert_eq!(params.len(), 1);
        }
    }

    // Feature: mysql-query-builder, Property 9: AND/OR 优先级处理
    // 验证需求:3.7
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_and_or_priority_handling(
            field1 in field_name_strategy(),
            field2 in field_name_strategy(),
            value1 in sql_value_strategy(),
            value2 in sql_value_strategy(),
            value3 in sql_value_strategy()
        ) {
            let mut params = Vec::new();

            // 构建 (field1 = value1 OR field1 = value2) AND field2 = value3
            let cond = Condition::And(vec![
                Condition::Or(vec![
                    Condition::Eq(field1.clone(), value1),
                    Condition::Eq(field1.clone(), value2),
                ]),
                Condition::Eq(field2.clone(), value3),
            ]);

            let sql = condition_to_sql(&cond, &mut params);

            // 验证 SQL 有正确的括号确保操作符优先级
            // 整个条件应该被括号包围
            prop_assert!(sql.starts_with('('));
            prop_assert!(sql.ends_with(')'));

            // OR 条件应该被括号包围
            prop_assert!(sql.contains(" OR "));
            prop_assert!(sql.contains(" AND "));

            // 参数数量应该正确
            prop_assert_eq!(params.len(), 3);
        }

        #[test]
        fn prop_nested_and_or_brackets(
            field in field_name_strategy(),
            values in prop::collection::vec(sql_value_strategy(), 2..5)
        ) {
            let mut params = Vec::new();

            // 构建多个 OR 条件的 AND 组合
            let or_conditions: Vec<Condition> = values
                .iter()
                .map(|v| Condition::Eq(field.clone(), v.clone()))
                .collect();

            let cond = Condition::And(vec![
                Condition::Or(or_conditions.clone()),
                Condition::Gt(field.clone(), SqlValue::Int(0)),
            ]);

            let sql = condition_to_sql(&cond, &mut params);

            // 验证括号匹配
            let open_count = sql.chars().filter(|&c| c == '(').count();
            let close_count = sql.chars().filter(|&c| c == ')').count();
            prop_assert_eq!(open_count, close_count);

            // 验证参数数量
            prop_assert_eq!(params.len(), values.len() + 1);
        }

        #[test]
        fn prop_multiple_and_conditions(
            field in field_name_strategy(),
            values in prop::collection::vec(sql_value_strategy(), 2..5)
        ) {
            let mut params = Vec::new();

            // 构建多个 AND 条件
            let and_conditions: Vec<Condition> = values
                .iter()
                .enumerate()
                .map(|(i, v)| {
                    if i % 2 == 0 {
                        Condition::Eq(field.clone(), v.clone())
                    } else {
                        Condition::Ne(field.clone(), v.clone())
                    }
                })
                .collect();

            let cond = Condition::And(and_conditions);
            let sql = condition_to_sql(&cond, &mut params);

            // 验证 AND 连接
            let and_count = sql.matches(" AND ").count();
            prop_assert_eq!(and_count, values.len() - 1);

            // 验证参数数量
            prop_assert_eq!(params.len(), values.len());
        }

        #[test]
        fn prop_or_conditions_always_bracketed(
            field in field_name_strategy(),
            values in prop::collection::vec(sql_value_strategy(), 2..5)
        ) {
            let mut params = Vec::new();

            // 构建 OR 条件
            let or_conditions: Vec<Condition> = values
                .iter()
                .map(|v| Condition::Eq(field.clone(), v.clone()))
                .collect();

            let cond = Condition::Or(or_conditions);
            let sql = condition_to_sql(&cond, &mut params);

            // OR 条件应该被括号包围
            prop_assert!(sql.starts_with('('));
            prop_assert!(sql.ends_with(')'));

            // 验证 OR 连接
            let or_count = sql.matches(" OR ").count();
            prop_assert_eq!(or_count, values.len() - 1);
        }
    }

    // **Validates: Requirements 5**
    //
    // 属性 P3:condition_to_sql_owned 与 condition_to_sql 等价性
    //
    // 形式化描述:对于任意 Condition c,
    // `condition_to_sql_owned(c.clone(), &mut p1)` 生成的 SQL 字符串
    // 与 `condition_to_sql(&c, &mut p2)` 完全相同,且参数列表长度相等。
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(200))]

        #[test]
        fn prop_owned_equals_borrowed_eq(
            field in field_name_strategy(),
            value in sql_value_strategy()
        ) {
            let cond = Condition::Eq(field, value);
            let mut p1 = vec![];
            let mut p2 = vec![];
            let sql1 = condition_to_sql_owned(cond.clone(), &mut p1);
            let sql2 = condition_to_sql(&cond, &mut p2);
            // SQL 字符串必须完全相同
            prop_assert_eq!(&sql1, &sql2);
            // 参数列表长度必须相等
            prop_assert_eq!(p1.len(), p2.len());
            // 参数值与顺序也必须完全一致(SqlValue 未实现 PartialEq,用整向量 Debug 串比较,
            // 一次同时覆盖元素值与顺序;sql_value_strategy 已把非有限 f64 归一为 0.0,Debug 确定)
            prop_assert_eq!(format!("{:?}", &p1), format!("{:?}", &p2));
        }

        #[test]
        fn prop_owned_equals_borrowed_ne(
            field in field_name_strategy(),
            value in sql_value_strategy()
        ) {
            let cond = Condition::Ne(field, value);
            let mut p1 = vec![];
            let mut p2 = vec![];
            let sql1 = condition_to_sql_owned(cond.clone(), &mut p1);
            let sql2 = condition_to_sql(&cond, &mut p2);
            prop_assert_eq!(&sql1, &sql2);
            prop_assert_eq!(p1.len(), p2.len());
            // 参数值与顺序也必须完全一致(SqlValue 未实现 PartialEq,用整向量 Debug 串比较,
            // 一次同时覆盖元素值与顺序;sql_value_strategy 已把非有限 f64 归一为 0.0,Debug 确定)
            prop_assert_eq!(format!("{:?}", &p1), format!("{:?}", &p2));
        }

        #[test]
        fn prop_owned_equals_borrowed_in(
            field in field_name_strategy(),
            values in prop::collection::vec(sql_value_strategy(), 0..8)
        ) {
            let cond = Condition::In(field, values);
            let mut p1 = vec![];
            let mut p2 = vec![];
            let sql1 = condition_to_sql_owned(cond.clone(), &mut p1);
            let sql2 = condition_to_sql(&cond, &mut p2);
            prop_assert_eq!(&sql1, &sql2);
            prop_assert_eq!(p1.len(), p2.len());
            // 参数值与顺序也必须完全一致(SqlValue 未实现 PartialEq,用整向量 Debug 串比较,
            // 一次同时覆盖元素值与顺序;sql_value_strategy 已把非有限 f64 归一为 0.0,Debug 确定)
            prop_assert_eq!(format!("{:?}", &p1), format!("{:?}", &p2));
        }

        #[test]
        fn prop_owned_equals_borrowed_between(
            field in field_name_strategy(),
            start in sql_value_strategy(),
            end in sql_value_strategy()
        ) {
            let cond = Condition::Between(field, start, end);
            let mut p1 = vec![];
            let mut p2 = vec![];
            let sql1 = condition_to_sql_owned(cond.clone(), &mut p1);
            let sql2 = condition_to_sql(&cond, &mut p2);
            prop_assert_eq!(&sql1, &sql2);
            prop_assert_eq!(p1.len(), p2.len());
            // 参数值与顺序也必须完全一致(SqlValue 未实现 PartialEq,用整向量 Debug 串比较,
            // 一次同时覆盖元素值与顺序;sql_value_strategy 已把非有限 f64 归一为 0.0,Debug 确定)
            prop_assert_eq!(format!("{:?}", &p1), format!("{:?}", &p2));
        }

        #[test]
        fn prop_owned_equals_borrowed_like(
            field in field_name_strategy(),
            pattern in "[a-zA-Z0-9_%]{1,20}"
        ) {
            let cond = Condition::Like(field, pattern);
            let mut p1 = vec![];
            let mut p2 = vec![];
            let sql1 = condition_to_sql_owned(cond.clone(), &mut p1);
            let sql2 = condition_to_sql(&cond, &mut p2);
            prop_assert_eq!(&sql1, &sql2);
            prop_assert_eq!(p1.len(), p2.len());
            // 参数值与顺序也必须完全一致(SqlValue 未实现 PartialEq,用整向量 Debug 串比较,
            // 一次同时覆盖元素值与顺序;sql_value_strategy 已把非有限 f64 归一为 0.0,Debug 确定)
            prop_assert_eq!(format!("{:?}", &p1), format!("{:?}", &p2));
        }

        #[test]
        fn prop_owned_equals_borrowed_and(
            field in field_name_strategy(),
            values in prop::collection::vec(sql_value_strategy(), 0..5)
        ) {
            // 构建 AND 条件
            let conditions: Vec<Condition> = values
                .iter()
                .map(|v| Condition::Eq(field.clone(), v.clone()))
                .collect();
            let cond = Condition::And(conditions);
            let mut p1 = vec![];
            let mut p2 = vec![];
            let sql1 = condition_to_sql_owned(cond.clone(), &mut p1);
            let sql2 = condition_to_sql(&cond, &mut p2);
            // SQL 字符串必须完全相同
            prop_assert_eq!(&sql1, &sql2);
            // 参数列表长度必须相等
            prop_assert_eq!(p1.len(), p2.len());
            // 参数值与顺序也必须完全一致(SqlValue 未实现 PartialEq,用整向量 Debug 串比较,
            // 一次同时覆盖元素值与顺序;sql_value_strategy 已把非有限 f64 归一为 0.0,Debug 确定)
            prop_assert_eq!(format!("{:?}", &p1), format!("{:?}", &p2));
        }

        #[test]
        fn prop_owned_equals_borrowed_or(
            field in field_name_strategy(),
            values in prop::collection::vec(sql_value_strategy(), 0..5)
        ) {
            // 构建 OR 条件
            let conditions: Vec<Condition> = values
                .iter()
                .map(|v| Condition::Eq(field.clone(), v.clone()))
                .collect();
            let cond = Condition::Or(conditions);
            let mut p1 = vec![];
            let mut p2 = vec![];
            let sql1 = condition_to_sql_owned(cond.clone(), &mut p1);
            let sql2 = condition_to_sql(&cond, &mut p2);
            // SQL 字符串必须完全相同
            prop_assert_eq!(&sql1, &sql2);
            // 参数列表长度必须相等
            prop_assert_eq!(p1.len(), p2.len());
            // 参数值与顺序也必须完全一致(SqlValue 未实现 PartialEq,用整向量 Debug 串比较,
            // 一次同时覆盖元素值与顺序;sql_value_strategy 已把非有限 f64 归一为 0.0,Debug 确定)
            prop_assert_eq!(format!("{:?}", &p1), format!("{:?}", &p2));
        }

        #[test]
        fn prop_owned_equals_borrowed_nested(
            field1 in field_name_strategy(),
            field2 in field_name_strategy(),
            values in prop::collection::vec(sql_value_strategy(), 2..4)
        ) {
            // 构建嵌套条件:(field1 = v1 OR field1 = v2) AND field2 = v3
            let or_conds: Vec<Condition> = values[..values.len()-1]
                .iter()
                .map(|v| Condition::Eq(field1.clone(), v.clone()))
                .collect();
            let cond = Condition::And(vec![
                Condition::Or(or_conds),
                Condition::Eq(field2.clone(), values.last().unwrap().clone()),
            ]);
            let mut p1 = vec![];
            let mut p2 = vec![];
            let sql1 = condition_to_sql_owned(cond.clone(), &mut p1);
            let sql2 = condition_to_sql(&cond, &mut p2);
            // SQL 字符串必须完全相同
            prop_assert_eq!(&sql1, &sql2);
            // 参数列表长度必须相等
            prop_assert_eq!(p1.len(), p2.len());
            // 参数值与顺序也必须完全一致(SqlValue 未实现 PartialEq,用整向量 Debug 串比较,
            // 一次同时覆盖元素值与顺序;sql_value_strategy 已把非有限 f64 归一为 0.0,Debug 确定)
            prop_assert_eq!(format!("{:?}", &p1), format!("{:?}", &p2));
        }
    }
}