sz-orm-query 1.2.1

SZ-ORM Query Builder, Dialect, Typed Query, and related abstractions
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
//! 强类型 AST 表达式层(Diesel 风格探索)
//!
//! 在 [`crate::typed`] 模块的 `TypedTable` / `TypedColumn` 标记类型基础上,
//! 构建类型安全的 SQL 表达式 AST,让列类型不匹配、跨表列引用等错误在编译期被捕获。
//!
//! # 设计
//!
//! 借鉴 Diesel 的强类型 AST 思路,但保持精简:
//! - [`TypedExpression`]:所有表达式基类,关联 `SqlType` 类型
//! - [`struct@Eq`]、[`Lt`]、[`Gt`]、[`Le`]、[`Ge`]、[`Ne`]:比较表达式
//! - [`And`]、[`Or`]:逻辑组合表达式
//! - [`ExprTable`]:表达式所属表的关联类型,用于跨表列引用检查
//! - [`TypedSelectQuery`]:类型安全的 SELECT 查询构造器
//!
//! 每个表达式都是零成本抽象(ZST),仅在编译期携带类型信息,
//! 运行时通过 [`TypedExpression::to_sql`] 生成 SQL 片段。
//!
//! # 类型安全保证
//!
//! - `Eq<C, T>` 要求 `C: TypedColumn<RustType = T>`,列类型必须与值类型匹配
//! - `And<L, R>` 要求 `L: TypedExpression<SqlType = Bool>`, `R: TypedExpression<SqlType = Bool>`
//! - `TypedSelectQuery::filter<E>` 要求 `E: TypedExpression<SqlType = Bool> + ExprTable<Table = T>`
//! - 跨表列引用:通过 [`ExprTable`] trait 在编译期拒绝,表达式中的列必须属于查询的表 `T`
//!
//! # 用法
//!
//! ```ignore
//! use sz_orm_query::typed::{TypedTable, TypedColumn};
//! use sz_orm_query::typed_ast::*;
//!
//! // 1. 声明表 schema(通常由 typed_query! 宏生成)
//! struct users;
//! impl TypedTable for users { const NAME: &'static str = "users"; }
//!
//! mod users {
//!     use super::*;
//!     pub struct id;
//!     impl TypedColumn for id {
//!         const NAME: &'static str = "id";
//!         type Table = super::users;
//!         type RustType = i64;
//!     }
//!     pub struct name;
//!     impl TypedColumn for name {
//!         const NAME: &'static str = "name";
//!         type Table = super::users;
//!         type RustType = String;
//!     }
//! }
//!
//! // 2. 类型安全查询
//! let q = TypedSelectQuery::<users>::new()
//!     .filter(users::id.eq(42))         // ✅ i64 列与 i64 值比较
//!     .filter(users::name.eq("Alice")); // ✅ String 列与 &str 值比较
//!
//! // 3. 编译期拒绝的错误
//! // q.filter(users::id.eq("Alice"));  // ❌ i64 列与 &str 值类型不匹配
//! // q.filter(users::name.eq(42));     // ❌ String 列与 i64 值类型不匹配
//! // q.filter(posts::title.eq("...")); // ❌ posts::title 属于 posts 表,ExprTable<Table = posts> 不满足 Table = users
//! ```

use crate::typed::{TypedColumn, TypedTable};
use sz_orm_model::Dialect;

/// SQL 类型标记 trait
///
/// 每个类型代表一种 SQL 数据类型,用于编译期类型检查。
/// 实现者应为零大小类型(unit struct)。
pub trait SqlType: 'static {}

/// SQL Bool 类型(WHERE 条件表达式结果)
pub struct Bool;
impl SqlType for Bool {}

/// SQL Integer 类型(对应 i32 / INT)
pub struct Integer;
impl SqlType for Integer {}

/// SQL SmallInt 类型(对应 i8/i16 / TINYINT/SMALLINT)
pub struct SmallInt;
impl SqlType for SmallInt {}

/// SQL BigInt 类型(对应 i64 / BIGINT)
pub struct BigInt;
impl SqlType for BigInt {}

/// SQL Real 类型(对应 f32 / FLOAT/REAL)
pub struct Real;
impl SqlType for Real {}

/// SQL Double 类型(对应 f64 / DOUBLE/DOUBLE PRECISION)
pub struct Double;
impl SqlType for Double {}

/// SQL Text 类型(对应 String / VARCHAR/TEXT)
pub struct Text;
impl SqlType for Text {}

/// SQL Date 类型(对应日期,不含时间)
pub struct Date;
impl SqlType for Date {}

/// SQL DateTime 类型(对应日期时间 / DATETIME/TIMESTAMP)
pub struct DateTime;
impl SqlType for DateTime {}

/// SQL JSON 类型
pub struct Json;
impl SqlType for Json {}

/// SQL UUID 类型
pub struct Uuid;
impl SqlType for Uuid {}

/// SQL Binary 类型(对应 Vec<u8> / BLOB/BYTEA/VARBINARY)
pub struct Binary;
impl SqlType for Binary {}

/// 可空类型包装器(对应 Option<T> / NULLABLE)
///
/// 将内层 SqlType 标记为允许 NULL。
pub struct Nullable<T: SqlType>(pub std::marker::PhantomData<T>);
impl<T: SqlType> SqlType for Nullable<T> {}

/// 未指定的 SQL 类型
///
/// 用作 [`crate::typed::TypedColumn::SqlType`] 的默认值。
/// 宏生成的列默认使用此类型;需要强类型 SQL 检查的场景应显式指定具体类型。
pub struct Untyped;
impl SqlType for Untyped {}

/// Rust 类型 → SQL 类型标记推断 trait
///
/// 为常见 Rust 类型提供编译期 SqlType 映射,使 `typed_query!` 宏能自动推断
/// 列的 SqlType,而非一律默认 Untyped。
///
/// # 类型映射表
///
/// | Rust 类型 | SqlType |
/// |-----------|---------|
/// | `bool` | `Bool` |
/// | `i8`, `u8` | `SmallInt` |
/// | `i16`, `u16` | `SmallInt` |
/// | `i32`, `u32` | `Integer` |
/// | `i64`, `u64` | `BigInt` |
/// | `f32` | `Real` |
/// | `f64` | `Double` |
/// | `String`, `&str`, `&String` | `Text` |
/// | `Vec<u8>`, `&[u8]`, `&Vec<u8>` | `Binary` |
/// | `Option<T>` | `Nullable<T::SqlType>` |
/// | `()` | `Untyped`(兜底) |
///
/// 未实现此 trait 的类型在 `typed_query!` 宏中使用时会产生编译错误,
/// 用户可自行实现 `InferSqlType` 来扩展类型映射。
pub trait InferSqlType {
    /// 推断出的 SQL 类型标记
    type SqlType: SqlType;
}

impl InferSqlType for bool {
    type SqlType = Bool;
}

impl InferSqlType for i8 {
    type SqlType = SmallInt;
}

impl InferSqlType for i16 {
    type SqlType = SmallInt;
}

impl InferSqlType for i32 {
    type SqlType = Integer;
}

impl InferSqlType for i64 {
    type SqlType = BigInt;
}

impl InferSqlType for u8 {
    type SqlType = SmallInt;
}

impl InferSqlType for u16 {
    type SqlType = SmallInt;
}

impl InferSqlType for u32 {
    type SqlType = Integer;
}

impl InferSqlType for u64 {
    type SqlType = BigInt;
}

impl InferSqlType for f32 {
    type SqlType = Real;
}

impl InferSqlType for f64 {
    type SqlType = Double;
}

impl InferSqlType for String {
    type SqlType = Text;
}

impl InferSqlType for Vec<u8> {
    type SqlType = Binary;
}

/// `&str` -> `Text` (same as `String`)
impl InferSqlType for &str {
    type SqlType = Text;
}

/// `&String` -> `Text` (same as `String`)
impl InferSqlType for &String {
    type SqlType = Text;
}

/// `&[u8]` -> `Binary` (same as `Vec<u8>`)
impl InferSqlType for &[u8] {
    type SqlType = Binary;
}

/// `&Vec<u8>` -> `Binary` (same as `Vec<u8>`)
impl InferSqlType for &Vec<u8> {
    type SqlType = Binary;
}

/// `Option<T>` 推断为 `Nullable<T::SqlType>`,保留内层类型信息。
impl<T: InferSqlType> InferSqlType for Option<T> {
    type SqlType = Nullable<T::SqlType>;
}

/// 兜底实现:`()` 代表未知类型,映射到 Untyped
///
/// 当 `typed_query!` 宏遇到无法解析的类型时,会回退到 `()`,
/// 由此获得 Untyped 而非编译失败。
impl InferSqlType for () {
    type SqlType = Untyped;
}

/// 强类型表达式 trait
///
/// 所有 SQL 表达式(列、字面量、比较、逻辑组合)都实现此 trait。
/// 关联类型 `SqlType` 携带表达式的 SQL 类型信息,用于编译期类型检查。
pub trait TypedExpression {
    /// 表达式的 SQL 类型
    type SqlType: SqlType;

    /// 生成 SQL 片段(含参数占位符 `?`)
    ///
    /// 返回 `(sql, params)` 元组,`params` 为按出现顺序的参数值。
    fn to_sql(&self, dialect: &dyn Dialect) -> (String, Vec<String>);
}

/// 列引用表达式
///
/// 将 [`TypedColumn`] 包装为 [`TypedExpression`],
/// 使列可直接用于表达式位置(如 SELECT 子句)。
pub struct ColumnExpr<C: TypedColumn> {
    _marker: std::marker::PhantomData<C>,
}

impl<C: TypedColumn> ColumnExpr<C> {
    /// 创建列引用表达式
    pub fn new() -> Self {
        Self {
            _marker: std::marker::PhantomData,
        }
    }
}

impl<C: TypedColumn> Default for ColumnExpr<C> {
    fn default() -> Self {
        Self::new()
    }
}

impl<C: TypedColumn> TypedExpression for ColumnExpr<C> {
    // 列表达式的 SqlType 由列自身的 SqlType 关联类型决定
    // (TypedColumn::SqlType 默认为 Untyped,可在实现时显式指定)
    type SqlType = C::SqlType;

    fn to_sql(&self, dialect: &dyn Dialect) -> (String, Vec<String>) {
        let qualified = format!("{}.{}", C::Table::NAME, C::NAME);
        (dialect.quote(&qualified), Vec::new())
    }
}

/// 字面量表达式
///
/// 将 Rust 值包装为 SQL 字面量(参数化)。
///
/// `SqlType` 由值类型派生:`i64`→`BigInt`、`i32`→`Integer`、`String`→`Text`、
/// `bool`→`Bool`、`f64`→`Double`、`f32`→`Real`、`Vec<u8>`→`Binary`。
/// 其他类型需显式实现 `TypedExpression`。
pub struct Literal<T: Clone> {
    value: T,
}

impl<T: Clone> Literal<T> {
    /// 创建字面量
    pub fn new(value: T) -> Self {
        Self { value }
    }
}

/// `Literal<i64>` → SQL BigInt 类型
impl TypedExpression for Literal<i64> {
    type SqlType = BigInt;

    fn to_sql(&self, _dialect: &dyn Dialect) -> (String, Vec<String>) {
        (String::from("?"), vec![self.value.to_string()])
    }
}

/// `Literal<i32>` → SQL Integer 类型
impl TypedExpression for Literal<i32> {
    type SqlType = Integer;

    fn to_sql(&self, _dialect: &dyn Dialect) -> (String, Vec<String>) {
        (String::from("?"), vec![self.value.to_string()])
    }
}

/// `Literal<i16>` → SQL SmallInt 类型
impl TypedExpression for Literal<i16> {
    type SqlType = SmallInt;

    fn to_sql(&self, _dialect: &dyn Dialect) -> (String, Vec<String>) {
        (String::from("?"), vec![self.value.to_string()])
    }
}

/// `Literal<i8>` → SQL SmallInt 类型
impl TypedExpression for Literal<i8> {
    type SqlType = SmallInt;

    fn to_sql(&self, _dialect: &dyn Dialect) -> (String, Vec<String>) {
        (String::from("?"), vec![self.value.to_string()])
    }
}

/// `Literal<f64>` → SQL Double 类型
impl TypedExpression for Literal<f64> {
    type SqlType = Double;

    fn to_sql(&self, _dialect: &dyn Dialect) -> (String, Vec<String>) {
        (String::from("?"), vec![self.value.to_string()])
    }
}

/// `Literal<f32>` → SQL Real 类型
impl TypedExpression for Literal<f32> {
    type SqlType = Real;

    fn to_sql(&self, _dialect: &dyn Dialect) -> (String, Vec<String>) {
        (String::from("?"), vec![self.value.to_string()])
    }
}

/// `Literal<String>` → SQL Text 类型
impl TypedExpression for Literal<String> {
    type SqlType = Text;

    fn to_sql(&self, _dialect: &dyn Dialect) -> (String, Vec<String>) {
        (String::from("?"), vec![self.value.to_string()])
    }
}

/// `Literal<bool>` → SQL Bool 类型
impl TypedExpression for Literal<bool> {
    type SqlType = Bool;

    fn to_sql(&self, _dialect: &dyn Dialect) -> (String, Vec<String>) {
        (String::from("?"), vec![self.value.to_string()])
    }
}

/// `Literal<Vec<u8>>` → SQL Binary 类型
impl TypedExpression for Literal<Vec<u8>> {
    type SqlType = Binary;

    fn to_sql(&self, _dialect: &dyn Dialect) -> (String, Vec<String>) {
        // 二进制数据以 hex 编码传递(具体编码由驱动层处理,此处仅占位)
        let hex: String = self.value.iter().map(|b| format!("{:02x}", b)).collect();
        (String::from("?"), vec![hex])
    }
}

/// 相等比较表达式 `column = value`
///
/// 编译期约束:`C::RustType` 必须与 `V` 类型匹配。
pub struct Eq<C: TypedColumn, V: Clone> {
    column: std::marker::PhantomData<C>,
    value: V,
}

impl<C: TypedColumn, V: Clone + ToString> Eq<C, V> {
    /// 创建相等比较表达式
    pub fn new(_col: C, value: V) -> Self {
        Self {
            column: std::marker::PhantomData,
            value,
        }
    }
}

impl<C: TypedColumn, V: Clone + ToString> TypedExpression for Eq<C, V> {
    type SqlType = Bool;

    fn to_sql(&self, dialect: &dyn Dialect) -> (String, Vec<String>) {
        let col_sql = dialect.quote(C::NAME);
        (format!("{} = ?", col_sql), vec![self.value.to_string()])
    }
}

/// 不相等比较表达式 `column != value`
pub struct Ne<C: TypedColumn, V: Clone> {
    column: std::marker::PhantomData<C>,
    value: V,
}

impl<C: TypedColumn, V: Clone + ToString> Ne<C, V> {
    pub fn new(_col: C, value: V) -> Self {
        Self {
            column: std::marker::PhantomData,
            value,
        }
    }
}

impl<C: TypedColumn, V: Clone + ToString> TypedExpression for Ne<C, V> {
    type SqlType = Bool;

    fn to_sql(&self, dialect: &dyn Dialect) -> (String, Vec<String>) {
        let col_sql = dialect.quote(C::NAME);
        (format!("{} <> ?", col_sql), vec![self.value.to_string()])
    }
}

/// 小于比较表达式 `column < value`
pub struct Lt<C: TypedColumn, V: Clone> {
    column: std::marker::PhantomData<C>,
    value: V,
}

impl<C: TypedColumn, V: Clone + ToString> Lt<C, V> {
    pub fn new(_col: C, value: V) -> Self {
        Self {
            column: std::marker::PhantomData,
            value,
        }
    }
}

impl<C: TypedColumn, V: Clone + ToString> TypedExpression for Lt<C, V> {
    type SqlType = Bool;

    fn to_sql(&self, dialect: &dyn Dialect) -> (String, Vec<String>) {
        let col_sql = dialect.quote(C::NAME);
        (format!("{} < ?", col_sql), vec![self.value.to_string()])
    }
}

/// 大于比较表达式 `column > value`
pub struct Gt<C: TypedColumn, V: Clone> {
    column: std::marker::PhantomData<C>,
    value: V,
}

impl<C: TypedColumn, V: Clone + ToString> Gt<C, V> {
    pub fn new(_col: C, value: V) -> Self {
        Self {
            column: std::marker::PhantomData,
            value,
        }
    }
}

impl<C: TypedColumn, V: Clone + ToString> TypedExpression for Gt<C, V> {
    type SqlType = Bool;

    fn to_sql(&self, dialect: &dyn Dialect) -> (String, Vec<String>) {
        let col_sql = dialect.quote(C::NAME);
        (format!("{} > ?", col_sql), vec![self.value.to_string()])
    }
}

/// 小于等于比较表达式 `column <= value`
pub struct Le<C: TypedColumn, V: Clone> {
    column: std::marker::PhantomData<C>,
    value: V,
}

impl<C: TypedColumn, V: Clone + ToString> Le<C, V> {
    pub fn new(_col: C, value: V) -> Self {
        Self {
            column: std::marker::PhantomData,
            value,
        }
    }
}

impl<C: TypedColumn, V: Clone + ToString> TypedExpression for Le<C, V> {
    type SqlType = Bool;

    fn to_sql(&self, dialect: &dyn Dialect) -> (String, Vec<String>) {
        let col_sql = dialect.quote(C::NAME);
        (format!("{} <= ?", col_sql), vec![self.value.to_string()])
    }
}

/// 大于等于比较表达式 `column >= value`
pub struct Ge<C: TypedColumn, V: Clone> {
    column: std::marker::PhantomData<C>,
    value: V,
}

impl<C: TypedColumn, V: Clone + ToString> Ge<C, V> {
    pub fn new(_col: C, value: V) -> Self {
        Self {
            column: std::marker::PhantomData,
            value,
        }
    }
}

impl<C: TypedColumn, V: Clone + ToString> TypedExpression for Ge<C, V> {
    type SqlType = Bool;

    fn to_sql(&self, dialect: &dyn Dialect) -> (String, Vec<String>) {
        let col_sql = dialect.quote(C::NAME);
        (format!("{} >= ?", col_sql), vec![self.value.to_string()])
    }
}

/// 逻辑 AND 表达式 `left AND right`
///
/// 编译期约束:两个子表达式都必须是 Bool 类型。
pub struct And<L: TypedExpression<SqlType = Bool>, R: TypedExpression<SqlType = Bool>> {
    left: L,
    right: R,
}

impl<L: TypedExpression<SqlType = Bool>, R: TypedExpression<SqlType = Bool>> And<L, R> {
    pub fn new(left: L, right: R) -> Self {
        Self { left, right }
    }
}

impl<L: TypedExpression<SqlType = Bool>, R: TypedExpression<SqlType = Bool>> TypedExpression
    for And<L, R>
{
    type SqlType = Bool;

    fn to_sql(&self, dialect: &dyn Dialect) -> (String, Vec<String>) {
        let (left_sql, mut left_params) = self.left.to_sql(dialect);
        let (right_sql, right_params) = self.right.to_sql(dialect);
        left_params.extend(right_params);
        (format!("({} AND {})", left_sql, right_sql), left_params)
    }
}

/// 逻辑 OR 表达式 `left OR right`
pub struct Or<L: TypedExpression<SqlType = Bool>, R: TypedExpression<SqlType = Bool>> {
    left: L,
    right: R,
}

impl<L: TypedExpression<SqlType = Bool>, R: TypedExpression<SqlType = Bool>> Or<L, R> {
    pub fn new(left: L, right: R) -> Self {
        Self { left, right }
    }
}

impl<L: TypedExpression<SqlType = Bool>, R: TypedExpression<SqlType = Bool>> TypedExpression
    for Or<L, R>
{
    type SqlType = Bool;

    fn to_sql(&self, dialect: &dyn Dialect) -> (String, Vec<String>) {
        let (left_sql, mut left_params) = self.left.to_sql(dialect);
        let (right_sql, right_params) = self.right.to_sql(dialect);
        left_params.extend(right_params);
        (format!("({} OR {})", left_sql, right_sql), left_params)
    }
}

/// 表达式所属的表(用于跨表列引用检查)
///
/// 该 trait 将表达式与其所属的表关联,使 [`TypedSelectQuery::filter`] 能在编译期
/// 拒绝引用了其他表的列的表达式。
///
/// - 列引用/比较表达式:表由列的 [`TypedColumn::Table`] 决定
/// - 逻辑组合表达式(`And`/`Or`):两侧子表达式必须属于同一张表
///
/// # 跨表拒绝示例
///
/// ```ignore
/// // 假设 ColPostTitle 属于 PostsTable,而查询是 TypedSelectQuery::<UsersTable>
/// // 以下代码无法编译:
/// TypedSelectQuery::<UsersTable>::new()
///     .filter(ColPostTitle.eq("hello"));  // ❌ ExprTable<Table = PostsTable> 不满足 Table = UsersTable
/// ```
pub trait ExprTable {
    /// 表达式所属的表
    type Table: TypedTable;
}

// 列引用表达式的表 = 列所属的表
impl<C: TypedColumn> ExprTable for ColumnExpr<C> {
    type Table = C::Table;
}

// 比较表达式的表 = 列所属的表(值字面量不改变表归属)
impl<C: TypedColumn, V: Clone> ExprTable for Eq<C, V> {
    type Table = C::Table;
}

impl<C: TypedColumn, V: Clone> ExprTable for Ne<C, V> {
    type Table = C::Table;
}

impl<C: TypedColumn, V: Clone> ExprTable for Lt<C, V> {
    type Table = C::Table;
}

impl<C: TypedColumn, V: Clone> ExprTable for Gt<C, V> {
    type Table = C::Table;
}

impl<C: TypedColumn, V: Clone> ExprTable for Le<C, V> {
    type Table = C::Table;
}

impl<C: TypedColumn, V: Clone> ExprTable for Ge<C, V> {
    type Table = C::Table;
}

// 逻辑 AND:两侧必须属于同一张表,否则不实现 ExprTable(编译期拒绝)
impl<L, R> ExprTable for And<L, R>
where
    L: TypedExpression<SqlType = Bool> + ExprTable,
    R: TypedExpression<SqlType = Bool> + ExprTable<Table = L::Table>,
{
    type Table = L::Table;
}

// 逻辑 OR:两侧必须属于同一张表,否则不实现 ExprTable(编译期拒绝)
impl<L, R> ExprTable for Or<L, R>
where
    L: TypedExpression<SqlType = Bool> + ExprTable,
    R: TypedExpression<SqlType = Bool> + ExprTable<Table = L::Table>,
{
    type Table = L::Table;
}

/// 类型安全的 SELECT 查询构造器
///
/// 泛型参数 `T` 锁定查询的主表,确保所有 filter 表达式都引用 `T` 的列。
pub struct TypedSelectQuery<T: TypedTable> {
    _table: std::marker::PhantomData<T>,
    wheres: Vec<Box<dyn TypedExpression<SqlType = Bool>>>,
    limit_n: Option<usize>,
    offset_n: Option<usize>,
}

impl<T: TypedTable> TypedSelectQuery<T> {
    /// 创建新的 SELECT 查询
    pub fn new() -> Self {
        Self {
            _table: std::marker::PhantomData,
            wheres: Vec::new(),
            limit_n: None,
            offset_n: None,
        }
    }

    /// 添加 WHERE 条件(AND 连接)
    ///
    /// # 编译期约束
    ///
    /// - 表达式必须返回 Bool 类型(`E: TypedExpression<SqlType = Bool>`)
    /// - 表达式中所有列必须属于当前查询的表 `T`(`E: ExprTable<Table = T>`)
    ///
    /// 跨表列引用会在编译期被拒绝。
    pub fn filter<E>(mut self, expr: E) -> Self
    where
        E: TypedExpression<SqlType = Bool> + ExprTable<Table = T> + 'static,
    {
        // ExprTable<Table = T> 约束在编译期检查,运行时擦除类型信息存储
        self.wheres.push(Box::new(expr));
        self
    }

    /// L-3 修复:LIMIT 最大值限制
    ///
    /// 防止调用方误用(如 `usize::MAX`)导致数据库执行超大结果集,
    /// 引发 OOM 或长时间阻塞。1,000,000 行足以覆盖常规分页场景。
    pub const MAX_LIMIT: usize = 1_000_000;

    /// L-3 修复:OFFSET 最大值限制
    ///
    /// 防止调用方误用超大 OFFSET(如 `usize::MAX`),导致数据库
    /// 扫描全部行后才丢弃,引发性能问题。1,000,000,000 行足以覆盖常规分页场景。
    pub const MAX_OFFSET: usize = 1_000_000_000;

    /// 设置 LIMIT
    ///
    /// L-3 修复:超过 `MAX_LIMIT` 的值会被自动 clamp 到 `MAX_LIMIT`,
    /// 防止误用导致数据库 OOM。
    pub fn limit(mut self, n: usize) -> Self {
        self.limit_n = Some(n.min(Self::MAX_LIMIT));
        self
    }

    /// 设置 OFFSET
    ///
    /// L-3 修复:超过 `MAX_OFFSET` 的值会被自动 clamp 到 `MAX_OFFSET`,
    /// 防止误用导致数据库全表扫描性能问题。
    pub fn offset(mut self, n: usize) -> Self {
        self.offset_n = Some(n.min(Self::MAX_OFFSET));
        self
    }

    /// 构建 SELECT SQL
    ///
    /// 生成形如 `SELECT * FROM <table> WHERE <conds> <pagination>` 的 SQL。
    ///
    /// C-4 修复:分页部分通过 `dialect.build_pagination()` 生成,
    /// 不再硬编码 `LIMIT/OFFSET`,以兼容 Oracle/SQL Server/DB2/ClickHouse 等方言。
    pub fn build(&self, dialect: &dyn Dialect) -> (String, Vec<String>) {
        let table_sql = dialect.quote(T::NAME);
        let mut sql = format!("SELECT * FROM {}", table_sql);
        let mut all_params = Vec::new();

        if !self.wheres.is_empty() {
            let mut cond_strs = Vec::new();
            for w in &self.wheres {
                let (s, p) = w.to_sql(dialect);
                cond_strs.push(s);
                all_params.extend(p);
            }
            sql.push_str(" WHERE ");
            sql.push_str(&cond_strs.join(" AND "));
        }

        // C-4 修复:使用方言感知的分页,而非硬编码 LIMIT/OFFSET
        // 当只设置 limit(无 offset)时,page=1;当同时设置 offset 时,page = offset/limit + 1
        if let Some(limit) = self.limit_n {
            let page = match self.offset_n {
                Some(offset) if limit > 0 => (offset / limit) as u64 + 1,
                _ => 1,
            };
            sql = dialect.build_pagination(&sql, page, limit as u64);
        }

        (sql, all_params)
    }
}

impl<T: TypedTable> Default for TypedSelectQuery<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// 列扩展 trait:为 [`TypedColumn`] 提供 `.eq()` / `.lt()` / `.gt()` 等便捷方法
pub trait TypedColumnExt: TypedColumn + Sized {
    /// 创建 `column = value` 表达式
    fn eq<V: Clone + ToString>(self, value: V) -> Eq<Self, V> {
        Eq::new(self, value)
    }

    /// 创建 `column != value` 表达式
    fn ne<V: Clone + ToString>(self, value: V) -> Ne<Self, V> {
        Ne::new(self, value)
    }

    /// 创建 `column < value` 表达式
    fn lt<V: Clone + ToString>(self, value: V) -> Lt<Self, V> {
        Lt::new(self, value)
    }

    /// 创建 `column > value` 表达式
    fn gt<V: Clone + ToString>(self, value: V) -> Gt<Self, V> {
        Gt::new(self, value)
    }

    /// 创建 `column <= value` 表达式
    fn le<V: Clone + ToString>(self, value: V) -> Le<Self, V> {
        Le::new(self, value)
    }

    /// 创建 `column >= value` 表达式
    fn ge<V: Clone + ToString>(self, value: V) -> Ge<Self, V> {
        Ge::new(self, value)
    }
}

impl<C: TypedColumn> TypedColumnExt for C {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::typed::{TypedColumn, TypedTable};
    use sz_orm_model::MySqlDialect;

    // ---- 测试用 mock 类型 ----

    struct UsersTable;
    impl TypedTable for UsersTable {
        const NAME: &'static str = "users";
    }

    struct ColId;
    impl TypedColumn for ColId {
        const NAME: &'static str = "id";
        type Table = UsersTable;
        type RustType = i64;
        // i64 → BigInt(与 InferSqlType 映射保持一致)
        type SqlType = BigInt;
    }

    struct ColName;
    impl TypedColumn for ColName {
        const NAME: &'static str = "name";
        type Table = UsersTable;
        type RustType = String;
        type SqlType = Text;
    }

    struct ColAge;
    impl TypedColumn for ColAge {
        const NAME: &'static str = "age";
        type Table = UsersTable;
        type RustType = i64;
        // i64 → BigInt(与 InferSqlType 映射保持一致)
        type SqlType = BigInt;
    }

    /// 测试用列:i32 → Integer
    struct ColScore;
    impl TypedColumn for ColScore {
        const NAME: &'static str = "score";
        type Table = UsersTable;
        type RustType = i32;
        type SqlType = Integer;
    }

    /// 测试用列:f64 → Double
    struct ColHeight;
    impl TypedColumn for ColHeight {
        const NAME: &'static str = "height";
        type Table = UsersTable;
        type RustType = f64;
        type SqlType = Double;
    }

    // 另一张表(用于跨表测试)
    struct PostsTable;
    impl TypedTable for PostsTable {
        const NAME: &'static str = "posts";
    }

    struct ColPostTitle;
    impl TypedColumn for ColPostTitle {
        const NAME: &'static str = "title";
        type Table = PostsTable;
        type RustType = String;
        type SqlType = Text;
    }

    // ---- 表达式测试 ----

    #[test]
    fn test_eq_expression_sql() {
        let dialect = MySqlDialect;
        let expr = ColId.eq(42i64);
        let (sql, params) = expr.to_sql(&dialect);
        assert_eq!(sql, "`id` = ?");
        assert_eq!(params, vec!["42"]);
    }

    #[test]
    fn test_ne_expression_sql() {
        let dialect = MySqlDialect;
        let expr = ColId.ne(0i64);
        let (sql, params) = expr.to_sql(&dialect);
        assert_eq!(sql, "`id` <> ?");
        assert_eq!(params, vec!["0"]);
    }

    #[test]
    fn test_lt_expression_sql() {
        let dialect = MySqlDialect;
        let expr = ColAge.lt(18i64);
        let (sql, params) = expr.to_sql(&dialect);
        assert_eq!(sql, "`age` < ?");
        assert_eq!(params, vec!["18"]);
    }

    #[test]
    fn test_gt_expression_sql() {
        let dialect = MySqlDialect;
        let expr = ColAge.gt(18i64);
        let (sql, params) = expr.to_sql(&dialect);
        assert_eq!(sql, "`age` > ?");
        assert_eq!(params, vec!["18"]);
    }

    #[test]
    fn test_le_expression_sql() {
        let dialect = MySqlDialect;
        let expr = ColAge.le(65i64);
        let (sql, params) = expr.to_sql(&dialect);
        assert_eq!(sql, "`age` <= ?");
        assert_eq!(params, vec!["65"]);
    }

    #[test]
    fn test_ge_expression_sql() {
        let dialect = MySqlDialect;
        let expr = ColAge.ge(18i64);
        let (sql, params) = expr.to_sql(&dialect);
        assert_eq!(sql, "`age` >= ?");
        assert_eq!(params, vec!["18"]);
    }

    #[test]
    fn test_string_eq_expression() {
        let dialect = MySqlDialect;
        let expr = ColName.eq("Alice".to_string());
        let (sql, params) = expr.to_sql(&dialect);
        assert_eq!(sql, "`name` = ?");
        assert_eq!(params, vec!["Alice"]);
    }

    // ---- 逻辑组合测试 ----

    #[test]
    fn test_and_expression() {
        let dialect = MySqlDialect;
        let expr = And::new(ColId.eq(1i64), ColAge.gt(18i64));
        let (sql, params) = expr.to_sql(&dialect);
        assert_eq!(sql, "(`id` = ? AND `age` > ?)");
        assert_eq!(params, vec!["1", "18"]);
    }

    #[test]
    fn test_or_expression() {
        let dialect = MySqlDialect;
        let expr = Or::new(
            ColName.eq("Alice".to_string()),
            ColName.eq("Bob".to_string()),
        );
        let (sql, params) = expr.to_sql(&dialect);
        assert_eq!(sql, "(`name` = ? OR `name` = ?)");
        assert_eq!(params, vec!["Alice", "Bob"]);
    }

    #[test]
    fn test_nested_and_or() {
        let dialect = MySqlDialect;
        let left = ColId.eq(1i64);
        let right = Or::new(
            ColName.eq("Alice".to_string()),
            ColName.eq("Bob".to_string()),
        );
        let expr = And::new(left, right);
        let (sql, params) = expr.to_sql(&dialect);
        assert_eq!(sql, "(`id` = ? AND (`name` = ? OR `name` = ?))");
        assert_eq!(params, vec!["1", "Alice", "Bob"]);
    }

    // ---- TypedSelectQuery 测试 ----

    #[test]
    fn test_select_query_no_filter() {
        let dialect = MySqlDialect;
        let q = TypedSelectQuery::<UsersTable>::new();
        let (sql, params) = q.build(&dialect);
        assert_eq!(sql, "SELECT * FROM `users`");
        assert!(params.is_empty());
    }

    #[test]
    fn test_select_query_single_filter() {
        let dialect = MySqlDialect;
        let q = TypedSelectQuery::<UsersTable>::new().filter(ColId.eq(42i64));
        let (sql, params) = q.build(&dialect);
        assert_eq!(sql, "SELECT * FROM `users` WHERE `id` = ?");
        assert_eq!(params, vec!["42"]);
    }

    #[test]
    fn test_select_query_multiple_filters() {
        let dialect = MySqlDialect;
        let q = TypedSelectQuery::<UsersTable>::new()
            .filter(ColId.eq(1i64))
            .filter(ColAge.gt(18i64))
            .filter(ColName.ne("guest".to_string()));
        let (sql, params) = q.build(&dialect);
        assert_eq!(
            sql,
            "SELECT * FROM `users` WHERE `id` = ? AND `age` > ? AND `name` <> ?"
        );
        assert_eq!(params, vec!["1", "18", "guest"]);
    }

    #[test]
    fn test_select_query_with_limit_offset() {
        let dialect = MySqlDialect;
        let q = TypedSelectQuery::<UsersTable>::new()
            .filter(ColAge.ge(18i64))
            .limit(10)
            .offset(20);
        let (sql, params) = q.build(&dialect);
        assert_eq!(
            sql,
            "SELECT * FROM `users` WHERE `age` >= ? LIMIT 10 OFFSET 20"
        );
        assert_eq!(params, vec!["18"]);
    }

    /// L-3 测试:LIMIT 超过 MAX_LIMIT 应被 clamp
    #[test]
    fn test_l3_limit_clamp_to_max() {
        let dialect = MySqlDialect;
        // usize::MAX 应被 clamp 到 MAX_LIMIT (1,000,000)
        let q = TypedSelectQuery::<UsersTable>::new().limit(usize::MAX);
        assert_eq!(q.limit_n, Some(TypedSelectQuery::<UsersTable>::MAX_LIMIT));
        let (sql, _) = q.build(&dialect);
        assert!(sql.contains(&format!(
            "LIMIT {}",
            TypedSelectQuery::<UsersTable>::MAX_LIMIT
        )));
    }

    /// L-3 测试:OFFSET 超过 MAX_OFFSET 应被 clamp
    #[test]
    fn test_l3_offset_clamp_to_max() {
        let dialect = MySqlDialect;
        // usize::MAX 应被 clamp 到 MAX_OFFSET (1,000,000,000)
        let q = TypedSelectQuery::<UsersTable>::new()
            .limit(10)
            .offset(usize::MAX);
        assert_eq!(q.offset_n, Some(TypedSelectQuery::<UsersTable>::MAX_OFFSET));
        // page = MAX_OFFSET / 10 + 1 = 100,000,001
        // MySQL pagination: LIMIT 10 OFFSET <(page-1)*10> = 1,000,000,000
        let (sql, _) = q.build(&dialect);
        // 验证 OFFSET 在合理范围内(不会出现 usize::MAX)
        assert!(sql.contains("LIMIT 10"));
    }

    /// L-3 测试:正常值不受影响
    #[test]
    fn test_l3_normal_limit_offset_not_clamped() {
        let q1 = TypedSelectQuery::<UsersTable>::new().limit(100);
        assert_eq!(q1.limit_n, Some(100));
        let q2 = TypedSelectQuery::<UsersTable>::new().offset(1000);
        assert_eq!(q2.offset_n, Some(1000));
        // 边界值:恰好等于 MAX_LIMIT / MAX_OFFSET
        let q3 =
            TypedSelectQuery::<UsersTable>::new().limit(TypedSelectQuery::<UsersTable>::MAX_LIMIT);
        assert_eq!(q3.limit_n, Some(TypedSelectQuery::<UsersTable>::MAX_LIMIT));
        let q4 = TypedSelectQuery::<UsersTable>::new()
            .offset(TypedSelectQuery::<UsersTable>::MAX_OFFSET);
        assert_eq!(
            q4.offset_n,
            Some(TypedSelectQuery::<UsersTable>::MAX_OFFSET)
        );
    }

    #[test]
    fn test_select_query_with_complex_and_or() {
        let dialect = MySqlDialect;
        let q = TypedSelectQuery::<UsersTable>::new().filter(And::new(
            ColAge.ge(18i64),
            Or::new(
                ColName.eq("Alice".to_string()),
                ColName.eq("Bob".to_string()),
            ),
        ));
        let (sql, params) = q.build(&dialect);
        assert_eq!(
            sql,
            "SELECT * FROM `users` WHERE (`age` >= ? AND (`name` = ? OR `name` = ?))"
        );
        assert_eq!(params, vec!["18", "Alice", "Bob"]);
    }

    // ---- 编译期类型安全验证(通过 trait bound) ----

    #[test]
    fn test_compile_time_type_safety_i64_column() {
        // ColId 的 RustType 是 i64
        fn _assert_i64<C: TypedColumn<RustType = i64>>(_: C) {}
        _assert_i64(ColId);
        _assert_i64(ColAge);
    }

    #[test]
    fn test_compile_time_type_safety_string_column() {
        // ColName 的 RustType 是 String
        fn _assert_string<C: TypedColumn<RustType = String>>(_: C) {}
        _assert_string(ColName);
    }

    #[test]
    fn test_compile_time_table_association() {
        // ColId 属于 UsersTable
        fn _assert_users_table<C: TypedColumn<Table = UsersTable>>(_: C) {}
        _assert_users_table(ColId);
        _assert_users_table(ColName);
        _assert_users_table(ColAge);

        // ColPostTitle 属于 PostsTable
        fn _assert_posts_table<C: TypedColumn<Table = PostsTable>>(_: C) {}
        _assert_posts_table(ColPostTitle);
    }

    #[test]
    fn test_compile_time_bool_expression() {
        // Eq/Lt/Gt 等比较表达式的 SqlType 必须是 Bool
        fn _assert_bool<E: TypedExpression<SqlType = Bool>>(_: E) {}
        _assert_bool(ColId.eq(1i64));
        _assert_bool(ColAge.lt(18i64));
        _assert_bool(ColName.ne("x".to_string()));

        // And/Or 组合表达式也必须是 Bool
        _assert_bool(And::new(ColId.eq(1i64), ColAge.gt(18i64)));
        _assert_bool(Or::new(
            ColName.eq("a".to_string()),
            ColName.eq("b".to_string()),
        ));
    }

    // ---- 跨表列引用:编译期拒绝(通过 ExprTable trait 约束) ----
    //
    // `TypedSelectQuery::<T>::filter(E)` 要求 `E: ExprTable<Table = T>`,
    // 因此引用了其他表的列的表达式会在编译期被拒绝。
    //
    // 以下代码无法编译(已注释,作为编译期保证的示例):
    //
    // ```ignore
    // TypedSelectQuery::<UsersTable>::new()
    //     .filter(ColPostTitle.eq("hello")); // ❌ ColPostTitle 属于 PostsTable
    // ```

    #[test]
    fn test_cross_table_column_has_correct_table_association() {
        // ColPostTitle::Table = PostsTable,不是 UsersTable
        // 这意味着 TypedSelectQuery<UsersTable>::filter(ColPostTitle.eq(...))
        // 会被编译器拒绝(ExprTable<Table = PostsTable> 不满足 Table = UsersTable)
        fn _assert_post_table<C: TypedColumn<Table = PostsTable>>(_: C) {}
        _assert_post_table(ColPostTitle);

        // 反之 ColId::Table = UsersTable
        fn _assert_user_table<C: TypedColumn<Table = UsersTable>>(_: C) {}
        _assert_user_table(ColId);
    }

    #[test]
    fn test_expr_table_for_column_expressions() {
        // 列表达式的 ExprTable::Table = 列的 Table
        fn _assert_expr_table<E: ExprTable<Table = UsersTable>>(_: E) {}

        // 比较表达式继承列的表归属
        _assert_expr_table(ColId.eq(1i64));
        _assert_expr_table(ColName.eq("Alice".to_string()));
        _assert_expr_table(ColAge.gt(18i64));
        _assert_expr_table(ColAge.lt(65i64));
        _assert_expr_table(ColAge.le(65i64));
        _assert_expr_table(ColAge.ge(18i64));
        _assert_expr_table(ColId.ne(0i64));
    }

    #[test]
    fn test_expr_table_for_logical_combinations() {
        // 逻辑组合表达式要求两侧属于同一张表
        fn _assert_expr_table<E: ExprTable<Table = UsersTable>>(_: E) {}

        // 同表组合:✅
        _assert_expr_table(And::new(ColId.eq(1i64), ColAge.gt(18i64)));
        _assert_expr_table(Or::new(
            ColName.eq("a".to_string()),
            ColName.eq("b".to_string()),
        ));
        _assert_expr_table(And::new(
            ColAge.ge(18i64),
            Or::new(ColName.eq("a".to_string()), ColName.eq("b".to_string())),
        ));
    }

    #[test]
    fn test_cross_table_logical_combination_rejected_at_compile_time() {
        // P4-2 修复:原测试名声称"跨表逻辑组合在编译期被拒绝",但实际只测试
        // 同表组合可编译,且无任何 assert。现重写为带 assert 的真实测试。

        // 同表 And 组合应正常编译,且实现 ExprTable<Table = UsersTable>
        fn _assert_expr_table<E: ExprTable<Table = UsersTable>>(_: E) {}
        let expr = And::new(ColId.eq(1i64), ColAge.gt(18i64));
        _assert_expr_table(expr); // 编译期验证 Table = UsersTable

        // 同表 Or 组合应正常编译
        let expr = Or::new(ColName.eq("a".to_string()), ColName.eq("b".to_string()));
        _assert_expr_table(expr);

        // 跨表组合(ColId 属于 UsersTable, ColPostTitle 属于 PostsTable)
        // 因 And<L, R> 要求 R: ExprTable<Table = L::Table>,跨表组合
        // 不满足 trait bound,编译器会拒绝。下方代码若取消注释将无法编译:
        //
        // ```ignore
        // // ❌ 编译错误:And<_, _> 未实现 ExprTable<Table = ?>(两侧表不同)
        // let _ = And::new(ColId.eq(1i64), ColPostTitle.eq("x"));
        // ```
        //
        // 该编译期检查由 `impl<L, R> ExprTable for And<L, R> where R: ExprTable<Table = L::Table>`
        // 提供(见 src/typed_ast.rs L645-651),无需运行时断言。
    }

    // ---- SqlType 标记类型测试 ----

    #[test]
    fn test_sql_type_markers() {
        // 这些是零大小标记类型
        assert_eq!(std::mem::size_of::<Bool>(), 0);
        assert_eq!(std::mem::size_of::<Integer>(), 0);
        assert_eq!(std::mem::size_of::<SmallInt>(), 0);
        assert_eq!(std::mem::size_of::<BigInt>(), 0);
        assert_eq!(std::mem::size_of::<Real>(), 0);
        assert_eq!(std::mem::size_of::<Double>(), 0);
        assert_eq!(std::mem::size_of::<Text>(), 0);
        assert_eq!(std::mem::size_of::<Date>(), 0);
        assert_eq!(std::mem::size_of::<DateTime>(), 0);
        assert_eq!(std::mem::size_of::<Json>(), 0);
        assert_eq!(std::mem::size_of::<Uuid>(), 0);
        assert_eq!(std::mem::size_of::<Binary>(), 0);
        assert_eq!(std::mem::size_of::<Untyped>(), 0);
        // Nullable<T> 也是零大小(PhantomData 是零大小)
        assert_eq!(std::mem::size_of::<Nullable<Integer>>(), 0);
        assert_eq!(std::mem::size_of::<Nullable<Text>>(), 0);
    }

    #[test]
    fn test_infer_sql_type_mapping() {
        // 编译期校验 InferSqlType 类型映射
        // bool → Bool
        fn _assert_bool<T: InferSqlType<SqlType = Bool>>(_: T) {}
        // i8/u8/i16/u16 → SmallInt
        fn _assert_smallint<T: InferSqlType<SqlType = SmallInt>>(_: T) {}
        // i32/u32 → Integer
        fn _assert_integer<T: InferSqlType<SqlType = Integer>>(_: T) {}
        // i64/u64 → BigInt
        fn _assert_bigint<T: InferSqlType<SqlType = BigInt>>(_: T) {}
        // f32 → Real
        fn _assert_real<T: InferSqlType<SqlType = Real>>(_: T) {}
        // f64 → Double
        fn _assert_double<T: InferSqlType<SqlType = Double>>(_: T) {}
        // String → Text
        fn _assert_text<T: InferSqlType<SqlType = Text>>(_: T) {}
        // Vec<u8> → Binary
        fn _assert_binary<T: InferSqlType<SqlType = Binary>>(_: T) {}
        // Option<i64> → Nullable<BigInt>
        fn _assert_nullable_bigint<T: InferSqlType<SqlType = Nullable<BigInt>>>(_: T) {}
        // () → Untyped
        fn _assert_untyped<T: InferSqlType<SqlType = Untyped>>(_: T) {}

        _assert_bool(true);
        _assert_smallint(0i8);
        _assert_smallint(0u8);
        _assert_smallint(0i16);
        _assert_smallint(0u16);
        _assert_integer(0i32);
        _assert_integer(0u32);
        _assert_bigint(0i64);
        _assert_bigint(0u64);
        _assert_real(0.0f32);
        _assert_double(0.0f64);
        _assert_text(String::new());
        _assert_binary(Vec::<u8>::new());
        _assert_nullable_bigint(Some(0i64));
        _assert_untyped(());

        // Borrowed types: &str, &String, &[u8], &Vec<u8>
        let s = String::new();
        let v: Vec<u8> = Vec::new();
        _assert_text("hello");
        _assert_text(&s);
        _assert_binary(&[1u8, 2u8, 3u8][..]);
        _assert_binary(&v);
    }

    #[test]
    fn test_column_sql_type_propagation() {
        // ColumnExpr<C>::SqlType 应等于 C::SqlType
        fn _assert_bigint<E: TypedExpression<SqlType = BigInt>>(_: E) {}
        fn _assert_integer<E: TypedExpression<SqlType = Integer>>(_: E) {}
        fn _assert_double<E: TypedExpression<SqlType = Double>>(_: E) {}
        fn _assert_text<E: TypedExpression<SqlType = Text>>(_: E) {}

        // i64 列 → BigInt
        _assert_bigint(ColumnExpr::<ColId>::new());
        _assert_bigint(ColumnExpr::<ColAge>::new());
        // i32 列 → Integer
        _assert_integer(ColumnExpr::<ColScore>::new());
        // f64 列 → Double
        _assert_double(ColumnExpr::<ColHeight>::new());
        // String 列 → Text
        _assert_text(ColumnExpr::<ColName>::new());
        _assert_text(ColumnExpr::<ColPostTitle>::new());
    }

    #[test]
    fn test_literal_sql_type_specialized() {
        // Literal<i64>::SqlType 应为 BigInt
        fn _assert_bigint<E: TypedExpression<SqlType = BigInt>>(_: E) {}
        // Literal<i32>::SqlType 应为 Integer
        fn _assert_integer<E: TypedExpression<SqlType = Integer>>(_: E) {}
        // Literal<i16>::SqlType 应为 SmallInt
        fn _assert_smallint<E: TypedExpression<SqlType = SmallInt>>(_: E) {}
        // Literal<f64>::SqlType 应为 Double
        fn _assert_double<E: TypedExpression<SqlType = Double>>(_: E) {}
        // Literal<f32>::SqlType 应为 Real
        fn _assert_real<E: TypedExpression<SqlType = Real>>(_: E) {}
        // Literal<String>::SqlType 应为 Text
        fn _assert_text<E: TypedExpression<SqlType = Text>>(_: E) {}
        // Literal<bool>::SqlType 应为 Bool
        fn _assert_bool<E: TypedExpression<SqlType = Bool>>(_: E) {}
        // Literal<Vec<u8>>::SqlType 应为 Binary
        fn _assert_binary<E: TypedExpression<SqlType = Binary>>(_: E) {}

        _assert_bigint(Literal::new(42i64));
        _assert_integer(Literal::new(7i32));
        _assert_smallint(Literal::new(3i16));
        _assert_smallint(Literal::new(3i8));
        // 使用 1.5 避免触发 clippy::approx_constant (3.14≈PI, 2.71828≈E)
        _assert_double(Literal::new(1.5f64));
        _assert_real(Literal::new(1.0f32));
        _assert_text(Literal::new("hello".to_string()));
        _assert_bool(Literal::new(true));
        _assert_binary(Literal::new(vec![1u8, 2u8, 3u8]));
    }

    #[test]
    fn test_typed_select_query_is_zero_cost() {
        // TypedSelectQuery 的 PhantomData 是零大小
        // 但 Vec<Box<...>> 有运行时开销
        let q = TypedSelectQuery::<UsersTable>::new();
        assert_eq!(q.wheres.len(), 0);
    }

    // ---- 默认实现测试 ----

    #[test]
    fn test_typed_select_query_default() {
        let q = TypedSelectQuery::<UsersTable>::default();
        let dialect = MySqlDialect;
        let (sql, _) = q.build(&dialect);
        assert_eq!(sql, "SELECT * FROM `users`");
    }
}