pgevolve-core 0.3.3

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
//! `ALTER TABLE` support for source DDL.
//!
//! Source SQL is declarative: tables, columns, constraints, etc. are stated as
//! the desired end-state via `CREATE`. Two classes of `ALTER TABLE` are accepted
//! because they cannot always be expressed inline:
//!
//! 1. **`ADD CONSTRAINT FOREIGN KEY`** — forward-referencing FKs: when two
//!    tables reference each other, neither can declare its FK inline because the
//!    other side does not exist yet at parse time.
//!
//! 2. **`ALTER COLUMN … SET STORAGE / SET COMPRESSION`** — per-column storage
//!    strategy and compression codec. These may appear after the `CREATE TABLE`
//!    (for example when the source is derived from `pg_dump`).
//!
//! Everything else raises [`ParseError::Structural`] pointing the user to the
//! declarative source-of-truth model.

use pg_query::NodeEnum;
use pg_query::protobuf::{
    AlterTableCmd, AlterTableStmt, AlterTableType, ConstrType, Constraint as PgConstraint,
    ObjectType, RoleSpecType,
};

use crate::identifier::{Identifier, QualifiedName};
use crate::ir::catalog::Catalog;
use crate::ir::column::{Compression, StorageKind};
use crate::ir::constraint::Constraint;
use crate::ir::reloptions::TableStorageOptions;
use crate::parse::builder::create_stmt;
use crate::parse::builder::shared;
use crate::parse::error::{ParseError, SourceLocation};

/// One forward-reference FK constraint to merge into a [`crate::ir::table::Table`]
/// after all tables have been built.
#[derive(Debug, Clone)]
pub struct PendingFk {
    /// Target table to attach the constraint to.
    pub target: QualifiedName,
    /// The constraint itself.
    pub constraint: Constraint,
}

/// A per-column attribute update (`SET STORAGE` / `SET COMPRESSION`) to apply
/// to an already-built [`crate::ir::column::Column`] once all tables exist.
#[derive(Debug, Clone)]
pub struct PendingColumnAttr {
    /// Table that owns the column.
    pub target: QualifiedName,
    /// Column to update.
    pub column: Identifier,
    /// The attribute change to apply.
    pub kind: PendingColumnAttrKind,
}

/// Which column attribute is being set.
#[derive(Debug, Clone)]
pub enum PendingColumnAttrKind {
    /// `ALTER COLUMN … SET STORAGE <strategy>`.
    Storage(StorageKind),
    /// `ALTER COLUMN … SET COMPRESSION <codec>` — `None` means `DEFAULT`
    /// (revert to cluster GUC).
    Compression(Option<Compression>),
}

/// An ownership assignment pending merge into the catalog.
#[derive(Debug, Clone)]
pub struct PendingOwner {
    /// Relation whose owner should be updated.
    pub target: QualifiedName,
    /// New owner role name.
    pub new_owner: Identifier,
}

/// An RLS mode toggle (`ENABLE / DISABLE / FORCE / NO FORCE ROW LEVEL SECURITY`)
/// pending application to its target table.
#[derive(Debug, Clone)]
pub struct PendingRlsToggle {
    /// Table to update.
    pub target: QualifiedName,
    /// The exact subcommand type — one of the four RLS `AlterTableType` variants.
    pub subtype: AlterTableType,
}

/// A `SET (...)` reloptions update from `ALTER TABLE / MATERIALIZED VIEW ... SET
/// (key = value, ...)`, pending merge into the target relation's `storage` field.
#[derive(Debug, Clone)]
pub struct PendingRelOptions {
    /// Relation whose storage options should be updated.
    pub target: QualifiedName,
    /// The decoded options to merge.
    pub options: TableStorageOptions,
}

/// The combined output of processing one `ALTER TABLE` statement.
#[derive(Debug, Default)]
pub struct AlterTableOutput {
    /// Forward-reference FK constraints to merge after all tables are parsed.
    pub pending_fks: Vec<PendingFk>,
    /// Per-column attribute updates to apply after all tables are parsed.
    pub pending_column_attrs: Vec<PendingColumnAttr>,
    /// Ownership assignments for relation-family objects.
    pub pending_owners: Vec<PendingOwner>,
    /// RLS mode toggles (ENABLE/DISABLE/FORCE/NO FORCE ROW LEVEL SECURITY).
    pub pending_rls_toggles: Vec<PendingRlsToggle>,
    /// Reloption SET (...) updates to apply after all tables/MVs are parsed.
    pub pending_rel_options: Vec<PendingRelOptions>,
}

/// Process an `ALTER TABLE` statement.
///
/// Returns a combined [`AlterTableOutput`] covering the two supported
/// subcommand classes. Any other subcommand raises [`ParseError::Structural`]
/// pointing the user to the declarative source-of-truth model.
pub fn build_alter_table(
    stmt: &AlterTableStmt,
    default_schema: Option<&Identifier>,
    location: &SourceLocation,
) -> Result<AlterTableOutput, ParseError> {
    let relation = stmt
        .relation
        .as_ref()
        .ok_or_else(|| ParseError::Structural {
            location: location.clone(),
            message: "ALTER TABLE missing relation".into(),
        })?;
    let target = shared::resolve_qname(relation, default_schema, location)?;

    let mut out = AlterTableOutput::default();
    for cmd_node in &stmt.cmds {
        let Some(NodeEnum::AlterTableCmd(cmd)) = cmd_node.node.as_ref() else {
            return Err(unsupported_alter(location));
        };
        process_cmd(cmd, &target, default_schema, location, &mut out)?;
    }
    Ok(out)
}

fn process_cmd(
    cmd: &AlterTableCmd,
    target: &QualifiedName,
    default_schema: Option<&Identifier>,
    location: &SourceLocation,
    out: &mut AlterTableOutput,
) -> Result<(), ParseError> {
    let subtype = AlterTableType::try_from(cmd.subtype).unwrap_or(AlterTableType::Undefined);
    match subtype {
        AlterTableType::AtAddConstraint => {
            let pending = process_add_constraint_cmd(cmd, target, default_schema, location)?;
            out.pending_fks.push(pending);
        }
        AlterTableType::AtSetStorage => {
            let pending = process_set_storage_cmd(cmd, target, location)?;
            out.pending_column_attrs.push(pending);
        }
        AlterTableType::AtSetCompression => {
            let pending = process_set_compression_cmd(cmd, target, location)?;
            out.pending_column_attrs.push(pending);
        }
        AlterTableType::AtChangeOwner => {
            let pending = process_change_owner_cmd(cmd, target, location)?;
            out.pending_owners.push(pending);
        }
        AlterTableType::AtEnableRowSecurity
        | AlterTableType::AtDisableRowSecurity
        | AlterTableType::AtForceRowSecurity
        | AlterTableType::AtNoForceRowSecurity => {
            out.pending_rls_toggles.push(PendingRlsToggle {
                target: target.clone(),
                subtype,
            });
        }
        AlterTableType::AtSetRelOptions => {
            let pending = process_set_rel_options_cmd(cmd, target, location)?;
            out.pending_rel_options.push(pending);
        }
        AlterTableType::AtResetRelOptions | AlterTableType::AtReplaceRelOptions => {
            return Err(ParseError::Structural {
                location: location.clone(),
                message: "ALTER TABLE ... RESET (...) in source is not supported — \
                          clear options out-of-band, then remove from source"
                    .into(),
            });
        }
        _ => return Err(unsupported_alter(location)),
    }
    Ok(())
}

fn process_add_constraint_cmd(
    cmd: &AlterTableCmd,
    target: &QualifiedName,
    default_schema: Option<&Identifier>,
    location: &SourceLocation,
) -> Result<PendingFk, ParseError> {
    let con = cmd
        .def
        .as_ref()
        .and_then(|d| d.node.as_ref())
        .and_then(|n| match n {
            NodeEnum::Constraint(c) => Some(c.as_ref()),
            _ => None,
        })
        .ok_or_else(|| ParseError::Structural {
            location: location.clone(),
            message: "ALTER TABLE ADD CONSTRAINT missing constraint definition".into(),
        })?;

    let kind = ConstrType::try_from(con.contype).unwrap_or(ConstrType::Undefined);
    if !matches!(kind, ConstrType::ConstrForeign) {
        return Err(ParseError::Structural {
            location: location.clone(),
            message: "ALTER TABLE may only ADD CONSTRAINT FOREIGN KEY in source DDL — \
                     other constraint kinds belong inline in the CREATE TABLE that \
                     declares them"
                .into(),
        });
    }

    let constraint = build_fk_constraint(con, target, default_schema, location)?;
    Ok(PendingFk {
        target: target.clone(),
        constraint,
    })
}

fn process_set_storage_cmd(
    cmd: &AlterTableCmd,
    target: &QualifiedName,
    location: &SourceLocation,
) -> Result<PendingColumnAttr, ParseError> {
    // cmd.name = column name; cmd.def = String node with lowercase strategy keyword.
    let column = shared::ident(&cmd.name, location)?;
    let keyword = def_as_string(cmd, location)?;
    let storage = match keyword.to_ascii_lowercase().as_str() {
        "plain" => StorageKind::Plain,
        "external" => StorageKind::External,
        "extended" => StorageKind::Extended,
        "main" => StorageKind::Main,
        other => {
            return Err(ParseError::Structural {
                location: location.clone(),
                message: format!("unknown STORAGE attribute '{other}'"),
            });
        }
    };
    Ok(PendingColumnAttr {
        target: target.clone(),
        column,
        kind: PendingColumnAttrKind::Storage(storage),
    })
}

fn process_set_compression_cmd(
    cmd: &AlterTableCmd,
    target: &QualifiedName,
    location: &SourceLocation,
) -> Result<PendingColumnAttr, ParseError> {
    // cmd.name = column name; cmd.def = String node with lowercase codec name.
    let column = shared::ident(&cmd.name, location)?;
    let keyword = def_as_string(cmd, location)?;
    let compression = match keyword.to_ascii_lowercase().as_str() {
        "default" => None,
        "pglz" => Some(Compression::Pglz),
        "lz4" => Some(Compression::Lz4),
        other => {
            return Err(ParseError::Structural {
                location: location.clone(),
                message: format!("unknown COMPRESSION codec '{other}'"),
            });
        }
    };
    Ok(PendingColumnAttr {
        target: target.clone(),
        column,
        kind: PendingColumnAttrKind::Compression(compression),
    })
}

/// Decode an `AT_ChangeOwner` sub-command into a [`PendingOwner`].
///
/// `pg_query` encodes the new owner as a `RoleSpec` in `cmd.newowner` (a
/// dedicated field on [`AlterTableCmd`], not in the generic `cmd.def`).
fn process_change_owner_cmd(
    cmd: &AlterTableCmd,
    target: &QualifiedName,
    location: &SourceLocation,
) -> Result<PendingOwner, ParseError> {
    let rs = cmd
        .newowner
        .as_ref()
        .ok_or_else(|| ParseError::Structural {
            location: location.clone(),
            message: "ALTER TABLE OWNER TO missing role specification".into(),
        })?;
    let roletype = RoleSpecType::try_from(rs.roletype).unwrap_or(RoleSpecType::Undefined);
    if roletype == RoleSpecType::RolespecPublic {
        return Err(ParseError::Structural {
            location: location.clone(),
            message: "ALTER TABLE OWNER TO PUBLIC is not valid — PUBLIC is not a role name".into(),
        });
    }
    let new_owner = shared::ident(&rs.rolename, location)?;
    Ok(PendingOwner {
        target: target.clone(),
        new_owner,
    })
}

fn process_set_rel_options_cmd(
    cmd: &AlterTableCmd,
    target: &QualifiedName,
    location: &SourceLocation,
) -> Result<PendingRelOptions, ParseError> {
    let items = crate::parse::builder::reloptions::extract_def_list(cmd.def.as_deref(), location)?;
    let options = crate::parse::builder::reloptions::decode_table_options(&items, location)?;
    Ok(PendingRelOptions {
        target: target.clone(),
        options,
    })
}

/// Apply accumulated `ALTER TABLE ... SET (...)` reloption updates to the
/// catalog. Tables and materialized views are both searched.
///
/// Called from `parse/mod.rs` after all relations are built.
pub fn apply_pending_rel_options(
    catalog: &mut Catalog,
    pending: Vec<PendingRelOptions>,
    location: &SourceLocation,
) -> Result<(), ParseError> {
    for p in pending {
        // Search tables first.
        if let Some(table) = catalog.tables.iter_mut().find(|t| t.qname == p.target) {
            merge_table_options(&mut table.storage, p.options);
            continue;
        }
        // Then materialized views.
        if let Some(mv) = catalog
            .materialized_views
            .iter_mut()
            .find(|m| m.qname == p.target)
        {
            merge_table_options(&mut mv.storage, p.options);
            continue;
        }
        return Err(ParseError::Structural {
            location: location.clone(),
            message: format!(
                "ALTER ... SET (...) referenced unknown relation {}",
                p.target
            ),
        });
    }
    Ok(())
}

/// Merge `src` options into `dst`, overwriting only the fields that are `Some`
/// in `src`. Fields that are `None` in `src` are left unchanged in `dst`.
fn merge_table_options(
    dst: &mut crate::ir::reloptions::TableStorageOptions,
    src: crate::ir::reloptions::TableStorageOptions,
) {
    if src.fillfactor.is_some() {
        dst.fillfactor = src.fillfactor;
    }
    if src.parallel_workers.is_some() {
        dst.parallel_workers = src.parallel_workers;
    }
    if src.toast_tuple_target.is_some() {
        dst.toast_tuple_target = src.toast_tuple_target;
    }
    if src.user_catalog_table.is_some() {
        dst.user_catalog_table = src.user_catalog_table;
    }
    if src.vacuum_truncate.is_some() {
        dst.vacuum_truncate = src.vacuum_truncate;
    }
    merge_autovacuum(&mut dst.autovacuum, &src.autovacuum);
    for (k, v) in src.extra {
        dst.extra.insert(k, v);
    }
}

const fn merge_autovacuum(
    dst: &mut crate::ir::reloptions::AutovacuumOptions,
    src: &crate::ir::reloptions::AutovacuumOptions,
) {
    if src.enabled.is_some() {
        dst.enabled = src.enabled;
    }
    if src.vacuum_threshold.is_some() {
        dst.vacuum_threshold = src.vacuum_threshold;
    }
    if src.vacuum_scale_factor.is_some() {
        dst.vacuum_scale_factor = src.vacuum_scale_factor;
    }
    if src.vacuum_cost_delay.is_some() {
        dst.vacuum_cost_delay = src.vacuum_cost_delay;
    }
    if src.vacuum_cost_limit.is_some() {
        dst.vacuum_cost_limit = src.vacuum_cost_limit;
    }
    if src.analyze_threshold.is_some() {
        dst.analyze_threshold = src.analyze_threshold;
    }
    if src.analyze_scale_factor.is_some() {
        dst.analyze_scale_factor = src.analyze_scale_factor;
    }
    if src.freeze_max_age.is_some() {
        dst.freeze_max_age = src.freeze_max_age;
    }
    if src.freeze_min_age.is_some() {
        dst.freeze_min_age = src.freeze_min_age;
    }
    if src.freeze_table_age.is_some() {
        dst.freeze_table_age = src.freeze_table_age;
    }
    if src.multixact_freeze_max_age.is_some() {
        dst.multixact_freeze_max_age = src.multixact_freeze_max_age;
    }
    if src.multixact_freeze_min_age.is_some() {
        dst.multixact_freeze_min_age = src.multixact_freeze_min_age;
    }
    if src.multixact_freeze_table_age.is_some() {
        dst.multixact_freeze_table_age = src.multixact_freeze_table_age;
    }
    if src.vacuum_insert_threshold.is_some() {
        dst.vacuum_insert_threshold = src.vacuum_insert_threshold;
    }
    if src.vacuum_insert_scale_factor.is_some() {
        dst.vacuum_insert_scale_factor = src.vacuum_insert_scale_factor;
    }
    if src.log_min_duration.is_some() {
        dst.log_min_duration = src.log_min_duration;
    }
}

/// Apply a list of ownership assignments to the catalog.
///
/// Called from `parse/mod.rs` after all relation-family objects are built.
pub fn apply_pending_owners(
    catalog: &mut Catalog,
    pending: Vec<PendingOwner>,
    location: &SourceLocation,
) -> Result<(), ParseError> {
    for po in pending {
        super::owner_stmt::set_owner_for_relation(
            catalog,
            &po.target,
            ObjectType::ObjectTable, // hint: try all relation types
            po.new_owner,
            location,
        )?;
    }
    Ok(())
}

/// Apply accumulated RLS mode toggles to the catalog.
///
/// Called from `parse/mod.rs` after all tables are built.
pub fn apply_pending_rls_toggles(
    catalog: &mut Catalog,
    pending: Vec<PendingRlsToggle>,
    location: &SourceLocation,
) -> Result<(), ParseError> {
    for toggle in pending {
        let table = catalog
            .tables
            .iter_mut()
            .find(|t| t.qname == toggle.target)
            .ok_or_else(|| ParseError::Structural {
                location: location.clone(),
                message: format!(
                    "ALTER TABLE … ROW LEVEL SECURITY referenced unknown table {}",
                    toggle.target
                ),
            })?;
        match toggle.subtype {
            AlterTableType::AtEnableRowSecurity => {
                table.rls_enabled = true;
            }
            AlterTableType::AtDisableRowSecurity => {
                table.rls_enabled = false;
            }
            AlterTableType::AtForceRowSecurity => {
                table.rls_forced = true;
            }
            AlterTableType::AtNoForceRowSecurity => {
                table.rls_forced = false;
            }
            _ => {
                return Err(ParseError::Structural {
                    location: location.clone(),
                    message: "unexpected subtype in PendingRlsToggle".into(),
                });
            }
        }
    }
    Ok(())
}

/// Extract the String node from `cmd.def` and return its `sval`.
fn def_as_string(cmd: &AlterTableCmd, location: &SourceLocation) -> Result<String, ParseError> {
    cmd.def
        .as_ref()
        .and_then(|d| d.node.as_ref())
        .and_then(|n| match n {
            NodeEnum::String(s) => Some(s.sval.clone()),
            _ => None,
        })
        .ok_or_else(|| ParseError::Structural {
            location: location.clone(),
            message: "ALTER COLUMN SET STORAGE/COMPRESSION missing keyword node".into(),
        })
}

/// Reuse the FK builder from `create_stmt` so source ALTER and inline
/// `REFERENCES` produce identical IR.
fn build_fk_constraint(
    con: &PgConstraint,
    target_table: &QualifiedName,
    default_schema: Option<&Identifier>,
    location: &SourceLocation,
) -> Result<Constraint, ParseError> {
    // Delegate to a public helper exposed by create_stmt to avoid duplicating
    // FK extraction logic.
    create_stmt::build_fk_for_alter(con, target_table, default_schema, location)
}

fn unsupported_alter(location: &SourceLocation) -> ParseError {
    ParseError::Structural {
        location: location.clone(),
        message: "ALTER TABLE in source DDL is restricted to ADD CONSTRAINT FOREIGN KEY, \
                 ALTER COLUMN SET STORAGE/COMPRESSION, and SET (reloptions); \
                 pgevolve treats source SQL as declarative — express the desired schema \
                 state via CREATE statements"
            .into(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::constraint::ConstraintKind;
    use std::path::PathBuf;

    fn loc() -> SourceLocation {
        SourceLocation::new(PathBuf::from("test.sql"), 1, 1)
    }

    fn build(sql: &str) -> Result<AlterTableOutput, ParseError> {
        let parsed = pg_query::parse(sql).expect("parses");
        let stmt = parsed
            .protobuf
            .stmts
            .into_iter()
            .next()
            .and_then(|raw| raw.stmt)
            .and_then(|n| n.node)
            .expect("stmt");
        let NodeEnum::AlterTableStmt(s) = stmt else {
            panic!("not AlterTableStmt")
        };
        build_alter_table(&s, None, &loc())
    }

    #[test]
    fn allowed_add_fk() {
        let out = build(
            "ALTER TABLE app.invoices ADD CONSTRAINT invoices_customer_fk \
             FOREIGN KEY (customer_id) REFERENCES app.customers (id);",
        )
        .expect("builds");
        assert_eq!(out.pending_fks.len(), 1);
        let p = &out.pending_fks[0];
        assert_eq!(p.target.to_string(), "app.invoices");
        assert!(matches!(p.constraint.kind, ConstraintKind::ForeignKey(_)));
    }

    #[test]
    fn alter_column_set_storage_external() {
        let out =
            build("ALTER TABLE app.t ALTER COLUMN doc SET STORAGE EXTERNAL;").expect("builds");
        assert_eq!(out.pending_column_attrs.len(), 1);
        let attr = &out.pending_column_attrs[0];
        assert_eq!(attr.target.to_string(), "app.t");
        assert_eq!(attr.column.as_str(), "doc");
        assert!(matches!(
            attr.kind,
            PendingColumnAttrKind::Storage(StorageKind::External)
        ));
    }

    #[test]
    fn alter_column_set_storage_plain() {
        let out = build("ALTER TABLE app.t ALTER COLUMN n SET STORAGE PLAIN;").expect("builds");
        let attr = &out.pending_column_attrs[0];
        assert!(matches!(
            attr.kind,
            PendingColumnAttrKind::Storage(StorageKind::Plain)
        ));
    }

    #[test]
    fn alter_column_set_storage_main() {
        let out = build("ALTER TABLE app.t ALTER COLUMN n SET STORAGE MAIN;").expect("builds");
        let attr = &out.pending_column_attrs[0];
        assert!(matches!(
            attr.kind,
            PendingColumnAttrKind::Storage(StorageKind::Main)
        ));
    }

    #[test]
    fn alter_column_set_compression_lz4() {
        let out = build("ALTER TABLE app.t ALTER COLUMN doc SET COMPRESSION lz4;").expect("builds");
        assert_eq!(out.pending_column_attrs.len(), 1);
        let attr = &out.pending_column_attrs[0];
        assert!(matches!(
            attr.kind,
            PendingColumnAttrKind::Compression(Some(Compression::Lz4))
        ));
    }

    #[test]
    fn alter_column_set_compression_pglz() {
        let out =
            build("ALTER TABLE app.t ALTER COLUMN doc SET COMPRESSION pglz;").expect("builds");
        let attr = &out.pending_column_attrs[0];
        assert!(matches!(
            attr.kind,
            PendingColumnAttrKind::Compression(Some(Compression::Pglz))
        ));
    }

    #[test]
    fn alter_column_set_compression_default() {
        let out =
            build("ALTER TABLE app.t ALTER COLUMN doc SET COMPRESSION DEFAULT;").expect("builds");
        let attr = &out.pending_column_attrs[0];
        assert!(matches!(
            attr.kind,
            PendingColumnAttrKind::Compression(None)
        ));
    }

    #[test]
    fn rejects_drop_column() {
        let err = build("ALTER TABLE app.users DROP COLUMN email;").unwrap_err();
        match err {
            ParseError::Structural { message, .. } => {
                assert!(
                    message.contains("declarative"),
                    "expected declarative message, got: {message}"
                );
            }
            other => panic!("expected Structural, got {other:?}"),
        }
    }

    #[test]
    fn rejects_add_column() {
        let err = build("ALTER TABLE app.users ADD COLUMN email text;").unwrap_err();
        match err {
            ParseError::Structural { message, .. } => {
                assert!(
                    message.contains("declarative") || message.contains("FOREIGN KEY"),
                    "got: {message}"
                );
            }
            other => panic!("expected Structural, got {other:?}"),
        }
    }

    /// Verify that `SET STORAGE BOGUS` always surfaces as an error, regardless
    /// of whether `pg_query` catches it at parse time or our decoder catches it.
    ///
    /// The error path under test is `process_set_storage_cmd` line 176-181
    /// (`unknown STORAGE attribute '…'`). If `pg_query` happens to accept the
    /// keyword and pass it down, that arm is exercised. If `pg_query` rejects it
    /// first, we confirm via a parse-level error — either way the contract holds.
    #[test]
    fn alter_column_set_storage_unknown_errors() {
        let sql = "ALTER TABLE app.t ALTER COLUMN doc SET STORAGE BOGUS;";
        // pg_query may reject this SQL outright (returning Err), or it may
        // accept it and pass the unknown keyword to our decoder.
        match pg_query::parse(sql) {
            Err(_pg_err) => {
                // pg_query rejected BOGUS before our decoder was reached.
                // The contract is satisfied: malformed SQL fails at parse time.
            }
            Ok(parsed) => {
                // pg_query accepted the keyword — our decoder must reject it.
                let stmt = parsed
                    .protobuf
                    .stmts
                    .into_iter()
                    .next()
                    .and_then(|raw| raw.stmt)
                    .and_then(|n| n.node)
                    .expect("stmt");
                let NodeEnum::AlterTableStmt(s) = stmt else {
                    panic!("expected AlterTableStmt");
                };
                let err = build_alter_table(&s, None, &loc())
                    .expect_err("BOGUS storage keyword must be rejected by our decoder");
                match err {
                    ParseError::Structural { ref message, .. } => {
                        assert!(
                            message.contains("STORAGE"),
                            "expected error to mention STORAGE, got: {message}"
                        );
                    }
                    other => panic!("expected Structural error, got {other:?}"),
                }
            }
        }
    }

    #[test]
    fn rejects_add_check_via_alter() {
        let err = build("ALTER TABLE app.t ADD CONSTRAINT c1 CHECK (n > 0);").unwrap_err();
        assert!(matches!(err, ParseError::Structural { .. }));
    }

    /// `pg_query` encodes the new owner in `cmd.newowner` (a dedicated
    /// [`pg_query::protobuf::RoleSpec`] field), not in `cmd.def`.  This test
    /// guards that `process_change_owner_cmd` reads from the right field.
    #[test]
    fn alter_table_owner_to_role_name() {
        let out = build("ALTER TABLE app.t OWNER TO app_owner;").expect("builds");
        assert_eq!(out.pending_owners.len(), 1);
        let po = &out.pending_owners[0];
        assert_eq!(po.target.to_string(), "app.t");
        assert_eq!(po.new_owner.as_str(), "app_owner");
    }

    // ── RLS toggle tests ──────────────────────────────────────────────────────

    #[test]
    fn enable_row_security_produces_toggle() {
        let out = build("ALTER TABLE app.docs ENABLE ROW LEVEL SECURITY;").expect("builds");
        assert_eq!(out.pending_rls_toggles.len(), 1);
        let t = &out.pending_rls_toggles[0];
        assert_eq!(t.target.to_string(), "app.docs");
        assert!(matches!(t.subtype, AlterTableType::AtEnableRowSecurity));
    }

    #[test]
    fn disable_row_security_produces_toggle() {
        let out = build("ALTER TABLE app.docs DISABLE ROW LEVEL SECURITY;").expect("builds");
        assert_eq!(out.pending_rls_toggles.len(), 1);
        let t = &out.pending_rls_toggles[0];
        assert!(matches!(t.subtype, AlterTableType::AtDisableRowSecurity));
    }

    #[test]
    fn force_row_security_produces_toggle() {
        let out = build("ALTER TABLE app.docs FORCE ROW LEVEL SECURITY;").expect("builds");
        assert_eq!(out.pending_rls_toggles.len(), 1);
        let t = &out.pending_rls_toggles[0];
        assert!(matches!(t.subtype, AlterTableType::AtForceRowSecurity));
    }

    #[test]
    fn no_force_row_security_produces_toggle() {
        let out = build("ALTER TABLE app.docs NO FORCE ROW LEVEL SECURITY;").expect("builds");
        assert_eq!(out.pending_rls_toggles.len(), 1);
        let t = &out.pending_rls_toggles[0];
        assert!(matches!(t.subtype, AlterTableType::AtNoForceRowSecurity));
    }

    // ── SET / RESET reloption tests ───────────────────────────────────────────

    #[test]
    fn alter_table_set_reloption_fillfactor() {
        let out = build("ALTER TABLE app.t SET (fillfactor = 80);").expect("builds");
        assert_eq!(out.pending_rel_options.len(), 1);
        let p = &out.pending_rel_options[0];
        assert_eq!(p.target.to_string(), "app.t");
        assert_eq!(p.options.fillfactor, Some(80));
    }

    #[test]
    fn alter_table_set_reloption_autovacuum_enabled() {
        let out = build("ALTER TABLE app.t SET (autovacuum_enabled = false);").expect("builds");
        assert_eq!(out.pending_rel_options.len(), 1);
        let p = &out.pending_rel_options[0];
        assert_eq!(p.options.autovacuum.enabled, Some(false));
    }

    #[test]
    fn alter_table_set_reloption_multiple_options() {
        let out = build("ALTER TABLE app.t SET (fillfactor = 70, parallel_workers = 2);")
            .expect("builds");
        let p = &out.pending_rel_options[0];
        assert_eq!(p.options.fillfactor, Some(70));
        assert_eq!(p.options.parallel_workers, Some(2));
    }

    #[test]
    fn alter_table_reset_reloption_errors() {
        let err = build("ALTER TABLE app.t RESET (fillfactor);").unwrap_err();
        assert!(
            matches!(err, ParseError::Structural { ref message, .. }
                if message.contains("RESET") || message.contains("not supported")),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn alter_table_set_fillfactor_out_of_range_errors() {
        let err = build("ALTER TABLE app.t SET (fillfactor = 5);").unwrap_err();
        assert!(
            matches!(err, ParseError::Structural { ref message, .. } if message.contains("out of range")),
            "unexpected error: {err:?}"
        );
    }
}