pgevolve-core 0.4.4

Postgres declarative schema management โ€” core library (parser, IR, diff, planner) powering the pgevolve CLI.
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
//! SQL rendering helpers for the rewrite pass.
//!
//! These functions produce canonical Postgres DDL strings from IR objects.
//! They are used both by the non-rewriting dispatcher in [`super`] and by the
//! online-rewrite submodules.
//!
//! Output is canonical (deterministic spacing, lowercase keywords, schema-qualified
//! names) so that two equal IR inputs produce byte-identical SQL โ€” required by
//! the plan-id hash in spec ยง6.6.

use super::reloptions::render_index_options;
use crate::identifier::{Identifier, QualifiedName};
use crate::ir::column::{
    Column, Compression, GeneratedKind, Identity, IdentityKind, SequenceOptions, StorageKind,
};
use crate::ir::constraint::{
    Constraint, ConstraintKind, Deferrable, FkMatchType, ForeignKey, ReferentialAction,
};
use crate::ir::default_expr::{DefaultExpr, LiteralValue};
use crate::ir::index::{Index, IndexColumn, IndexColumnExpr, IndexMethod, NullsOrder, SortOrder};
use crate::ir::schema::Schema;
use crate::ir::sequence::{Sequence, SequenceOwner};
use crate::ir::table::Table;

// ---------------------------------------------------------------------------
// Top-level statements
// ---------------------------------------------------------------------------

/// `CREATE SCHEMA name;`
pub fn create_schema(s: &Schema) -> String {
    format!("CREATE SCHEMA {};", s.name.render_sql())
}

/// `DROP SCHEMA name;`
pub fn drop_schema(name: &Identifier) -> String {
    format!("DROP SCHEMA {};", name.render_sql())
}

/// `COMMENT ON SCHEMA name IS '...';` (or `IS NULL` to clear).
pub fn comment_on_schema(name: &Identifier, comment: Option<&str>) -> String {
    format!(
        "COMMENT ON SCHEMA {} IS {};",
        name.render_sql(),
        render_comment(comment),
    )
}

/// `CREATE TABLE schema.name ( ... );` with inline columns and constraints.
///
/// When `table.partition_of` is set the column list is omitted entirely
/// (partitions inherit their columns) and a `PARTITION OF parent FOR VALUES
/// โ€ฆ` clause is emitted instead.  When `table.partition_by` is set a
/// `PARTITION BY โ€ฆ` clause is appended before the trailing `;`.
pub fn create_table(t: &Table) -> String {
    let mut s = String::new();
    s.push_str("CREATE TABLE ");
    s.push_str(&t.qname.render_sql());

    if let Some(po) = &t.partition_of {
        // Child partition: no column list โ€” columns are inherited from the
        // parent.  Emit the PARTITION OF clause directly.
        s.push(' ');
        s.push_str(&crate::plan::rewrite::partitions::render_partition_of(po));
    } else {
        // Normal table (possibly a partitioned parent): emit the column list.
        s.push_str(" (");
        let mut first = true;
        for col in &t.columns {
            if !first {
                s.push(',');
            }
            s.push('\n');
            s.push_str("    ");
            s.push_str(&column_def(col));
            first = false;
        }
        for c in &t.constraints {
            if !first {
                s.push(',');
            }
            s.push('\n');
            s.push_str("    ");
            s.push_str(&inline_constraint(c));
            first = false;
        }
        if !first {
            s.push('\n');
        }
        s.push(')');
    }

    if let Some(pb) = &t.partition_by {
        s.push(' ');
        s.push_str(&crate::plan::rewrite::partitions::render_partition_by(pb));
    }

    // USING <access_method> goes after the element list / PARTITION BY clause
    // and before any WITH (...) / TABLESPACE options (PG grammar order).
    if let Some(am) = &t.access_method {
        s.push_str(" USING ");
        s.push_str(&am.render_sql());
    }

    // TABLESPACE clause โ€” omit when None (use cluster default implicitly).
    if let Some(ts) = &t.tablespace {
        s.push_str(" TABLESPACE ");
        s.push_str(&ts.render_sql());
    }

    s.push(';');
    s
}

/// `DROP TABLE schema.name;`
pub fn drop_table(qname: &QualifiedName) -> String {
    format!("DROP TABLE {};", qname.render_sql())
}

/// `ALTER TABLE qname SET TABLESPACE name;`
///
/// When `name` is `None` the literal `pg_default` is used (the cluster default
/// tablespace).
pub fn alter_table_set_tablespace(qname: &QualifiedName, name: Option<&Identifier>) -> String {
    let ts = name.map_or_else(|| "pg_default".to_owned(), Identifier::render_sql);
    format!("ALTER TABLE {} SET TABLESPACE {};", qname.render_sql(), ts)
}

/// `COMMENT ON TABLE qname IS '...';`
pub fn comment_on_table(qname: &QualifiedName, comment: Option<&str>) -> String {
    format!(
        "COMMENT ON TABLE {} IS {};",
        qname.render_sql(),
        render_comment(comment),
    )
}

/// `CREATE [UNIQUE] INDEX [CONCURRENTLY] name ON table USING method (...) [INCLUDE (...)] [WHERE ...];`
pub fn create_index(idx: &Index, concurrently: bool) -> String {
    let mut s = String::from("CREATE ");
    if idx.unique {
        s.push_str("UNIQUE ");
    }
    s.push_str("INDEX ");
    if concurrently {
        s.push_str("CONCURRENTLY ");
    }
    s.push_str(&idx.qname.name.render_sql());
    s.push_str(" ON ");
    s.push_str(&idx.on.qname().render_sql());
    s.push_str(" USING ");
    s.push_str(index_method(idx.method));
    s.push_str(" (");
    s.push_str(&render_index_columns(&idx.columns));
    s.push(')');
    if !idx.include.is_empty() {
        s.push_str(" INCLUDE (");
        s.push_str(&render_idents(&idx.include));
        s.push(')');
    }
    if idx.unique && idx.nulls_not_distinct {
        s.push_str(" NULLS NOT DISTINCT");
    }
    if !idx.storage.is_empty() {
        s.push_str(" WITH (");
        s.push_str(&render_index_options(&idx.storage));
        s.push(')');
    }
    if let Some(ts) = &idx.tablespace {
        s.push_str(" TABLESPACE ");
        s.push_str(&ts.render_sql());
    }
    if let Some(pred) = &idx.predicate {
        s.push_str(" WHERE ");
        s.push_str(&pred.canonical_text);
    }
    s.push(';');
    s
}

/// `DROP INDEX [CONCURRENTLY] name;`
pub fn drop_index(qname: &QualifiedName, concurrently: bool) -> String {
    if concurrently {
        format!("DROP INDEX CONCURRENTLY {};", qname.render_sql())
    } else {
        format!("DROP INDEX {};", qname.render_sql())
    }
}

/// `CREATE SEQUENCE schema.name AS T [INCREMENT BY n] ...`.
pub fn create_sequence(s: &Sequence) -> String {
    let mut out = String::from("CREATE SEQUENCE ");
    out.push_str(&s.qname.render_sql());
    out.push_str(" AS ");
    out.push_str(&s.data_type.render_sql());
    out.push_str(&format!(" INCREMENT BY {}", s.increment));
    if let Some(min) = s.min_value {
        out.push_str(&format!(" MINVALUE {min}"));
    } else {
        out.push_str(" NO MINVALUE");
    }
    if let Some(max) = s.max_value {
        out.push_str(&format!(" MAXVALUE {max}"));
    } else {
        out.push_str(" NO MAXVALUE");
    }
    out.push_str(&format!(" START WITH {}", s.start));
    out.push_str(&format!(" CACHE {}", s.cache));
    if s.cycle {
        out.push_str(" CYCLE");
    } else {
        out.push_str(" NO CYCLE");
    }
    if let Some(owner) = &s.owned_by {
        out.push_str(" OWNED BY ");
        out.push_str(&render_owner(owner));
    }
    out.push(';');
    out
}

/// `DROP SEQUENCE schema.name;`
pub fn drop_sequence(qname: &QualifiedName) -> String {
    format!("DROP SEQUENCE {};", qname.render_sql())
}

// ---------------------------------------------------------------------------
// ALTER TABLE column / constraint operations
// ---------------------------------------------------------------------------

/// `ALTER TABLE qname ADD COLUMN ...;`
pub fn alter_table_add_column(qname: &QualifiedName, c: &Column) -> String {
    format!(
        "ALTER TABLE {} ADD COLUMN {};",
        qname.render_sql(),
        column_def(c),
    )
}

/// `ALTER TABLE qname DROP COLUMN name;`
pub fn alter_table_drop_column(qname: &QualifiedName, name: &Identifier) -> String {
    format!(
        "ALTER TABLE {} DROP COLUMN {};",
        qname.render_sql(),
        name.render_sql(),
    )
}

/// `ALTER TABLE qname ALTER COLUMN name TYPE T [USING expr];`
pub fn alter_column_type(
    qname: &QualifiedName,
    name: &Identifier,
    to: &crate::ir::column_type::ColumnType,
    using: Option<&crate::ir::default_expr::NormalizedExpr>,
) -> String {
    let mut s = format!(
        "ALTER TABLE {} ALTER COLUMN {} TYPE {}",
        qname.render_sql(),
        name.render_sql(),
        to.render_sql(),
    );
    if let Some(u) = using {
        s.push_str(" USING ");
        s.push_str(&u.canonical_text);
    }
    s.push(';');
    s
}

/// `ALTER TABLE qname ALTER COLUMN name {SET|DROP} NOT NULL;`
pub fn alter_column_set_nullable(
    qname: &QualifiedName,
    name: &Identifier,
    nullable: bool,
) -> String {
    let action = if nullable {
        "DROP NOT NULL"
    } else {
        "SET NOT NULL"
    };
    format!(
        "ALTER TABLE {} ALTER COLUMN {} {};",
        qname.render_sql(),
        name.render_sql(),
        action,
    )
}

/// `ALTER TABLE qname ALTER COLUMN name {SET DEFAULT expr|DROP DEFAULT};`
pub fn alter_column_set_default(
    qname: &QualifiedName,
    name: &Identifier,
    default: Option<&DefaultExpr>,
) -> String {
    match default {
        Some(d) => format!(
            "ALTER TABLE {} ALTER COLUMN {} SET DEFAULT {};",
            qname.render_sql(),
            name.render_sql(),
            render_default_expr(d),
        ),
        None => format!(
            "ALTER TABLE {} ALTER COLUMN {} DROP DEFAULT;",
            qname.render_sql(),
            name.render_sql(),
        ),
    }
}

/// `ALTER TABLE qname ALTER COLUMN name { ADD GENERATED ... AS IDENTITY | DROP IDENTITY };`
pub fn alter_column_set_identity(
    qname: &QualifiedName,
    name: &Identifier,
    identity: Option<&Identity>,
) -> String {
    match identity {
        Some(id) => format!(
            "ALTER TABLE {} ALTER COLUMN {} ADD GENERATED {} AS IDENTITY{};",
            qname.render_sql(),
            name.render_sql(),
            identity_kind(id.kind),
            render_sequence_options(&id.sequence),
        ),
        None => format!(
            "ALTER TABLE {} ALTER COLUMN {} DROP IDENTITY;",
            qname.render_sql(),
            name.render_sql(),
        ),
    }
}

/// `ALTER TABLE qname ALTER COLUMN name DROP EXPRESSION;`
///
/// Note: Postgres has no direct `ALTER COLUMN ... ADD GENERATED ... STORED`
/// for non-identity stored expressions. Setting a generated expression on
/// an existing column requires drop + readd of the column. v0.1 emits
/// `DROP EXPRESSION` for `None`; for `Some`, emits a marker statement that
/// makes the unsupported case visible as a plan error rather than silent.
pub fn alter_column_set_generated(
    qname: &QualifiedName,
    name: &Identifier,
    generated: Option<&crate::ir::column::Generated>,
) -> String {
    match generated {
        None => format!(
            "ALTER TABLE {} ALTER COLUMN {} DROP EXPRESSION;",
            qname.render_sql(),
            name.render_sql(),
        ),
        Some(g) => {
            // Best-effort: emit Postgres' currently-unsupported syntax so the
            // executor surfaces a clear error rather than silently no-op'ing.
            // The expected resolution is for the differ to produce a column
            // recreate in this case; until then this string serves as an
            // explicit, debuggable marker.
            format!(
                "ALTER TABLE {} ALTER COLUMN {} SET EXPRESSION AS ({}) {};",
                qname.render_sql(),
                name.render_sql(),
                g.expression.canonical_text,
                generated_kind(g.kind),
            )
        }
    }
}

/// `ALTER TABLE qname ALTER COLUMN name SET STORAGE {PLAIN|EXTERNAL|EXTENDED|MAIN};`
pub fn alter_column_set_storage(
    qname: &QualifiedName,
    name: &Identifier,
    storage: StorageKind,
) -> String {
    let kw = match storage {
        StorageKind::Plain => "PLAIN",
        StorageKind::External => "EXTERNAL",
        StorageKind::Extended => "EXTENDED",
        StorageKind::Main => "MAIN",
    };
    format!(
        "ALTER TABLE {} ALTER COLUMN {} SET STORAGE {};",
        qname.render_sql(),
        name.render_sql(),
        kw,
    )
}

/// `ALTER TABLE qname ALTER COLUMN name SET COMPRESSION {pglz|lz4|DEFAULT};`
pub fn alter_column_set_compression(
    qname: &QualifiedName,
    name: &Identifier,
    compression: Option<Compression>,
) -> String {
    let kw = match compression {
        Some(Compression::Pglz) => "pglz",
        Some(Compression::Lz4) => "lz4",
        None => "DEFAULT",
    };
    format!(
        "ALTER TABLE {} ALTER COLUMN {} SET COMPRESSION {};",
        qname.render_sql(),
        name.render_sql(),
        kw,
    )
}

/// `COMMENT ON COLUMN qname.col IS '...';`
pub fn comment_on_column(qname: &QualifiedName, col: &Identifier, comment: Option<&str>) -> String {
    format!(
        "COMMENT ON COLUMN {}.{} IS {};",
        qname.render_sql(),
        col.render_sql(),
        render_comment(comment),
    )
}

/// `ALTER TABLE qname ADD CONSTRAINT ...;` (validated form).
pub fn alter_table_add_constraint(qname: &QualifiedName, c: &Constraint) -> String {
    format!(
        "ALTER TABLE {} ADD {};",
        qname.render_sql(),
        constraint_def_with_name(c),
    )
}

/// `ALTER TABLE qname ADD CONSTRAINT ... NOT VALID;`
pub fn alter_table_add_constraint_not_valid(qname: &QualifiedName, c: &Constraint) -> String {
    format!(
        "ALTER TABLE {} ADD {} NOT VALID;",
        qname.render_sql(),
        constraint_def_with_name(c),
    )
}

/// `ALTER TABLE qname VALIDATE CONSTRAINT name;`
pub fn alter_table_validate_constraint(qname: &QualifiedName, cname: &Identifier) -> String {
    format!(
        "ALTER TABLE {} VALIDATE CONSTRAINT {};",
        qname.render_sql(),
        cname.render_sql(),
    )
}

/// `ALTER TABLE qname DROP CONSTRAINT name;`
pub fn alter_table_drop_constraint(qname: &QualifiedName, cname: &Identifier) -> String {
    format!(
        "ALTER TABLE {} DROP CONSTRAINT {};",
        qname.render_sql(),
        cname.render_sql(),
    )
}

/// `COMMENT ON CONSTRAINT name ON qname IS '...';`
pub fn comment_on_constraint(
    qname: &QualifiedName,
    cname: &Identifier,
    comment: Option<&str>,
) -> String {
    format!(
        "COMMENT ON CONSTRAINT {} ON {} IS {};",
        cname.render_sql(),
        qname.render_sql(),
        render_comment(comment),
    )
}

/// `COMMENT ON INDEX qname IS '...';`
pub fn comment_on_index(qname: &QualifiedName, comment: Option<&str>) -> String {
    format!(
        "COMMENT ON INDEX {} IS {};",
        qname.render_sql(),
        render_comment(comment),
    )
}

/// `COMMENT ON SEQUENCE qname IS '...';`
pub fn comment_on_sequence(qname: &QualifiedName, comment: Option<&str>) -> String {
    format!(
        "COMMENT ON SEQUENCE {} IS {};",
        qname.render_sql(),
        render_comment(comment),
    )
}

// ---------------------------------------------------------------------------
// ALTER SEQUENCE field-level ops
// ---------------------------------------------------------------------------

/// `ALTER SEQUENCE qname INCREMENT BY n;`
pub fn alter_sequence_increment(qname: &QualifiedName, n: i64) -> String {
    format!("ALTER SEQUENCE {} INCREMENT BY {n};", qname.render_sql())
}

/// `ALTER SEQUENCE qname { MINVALUE n | NO MINVALUE };`
pub fn alter_sequence_min_value(qname: &QualifiedName, v: Option<i64>) -> String {
    match v {
        Some(n) => format!("ALTER SEQUENCE {} MINVALUE {n};", qname.render_sql()),
        None => format!("ALTER SEQUENCE {} NO MINVALUE;", qname.render_sql()),
    }
}

/// `ALTER SEQUENCE qname { MAXVALUE n | NO MAXVALUE };`
pub fn alter_sequence_max_value(qname: &QualifiedName, v: Option<i64>) -> String {
    match v {
        Some(n) => format!("ALTER SEQUENCE {} MAXVALUE {n};", qname.render_sql()),
        None => format!("ALTER SEQUENCE {} NO MAXVALUE;", qname.render_sql()),
    }
}

/// `ALTER SEQUENCE qname CACHE n;`
pub fn alter_sequence_cache(qname: &QualifiedName, n: i64) -> String {
    format!("ALTER SEQUENCE {} CACHE {n};", qname.render_sql())
}

/// `ALTER SEQUENCE qname { CYCLE | NO CYCLE };`
pub fn alter_sequence_cycle(qname: &QualifiedName, cycle: bool) -> String {
    let kw = if cycle { "CYCLE" } else { "NO CYCLE" };
    format!("ALTER SEQUENCE {} {kw};", qname.render_sql())
}

/// `ALTER SEQUENCE qname AS T;`
pub fn alter_sequence_data_type(
    qname: &QualifiedName,
    ty: &crate::ir::column_type::ColumnType,
) -> String {
    format!(
        "ALTER SEQUENCE {} AS {};",
        qname.render_sql(),
        ty.render_sql(),
    )
}

/// `ALTER SEQUENCE qname OWNED BY { table.col | NONE };`
pub fn alter_sequence_owned_by(qname: &QualifiedName, owner: Option<&SequenceOwner>) -> String {
    match owner {
        Some(o) => format!(
            "ALTER SEQUENCE {} OWNED BY {};",
            qname.render_sql(),
            render_owner(o),
        ),
        None => format!("ALTER SEQUENCE {} OWNED BY NONE;", qname.render_sql()),
    }
}

// ---------------------------------------------------------------------------
// Helpers โ€” column / constraint / index / sequence sub-pieces
// ---------------------------------------------------------------------------

/// One column in `CREATE TABLE` or `ALTER TABLE ADD COLUMN`.
pub fn column_def(c: &Column) -> String {
    let mut s = String::new();
    s.push_str(&c.name.render_sql());
    s.push(' ');
    s.push_str(&c.ty.render_sql());
    if let Some(coll) = &c.collation {
        s.push_str(" COLLATE ");
        s.push_str(&coll.render_sql());
    }
    // COMPRESSION must appear before column constraints (including NOT NULL) โ€”
    // that is the order the Postgres grammar requires.
    //
    // NOTE: Inline `STORAGE` in `CREATE TABLE` / `ALTER TABLE ADD COLUMN` is a
    // PG 16+ feature (added in PostgreSQL 16).  PG 14 and PG 15 only accept
    // `ALTER TABLE โ€ฆ ALTER COLUMN โ€ฆ SET STORAGE โ€ฆ` (a separate post-CREATE
    // statement).  We therefore never emit inline STORAGE here; callers that
    // produce `CREATE TABLE` or `ADD COLUMN` steps must follow up with
    // `alter_column_set_storage` for any column whose `storage` field is
    // `Some(โ€ฆ)`.  See `emit::table::create` and `emit::table::op` for where
    // those follow-up steps are emitted.
    //
    // Inline COMPRESSION is fine on all supported targets (PG 14+).
    if let Some(compression) = c.compression {
        let kw = match compression {
            Compression::Pglz => "pglz",
            Compression::Lz4 => "lz4",
        };
        s.push_str(" COMPRESSION ");
        s.push_str(kw);
    }
    if !c.nullable {
        s.push_str(" NOT NULL");
    }
    if let Some(d) = &c.default {
        s.push_str(" DEFAULT ");
        s.push_str(&render_default_expr(d));
    }
    if let Some(id) = &c.identity {
        s.push_str(" GENERATED ");
        s.push_str(identity_kind(id.kind));
        s.push_str(" AS IDENTITY");
        s.push_str(&render_sequence_options(&id.sequence));
    }
    if let Some(g) = &c.generated {
        s.push_str(" GENERATED ALWAYS AS (");
        s.push_str(&g.expression.canonical_text);
        s.push_str(") ");
        s.push_str(generated_kind(g.kind));
    }
    s
}

/// A constraint clause as it appears inline in `CREATE TABLE`.
fn inline_constraint(c: &Constraint) -> String {
    constraint_def_with_name(c)
}

/// `CONSTRAINT name <body>` โ€” used for both inline and `ADD CONSTRAINT` forms.
pub fn constraint_def_with_name(c: &Constraint) -> String {
    let mut s = format!(
        "CONSTRAINT {} {}",
        c.qname.name.render_sql(),
        constraint_body(&c.kind)
    );
    match c.deferrable {
        Deferrable::NotDeferrable => {}
        Deferrable::Deferrable {
            initially_deferred: true,
        } => s.push_str(" DEFERRABLE INITIALLY DEFERRED"),
        Deferrable::Deferrable {
            initially_deferred: false,
        } => s.push_str(" DEFERRABLE INITIALLY IMMEDIATE"),
    }
    s
}

fn constraint_body(k: &ConstraintKind) -> String {
    match k {
        ConstraintKind::PrimaryKey { columns, include } => {
            let mut s = format!("PRIMARY KEY ({})", render_idents(columns));
            if !include.is_empty() {
                s.push_str(&format!(" INCLUDE ({})", render_idents(include)));
            }
            s
        }
        ConstraintKind::Unique {
            columns,
            include,
            nulls_distinct,
        } => {
            let mut s = String::from("UNIQUE");
            if !nulls_distinct {
                s.push_str(" NULLS NOT DISTINCT");
            }
            s.push_str(&format!(" ({})", render_idents(columns)));
            if !include.is_empty() {
                s.push_str(&format!(" INCLUDE ({})", render_idents(include)));
            }
            s
        }
        ConstraintKind::ForeignKey(fk) => render_fk(fk),
        ConstraintKind::Check {
            expression,
            no_inherit,
        } => {
            let mut s = format!("CHECK ({})", expression.canonical_text);
            if *no_inherit {
                s.push_str(" NO INHERIT");
            }
            s
        }
    }
}

fn render_fk(fk: &ForeignKey) -> String {
    let mut s = format!(
        "FOREIGN KEY ({}) REFERENCES {} ({})",
        render_idents(&fk.columns),
        fk.referenced_table.render_sql(),
        render_idents(&fk.referenced_columns),
    );
    if !matches!(fk.match_type, FkMatchType::Simple) {
        s.push_str(" MATCH ");
        s.push_str(match fk.match_type {
            FkMatchType::Simple => "SIMPLE",
            FkMatchType::Full => "FULL",
        });
    }
    if !matches!(fk.on_update, ReferentialAction::NoAction) {
        s.push_str(" ON UPDATE ");
        s.push_str(&referential_action(&fk.on_update));
    }
    if !matches!(fk.on_delete, ReferentialAction::NoAction) {
        s.push_str(" ON DELETE ");
        s.push_str(&referential_action(&fk.on_delete));
    }
    s
}

fn referential_action(a: &ReferentialAction) -> String {
    match a {
        ReferentialAction::NoAction => "NO ACTION".into(),
        ReferentialAction::Restrict => "RESTRICT".into(),
        ReferentialAction::Cascade => "CASCADE".into(),
        ReferentialAction::SetNull(cols) => {
            if cols.is_empty() {
                "SET NULL".into()
            } else {
                format!("SET NULL ({})", render_idents(cols))
            }
        }
        ReferentialAction::SetDefault(cols) => {
            if cols.is_empty() {
                "SET DEFAULT".into()
            } else {
                format!("SET DEFAULT ({})", render_idents(cols))
            }
        }
    }
}

fn render_index_columns(cols: &[IndexColumn]) -> String {
    let mut parts = Vec::with_capacity(cols.len());
    for c in cols {
        let mut s = match &c.expr {
            IndexColumnExpr::Column(id) => id.render_sql(),
            IndexColumnExpr::Expression(e) => format!("({})", e.canonical_text),
        };
        if let Some(coll) = &c.collation {
            s.push_str(" COLLATE ");
            s.push_str(&coll.render_sql());
        }
        if let Some(opc) = &c.opclass {
            s.push(' ');
            s.push_str(&opc.render_sql());
        }
        match c.sort_order {
            SortOrder::Asc => {} // ASC is the default; emit only DESC.
            SortOrder::Desc => s.push_str(" DESC"),
        }
        match c.nulls_order {
            NullsOrder::NullsFirst => s.push_str(" NULLS FIRST"),
            NullsOrder::NullsLast => {} // NULLS LAST is btree default for ASC.
        }
        parts.push(s);
    }
    parts.join(", ")
}

const fn index_method(m: IndexMethod) -> &'static str {
    match m {
        IndexMethod::BTree => "btree",
        IndexMethod::Hash => "hash",
        IndexMethod::Gin => "gin",
        IndexMethod::Gist => "gist",
        IndexMethod::Brin => "brin",
        IndexMethod::Spgist => "spgist",
    }
}

const fn identity_kind(k: IdentityKind) -> &'static str {
    match k {
        IdentityKind::Always => "ALWAYS",
        IdentityKind::ByDefault => "BY DEFAULT",
    }
}

const fn generated_kind(k: GeneratedKind) -> &'static str {
    match k {
        GeneratedKind::Stored => "STORED",
    }
}

fn render_sequence_options(o: &SequenceOptions) -> String {
    // Only emit the parenthesized clause if any value differs from PG defaults.
    let defaults = SequenceOptions {
        start: 1,
        increment: 1,
        min_value: None,
        max_value: None,
        cache: 1,
        cycle: false,
    };
    if o == &defaults {
        return String::new();
    }
    let mut parts: Vec<String> = Vec::new();
    if o.start != defaults.start {
        parts.push(format!("START WITH {}", o.start));
    }
    if o.increment != defaults.increment {
        parts.push(format!("INCREMENT BY {}", o.increment));
    }
    if let Some(min) = o.min_value {
        parts.push(format!("MINVALUE {min}"));
    }
    if let Some(max) = o.max_value {
        parts.push(format!("MAXVALUE {max}"));
    }
    if o.cache != defaults.cache {
        parts.push(format!("CACHE {}", o.cache));
    }
    if o.cycle {
        parts.push("CYCLE".into());
    }
    if parts.is_empty() {
        String::new()
    } else {
        format!(" ({})", parts.join(" "))
    }
}

fn render_default_expr(d: &DefaultExpr) -> String {
    match d {
        DefaultExpr::Literal(LiteralValue::Bool(b)) => {
            if *b {
                "true".into()
            } else {
                "false".into()
            }
        }
        DefaultExpr::Literal(LiteralValue::Integer(i)) => i.to_string(),
        DefaultExpr::Literal(LiteralValue::Float(f)) => f.to_string(),
        DefaultExpr::Literal(LiteralValue::Text(t)) => sql_string_literal(t),
        DefaultExpr::Literal(LiteralValue::Bytea(b)) => format!("'\\x{}'", hex(b)),
        DefaultExpr::Literal(LiteralValue::Null) => "NULL".into(),
        DefaultExpr::Sequence(q) => format!("nextval('{}')", q.render_sql()),
        DefaultExpr::Expr(e) => e.canonical_text.clone(),
    }
}

fn hex(bytes: &[u8]) -> String {
    use std::fmt::Write as _;
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        let _ = write!(s, "{b:02x}");
    }
    s
}

fn render_idents(v: &[Identifier]) -> String {
    let mut s = String::new();
    for (i, id) in v.iter().enumerate() {
        if i > 0 {
            s.push_str(", ");
        }
        s.push_str(&id.render_sql());
    }
    s
}

fn render_owner(o: &SequenceOwner) -> String {
    format!("{}.{}", o.table.render_sql(), o.column.render_sql())
}

/// Render `s` as a complete single-quoted SQL string literal (doubles embedded
/// single quotes). The single place literal escaping is defined.
#[must_use]
pub(crate) fn sql_string_literal(s: &str) -> String {
    format!("'{}'", escape_sql_literal_body(s))
}

/// Double embedded single quotes for embedding inside a manually-quoted SQL
/// literal. Prefer [`sql_string_literal`] when you control the whole literal.
#[must_use]
pub(crate) fn escape_sql_literal_body(s: &str) -> String {
    s.replace('\'', "''")
}

fn render_comment(comment: Option<&str>) -> String {
    match comment {
        Some(t) => sql_string_literal(t),
        None => "NULL".into(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::identifier::Identifier;
    use crate::ir::column_type::ColumnType;
    use crate::ir::partition::{
        BoundDatum, PartitionBounds, PartitionBy, PartitionColumn, PartitionColumnKind,
        PartitionOf, PartitionStrategy,
    };

    fn id(s: &str) -> Identifier {
        Identifier::from_unquoted(s).unwrap()
    }

    fn qn(schema: &str, name: &str) -> QualifiedName {
        QualifiedName::new(id(schema), id(name))
    }

    fn simple_col(name: &str) -> Column {
        Column {
            name: id(name),
            ty: ColumnType::Text,
            nullable: true,
            collation: None,
            default: None,
            identity: None,
            generated: None,
            storage: None,
            compression: None,
            comment: None,
        }
    }

    fn lit(s: &str) -> crate::ir::default_expr::NormalizedExpr {
        crate::ir::default_expr::NormalizedExpr::from_text(s)
    }

    fn empty_table(qname: QualifiedName) -> Table {
        Table {
            qname,
            columns: vec![],
            constraints: vec![],
            partition_by: None,
            partition_of: None,
            comment: None,
            owner: None,
            grants: vec![],
            rls_enabled: false,
            rls_forced: false,
            policies: vec![],
            storage: crate::ir::reloptions::TableStorageOptions::default(),
            access_method: None,
            tablespace: None,
        }
    }

    #[test]
    fn partitioned_parent_includes_partition_by() {
        let mut t = empty_table(qn("app", "orders"));
        t.columns = vec![simple_col("region")];
        t.partition_by = Some(PartitionBy {
            strategy: PartitionStrategy::List,
            columns: vec![PartitionColumn {
                kind: PartitionColumnKind::Column(id("region")),
                collation: None,
                opclass: None,
            }],
        });
        let sql = create_table(&t);
        assert!(
            sql.ends_with("PARTITION BY LIST (region);"),
            "expected PARTITION BY LIST (region); at end, got: {sql}"
        );
        assert!(
            sql.contains("region text"),
            "expected column def, got: {sql}"
        );
    }

    #[test]
    fn child_partition_emits_partition_of_no_column_list() {
        let mut t = empty_table(qn("app", "orders_2024"));
        t.partition_of = Some(PartitionOf {
            parent: qn("app", "orders"),
            bounds: PartitionBounds::Range {
                from: vec![BoundDatum::Literal(lit("'2024-01-01'"))],
                to: vec![BoundDatum::Literal(lit("'2025-01-01'"))],
            },
        });
        let sql = create_table(&t);
        assert_eq!(
            sql,
            "CREATE TABLE app.orders_2024 PARTITION OF app.orders FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');"
        );
        // Must not contain a column list parenthesis block
        assert!(
            !sql.contains('(') || sql.contains("FOR VALUES FROM ("),
            "should not contain a column list opening paren, got: {sql}"
        );
    }

    // -----------------------------------------------------------------------
    // SQL helpers: alter_column_set_storage / alter_column_set_compression
    // -----------------------------------------------------------------------

    #[test]
    fn renders_set_storage_external() {
        let s = alter_column_set_storage(&qn("app", "t"), &id("c"), StorageKind::External);
        assert_eq!(
            s.trim(),
            "ALTER TABLE app.t ALTER COLUMN c SET STORAGE EXTERNAL;"
        );
    }

    #[test]
    fn renders_all_storage_variants() {
        for (storage, expected) in [
            (StorageKind::Plain, "PLAIN"),
            (StorageKind::External, "EXTERNAL"),
            (StorageKind::Extended, "EXTENDED"),
            (StorageKind::Main, "MAIN"),
        ] {
            let s = alter_column_set_storage(&qn("app", "t"), &id("c"), storage);
            assert!(s.contains(&format!("SET STORAGE {expected}")), "got: {s}");
        }
    }

    #[test]
    fn renders_set_compression_lz4() {
        let s = alter_column_set_compression(&qn("app", "t"), &id("c"), Some(Compression::Lz4));
        assert_eq!(
            s.trim(),
            "ALTER TABLE app.t ALTER COLUMN c SET COMPRESSION lz4;"
        );
    }

    #[test]
    fn renders_set_compression_pglz() {
        let s = alter_column_set_compression(&qn("app", "t"), &id("c"), Some(Compression::Pglz));
        assert_eq!(
            s.trim(),
            "ALTER TABLE app.t ALTER COLUMN c SET COMPRESSION pglz;"
        );
    }

    #[test]
    fn renders_set_compression_default() {
        let s = alter_column_set_compression(&qn("app", "t"), &id("c"), None);
        assert_eq!(
            s.trim(),
            "ALTER TABLE app.t ALTER COLUMN c SET COMPRESSION DEFAULT;"
        );
    }

    // -----------------------------------------------------------------------
    // column_def: inline COMPRESSION only (no inline STORAGE โ€” PG 14/15 do
    // not support inline STORAGE; callers emit a separate SET STORAGE step)
    // -----------------------------------------------------------------------

    #[test]
    fn column_def_never_renders_inline_storage() {
        // Even when `storage` is set, `column_def` must NOT emit an inline
        // STORAGE clause.  Callers (`create_table`, `add_column`) are
        // responsible for emitting a separate ALTER TABLE โ€ฆ SET STORAGE step.
        for storage in [
            StorageKind::Plain,
            StorageKind::External,
            StorageKind::Extended,
            StorageKind::Main,
        ] {
            let mut c = simple_col("doc");
            c.storage = Some(storage);
            let s = column_def(&c);
            assert!(
                !s.contains("STORAGE"),
                "column_def must not emit inline STORAGE (PG 14/15 do not support it), got: {s}"
            );
        }
    }

    #[test]
    fn column_def_renders_compression_lz4() {
        let mut c = simple_col("blob");
        c.compression = Some(Compression::Lz4);
        let s = column_def(&c);
        assert!(s.contains("COMPRESSION lz4"), "got: {s}");
    }

    #[test]
    fn column_def_renders_no_clauses_when_none() {
        let c = simple_col("plain");
        let s = column_def(&c);
        assert!(!s.contains("STORAGE"), "got: {s}");
        assert!(!s.contains("COMPRESSION"), "got: {s}");
    }

    // -----------------------------------------------------------------------
    // create_index: WITH (...) storage clause
    // -----------------------------------------------------------------------

    fn simple_index() -> Index {
        use crate::ir::index::{IndexColumn, IndexColumnExpr, IndexParent, NullsOrder, SortOrder};
        Index {
            qname: qn("app", "idx_test"),
            on: IndexParent::Table(qn("app", "t")),
            method: crate::ir::index::IndexMethod::BTree,
            columns: vec![IndexColumn {
                expr: IndexColumnExpr::Column(id("col1")),
                collation: None,
                opclass: None,
                sort_order: SortOrder::Asc,
                nulls_order: NullsOrder::NullsLast,
            }],
            include: vec![],
            unique: false,
            nulls_not_distinct: false,
            predicate: None,
            tablespace: None,
            comment: None,
            storage: crate::ir::reloptions::IndexStorageOptions::default(),
        }
    }

    #[test]
    fn create_index_emits_with_clause_when_fillfactor_set() {
        let mut idx = simple_index();
        idx.storage = crate::ir::reloptions::IndexStorageOptions {
            fillfactor: Some(80),
            ..Default::default()
        };
        let sql = create_index(&idx, false);
        assert!(
            sql.contains("WITH (fillfactor = 80)"),
            "expected WITH (fillfactor = 80) in SQL, got: {sql}"
        );
    }

    #[test]
    fn create_index_no_with_clause_for_default_storage() {
        let idx = simple_index();
        let sql = create_index(&idx, false);
        assert!(
            !sql.contains("WITH ("),
            "expected no WITH clause for default storage, got: {sql}"
        );
    }

    // -----------------------------------------------------------------------
    // create_table: USING <access_method>
    // -----------------------------------------------------------------------

    #[test]
    fn create_table_with_access_method_emits_using_clause() {
        let mut t = empty_table(qn("app", "events"));
        t.columns = vec![simple_col("id")];
        t.access_method = Some(Identifier::from_unquoted("columnar").unwrap());
        let sql = create_table(&t);
        // USING must appear after the closing ')' of the column list
        let paren_close = sql.find(')').expect("closing paren");
        let using_pos = sql
            .find(" USING columnar")
            .expect("USING columnar not found in SQL");
        assert!(
            using_pos > paren_close,
            "USING must come after the closing ')' of the column list; got: {sql}"
        );
        assert!(sql.ends_with(';'), "SQL must end with ';', got: {sql}");
    }

    #[test]
    fn create_table_without_access_method_emits_no_using_clause() {
        let mut t = empty_table(qn("app", "events"));
        t.columns = vec![simple_col("id")];
        // access_method is None (the default)
        let sql = create_table(&t);
        assert!(
            !sql.contains("USING"),
            "expected no USING clause when access_method is None, got: {sql}"
        );
    }

    // --- tablespace tests ---

    #[test]
    fn alter_table_set_tablespace_with_name() {
        let qname = qn("app", "orders");
        let ts = id("fast");
        let sql = alter_table_set_tablespace(&qname, Some(&ts));
        assert_eq!(sql, "ALTER TABLE app.orders SET TABLESPACE fast;");
    }

    #[test]
    fn alter_table_set_tablespace_none_uses_pg_default() {
        let qname = qn("app", "orders");
        let sql = alter_table_set_tablespace(&qname, None);
        assert_eq!(sql, "ALTER TABLE app.orders SET TABLESPACE pg_default;");
    }

    #[test]
    fn create_table_with_tablespace_appends_clause() {
        let mut t = empty_table(qn("app", "events"));
        t.columns = vec![simple_col("id")];
        t.tablespace = Some(id("fast_ssd"));
        let sql = create_table(&t);
        assert!(
            sql.ends_with(" TABLESPACE fast_ssd;"),
            "expected TABLESPACE clause at end, got: {sql}"
        );
    }

    #[test]
    fn create_table_without_tablespace_omits_clause() {
        let mut t = empty_table(qn("app", "events"));
        t.columns = vec![simple_col("id")];
        // tablespace is None (the default)
        let sql = create_table(&t);
        assert!(
            !sql.contains("TABLESPACE"),
            "expected no TABLESPACE clause when tablespace is None, got: {sql}"
        );
    }
}