Skip to main content

pgevolve_core/diff/
change.rs

1//! `Change` — one entry in a [`ChangeSet`](super::changeset::ChangeSet).
2//!
3//! A `Change` describes a structural difference between a target catalog and
4//! a source catalog at the level of a top-level object (schema, table, index,
5//! sequence). Per-column / per-constraint operations live inside the
6//! [`AlterTable`](Change::AlterTable) variant as a list of
7//! [`TableOpEntry`]; per-field sequence updates
8//! live inside [`AlterSequence`](Change::AlterSequence) as
9//! [`SequenceOpEntry`].
10
11use serde::{Deserialize, Serialize};
12
13use crate::identifier::{Identifier, QualifiedName};
14use crate::ir::collation::Collation;
15use crate::ir::column_type::ColumnType;
16use crate::ir::default_expr::NormalizedExpr;
17use crate::ir::default_privileges::DefaultPrivObjectType;
18use crate::ir::extension::Extension;
19use crate::ir::function::{Function, NormalizedArgTypes};
20use crate::ir::grant::Grant;
21use crate::ir::index::Index;
22use crate::ir::partition::PartitionBounds;
23use crate::ir::procedure::Procedure;
24use crate::ir::schema::Schema;
25use crate::ir::sequence::Sequence;
26use crate::ir::table::Table;
27use crate::ir::trigger::Trigger;
28use crate::ir::user_type::{CompositeAttribute, DomainCheck, UserType};
29use crate::ir::view::{MaterializedView, View};
30
31use super::destructiveness::Destructiveness;
32use super::owner_op::{AlterObjectOwner, OwnerObjectKind};
33use super::sequence_op::SequenceOpEntry;
34use super::table_op::TableOpEntry;
35
36/// A change paired with its destructiveness classification.
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38pub struct ChangeEntry {
39    /// The structural change.
40    pub change: Change,
41    /// Risk classification for this change.
42    pub destructiveness: Destructiveness,
43}
44
45/// One structural change between two catalogs.
46///
47/// `Change` is intentionally not boxed: the enum's footprint is dominated by
48/// `CreateTable` / `CreateIndex` / `ReplaceIndex` payloads, but `ChangeSet`
49/// only stores at most one of each per object, so `Vec` overhead is the
50/// dominant cost and boxing would just add an extra allocation per entry.
51#[allow(clippy::large_enum_variant)]
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
53#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
54pub enum Change {
55    /// Add a schema.
56    CreateSchema(Schema),
57    /// Drop a schema by name.
58    DropSchema(Identifier),
59    /// Update schema metadata (only `comment` in v0.1).
60    AlterSchema {
61        /// Schema name.
62        name: Identifier,
63        /// New comment value (`None` clears the comment).
64        comment: Option<String>,
65    },
66
67    /// Add a table.
68    CreateTable(Table),
69    /// Drop a table.
70    DropTable {
71        /// Table qname.
72        qname: QualifiedName,
73        /// Best-effort estimate of row count, populated by the planner from
74        /// `pg_class.reltuples`. The differ leaves this `None`.
75        row_count_estimate: Option<i64>,
76    },
77    /// Alter a table — column / constraint / comment operations.
78    AlterTable {
79        /// Target table qname.
80        qname: QualifiedName,
81        /// Per-table operations. Order is the planner's job; the differ emits
82        /// these in arbitrary order.
83        ops: Vec<TableOpEntry>,
84    },
85
86    /// Create an index.
87    CreateIndex(Index),
88    /// Drop an index.
89    DropIndex(QualifiedName),
90    /// Replace an index (DROP + CREATE) when a property change requires it.
91    ReplaceIndex {
92        /// The index as it exists in the target.
93        from: Index,
94        /// The index as it should exist in the source.
95        to: Index,
96    },
97
98    /// Create a sequence.
99    CreateSequence(Sequence),
100    /// Drop a sequence.
101    DropSequence(QualifiedName),
102    /// Alter a sequence — per-field operations.
103    AlterSequence {
104        /// Target sequence qname.
105        qname: QualifiedName,
106        /// Per-sequence operations.
107        ops: Vec<SequenceOpEntry>,
108    },
109
110    /// A constraint exists in the catalog but is `NOT VALID`
111    /// (`pg_constraint.convalidated = false`). Planner emits
112    /// `VALIDATE CONSTRAINT`. Non-destructive.
113    ValidateConstraint {
114        /// Qualified name of the table owning the constraint.
115        table: QualifiedName,
116        /// Constraint name.
117        constraint: Identifier,
118    },
119    /// An index exists in the catalog but is `INVALID`
120    /// (`pg_index.indisvalid = false`). Planner emits `DROP INDEX + CREATE
121    /// INDEX` to rebuild it. Non-destructive.
122    RecreateIndex {
123        /// Qualified name of the invalid index.
124        qname: QualifiedName,
125    },
126
127    /// A view-level change.
128    View(ViewChange),
129    /// `CREATE OR REPLACE VIEW … WITH [LOCAL|CASCADED] CHECK OPTION` or the
130    /// inverse (set/unset check option on an existing view). PG has no direct
131    /// `ALTER VIEW … SET CHECK OPTION`; pgevolve emits a full
132    /// `CREATE OR REPLACE VIEW` carrying the new option.
133    AlterViewSetCheckOption {
134        /// Schema-qualified view name.
135        qname: QualifiedName,
136        /// The desired check option state in the source.
137        /// `None` = source declares no check option (clear it).
138        new_value: Option<crate::ir::view::CheckOption>,
139    },
140    /// A materialized-view-level change.
141    Mv(MvChange),
142    /// A user-defined type change (enum, domain, composite).
143    UserType(UserTypeChange),
144    /// A user-defined function change.
145    Function(FunctionChange),
146    /// A user-defined procedure change.
147    Procedure(ProcedureChange),
148    /// An extension change.
149    Extension(ExtensionChange),
150    /// A trigger change.
151    Trigger(TriggerChange),
152    /// A partition-membership change (ATTACH / DETACH PARTITION).
153    Table(TableChange),
154    /// Grant an object-level privilege on a grantable object (non-column).
155    ///
156    /// Emitted when a grant appears in source but not in the target catalog.
157    GrantObjectPrivilege {
158        /// Qualified name of the grantable object (schema, table, sequence,
159        /// view, function, procedure, or type).
160        qname: QualifiedName,
161        /// Which kind of object this is (drives the SQL keyword in the renderer).
162        kind: OwnerObjectKind,
163        /// Argument signature for routines (e.g., `"(int, text)"`).
164        /// Empty string for non-routine object kinds.
165        #[serde(default)]
166        signature: String,
167        /// The full grant to apply.
168        grant: Grant,
169    },
170    /// Revoke an object-level privilege from a grantable object (non-column).
171    ///
172    /// Only emitted for managed grantees (see [`super::grants::diff_grants`]).
173    RevokeObjectPrivilege {
174        /// Qualified name of the grantable object.
175        qname: QualifiedName,
176        /// Which kind of object this is.
177        kind: OwnerObjectKind,
178        /// Argument signature for routines (e.g., `"(int, text)"`).
179        /// Empty string for non-routine object kinds.
180        #[serde(default)]
181        signature: String,
182        /// The full grant to revoke.
183        grant: Grant,
184    },
185    /// Grant a column-level privilege on a table, view, or materialized view.
186    ///
187    /// Emitted when the grant's `columns` field is `Some(_)`.
188    GrantColumnPrivilege {
189        /// Qualified name of the table / view / materialized view.
190        qname: QualifiedName,
191        /// The full grant (including the `columns` list).
192        grant: Grant,
193    },
194    /// Revoke a column-level privilege from a table, view, or materialized view.
195    ///
196    /// Only emitted for managed grantees.
197    RevokeColumnPrivilege {
198        /// Qualified name of the table / view / materialized view.
199        qname: QualifiedName,
200        /// The full grant (including the `columns` list).
201        grant: Grant,
202    },
203    /// Change the owner of a grantable object.
204    ///
205    /// Emitted when the source declares an owner (`owner: Some(_)`) and the
206    /// target owner differs. When the source has `owner: None`, ownership is
207    /// unmanaged and no change is emitted.
208    AlterObjectOwner(AlterObjectOwner),
209    /// Add or remove a default privilege for a `(FOR ROLE, IN SCHEMA?,
210    /// object-type)` key.
211    AlterDefaultPrivileges {
212        /// `FOR ROLE x` — the grantor role.
213        target_role: Identifier,
214        /// `IN SCHEMA y` — scope. `None` = global.
215        schema: Option<Identifier>,
216        /// Object-type discriminant.
217        object_type: DefaultPrivObjectType,
218        /// `true` = GRANT step, `false` = REVOKE step.
219        is_grant: bool,
220        /// The grantee and privilege being adjusted.
221        grant: Grant,
222    },
223
224    /// Create a new policy on the named table.
225    CreatePolicy {
226        /// Table the policy belongs to.
227        table: QualifiedName,
228        /// The policy to create.
229        policy: crate::ir::policy::Policy,
230    },
231    /// Drop a policy from the named table.
232    DropPolicy {
233        /// Table the policy belongs to.
234        table: QualifiedName,
235        /// Name of the policy to drop.
236        name: Identifier,
237    },
238    /// Alter a policy's roles / USING / WITH CHECK.
239    ///
240    /// Note: PG rejects `ALTER POLICY` when the command kind changes — the
241    /// differ emits `DropPolicy` + `CreatePolicy` in that case instead.
242    AlterPolicy {
243        /// Table the policy belongs to.
244        table: QualifiedName,
245        /// The desired policy state.
246        policy: crate::ir::policy::Policy,
247    },
248    /// Toggle a table's `ROW LEVEL SECURITY`.
249    SetTableRowSecurity {
250        /// Qualified name of the table.
251        qname: QualifiedName,
252        /// `true` = `ENABLE ROW LEVEL SECURITY`, `false` = `DISABLE`.
253        enable: bool,
254    },
255    /// Toggle a table's `FORCE ROW LEVEL SECURITY`.
256    SetTableForceRowSecurity {
257        /// Qualified name of the table.
258        qname: QualifiedName,
259        /// `true` = `FORCE ROW LEVEL SECURITY`, `false` = `NO FORCE`.
260        force: bool,
261    },
262
263    /// Set table storage reloptions. `options` carries the sparse delta — only
264    /// the fields whose source value differs from the catalog.
265    ///
266    /// No `Reset*` variant: the lenient policy treats source `None` as "skip".
267    SetTableStorage {
268        /// Qualified name of the table.
269        qname: QualifiedName,
270        /// Sparse delta of options to apply.
271        options: crate::ir::reloptions::TableStorageOptions,
272    },
273    /// Set index storage reloptions. Sparse delta.
274    ///
275    /// No `Reset*` variant: the lenient policy treats source `None` as "skip".
276    SetIndexStorage {
277        /// Qualified name of the index.
278        qname: QualifiedName,
279        /// Sparse delta of options to apply.
280        options: crate::ir::reloptions::IndexStorageOptions,
281    },
282    /// Set materialized view storage reloptions. Sparse delta.
283    ///
284    /// No `Reset*` variant: the lenient policy treats source `None` as "skip".
285    SetMaterializedViewStorage {
286        /// Qualified name of the materialized view.
287        qname: QualifiedName,
288        /// Sparse delta of options to apply.
289        options: crate::ir::reloptions::TableStorageOptions,
290    },
291
292    /// A nested change to a single publication. See [`PublicationChange`].
293    Publication(PublicationChange),
294    /// A nested change to a single subscription. See [`SubscriptionChange`].
295    Subscription(SubscriptionChange),
296    /// A nested change to a single statistic. See [`StatisticChange`].
297    Statistic(StatisticChange),
298    /// A nested change to a single collation. See [`CollationChange`].
299    Collation(CollationChange),
300
301    /// A change that cannot be performed in-place.
302    ///
303    /// Emitted by the differ when it detects a structural difference that has
304    /// no safe automatic migration path (e.g., changing a table's `PARTITION BY`
305    /// clause). The ordering phase converts this into a [`PlanError`] so the
306    /// plan never reaches execution.
307    ///
308    /// [`PlanError`]: crate::plan::error::PlanError
309    UnsupportedDiff {
310        /// Human-readable explanation of what changed and why it cannot be
311        /// performed in-place.
312        reason: String,
313    },
314}
315
316/// A structural change to a single user-defined type.
317#[allow(clippy::large_enum_variant)]
318#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
319#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
320pub enum UserTypeChange {
321    /// Create a new user-defined type.
322    Create(UserType),
323    /// Drop a user-defined type by qualified name.
324    Drop(QualifiedName),
325
326    /// Add a new label to an existing enum type.
327    EnumAddValue {
328        /// Qualified name of the enum type.
329        qname: QualifiedName,
330        /// The new label string.
331        value: String,
332        /// If `Some`, the new value is placed immediately before this label.
333        before: Option<String>,
334        /// If `Some`, the new value is placed immediately after this label.
335        after: Option<String>,
336    },
337    /// Rename an existing enum label.
338    EnumRenameValue {
339        /// Qualified name of the enum type.
340        qname: QualifiedName,
341        /// The existing label to rename.
342        from: String,
343        /// The new label name.
344        to: String,
345    },
346
347    /// Add a CHECK constraint to a domain.
348    DomainAddCheck {
349        /// Qualified name of the domain type.
350        qname: QualifiedName,
351        /// The constraint to add.
352        constraint: DomainCheck,
353    },
354    /// Drop a named CHECK constraint from a domain.
355    DomainDropCheck {
356        /// Qualified name of the domain type.
357        qname: QualifiedName,
358        /// The constraint name to drop.
359        name: Identifier,
360    },
361    /// Set (or clear) the DEFAULT expression on a domain.
362    DomainSetDefault {
363        /// Qualified name of the domain type.
364        qname: QualifiedName,
365        /// New default expression (`None` clears the default).
366        default: Option<NormalizedExpr>,
367    },
368    /// Toggle the `NOT NULL` constraint on a domain.
369    DomainSetNotNull {
370        /// Qualified name of the domain type.
371        qname: QualifiedName,
372        /// `true` means NOT NULL (i.e., `nullable = false`).
373        not_null: bool,
374    },
375
376    /// Add a new attribute to a composite type.
377    CompositeAddAttribute {
378        /// Qualified name of the composite type.
379        qname: QualifiedName,
380        /// The attribute to add.
381        attribute: CompositeAttribute,
382    },
383    /// Drop an attribute from a composite type.
384    CompositeDropAttribute {
385        /// Qualified name of the composite type.
386        qname: QualifiedName,
387        /// The attribute name to drop.
388        name: Identifier,
389    },
390    /// Change the type of an existing composite attribute.
391    CompositeAlterAttributeType {
392        /// Qualified name of the composite type.
393        qname: QualifiedName,
394        /// The attribute name whose type is being changed.
395        attribute: Identifier,
396        /// The new column type.
397        new_type: ColumnType,
398    },
399
400    /// Set (or clear) the `COMMENT ON TYPE` for this type.
401    SetComment {
402        /// Qualified name of the type.
403        qname: QualifiedName,
404        /// New comment (`None` clears the comment).
405        comment: Option<String>,
406    },
407
408    /// Emitted when the requested change cannot be done in place via `ALTER`.
409    ///
410    /// T8's cascade walker appends `ReplaceBody` for any views/MVs that depend
411    /// on the type so they are recreated after the type is rebuilt. T9's SQL
412    /// emitter expands this single entry into `DROP TYPE … CASCADE` plus
413    /// `CREATE TYPE`, then the recreated dependents follow in topological
414    /// order. The planner never emits this entry as one raw SQL step.
415    ReplaceWithCascade {
416        /// The desired type (source).
417        source: UserType,
418        /// The existing type (catalog / live database).
419        catalog: UserType,
420    },
421}
422
423/// A structural change to a single view.
424#[allow(clippy::large_enum_variant)]
425#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
426#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
427pub enum ViewChange {
428    /// Create a new view.
429    Create(View),
430    /// Drop an existing view.
431    Drop(QualifiedName),
432    /// Replace the SELECT body of a view.
433    ///
434    /// `compatible` is `true` when Postgres's `CREATE OR REPLACE VIEW` rules
435    /// are satisfied (same column names and types at the same indexes, with
436    /// new columns only appended at the end). When `compatible` is `false`,
437    /// the planner must `DROP` then re-`CREATE` the view (and rebuild its
438    /// dependents).
439    ReplaceBody {
440        /// The view as it should exist (source SQL).
441        source: View,
442        /// The view as it currently exists (live catalog).
443        catalog: View,
444        /// Whether `CREATE OR REPLACE VIEW` can be used (`true`) or a
445        /// `DROP` + `CREATE` cycle is required (`false`).
446        compatible: bool,
447    },
448    /// Change `WITH (security_barrier = ..., security_invoker = ...)` reloptions.
449    SetReloption {
450        /// View qname.
451        qname: QualifiedName,
452        /// Desired `security_barrier` value (`None` clears the option).
453        security_barrier: Option<bool>,
454        /// Desired `security_invoker` value (`None` clears the option).
455        security_invoker: Option<bool>,
456    },
457    /// Set (or clear) the view-level `COMMENT ON VIEW`.
458    SetComment {
459        /// View qname.
460        qname: QualifiedName,
461        /// New comment (`None` clears the comment).
462        comment: Option<String>,
463    },
464    /// Set (or clear) a `COMMENT ON COLUMN view.col`.
465    SetColumnComment {
466        /// View qname.
467        qname: QualifiedName,
468        /// Column name.
469        column: Identifier,
470        /// New comment (`None` clears the comment).
471        comment: Option<String>,
472    },
473}
474
475/// A structural change to a single materialized view.
476#[allow(clippy::large_enum_variant)]
477#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
478#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
479pub enum MvChange {
480    /// Create a new materialized view.
481    Create(MaterializedView),
482    /// Drop an existing materialized view.
483    ///
484    /// Unlike `ViewChange::Drop`, this is classified as `Safe` because
485    /// materialized views are derived data that can be recreated by refreshing.
486    Drop(QualifiedName),
487    /// Replace the SELECT body of a materialized view.
488    ///
489    /// Materialized views do not support `CREATE OR REPLACE`; the planner must
490    /// always `DROP` then `CREATE` the MV (and rebuild any indexes on it).
491    ReplaceBody {
492        /// The MV as it should exist (source SQL).
493        source: MaterializedView,
494        /// The MV as it currently exists (live catalog).
495        catalog: MaterializedView,
496    },
497    /// Set (or clear) the MV-level `COMMENT ON MATERIALIZED VIEW`.
498    SetComment {
499        /// MV qname.
500        qname: QualifiedName,
501        /// New comment (`None` clears the comment).
502        comment: Option<String>,
503    },
504    /// Set (or clear) a `COMMENT ON COLUMN mv.col`.
505    SetColumnComment {
506        /// MV qname.
507        qname: QualifiedName,
508        /// Column name.
509        column: Identifier,
510        /// New comment (`None` clears the comment).
511        comment: Option<String>,
512    },
513}
514
515/// A structural change to a single user-defined function.
516#[allow(clippy::large_enum_variant)]
517#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
518#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
519pub enum FunctionChange {
520    /// Create a new function.
521    Create(Function),
522    /// Drop an existing function by qualified name and normalized arg types.
523    Drop {
524        /// Qualified name of the function.
525        qname: QualifiedName,
526        /// Normalized argument types (IN/INOUT/VARIADIC only) used to
527        /// disambiguate overloads in the DROP FUNCTION statement.
528        args: NormalizedArgTypes,
529    },
530    /// Replace the function body and/or attributes using `CREATE OR REPLACE
531    /// FUNCTION`. Only valid when `function_can_or_replace` returns `true`.
532    CreateOrReplace(Function),
533    /// The function's return type or language changed in a way that PG's
534    /// `CREATE OR REPLACE FUNCTION` rejects. The planner must emit
535    /// `DROP FUNCTION … CASCADE` followed by `CREATE FUNCTION`.
536    ReplaceWithCascade {
537        /// The desired function (source).
538        source: Function,
539        /// The existing function (catalog / live database).
540        catalog: Function,
541    },
542    /// Set (or clear) `COMMENT ON FUNCTION`.
543    SetComment {
544        /// Qualified name of the function.
545        qname: QualifiedName,
546        /// Normalized argument types for disambiguation.
547        args: NormalizedArgTypes,
548        /// New comment (`None` clears the comment).
549        comment: Option<String>,
550    },
551}
552
553/// A structural change to a single user-defined procedure.
554#[allow(clippy::large_enum_variant)]
555#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
556#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
557pub enum ProcedureChange {
558    /// Create a new procedure.
559    Create(Procedure),
560    /// Drop an existing procedure by qualified name.
561    Drop(QualifiedName),
562    /// Replace the procedure body and/or attributes using `CREATE OR REPLACE
563    /// PROCEDURE`.
564    CreateOrReplace(Procedure),
565    /// Set (or clear) `COMMENT ON PROCEDURE`.
566    SetComment {
567        /// Qualified name of the procedure.
568        qname: QualifiedName,
569        /// New comment (`None` clears the comment).
570        comment: Option<String>,
571    },
572}
573
574/// Change to one extension. Pair-by-name semantics.
575#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
576#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
577pub enum ExtensionChange {
578    /// Install a new extension.
579    Create(Extension),
580    /// Drop an extension by name. Emits `DROP EXTENSION ... CASCADE`.
581    Drop(Identifier),
582    /// Bump extension version: `ALTER EXTENSION ... UPDATE TO 'v'`.
583    AlterUpdate {
584        /// Extension name.
585        name: Identifier,
586        /// New version to update to.
587        to_version: String,
588    },
589    /// Schema-changing replace (DROP CASCADE + CREATE).
590    ReplaceWithCascade(Extension),
591    /// Change the `COMMENT ON EXTENSION` text.
592    CommentOn {
593        /// Extension name.
594        name: Identifier,
595        /// New comment value (`None` clears the comment).
596        comment: Option<String>,
597    },
598}
599
600/// Change to one trigger. Pair-by-qname semantics; any structural
601/// difference emits `Replace`.
602#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
603#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
604pub enum TriggerChange {
605    /// Install a new trigger.
606    Create(Trigger),
607    /// Drop a trigger by qname (needs the table for `DROP TRIGGER name ON table`).
608    Drop {
609        /// Qualified name of the trigger.
610        qname: QualifiedName,
611        /// Owning table (needed for `DROP TRIGGER name ON table`).
612        table: QualifiedName,
613    },
614    /// Any structural change: drop + create.
615    Replace(Trigger),
616    /// Change the `COMMENT ON TRIGGER` text.
617    CommentOn {
618        /// Qualified name of the trigger.
619        qname: QualifiedName,
620        /// Owning table (needed for `COMMENT ON TRIGGER name ON table`).
621        table: QualifiedName,
622        /// New comment value (`None` clears the comment).
623        comment: Option<String>,
624    },
625}
626
627/// A partition-membership change on a child table.
628///
629/// These changes are emitted by the differ when the `partition_of` field of a
630/// table changes. Wiring to SQL steps lands in PART9.
631#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
632#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
633pub enum TableChange {
634    /// Attach a child table to a parent partitioned table.
635    ///
636    /// Corresponds to `ALTER TABLE <parent> ATTACH PARTITION <child> <bounds>`.
637    AttachPartition {
638        /// The partitioned parent table.
639        parent: QualifiedName,
640        /// The child table being attached.
641        child: QualifiedName,
642        /// The partition bounds clause.
643        bounds: PartitionBounds,
644    },
645    /// Detach a child table from a parent partitioned table.
646    ///
647    /// Corresponds to `ALTER TABLE <parent> DETACH PARTITION <child>`.
648    DetachPartition {
649        /// The partitioned parent table.
650        parent: QualifiedName,
651        /// The child table being detached.
652        child: QualifiedName,
653    },
654}
655
656/// A structural change to a single publication.
657#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
658#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
659pub enum PublicationChange {
660    /// `CREATE PUBLICATION ...`
661    Create(crate::ir::publication::Publication),
662    /// `DROP PUBLICATION ...` — destructive.
663    Drop {
664        /// Publication name.
665        name: Identifier,
666    },
667    /// `DROP PUBLICATION old; CREATE PUBLICATION new;` — destructive; used
668    /// when the publication's scope mode switches (`AllTables` ↔ `Selective`).
669    Replace {
670        /// The publication as it exists in the target.
671        from: crate::ir::publication::Publication,
672        /// The publication as it should exist in the source.
673        to: crate::ir::publication::Publication,
674    },
675    /// `ALTER PUBLICATION p ADD TABLE x [(cols)] [WHERE (filter)]`
676    AddTable {
677        /// Publication name.
678        publication: Identifier,
679        /// The table entry to add.
680        table: crate::ir::publication::PublishedTable,
681    },
682    /// `ALTER PUBLICATION p DROP TABLE x`
683    DropTable {
684        /// Publication name.
685        publication: Identifier,
686        /// Qualified name of the table to drop.
687        qname: QualifiedName,
688    },
689    /// `ALTER PUBLICATION p SET TABLE x (cols) WHERE (filter)`
690    SetTable {
691        /// Publication name.
692        publication: Identifier,
693        /// The desired table entry state.
694        table: crate::ir::publication::PublishedTable,
695    },
696    /// `ALTER PUBLICATION p ADD TABLES IN SCHEMA s` (PG15+)
697    AddSchema {
698        /// Publication name.
699        publication: Identifier,
700        /// Schema to add.
701        schema: Identifier,
702    },
703    /// `ALTER PUBLICATION p DROP TABLES IN SCHEMA s` (PG15+)
704    DropSchema {
705        /// Publication name.
706        publication: Identifier,
707        /// Schema to drop.
708        schema: Identifier,
709    },
710    /// `ALTER PUBLICATION p SET (publish = '...')`
711    SetPublish {
712        /// Publication name.
713        publication: Identifier,
714        /// Desired publish-kinds bitset.
715        kinds: crate::ir::publication::PublishKinds,
716    },
717    /// `ALTER PUBLICATION p SET (publish_via_partition_root = ...)`
718    SetViaRoot {
719        /// Publication name.
720        publication: Identifier,
721        /// Desired value.
722        value: bool,
723    },
724    /// `COMMENT ON PUBLICATION p IS '...'`
725    CommentOn {
726        /// Publication name.
727        name: Identifier,
728        /// New comment value (`None` clears the comment).
729        comment: Option<String>,
730    },
731}
732
733/// A structural change to a single subscription.
734#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
735#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
736pub enum SubscriptionChange {
737    /// `CREATE SUBSCRIPTION ...`
738    Create(crate::ir::subscription::Subscription),
739    /// `DROP SUBSCRIPTION ...` — destructive.
740    Drop {
741        /// Subscription name.
742        name: Identifier,
743    },
744    /// `ALTER SUBSCRIPTION s CONNECTION '...'`
745    AlterConnection {
746        /// Subscription name.
747        name: Identifier,
748        /// New connection string (may contain `${VAR}` placeholders).
749        new_connection: String,
750    },
751    /// `ALTER SUBSCRIPTION s ADD PUBLICATION p`
752    AddPublication {
753        /// Subscription name.
754        name: Identifier,
755        /// Publication to add.
756        publication: Identifier,
757    },
758    /// `ALTER SUBSCRIPTION s DROP PUBLICATION p`
759    DropPublication {
760        /// Subscription name.
761        name: Identifier,
762        /// Publication to drop.
763        publication: Identifier,
764    },
765    /// `ALTER SUBSCRIPTION s SET (option = value, ...)` — sparse-delta.
766    ///
767    /// `create_slot` and `copy_data` are NEVER included (CREATE-only PG options).
768    SetOptions {
769        /// Subscription name.
770        name: Identifier,
771        /// Sparse options delta — only changed fields are `Some`.
772        options: crate::ir::subscription::SubscriptionOptions,
773    },
774    /// `COMMENT ON SUBSCRIPTION s IS '...'`
775    CommentOn {
776        /// Subscription name.
777        name: Identifier,
778        /// New comment value (`None` clears the comment).
779        comment: Option<String>,
780    },
781}
782
783/// A structural change to a single statistic.
784#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
785#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
786pub enum StatisticChange {
787    /// `CREATE STATISTICS ...`
788    Create(crate::ir::statistic::Statistic),
789    /// `DROP STATISTICS ...` — destructive.
790    Drop {
791        /// Schema-qualified statistic name.
792        qname: QualifiedName,
793    },
794    /// `DROP STATISTICS old; CREATE STATISTICS new;` — destructive; used
795    /// when columns / kinds / target table differ (PG has no in-place ALTER
796    /// for those fields).
797    Replace {
798        /// The statistic as it exists in the target.
799        from: crate::ir::statistic::Statistic,
800        /// The statistic as it should exist in the source.
801        to: crate::ir::statistic::Statistic,
802    },
803    /// `ALTER STATISTICS s SET STATISTICS n` — analyze target.
804    AlterSetTarget {
805        /// Schema-qualified statistic name.
806        qname: QualifiedName,
807        /// New statistics target value.
808        value: i32,
809    },
810    /// `COMMENT ON STATISTICS s IS '...'`
811    CommentOn {
812        /// Schema-qualified statistic name.
813        qname: QualifiedName,
814        /// New comment value (`None` clears the comment).
815        comment: Option<String>,
816    },
817}
818
819/// A structural change to a single collation.
820#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
821#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
822pub enum CollationChange {
823    /// `CREATE COLLATION ...`
824    Create(Collation),
825    /// `DROP COLLATION qname` — destructive.
826    ///
827    /// Not emitted by the differ: collations are lenient like other v0.3.x
828    /// managed kinds (no auto-drop; unmanaged drift surfaces via the
829    /// `unmanaged-collation` lint). This variant exists for the parser and
830    /// future explicit-drop use cases.
831    Drop {
832        /// Schema-qualified collation name.
833        qname: QualifiedName,
834    },
835    /// `ALTER COLLATION qname RENAME TO new_name`.
836    ///
837    /// Not emitted by the differ: rename intent is not structurally derivable
838    /// from name-mismatched-but-same-shape collations (the user could equally
839    /// have meant drop-old + create-new). This variant exists for the parser
840    /// and future explicit-rename use cases.
841    Rename {
842        /// Existing qname.
843        from: QualifiedName,
844        /// New unqualified name (same schema).
845        to: Identifier,
846    },
847    /// `DROP COLLATION old; CREATE COLLATION new;` — PG has no in-place
848    /// ALTER for provider / locale / deterministic.
849    Replace {
850        /// The collation as it exists in the target.
851        from: Collation,
852        /// The collation as it should exist in the source.
853        to: Collation,
854    },
855    /// `COMMENT ON COLLATION qname IS '...'`.
856    CommentOn {
857        /// Schema-qualified collation name.
858        qname: QualifiedName,
859        /// New comment (`None` clears).
860        comment: Option<String>,
861    },
862}
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867    use crate::identifier::Identifier;
868    use crate::ir::column::Column;
869    use crate::ir::column_type::ColumnType;
870
871    fn id(s: &str) -> Identifier {
872        Identifier::from_unquoted(s).unwrap()
873    }
874
875    fn qn(schema: &str, name: &str) -> QualifiedName {
876        QualifiedName::new(id(schema), id(name))
877    }
878
879    fn table_users() -> Table {
880        Table {
881            qname: qn("app", "users"),
882            columns: vec![Column {
883                name: id("id"),
884                ty: ColumnType::BigInt,
885                nullable: false,
886                default: None,
887                identity: None,
888                generated: None,
889                collation: None,
890                storage: None,
891                compression: None,
892                comment: None,
893            }],
894            constraints: vec![],
895            partition_by: None,
896            partition_of: None,
897            comment: None,
898            owner: None,
899            grants: vec![],
900            rls_enabled: false,
901            rls_forced: false,
902            policies: vec![],
903            storage: crate::ir::reloptions::TableStorageOptions::default(),
904        }
905    }
906
907    #[test]
908    fn create_table_entry_serde_round_trip() {
909        let entry = ChangeEntry {
910            change: Change::CreateTable(table_users()),
911            destructiveness: Destructiveness::Safe,
912        };
913        let json = serde_json::to_string(&entry).unwrap();
914        let back: ChangeEntry = serde_json::from_str(&json).unwrap();
915        assert_eq!(entry, back);
916    }
917
918    #[test]
919    fn drop_table_entry_serde_round_trip() {
920        let entry = ChangeEntry {
921            change: Change::DropTable {
922                qname: qn("app", "users"),
923                row_count_estimate: None,
924            },
925            destructiveness: Destructiveness::RequiresApprovalAndDataLossWarning {
926                reason: "drops table app.users".into(),
927            },
928        };
929        let json = serde_json::to_string(&entry).unwrap();
930        let back: ChangeEntry = serde_json::from_str(&json).unwrap();
931        assert_eq!(entry, back);
932    }
933
934    #[test]
935    fn equal_create_table_changes_compare_equal() {
936        let a = Change::CreateTable(table_users());
937        let b = Change::CreateTable(table_users());
938        assert_eq!(a, b);
939    }
940}