prax-query 0.9.1

Type-safe query builder for the Prax ORM
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
//! Table partitioning and sharding support.
//!
//! This module provides types for defining and managing table partitions
//! across different database backends.
//!
//! # Supported Features
//!
//! | Feature            | PostgreSQL | MySQL | SQLite | MSSQL | MongoDB |
//! |--------------------|------------|-------|--------|-------|---------|
//! | Range Partitioning | ✅         | ✅    | ❌     | ✅    | ✅*     |
//! | List Partitioning  | ✅         | ✅    | ❌     | ✅    | ❌      |
//! | Hash Partitioning  | ✅         | ✅    | ❌     | ✅    | ✅*     |
//! | Partition Pruning  | ✅         | ✅    | ❌     | ✅    | ✅      |
//! | Zone Sharding      | ❌         | ❌    | ❌     | ❌    | ✅      |
//!
//! > *MongoDB uses sharding with range or hashed shard keys
//!
//! # Example Usage
//!
//! ```rust,ignore
//! use prax_query::partition::{Partition, PartitionType, RangeBound};
//!
//! // Define a range-partitioned table
//! let partition = Partition::builder("orders")
//!     .range_partition()
//!     .column("created_at")
//!     .add_range("orders_2024_q1", RangeBound::from("2024-01-01"), RangeBound::to("2024-04-01"))
//!     .add_range("orders_2024_q2", RangeBound::from("2024-04-01"), RangeBound::to("2024-07-01"))
//!     .build();
//!
//! // Generate SQL
//! let sql = partition.to_postgres_sql()?;
//! ```

use std::borrow::Cow;

use serde::{Deserialize, Serialize};

use crate::error::{QueryError, QueryResult};
use crate::sql::DatabaseType;

/// The type of partitioning strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PartitionType {
    /// Partition by value ranges (e.g., date ranges).
    Range,
    /// Partition by specific values (e.g., country codes).
    List,
    /// Partition by hash of column values.
    Hash,
}

impl PartitionType {
    /// Convert to SQL keyword for PostgreSQL.
    pub fn to_postgres_sql(&self) -> &'static str {
        match self {
            Self::Range => "RANGE",
            Self::List => "LIST",
            Self::Hash => "HASH",
        }
    }

    /// Convert to SQL keyword for MySQL.
    pub fn to_mysql_sql(&self) -> &'static str {
        match self {
            Self::Range => "RANGE",
            Self::List => "LIST",
            Self::Hash => "HASH",
        }
    }

    /// Convert to SQL keyword for MSSQL.
    pub fn to_mssql_sql(&self) -> &'static str {
        match self {
            Self::Range => "RANGE",
            Self::List => "LIST",
            Self::Hash => "HASH",
        }
    }
}

/// A bound value for range partitions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RangeBound {
    /// Minimum value (MINVALUE in PostgreSQL).
    MinValue,
    /// Maximum value (MAXVALUE in PostgreSQL).
    MaxValue,
    /// A specific value.
    Value(String),
    /// A date value.
    Date(String),
    /// An integer value.
    Int(i64),
}

impl RangeBound {
    /// Create a specific value bound.
    pub fn value(v: impl Into<String>) -> Self {
        Self::Value(v.into())
    }

    /// Create a date bound.
    pub fn date(d: impl Into<String>) -> Self {
        Self::Date(d.into())
    }

    /// Create an integer bound.
    pub fn int(i: i64) -> Self {
        Self::Int(i)
    }

    /// Convert to SQL expression.
    pub fn to_sql(&self) -> Cow<'static, str> {
        match self {
            Self::MinValue => Cow::Borrowed("MINVALUE"),
            Self::MaxValue => Cow::Borrowed("MAXVALUE"),
            Self::Value(v) => Cow::Owned(format!("'{}'", v)),
            Self::Date(d) => Cow::Owned(format!("'{}'", d)),
            Self::Int(i) => Cow::Owned(i.to_string()),
        }
    }
}

/// A range partition definition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RangePartitionDef {
    /// Partition name.
    pub name: String,
    /// Lower bound (inclusive).
    pub from: RangeBound,
    /// Upper bound (exclusive).
    pub to: RangeBound,
    /// Tablespace (optional).
    pub tablespace: Option<String>,
}

impl RangePartitionDef {
    /// Create a new range partition definition.
    pub fn new(name: impl Into<String>, from: RangeBound, to: RangeBound) -> Self {
        Self {
            name: name.into(),
            from,
            to,
            tablespace: None,
        }
    }

    /// Set the tablespace.
    pub fn tablespace(mut self, tablespace: impl Into<String>) -> Self {
        self.tablespace = Some(tablespace.into());
        self
    }
}

/// A list partition definition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListPartitionDef {
    /// Partition name.
    pub name: String,
    /// Values in this partition.
    pub values: Vec<String>,
    /// Tablespace (optional).
    pub tablespace: Option<String>,
}

impl ListPartitionDef {
    /// Create a new list partition definition.
    pub fn new(
        name: impl Into<String>,
        values: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            name: name.into(),
            values: values.into_iter().map(Into::into).collect(),
            tablespace: None,
        }
    }

    /// Set the tablespace.
    pub fn tablespace(mut self, tablespace: impl Into<String>) -> Self {
        self.tablespace = Some(tablespace.into());
        self
    }
}

/// A hash partition definition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HashPartitionDef {
    /// Partition name.
    pub name: String,
    /// Modulus for hash partitioning.
    pub modulus: u32,
    /// Remainder for this partition.
    pub remainder: u32,
    /// Tablespace (optional).
    pub tablespace: Option<String>,
}

impl HashPartitionDef {
    /// Create a new hash partition definition.
    pub fn new(name: impl Into<String>, modulus: u32, remainder: u32) -> Self {
        Self {
            name: name.into(),
            modulus,
            remainder,
            tablespace: None,
        }
    }

    /// Set the tablespace.
    pub fn tablespace(mut self, tablespace: impl Into<String>) -> Self {
        self.tablespace = Some(tablespace.into());
        self
    }
}

/// Partition definitions based on partition type.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PartitionDef {
    /// Range partitions.
    Range(Vec<RangePartitionDef>),
    /// List partitions.
    List(Vec<ListPartitionDef>),
    /// Hash partitions.
    Hash(Vec<HashPartitionDef>),
}

/// A table partition specification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Partition {
    /// Table name.
    pub table: String,
    /// Schema name (optional).
    pub schema: Option<String>,
    /// Partition type.
    pub partition_type: PartitionType,
    /// Partition columns.
    pub columns: Vec<String>,
    /// Partition definitions.
    pub partitions: PartitionDef,
    /// Optional comment.
    pub comment: Option<String>,
}

impl Partition {
    /// Create a new partition builder.
    pub fn builder(table: impl Into<String>) -> PartitionBuilder {
        PartitionBuilder::new(table)
    }

    /// Get the fully qualified table name.
    pub fn qualified_table(&self) -> Cow<'_, str> {
        match &self.schema {
            Some(schema) => Cow::Owned(format!("{}.{}", schema, self.table)),
            None => Cow::Borrowed(&self.table),
        }
    }

    /// Generate PostgreSQL CREATE TABLE with partitioning.
    pub fn to_postgres_partition_clause(&self) -> String {
        format!(
            "PARTITION BY {} ({})",
            self.partition_type.to_postgres_sql(),
            self.columns.join(", ")
        )
    }

    /// Generate PostgreSQL CREATE TABLE for a child partition.
    pub fn to_postgres_create_partition(&self, def: &RangePartitionDef) -> String {
        let mut sql = format!(
            "CREATE TABLE {} PARTITION OF {}\n    FOR VALUES FROM ({}) TO ({})",
            def.name,
            self.qualified_table(),
            def.from.to_sql(),
            def.to.to_sql()
        );

        if let Some(ref ts) = def.tablespace {
            sql.push_str(&format!("\n    TABLESPACE {}", ts));
        }

        sql.push(';');
        sql
    }

    /// Generate PostgreSQL CREATE TABLE for a list partition.
    pub fn to_postgres_create_list_partition(&self, def: &ListPartitionDef) -> String {
        let values: Vec<String> = def.values.iter().map(|v| format!("'{}'", v)).collect();

        let mut sql = format!(
            "CREATE TABLE {} PARTITION OF {}\n    FOR VALUES IN ({})",
            def.name,
            self.qualified_table(),
            values.join(", ")
        );

        if let Some(ref ts) = def.tablespace {
            sql.push_str(&format!("\n    TABLESPACE {}", ts));
        }

        sql.push(';');
        sql
    }

    /// Generate PostgreSQL CREATE TABLE for a hash partition.
    pub fn to_postgres_create_hash_partition(&self, def: &HashPartitionDef) -> String {
        let mut sql = format!(
            "CREATE TABLE {} PARTITION OF {}\n    FOR VALUES WITH (MODULUS {}, REMAINDER {})",
            def.name,
            self.qualified_table(),
            def.modulus,
            def.remainder
        );

        if let Some(ref ts) = def.tablespace {
            sql.push_str(&format!("\n    TABLESPACE {}", ts));
        }

        sql.push(';');
        sql
    }

    /// Generate all PostgreSQL partition creation SQL.
    pub fn to_postgres_create_all_partitions(&self) -> Vec<String> {
        match &self.partitions {
            PartitionDef::Range(ranges) => ranges
                .iter()
                .map(|r| self.to_postgres_create_partition(r))
                .collect(),
            PartitionDef::List(lists) => lists
                .iter()
                .map(|l| self.to_postgres_create_list_partition(l))
                .collect(),
            PartitionDef::Hash(hashes) => hashes
                .iter()
                .map(|h| self.to_postgres_create_hash_partition(h))
                .collect(),
        }
    }

    /// Generate MySQL PARTITION BY clause.
    pub fn to_mysql_partition_clause(&self) -> String {
        let columns_expr = if self.columns.len() == 1 {
            self.columns[0].clone()
        } else {
            format!("({})", self.columns.join(", "))
        };

        let mut sql = format!(
            "PARTITION BY {} ({})",
            self.partition_type.to_mysql_sql(),
            columns_expr
        );

        // Add partition definitions inline for MySQL
        match &self.partitions {
            PartitionDef::Range(ranges) => {
                sql.push_str(" (\n");
                for (i, r) in ranges.iter().enumerate() {
                    if i > 0 {
                        sql.push_str(",\n");
                    }
                    sql.push_str(&format!(
                        "    PARTITION {} VALUES LESS THAN ({})",
                        r.name,
                        r.to.to_sql()
                    ));
                }
                sql.push_str("\n)");
            }
            PartitionDef::List(lists) => {
                sql.push_str(" (\n");
                for (i, l) in lists.iter().enumerate() {
                    if i > 0 {
                        sql.push_str(",\n");
                    }
                    let values: Vec<String> = l.values.iter().map(|v| format!("'{}'", v)).collect();
                    sql.push_str(&format!(
                        "    PARTITION {} VALUES IN ({})",
                        l.name,
                        values.join(", ")
                    ));
                }
                sql.push_str("\n)");
            }
            PartitionDef::Hash(hashes) => {
                sql.push_str(&format!(" PARTITIONS {}", hashes.len()));
            }
        }

        sql
    }

    /// Generate MSSQL partition function and scheme.
    pub fn to_mssql_partition_sql(&self) -> QueryResult<Vec<String>> {
        match &self.partitions {
            PartitionDef::Range(ranges) => {
                let mut sqls = Vec::new();

                // Create partition function
                let boundaries: Vec<String> = ranges
                    .iter()
                    .filter(|r| !matches!(r.to, RangeBound::MaxValue))
                    .map(|r| r.to.to_sql().into_owned())
                    .collect();

                let func_name = format!("{}_pf", self.table);
                sqls.push(format!(
                    "CREATE PARTITION FUNCTION {}(datetime2)\nAS RANGE RIGHT FOR VALUES ({});",
                    func_name,
                    boundaries.join(", ")
                ));

                // Create partition scheme
                let scheme_name = format!("{}_ps", self.table);
                let filegroups: Vec<String> =
                    ranges.iter().map(|_| "PRIMARY".to_string()).collect();
                sqls.push(format!(
                    "CREATE PARTITION SCHEME {}\nAS PARTITION {}\nTO ({});",
                    scheme_name,
                    func_name,
                    filegroups.join(", ")
                ));

                Ok(sqls)
            }
            PartitionDef::List(_) => Err(QueryError::unsupported(
                "MSSQL uses partition functions differently for list partitioning. Consider using range partitioning.",
            )),
            PartitionDef::Hash(_) => Err(QueryError::unsupported(
                "MSSQL does not directly support hash partitioning. Use a computed column with range partitioning.",
            )),
        }
    }

    /// Generate SQL for attaching a partition.
    pub fn attach_partition_sql(
        &self,
        partition_name: &str,
        db_type: DatabaseType,
    ) -> QueryResult<String> {
        match db_type {
            DatabaseType::PostgreSQL => Ok(format!(
                "ALTER TABLE {} ATTACH PARTITION {};",
                self.qualified_table(),
                partition_name
            )),
            DatabaseType::MySQL => Err(QueryError::unsupported(
                "MySQL does not support ATTACH PARTITION. Use ALTER TABLE ... REORGANIZE PARTITION.",
            )),
            DatabaseType::SQLite => Err(QueryError::unsupported(
                "SQLite does not support table partitioning.",
            )),
            DatabaseType::MSSQL => Err(QueryError::unsupported(
                "MSSQL uses SWITCH to move partitions. Use partition switching instead.",
            )),
        }
    }

    /// Generate SQL for detaching a partition.
    pub fn detach_partition_sql(
        &self,
        partition_name: &str,
        db_type: DatabaseType,
    ) -> QueryResult<String> {
        match db_type {
            DatabaseType::PostgreSQL => Ok(format!(
                "ALTER TABLE {} DETACH PARTITION {};",
                self.qualified_table(),
                partition_name
            )),
            DatabaseType::MySQL => Err(QueryError::unsupported(
                "MySQL does not support DETACH PARTITION. Drop and recreate the partition.",
            )),
            DatabaseType::SQLite => Err(QueryError::unsupported(
                "SQLite does not support table partitioning.",
            )),
            DatabaseType::MSSQL => Err(QueryError::unsupported(
                "MSSQL uses SWITCH to move partitions. Use partition switching instead.",
            )),
        }
    }

    /// Generate SQL for dropping a partition.
    pub fn drop_partition_sql(
        &self,
        partition_name: &str,
        db_type: DatabaseType,
    ) -> QueryResult<String> {
        match db_type {
            DatabaseType::PostgreSQL => Ok(format!("DROP TABLE IF EXISTS {};", partition_name)),
            DatabaseType::MySQL => Ok(format!(
                "ALTER TABLE {} DROP PARTITION {};",
                self.qualified_table(),
                partition_name
            )),
            DatabaseType::SQLite => Err(QueryError::unsupported(
                "SQLite does not support table partitioning.",
            )),
            DatabaseType::MSSQL => Ok(format!(
                "ALTER TABLE {} DROP PARTITION {};",
                self.qualified_table(),
                partition_name
            )),
        }
    }
}

/// Builder for creating partition specifications.
#[derive(Debug, Clone)]
pub struct PartitionBuilder {
    table: String,
    schema: Option<String>,
    partition_type: Option<PartitionType>,
    columns: Vec<String>,
    range_partitions: Vec<RangePartitionDef>,
    list_partitions: Vec<ListPartitionDef>,
    hash_partitions: Vec<HashPartitionDef>,
    comment: Option<String>,
}

impl PartitionBuilder {
    /// Create a new partition builder.
    pub fn new(table: impl Into<String>) -> Self {
        Self {
            table: table.into(),
            schema: None,
            partition_type: None,
            columns: Vec::new(),
            range_partitions: Vec::new(),
            list_partitions: Vec::new(),
            hash_partitions: Vec::new(),
            comment: None,
        }
    }

    /// Set the schema.
    pub fn schema(mut self, schema: impl Into<String>) -> Self {
        self.schema = Some(schema.into());
        self
    }

    /// Set to range partitioning.
    pub fn range_partition(mut self) -> Self {
        self.partition_type = Some(PartitionType::Range);
        self
    }

    /// Set to list partitioning.
    pub fn list_partition(mut self) -> Self {
        self.partition_type = Some(PartitionType::List);
        self
    }

    /// Set to hash partitioning.
    pub fn hash_partition(mut self) -> Self {
        self.partition_type = Some(PartitionType::Hash);
        self
    }

    /// Add a partition column.
    pub fn column(mut self, column: impl Into<String>) -> Self {
        self.columns.push(column.into());
        self
    }

    /// Add multiple partition columns.
    pub fn columns(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.columns.extend(columns.into_iter().map(Into::into));
        self
    }

    /// Add a range partition.
    pub fn add_range(mut self, name: impl Into<String>, from: RangeBound, to: RangeBound) -> Self {
        self.range_partitions
            .push(RangePartitionDef::new(name, from, to));
        self
    }

    /// Add a range partition with tablespace.
    pub fn add_range_with_tablespace(
        mut self,
        name: impl Into<String>,
        from: RangeBound,
        to: RangeBound,
        tablespace: impl Into<String>,
    ) -> Self {
        self.range_partitions
            .push(RangePartitionDef::new(name, from, to).tablespace(tablespace));
        self
    }

    /// Add a list partition.
    pub fn add_list(
        mut self,
        name: impl Into<String>,
        values: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.list_partitions
            .push(ListPartitionDef::new(name, values));
        self
    }

    /// Add a hash partition.
    pub fn add_hash(mut self, name: impl Into<String>, modulus: u32, remainder: u32) -> Self {
        self.hash_partitions
            .push(HashPartitionDef::new(name, modulus, remainder));
        self
    }

    /// Add multiple hash partitions automatically.
    pub fn add_hash_partitions(mut self, count: u32, name_prefix: impl Into<String>) -> Self {
        let prefix = name_prefix.into();
        for i in 0..count {
            self.hash_partitions
                .push(HashPartitionDef::new(format!("{}_{}", prefix, i), count, i));
        }
        self
    }

    /// Add a comment.
    pub fn comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Build the partition specification.
    pub fn build(self) -> QueryResult<Partition> {
        let partition_type = self.partition_type.ok_or_else(|| {
            QueryError::invalid_input(
                "partition_type",
                "Must specify partition type (range_partition, list_partition, or hash_partition)",
            )
        })?;

        if self.columns.is_empty() {
            return Err(QueryError::invalid_input(
                "columns",
                "Must specify at least one partition column",
            ));
        }

        let partitions = match partition_type {
            PartitionType::Range => {
                if self.range_partitions.is_empty() {
                    return Err(QueryError::invalid_input(
                        "partitions",
                        "Must define at least one range partition with add_range()",
                    ));
                }
                PartitionDef::Range(self.range_partitions)
            }
            PartitionType::List => {
                if self.list_partitions.is_empty() {
                    return Err(QueryError::invalid_input(
                        "partitions",
                        "Must define at least one list partition with add_list()",
                    ));
                }
                PartitionDef::List(self.list_partitions)
            }
            PartitionType::Hash => {
                if self.hash_partitions.is_empty() {
                    return Err(QueryError::invalid_input(
                        "partitions",
                        "Must define at least one hash partition with add_hash() or add_hash_partitions()",
                    ));
                }
                PartitionDef::Hash(self.hash_partitions)
            }
        };

        Ok(Partition {
            table: self.table,
            schema: self.schema,
            partition_type,
            columns: self.columns,
            partitions,
            comment: self.comment,
        })
    }
}

/// Time-based partition generation helpers.
pub mod time_partitions {
    use super::*;

    /// Generate monthly partitions for a date range.
    pub fn monthly_partitions(
        table: &str,
        column: &str,
        start_year: i32,
        start_month: u32,
        count: u32,
    ) -> PartitionBuilder {
        let mut builder = Partition::builder(table).range_partition().column(column);

        let mut year = start_year;
        let mut month = start_month;

        for _ in 0..count {
            let from_date = format!("{:04}-{:02}-01", year, month);

            // Calculate next month
            let (next_year, next_month) = if month == 12 {
                (year + 1, 1)
            } else {
                (year, month + 1)
            };
            let to_date = format!("{:04}-{:02}-01", next_year, next_month);

            let partition_name = format!("{}_{:04}_{:02}", table, year, month);

            builder = builder.add_range(
                partition_name,
                RangeBound::date(from_date),
                RangeBound::date(to_date),
            );

            year = next_year;
            month = next_month;
        }

        builder
    }

    /// Generate quarterly partitions for a date range.
    pub fn quarterly_partitions(
        table: &str,
        column: &str,
        start_year: i32,
        count: u32,
    ) -> PartitionBuilder {
        let mut builder = Partition::builder(table).range_partition().column(column);

        let mut year = start_year;
        let mut quarter = 1;

        for _ in 0..count {
            let from_month = (quarter - 1) * 3 + 1;
            let from_date = format!("{:04}-{:02}-01", year, from_month);

            let (next_year, next_quarter) = if quarter == 4 {
                (year + 1, 1)
            } else {
                (year, quarter + 1)
            };
            let to_month = (next_quarter - 1) * 3 + 1;
            let to_date = format!("{:04}-{:02}-01", next_year, to_month);

            let partition_name = format!("{}_{}q{}", table, year, quarter);

            builder = builder.add_range(
                partition_name,
                RangeBound::date(from_date),
                RangeBound::date(to_date),
            );

            year = next_year;
            quarter = next_quarter;
        }

        builder
    }

    /// Generate yearly partitions.
    pub fn yearly_partitions(
        table: &str,
        column: &str,
        start_year: i32,
        count: u32,
    ) -> PartitionBuilder {
        let mut builder = Partition::builder(table).range_partition().column(column);

        for i in 0..count {
            let year = start_year + i as i32;
            let from_date = format!("{:04}-01-01", year);
            let to_date = format!("{:04}-01-01", year + 1);
            let partition_name = format!("{}_{}", table, year);

            builder = builder.add_range(
                partition_name,
                RangeBound::date(from_date),
                RangeBound::date(to_date),
            );
        }

        builder
    }
}

/// MongoDB sharding support.
pub mod mongodb {
    use serde::{Deserialize, Serialize};

    /// Shard key type for MongoDB.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
    pub enum ShardKeyType {
        /// Range-based sharding (good for range queries).
        Range,
        /// Hash-based sharding (better distribution).
        Hashed,
    }

    impl ShardKeyType {
        /// Get the MongoDB index specification value.
        pub fn as_index_value(&self) -> serde_json::Value {
            match self {
                Self::Range => serde_json::json!(1),
                Self::Hashed => serde_json::json!("hashed"),
            }
        }
    }

    /// A shard key definition.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ShardKey {
        /// Fields in the shard key.
        pub fields: Vec<(String, ShardKeyType)>,
        /// Whether the collection is unique on the shard key.
        pub unique: bool,
    }

    impl ShardKey {
        /// Create a new shard key builder.
        pub fn builder() -> ShardKeyBuilder {
            ShardKeyBuilder::new()
        }

        /// Get the shardCollection command.
        pub fn shard_collection_command(
            &self,
            database: &str,
            collection: &str,
        ) -> serde_json::Value {
            let mut key = serde_json::Map::new();
            for (field, key_type) in &self.fields {
                key.insert(field.clone(), key_type.as_index_value());
            }

            serde_json::json!({
                "shardCollection": format!("{}.{}", database, collection),
                "key": key,
                "unique": self.unique
            })
        }

        /// Get the index specification for the shard key.
        pub fn index_spec(&self) -> serde_json::Value {
            let mut spec = serde_json::Map::new();
            for (field, key_type) in &self.fields {
                spec.insert(field.clone(), key_type.as_index_value());
            }
            serde_json::Value::Object(spec)
        }
    }

    /// Builder for shard keys.
    #[derive(Debug, Clone, Default)]
    pub struct ShardKeyBuilder {
        fields: Vec<(String, ShardKeyType)>,
        unique: bool,
    }

    impl ShardKeyBuilder {
        /// Create a new shard key builder.
        pub fn new() -> Self {
            Self::default()
        }

        /// Add a range field to the shard key.
        pub fn range_field(mut self, field: impl Into<String>) -> Self {
            self.fields.push((field.into(), ShardKeyType::Range));
            self
        }

        /// Add a hashed field to the shard key.
        pub fn hashed_field(mut self, field: impl Into<String>) -> Self {
            self.fields.push((field.into(), ShardKeyType::Hashed));
            self
        }

        /// Set whether the shard key should enforce uniqueness.
        pub fn unique(mut self, unique: bool) -> Self {
            self.unique = unique;
            self
        }

        /// Build the shard key.
        pub fn build(self) -> ShardKey {
            ShardKey {
                fields: self.fields,
                unique: self.unique,
            }
        }
    }

    /// Zone (tag-based) sharding configuration.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ShardZone {
        /// Zone name.
        pub name: String,
        /// Minimum shard key value.
        pub min: serde_json::Value,
        /// Maximum shard key value.
        pub max: serde_json::Value,
    }

    impl ShardZone {
        /// Create a new shard zone.
        pub fn new(
            name: impl Into<String>,
            min: serde_json::Value,
            max: serde_json::Value,
        ) -> Self {
            Self {
                name: name.into(),
                min,
                max,
            }
        }

        /// Get the updateZoneKeyRange command.
        pub fn update_zone_key_range_command(&self, namespace: &str) -> serde_json::Value {
            serde_json::json!({
                "updateZoneKeyRange": namespace,
                "min": self.min,
                "max": self.max,
                "zone": self.name
            })
        }

        /// Get the addShardToZone command.
        pub fn add_shard_to_zone_command(&self, shard: &str) -> serde_json::Value {
            serde_json::json!({
                "addShardToZone": shard,
                "zone": self.name
            })
        }
    }

    /// Builder for zone sharding configuration.
    #[derive(Debug, Clone, Default)]
    pub struct ZoneShardingBuilder {
        zones: Vec<ShardZone>,
        shard_assignments: Vec<(String, String)>, // (shard_name, zone_name)
    }

    impl ZoneShardingBuilder {
        /// Create a new zone sharding builder.
        pub fn new() -> Self {
            Self::default()
        }

        /// Add a zone.
        pub fn add_zone(
            mut self,
            name: impl Into<String>,
            min: serde_json::Value,
            max: serde_json::Value,
        ) -> Self {
            self.zones.push(ShardZone::new(name, min, max));
            self
        }

        /// Assign a shard to a zone.
        pub fn assign_shard(mut self, shard: impl Into<String>, zone: impl Into<String>) -> Self {
            self.shard_assignments.push((shard.into(), zone.into()));
            self
        }

        /// Get all configuration commands.
        pub fn build_commands(&self, namespace: &str) -> Vec<serde_json::Value> {
            let mut commands = Vec::new();

            // Add shard to zone assignments
            for (shard, zone) in &self.shard_assignments {
                commands.push(serde_json::json!({
                    "addShardToZone": shard,
                    "zone": zone
                }));
            }

            // Add zone key ranges
            for zone in &self.zones {
                commands.push(zone.update_zone_key_range_command(namespace));
            }

            commands
        }
    }

    /// Helper to create a shard key.
    pub fn shard_key() -> ShardKeyBuilder {
        ShardKeyBuilder::new()
    }

    /// Helper to create zone sharding configuration.
    pub fn zone_sharding() -> ZoneShardingBuilder {
        ZoneShardingBuilder::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_range_partition_builder() {
        let partition = Partition::builder("orders")
            .schema("sales")
            .range_partition()
            .column("created_at")
            .add_range(
                "orders_2024_q1",
                RangeBound::date("2024-01-01"),
                RangeBound::date("2024-04-01"),
            )
            .add_range(
                "orders_2024_q2",
                RangeBound::date("2024-04-01"),
                RangeBound::date("2024-07-01"),
            )
            .build()
            .unwrap();

        assert_eq!(partition.table, "orders");
        assert_eq!(partition.partition_type, PartitionType::Range);
        assert_eq!(partition.columns, vec!["created_at"]);
    }

    #[test]
    fn test_postgres_partition_clause() {
        let partition = Partition::builder("orders")
            .range_partition()
            .column("created_at")
            .add_range(
                "orders_2024",
                RangeBound::date("2024-01-01"),
                RangeBound::date("2025-01-01"),
            )
            .build()
            .unwrap();

        let clause = partition.to_postgres_partition_clause();
        assert_eq!(clause, "PARTITION BY RANGE (created_at)");
    }

    #[test]
    fn test_postgres_create_partition() {
        let partition = Partition::builder("orders")
            .range_partition()
            .column("created_at")
            .add_range(
                "orders_2024",
                RangeBound::date("2024-01-01"),
                RangeBound::date("2025-01-01"),
            )
            .build()
            .unwrap();

        let sqls = partition.to_postgres_create_all_partitions();
        assert_eq!(sqls.len(), 1);
        assert!(sqls[0].contains("CREATE TABLE orders_2024 PARTITION OF orders"));
        assert!(sqls[0].contains("FOR VALUES FROM ('2024-01-01') TO ('2025-01-01')"));
    }

    #[test]
    fn test_list_partition() {
        let partition = Partition::builder("users")
            .list_partition()
            .column("country")
            .add_list("users_us", ["US", "USA"])
            .add_list("users_eu", ["DE", "FR", "GB", "IT"])
            .build()
            .unwrap();

        assert_eq!(partition.partition_type, PartitionType::List);

        let sqls = partition.to_postgres_create_all_partitions();
        assert_eq!(sqls.len(), 2);
        assert!(sqls[0].contains("FOR VALUES IN"));
    }

    #[test]
    fn test_hash_partition() {
        let partition = Partition::builder("events")
            .hash_partition()
            .column("user_id")
            .add_hash_partitions(4, "events")
            .build()
            .unwrap();

        assert_eq!(partition.partition_type, PartitionType::Hash);

        let sqls = partition.to_postgres_create_all_partitions();
        assert_eq!(sqls.len(), 4);
        assert!(sqls[0].contains("MODULUS 4"));
        assert!(sqls[0].contains("REMAINDER 0"));
    }

    #[test]
    fn test_mysql_partition_clause() {
        let partition = Partition::builder("orders")
            .range_partition()
            .column("created_at")
            .add_range(
                "p2024",
                RangeBound::MinValue,
                RangeBound::date("2025-01-01"),
            )
            .add_range(
                "p_future",
                RangeBound::date("2025-01-01"),
                RangeBound::MaxValue,
            )
            .build()
            .unwrap();

        let clause = partition.to_mysql_partition_clause();
        assert!(clause.contains("PARTITION BY RANGE"));
        assert!(clause.contains("PARTITION p2024"));
        assert!(clause.contains("PARTITION p_future"));
    }

    #[test]
    fn test_detach_partition() {
        let partition = Partition::builder("orders")
            .range_partition()
            .column("created_at")
            .add_range(
                "orders_2024",
                RangeBound::date("2024-01-01"),
                RangeBound::date("2025-01-01"),
            )
            .build()
            .unwrap();

        let sql = partition
            .detach_partition_sql("orders_2024", DatabaseType::PostgreSQL)
            .unwrap();
        assert_eq!(sql, "ALTER TABLE orders DETACH PARTITION orders_2024;");
    }

    #[test]
    fn test_drop_partition() {
        let partition = Partition::builder("orders")
            .range_partition()
            .column("created_at")
            .add_range(
                "orders_2024",
                RangeBound::date("2024-01-01"),
                RangeBound::date("2025-01-01"),
            )
            .build()
            .unwrap();

        let pg_sql = partition
            .drop_partition_sql("orders_2024", DatabaseType::PostgreSQL)
            .unwrap();
        assert_eq!(pg_sql, "DROP TABLE IF EXISTS orders_2024;");

        let mysql_sql = partition
            .drop_partition_sql("orders_2024", DatabaseType::MySQL)
            .unwrap();
        assert!(mysql_sql.contains("DROP PARTITION"));
    }

    #[test]
    fn test_missing_partition_type() {
        let result = Partition::builder("orders")
            .column("created_at")
            .add_range("p1", RangeBound::MinValue, RangeBound::MaxValue)
            .build();

        assert!(result.is_err());
    }

    #[test]
    fn test_missing_columns() {
        let result = Partition::builder("orders")
            .range_partition()
            .add_range("p1", RangeBound::MinValue, RangeBound::MaxValue)
            .build();

        assert!(result.is_err());
    }

    mod time_partition_tests {
        use super::super::time_partitions;

        #[test]
        fn test_monthly_partitions() {
            let builder = time_partitions::monthly_partitions("orders", "created_at", 2024, 1, 3);
            let partition = builder.build().unwrap();

            if let super::PartitionDef::Range(ranges) = &partition.partitions {
                assert_eq!(ranges.len(), 3);
                assert_eq!(ranges[0].name, "orders_2024_01");
                assert_eq!(ranges[1].name, "orders_2024_02");
                assert_eq!(ranges[2].name, "orders_2024_03");
            } else {
                panic!("Expected range partitions");
            }
        }

        #[test]
        fn test_quarterly_partitions() {
            let builder = time_partitions::quarterly_partitions("sales", "order_date", 2024, 4);
            let partition = builder.build().unwrap();

            if let super::PartitionDef::Range(ranges) = &partition.partitions {
                assert_eq!(ranges.len(), 4);
                assert_eq!(ranges[0].name, "sales_2024q1");
                assert_eq!(ranges[3].name, "sales_2024q4");
            } else {
                panic!("Expected range partitions");
            }
        }

        #[test]
        fn test_yearly_partitions() {
            let builder = time_partitions::yearly_partitions("logs", "timestamp", 2020, 5);
            let partition = builder.build().unwrap();

            if let super::PartitionDef::Range(ranges) = &partition.partitions {
                assert_eq!(ranges.len(), 5);
                assert_eq!(ranges[0].name, "logs_2020");
                assert_eq!(ranges[4].name, "logs_2024");
            } else {
                panic!("Expected range partitions");
            }
        }
    }

    mod mongodb_tests {
        use super::super::mongodb::*;

        #[test]
        fn test_shard_key_builder() {
            let key = shard_key()
                .hashed_field("tenant_id")
                .range_field("created_at")
                .unique(false)
                .build();

            assert_eq!(key.fields.len(), 2);
            assert_eq!(
                key.fields[0],
                ("tenant_id".to_string(), ShardKeyType::Hashed)
            );
            assert_eq!(
                key.fields[1],
                ("created_at".to_string(), ShardKeyType::Range)
            );
        }

        #[test]
        fn test_shard_collection_command() {
            let key = shard_key().hashed_field("user_id").build();

            let cmd = key.shard_collection_command("mydb", "users");
            assert_eq!(cmd["shardCollection"], "mydb.users");
            assert_eq!(cmd["key"]["user_id"], "hashed");
        }

        #[test]
        fn test_zone_sharding() {
            let builder = zone_sharding()
                .add_zone(
                    "US",
                    serde_json::json!({"region": "US"}),
                    serde_json::json!({"region": "US~"}),
                )
                .add_zone(
                    "EU",
                    serde_json::json!({"region": "EU"}),
                    serde_json::json!({"region": "EU~"}),
                )
                .assign_shard("shard0", "US")
                .assign_shard("shard1", "EU");

            let commands = builder.build_commands("mydb.users");
            assert_eq!(commands.len(), 4); // 2 shard assignments + 2 zone ranges
        }

        #[test]
        fn test_shard_key_index_spec() {
            let key = shard_key()
                .range_field("tenant_id")
                .range_field("created_at")
                .build();

            let spec = key.index_spec();
            assert_eq!(spec["tenant_id"], 1);
            assert_eq!(spec["created_at"], 1);
        }
    }
}