drizzle-types 0.1.5

A type-safe SQL query builder for Rust
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
//! SQL generation for PostgreSQL DDL types
//!
//! This module provides SQL generation methods for DDL types, enabling
//! unified SQL output from both compile-time and runtime schema definitions.

use crate::alloc_prelude::*;

use super::{
    CheckConstraint, Column, Enum, ForeignKey, Generated, GeneratedType, Identity, IdentityType,
    Index, IndexColumnDef, Policy, PrimaryKey, Sequence, Table, UniqueConstraint, View,
};

// =============================================================================
// Table SQL Generation
// =============================================================================

/// A complete table definition with all related entities for SQL generation
#[derive(Clone, Debug)]
pub struct TableSql<'a> {
    pub table: &'a Table,
    pub columns: &'a [Column],
    pub primary_key: Option<&'a PrimaryKey>,
    pub foreign_keys: &'a [ForeignKey],
    pub unique_constraints: &'a [UniqueConstraint],
    pub check_constraints: &'a [CheckConstraint],
    pub indexes: &'a [Index],
    pub policies: &'a [Policy],
}

impl<'a> TableSql<'a> {
    /// Create a new TableSql for SQL generation
    pub fn new(table: &'a Table) -> Self {
        Self {
            table,
            columns: &[],
            primary_key: None,
            foreign_keys: &[],
            unique_constraints: &[],
            check_constraints: &[],
            indexes: &[],
            policies: &[],
        }
    }

    /// Set columns
    pub fn columns(mut self, columns: &'a [Column]) -> Self {
        self.columns = columns;
        self
    }

    /// Set primary key
    pub fn primary_key(mut self, pk: Option<&'a PrimaryKey>) -> Self {
        self.primary_key = pk;
        self
    }

    /// Set foreign keys
    pub fn foreign_keys(mut self, fks: &'a [ForeignKey]) -> Self {
        self.foreign_keys = fks;
        self
    }

    /// Set unique constraints
    pub fn unique_constraints(mut self, uniques: &'a [UniqueConstraint]) -> Self {
        self.unique_constraints = uniques;
        self
    }

    /// Set check constraints
    pub fn check_constraints(mut self, checks: &'a [CheckConstraint]) -> Self {
        self.check_constraints = checks;
        self
    }

    /// Set indexes
    pub fn indexes(mut self, indexes: &'a [Index]) -> Self {
        self.indexes = indexes;
        self
    }

    /// Set policies
    pub fn policies(mut self, policies: &'a [Policy]) -> Self {
        self.policies = policies;
        self
    }

    fn schema_prefix(&self) -> String {
        if self.table.schema() != "public" {
            format!("\"{}\".", self.table.schema())
        } else {
            String::new()
        }
    }

    /// Generate CREATE TABLE SQL
    pub fn create_table_sql(&self) -> String {
        let schema_prefix = self.schema_prefix();
        let mut sql = format!(
            "CREATE TABLE {}\"{}\" (\n",
            schema_prefix,
            self.table.name()
        );

        let mut lines = Vec::new();

        // Column definitions
        for column in self.columns {
            lines.push(format!("\t{}", column.to_column_sql()));
        }

        // Primary key
        if let Some(pk) = &self.primary_key {
            let cols = pk
                .columns
                .iter()
                .map(|c| format!("\"{}\"", c))
                .collect::<Vec<_>>()
                .join(", ");
            if pk.name_explicit {
                lines.push(format!(
                    "\tCONSTRAINT \"{}\" PRIMARY KEY({})",
                    pk.name(),
                    cols
                ));
            } else {
                lines.push(format!("\tPRIMARY KEY({})", cols));
            }
        }

        // Foreign keys
        for fk in self.foreign_keys {
            lines.push(format!("\t{}", fk.to_constraint_sql()));
        }

        // Unique constraints
        for unique in self.unique_constraints {
            let cols = unique
                .columns
                .iter()
                .map(|c| format!("\"{}\"", c))
                .collect::<Vec<_>>()
                .join(", ");
            lines.push(format!(
                "\tCONSTRAINT \"{}\" UNIQUE({})",
                unique.name(),
                cols
            ));
        }

        // Check constraints
        for check in self.check_constraints {
            lines.push(format!(
                "\tCONSTRAINT \"{}\" CHECK ({})",
                check.name(),
                &check.value
            ));
        }

        sql.push_str(&lines.join(",\n"));
        sql.push_str("\n);");

        sql
    }

    /// Generate DROP TABLE SQL
    pub fn drop_table_sql(&self) -> String {
        let schema_prefix = self.schema_prefix();
        format!("DROP TABLE {}\"{}\";", schema_prefix, self.table.name())
    }

    /// Generate all related indexes
    pub fn create_indexes_sql(&self) -> Vec<String> {
        self.indexes.iter().map(|i| i.create_index_sql()).collect()
    }

    /// Generate RLS enable statement if needed
    pub fn enable_rls_sql(&self) -> Option<String> {
        if self.table.is_rls_enabled.unwrap_or(false) {
            let schema_prefix = self.schema_prefix();
            Some(format!(
                "ALTER TABLE {}\"{}\" ENABLE ROW LEVEL SECURITY;",
                schema_prefix,
                self.table.name()
            ))
        } else {
            None
        }
    }

    /// Generate all policies
    pub fn create_policies_sql(&self) -> Vec<String> {
        self.policies
            .iter()
            .map(|p| p.create_policy_sql())
            .collect()
    }
}

// =============================================================================
// Column SQL Generation
// =============================================================================

impl Column {
    /// Generate the column definition SQL (without leading/trailing punctuation)
    pub fn to_column_sql(&self) -> String {
        let mut sql = format!("\"{}\" {}", self.name(), self.sql_type());

        // Handle identity columns
        if let Some(identity) = &self.identity {
            sql.push_str(&identity.to_sql());
        }

        // Handle generated columns
        if let Some(generated) = &self.generated {
            sql.push_str(&generated.to_sql());
        }

        // Default value (skip if identity or generated - PostgreSQL doesn't allow both)
        if self.identity.is_none()
            && self.generated.is_none()
            && let Some(default) = self.default.as_ref()
        {
            sql.push_str(&format!(" DEFAULT {}", default));
        }

        // NOT NULL
        if self.not_null {
            sql.push_str(" NOT NULL");
        }

        sql
    }

    /// Generate ADD COLUMN SQL
    pub fn add_column_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "ALTER TABLE {}\"{}\" ADD COLUMN {};",
            schema_prefix,
            self.table(),
            self.to_column_sql()
        )
    }

    /// Generate DROP COLUMN SQL
    pub fn drop_column_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "ALTER TABLE {}\"{}\" DROP COLUMN \"{}\";",
            schema_prefix,
            self.table(),
            self.name()
        )
    }
}

// =============================================================================
// Identity Column SQL
// =============================================================================

impl Identity {
    /// Generate the GENERATED AS IDENTITY clause
    pub fn to_sql(&self) -> String {
        let identity_type = match self.type_ {
            IdentityType::Always => "ALWAYS",
            IdentityType::ByDefault => "BY DEFAULT",
        };

        let mut sql = format!(" GENERATED {} AS IDENTITY", identity_type);

        // Add sequence options if any are specified
        let mut options = Vec::new();

        if let Some(increment) = self.increment.as_ref() {
            options.push(format!("INCREMENT BY {}", increment));
        }
        if let Some(min) = self.min_value.as_ref() {
            options.push(format!("MINVALUE {}", min));
        }
        if let Some(max) = self.max_value.as_ref() {
            options.push(format!("MAXVALUE {}", max));
        }
        if let Some(start) = self.start_with.as_ref() {
            options.push(format!("START WITH {}", start));
        }
        if let Some(cache) = self.cache {
            options.push(format!("CACHE {}", cache));
        }
        if self.cycle.unwrap_or(false) {
            options.push("CYCLE".to_string());
        }

        if !options.is_empty() {
            sql.push_str(&format!(" ({})", options.join(" ")));
        }

        sql
    }
}

// =============================================================================
// Generated Column SQL
// =============================================================================

impl Generated {
    /// Generate the GENERATED clause SQL
    pub fn to_sql(&self) -> String {
        let gen_type = match self.gen_type {
            GeneratedType::Stored => "STORED",
        };
        format!(" GENERATED ALWAYS AS ({}) {}", self.expression, gen_type)
    }
}

// =============================================================================
// Foreign Key SQL Generation
// =============================================================================

impl ForeignKey {
    /// Generate the CONSTRAINT ... FOREIGN KEY clause SQL
    pub fn to_constraint_sql(&self) -> String {
        let from_cols = self
            .columns
            .iter()
            .map(|c| format!("\"{}\"", c))
            .collect::<Vec<_>>()
            .join(", ");

        let to_cols = self
            .columns_to
            .iter()
            .map(|c| format!("\"{}\"", c))
            .collect::<Vec<_>>()
            .join(", ");

        let to_schema_prefix = if self.schema_to() != "public" {
            format!("\"{}\".", self.schema_to())
        } else {
            String::new()
        };

        let mut sql = format!(
            "CONSTRAINT \"{}\" FOREIGN KEY ({}) REFERENCES {}\"{}\"({})",
            self.name(),
            from_cols,
            to_schema_prefix,
            self.table_to(),
            to_cols
        );

        if let Some(on_update) = self.on_update.as_ref()
            && on_update != "NO ACTION"
        {
            sql.push_str(&format!(" ON UPDATE {}", on_update.to_uppercase()));
        }

        if let Some(on_delete) = self.on_delete.as_ref()
            && on_delete != "NO ACTION"
        {
            sql.push_str(&format!(" ON DELETE {}", on_delete.to_uppercase()));
        }

        sql
    }

    /// Generate ADD FOREIGN KEY SQL
    pub fn add_fk_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "ALTER TABLE {}\"{}\" ADD {};",
            schema_prefix,
            self.table(),
            self.to_constraint_sql()
        )
    }

    /// Generate DROP FOREIGN KEY SQL
    pub fn drop_fk_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "ALTER TABLE {}\"{}\" DROP CONSTRAINT \"{}\";",
            schema_prefix,
            self.table(),
            self.name()
        )
    }
}

// =============================================================================
// Index SQL Generation
// =============================================================================

impl Index {
    /// Generate CREATE INDEX SQL
    pub fn create_index_sql(&self) -> String {
        let unique = if self.is_unique { "UNIQUE " } else { "" };

        let concurrently = if self.concurrently {
            "CONCURRENTLY "
        } else {
            ""
        };

        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };

        let columns = self
            .columns
            .iter()
            .map(|c| c.to_sql())
            .collect::<Vec<_>>()
            .join(", ");

        let using = self
            .method
            .as_ref()
            .map(|m| format!(" USING {}", m))
            .unwrap_or_default();

        let mut sql = format!(
            "CREATE {}{}INDEX \"{}\" ON {}\"{}\"{}({});",
            unique,
            concurrently,
            self.name(),
            schema_prefix,
            self.table(),
            using,
            columns
        );

        if let Some(where_clause) = self.where_clause.as_ref() {
            // Remove trailing semicolon to add WHERE
            sql.pop();
            sql.push_str(&format!(" WHERE {};", where_clause));
        }

        sql
    }

    /// Generate DROP INDEX SQL
    pub fn drop_index_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!("DROP INDEX {}\"{}\";", schema_prefix, self.name())
    }
}

impl IndexColumnDef {
    /// Generate the column reference for an index
    pub fn to_sql(&self) -> String {
        let mut sql = if self.is_expression {
            format!("({})", self.value)
        } else {
            format!("\"{}\"", self.value)
        };

        if let Some(op) = self.opclass.as_ref() {
            sql.push_str(&format!(" {}", op));
        }

        if !self.asc {
            sql.push_str(" DESC");
        }

        if self.nulls_first {
            sql.push_str(" NULLS FIRST");
        }

        sql
    }
}

// =============================================================================
// Enum SQL Generation
// =============================================================================

impl Enum {
    /// Generate CREATE TYPE ... AS ENUM SQL
    pub fn create_enum_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        let values = self
            .values
            .iter()
            .map(|v| format!("'{}'", v))
            .collect::<Vec<_>>()
            .join(", ");
        format!(
            "CREATE TYPE {}\"{}\" AS ENUM ({});",
            schema_prefix,
            self.name(),
            values
        )
    }

    /// Generate DROP TYPE SQL
    pub fn drop_enum_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!("DROP TYPE {}\"{}\";", schema_prefix, self.name())
    }

    /// Generate ALTER TYPE ... ADD VALUE SQL
    pub fn add_value_sql(&self, value: &str, before: Option<&str>) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        if let Some(before_value) = before {
            format!(
                "ALTER TYPE {}\"{}\" ADD VALUE '{}' BEFORE '{}';",
                schema_prefix,
                self.name(),
                value,
                before_value
            )
        } else {
            format!(
                "ALTER TYPE {}\"{}\" ADD VALUE '{}';",
                schema_prefix,
                self.name(),
                value
            )
        }
    }
}

// =============================================================================
// Sequence SQL Generation
// =============================================================================

impl Sequence {
    /// Generate CREATE SEQUENCE SQL
    pub fn create_sequence_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };

        let mut sql = format!("CREATE SEQUENCE {}\"{}\"", schema_prefix, self.name());

        if let Some(inc) = self.increment_by.as_ref() {
            sql.push_str(&format!(" INCREMENT BY {}", inc));
        }
        if let Some(min) = self.min_value.as_ref() {
            sql.push_str(&format!(" MINVALUE {}", min));
        }
        if let Some(max) = self.max_value.as_ref() {
            sql.push_str(&format!(" MAXVALUE {}", max));
        }
        if let Some(start) = self.start_with.as_ref() {
            sql.push_str(&format!(" START WITH {}", start));
        }
        if let Some(cache) = self.cache_size {
            sql.push_str(&format!(" CACHE {}", cache));
        }
        if self.cycle.unwrap_or(false) {
            sql.push_str(" CYCLE");
        }

        sql.push(';');
        sql
    }

    /// Generate DROP SEQUENCE SQL
    pub fn drop_sequence_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!("DROP SEQUENCE {}\"{}\";", schema_prefix, self.name())
    }
}

// =============================================================================
// View SQL Generation
// =============================================================================

impl View {
    /// Generate CREATE VIEW SQL
    pub fn create_view_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };

        let materialized = if self.materialized {
            "MATERIALIZED "
        } else {
            ""
        };

        let Some(def) = self.definition.as_ref() else {
            return format!(
                "-- {}View {}\"{}\" has no definition",
                materialized,
                schema_prefix,
                self.name()
            );
        };

        use core::fmt::Write;

        let mut sql = String::with_capacity(def.len() + 64);
        let _ = write!(
            sql,
            "CREATE {}VIEW {}\"{}\"",
            materialized,
            schema_prefix,
            self.name(),
        );

        if let Some(using) = self.using.as_ref() {
            let _ = write!(sql, " USING {}", using);
        }

        let mut check_option_clause = None;
        if let Some(with_opts) = self.with.as_ref() {
            let mut options = String::new();
            let mut has_option = false;

            macro_rules! push_option {
                ($name:expr, $value:expr) => {{
                    if has_option {
                        options.push_str(", ");
                    } else {
                        has_option = true;
                    }
                    let _ = write!(options, "{} = {}", $name, $value);
                }};
            }

            if let Some(check_option) = with_opts.check_option.as_deref() {
                check_option_clause = Some(check_option.to_ascii_uppercase());
            }

            if let Some(value) = with_opts.security_barrier {
                push_option!("security_barrier", value);
            }
            if let Some(value) = with_opts.security_invoker {
                push_option!("security_invoker", value);
            }
            if let Some(value) = with_opts.fillfactor {
                push_option!("fillfactor", value);
            }
            if let Some(value) = with_opts.toast_tuple_target {
                push_option!("toast_tuple_target", value);
            }
            if let Some(value) = with_opts.parallel_workers {
                push_option!("parallel_workers", value);
            }
            if let Some(value) = with_opts.autovacuum_enabled {
                push_option!("autovacuum_enabled", value);
            }
            if let Some(value) = with_opts.vacuum_index_cleanup.as_ref() {
                push_option!("vacuum_index_cleanup", value);
            }
            if let Some(value) = with_opts.vacuum_truncate {
                push_option!("vacuum_truncate", value);
            }
            if let Some(value) = with_opts.autovacuum_vacuum_threshold {
                push_option!("autovacuum_vacuum_threshold", value);
            }
            if let Some(value) = with_opts.autovacuum_vacuum_scale_factor {
                push_option!("autovacuum_vacuum_scale_factor", value);
            }
            if let Some(value) = with_opts.autovacuum_vacuum_cost_delay {
                push_option!("autovacuum_vacuum_cost_delay", value);
            }
            if let Some(value) = with_opts.autovacuum_vacuum_cost_limit {
                push_option!("autovacuum_vacuum_cost_limit", value);
            }
            if let Some(value) = with_opts.autovacuum_freeze_min_age {
                push_option!("autovacuum_freeze_min_age", value);
            }
            if let Some(value) = with_opts.autovacuum_freeze_max_age {
                push_option!("autovacuum_freeze_max_age", value);
            }
            if let Some(value) = with_opts.autovacuum_freeze_table_age {
                push_option!("autovacuum_freeze_table_age", value);
            }
            if let Some(value) = with_opts.autovacuum_multixact_freeze_min_age {
                push_option!("autovacuum_multixact_freeze_min_age", value);
            }
            if let Some(value) = with_opts.autovacuum_multixact_freeze_max_age {
                push_option!("autovacuum_multixact_freeze_max_age", value);
            }
            if let Some(value) = with_opts.autovacuum_multixact_freeze_table_age {
                push_option!("autovacuum_multixact_freeze_table_age", value);
            }
            if let Some(value) = with_opts.log_autovacuum_min_duration {
                push_option!("log_autovacuum_min_duration", value);
            }
            if let Some(value) = with_opts.user_catalog_table {
                push_option!("user_catalog_table", value);
            }

            if has_option {
                let _ = write!(sql, " WITH ({})", options);
            }
        }

        if let Some(tablespace) = self.tablespace.as_ref() {
            let _ = write!(sql, " TABLESPACE \"{}\"", tablespace);
        }

        sql.push_str(" AS ");
        sql.push_str(def);

        if let Some(check_option) = check_option_clause {
            let _ = write!(sql, " WITH {} CHECK OPTION", check_option);
        }

        if self.materialized && matches!(self.with_no_data, Some(true)) {
            sql.push_str(" WITH NO DATA");
        }

        sql.push(';');
        sql
    }

    /// Generate DROP VIEW SQL
    pub fn drop_view_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        let materialized = if self.materialized {
            "MATERIALIZED "
        } else {
            ""
        };
        format!(
            "DROP {}VIEW {}\"{}\";",
            materialized,
            schema_prefix,
            self.name()
        )
    }
}

// =============================================================================
// Policy SQL Generation
// =============================================================================

impl Policy {
    /// Generate CREATE POLICY SQL
    pub fn create_policy_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };

        let mut sql = format!(
            "CREATE POLICY \"{}\" ON {}\"{}\"",
            self.name(),
            schema_prefix,
            self.table()
        );

        if let Some(r#for) = self.for_clause.as_ref() {
            sql.push_str(&format!(" FOR {}", r#for.to_uppercase()));
        }

        if let Some(to) = self.to.as_ref()
            && !to.is_empty()
        {
            let to_roles = to
                .iter()
                .map(|r| {
                    if *r == "public" {
                        "PUBLIC".to_string()
                    } else {
                        format!("\"{}\"", r)
                    }
                })
                .collect::<Vec<_>>()
                .join(", ");
            sql.push_str(&format!(" TO {}", to_roles));
        }

        if let Some(using) = self.using.as_ref() {
            sql.push_str(&format!(" USING ({})", using));
        }

        if let Some(with_check) = self.with_check.as_ref() {
            sql.push_str(&format!(" WITH CHECK ({})", with_check));
        }

        sql.push(';');
        sql
    }

    /// Generate DROP POLICY SQL
    pub fn drop_policy_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "DROP POLICY \"{}\" ON {}\"{}\";",
            self.name(),
            schema_prefix,
            self.table()
        )
    }
}

// =============================================================================
// Table-level utilities
// =============================================================================

impl Table {
    /// Generate DROP TABLE SQL
    pub fn drop_table_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!("DROP TABLE {}\"{}\";", schema_prefix, self.name())
    }

    /// Generate RENAME TABLE SQL
    pub fn rename_table_sql(&self, new_name: &str) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "ALTER TABLE {}\"{}\" RENAME TO \"{}\";",
            schema_prefix,
            self.name(),
            new_name
        )
    }
}

// =============================================================================
// Primary Key SQL Generation
// =============================================================================

impl PrimaryKey {
    /// Generate the PRIMARY KEY constraint clause
    pub fn to_constraint_sql(&self) -> String {
        let cols = self
            .columns
            .iter()
            .map(|c| format!("\"{}\"", c))
            .collect::<Vec<_>>()
            .join(", ");

        format!("CONSTRAINT \"{}\" PRIMARY KEY({})", self.name(), cols)
    }

    /// Generate ADD PRIMARY KEY SQL
    pub fn add_pk_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "ALTER TABLE {}\"{}\" ADD {};",
            schema_prefix,
            self.table(),
            self.to_constraint_sql()
        )
    }

    /// Generate DROP PRIMARY KEY SQL
    pub fn drop_pk_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "ALTER TABLE {}\"{}\" DROP CONSTRAINT \"{}\";",
            schema_prefix,
            self.table(),
            self.name()
        )
    }
}

// =============================================================================
// Unique Constraint SQL Generation
// =============================================================================

impl UniqueConstraint {
    /// Generate the UNIQUE constraint clause
    pub fn to_constraint_sql(&self) -> String {
        let cols = self
            .columns
            .iter()
            .map(|c| format!("\"{}\"", c))
            .collect::<Vec<_>>()
            .join(", ");

        format!("CONSTRAINT \"{}\" UNIQUE({})", self.name(), cols)
    }

    /// Generate ADD UNIQUE SQL
    pub fn add_unique_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "ALTER TABLE {}\"{}\" ADD {};",
            schema_prefix,
            self.table(),
            self.to_constraint_sql()
        )
    }

    /// Generate DROP UNIQUE SQL
    pub fn drop_unique_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "ALTER TABLE {}\"{}\" DROP CONSTRAINT \"{}\";",
            schema_prefix,
            self.table(),
            self.name()
        )
    }
}

// =============================================================================
// Check Constraint SQL Generation
// =============================================================================

impl CheckConstraint {
    /// Generate the CHECK constraint clause
    pub fn to_constraint_sql(&self) -> String {
        format!("CONSTRAINT \"{}\" CHECK ({})", self.name(), &self.value)
    }

    /// Generate ADD CHECK SQL
    pub fn add_check_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "ALTER TABLE {}\"{}\" ADD {};",
            schema_prefix,
            self.table(),
            self.to_constraint_sql()
        )
    }

    /// Generate DROP CHECK SQL
    pub fn drop_check_sql(&self) -> String {
        let schema_prefix = if self.schema() != "public" {
            format!("\"{}\".", self.schema())
        } else {
            String::new()
        };
        format!(
            "ALTER TABLE {}\"{}\" DROP CONSTRAINT \"{}\";",
            schema_prefix,
            self.table(),
            self.name()
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::postgres::ddl::{ColumnDef, PrimaryKeyDef, TableDef};
    use std::borrow::Cow;

    #[test]
    fn test_simple_create_table() {
        let table = TableDef::new("public", "users").into_table();
        let columns = [
            ColumnDef::new("public", "users", "id", "SERIAL")
                .not_null()
                .into_column(),
            ColumnDef::new("public", "users", "name", "TEXT")
                .not_null()
                .into_column(),
            ColumnDef::new("public", "users", "email", "TEXT").into_column(),
        ];
        const PK_COLS: &[Cow<'static, str>] = &[Cow::Borrowed("id")];
        let pk = PrimaryKeyDef::new("public", "users", "users_pkey")
            .columns(PK_COLS)
            .into_primary_key();

        let sql = TableSql::new(&table)
            .columns(&columns)
            .primary_key(Some(&pk))
            .create_table_sql();

        assert!(sql.contains("CREATE TABLE \"users\""));
        assert!(sql.contains("\"id\" SERIAL NOT NULL"));
        assert!(sql.contains("\"name\" TEXT NOT NULL"));
        assert!(sql.contains("\"email\" TEXT"));
    }

    #[test]
    fn test_table_with_schema() {
        let table = TableDef::new("myschema", "users").into_table();
        let sql = TableSql::new(&table).create_table_sql();
        assert!(sql.contains("\"myschema\".\"users\""));
    }
}