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 change to an event trigger. See [`EventTriggerChange`].
297 EventTrigger(EventTriggerChange),
298 /// A nested change to a single statistic. See [`StatisticChange`].
299 Statistic(StatisticChange),
300 /// A nested change to a single collation. See [`CollationChange`].
301 Collation(CollationChange),
302
303 /// A change that cannot be performed in-place.
304 ///
305 /// Emitted by the differ when it detects a structural difference that has
306 /// no safe automatic migration path (e.g., changing a table's `PARTITION BY`
307 /// clause). The ordering phase converts this into a [`PlanError`] so the
308 /// plan never reaches execution.
309 ///
310 /// [`PlanError`]: crate::plan::error::PlanError
311 UnsupportedDiff {
312 /// Human-readable explanation of what changed and why it cannot be
313 /// performed in-place.
314 reason: String,
315 },
316}
317
318/// A structural change to a single user-defined type.
319#[allow(clippy::large_enum_variant)]
320#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
321#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
322pub enum UserTypeChange {
323 /// Create a new user-defined type.
324 Create(UserType),
325 /// Drop a user-defined type by qualified name.
326 Drop(QualifiedName),
327
328 /// Add a new label to an existing enum type.
329 EnumAddValue {
330 /// Qualified name of the enum type.
331 qname: QualifiedName,
332 /// The new label string.
333 value: String,
334 /// If `Some`, the new value is placed immediately before this label.
335 before: Option<String>,
336 /// If `Some`, the new value is placed immediately after this label.
337 after: Option<String>,
338 },
339 /// Rename an existing enum label.
340 EnumRenameValue {
341 /// Qualified name of the enum type.
342 qname: QualifiedName,
343 /// The existing label to rename.
344 from: String,
345 /// The new label name.
346 to: String,
347 },
348
349 /// Add a CHECK constraint to a domain.
350 DomainAddCheck {
351 /// Qualified name of the domain type.
352 qname: QualifiedName,
353 /// The constraint to add.
354 constraint: DomainCheck,
355 },
356 /// Drop a named CHECK constraint from a domain.
357 DomainDropCheck {
358 /// Qualified name of the domain type.
359 qname: QualifiedName,
360 /// The constraint name to drop.
361 name: Identifier,
362 },
363 /// Set (or clear) the DEFAULT expression on a domain.
364 DomainSetDefault {
365 /// Qualified name of the domain type.
366 qname: QualifiedName,
367 /// New default expression (`None` clears the default).
368 default: Option<NormalizedExpr>,
369 },
370 /// Toggle the `NOT NULL` constraint on a domain.
371 DomainSetNotNull {
372 /// Qualified name of the domain type.
373 qname: QualifiedName,
374 /// `true` means NOT NULL (i.e., `nullable = false`).
375 not_null: bool,
376 },
377
378 /// Add a new attribute to a composite type.
379 CompositeAddAttribute {
380 /// Qualified name of the composite type.
381 qname: QualifiedName,
382 /// The attribute to add.
383 attribute: CompositeAttribute,
384 },
385 /// Drop an attribute from a composite type.
386 CompositeDropAttribute {
387 /// Qualified name of the composite type.
388 qname: QualifiedName,
389 /// The attribute name to drop.
390 name: Identifier,
391 },
392 /// Change the type of an existing composite attribute.
393 CompositeAlterAttributeType {
394 /// Qualified name of the composite type.
395 qname: QualifiedName,
396 /// The attribute name whose type is being changed.
397 attribute: Identifier,
398 /// The new column type.
399 new_type: ColumnType,
400 },
401
402 /// Set (or clear) the `COMMENT ON TYPE` for this type.
403 SetComment {
404 /// Qualified name of the type.
405 qname: QualifiedName,
406 /// New comment (`None` clears the comment).
407 comment: Option<String>,
408 },
409
410 /// Emitted when the requested change cannot be done in place via `ALTER`.
411 ///
412 /// T8's cascade walker appends `ReplaceBody` for any views/MVs that depend
413 /// on the type so they are recreated after the type is rebuilt. T9's SQL
414 /// emitter expands this single entry into `DROP TYPE … CASCADE` plus
415 /// `CREATE TYPE`, then the recreated dependents follow in topological
416 /// order. The planner never emits this entry as one raw SQL step.
417 ReplaceWithCascade {
418 /// The desired type (source).
419 source: UserType,
420 /// The existing type (catalog / live database).
421 catalog: UserType,
422 },
423}
424
425/// A structural change to a single view.
426#[allow(clippy::large_enum_variant)]
427#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
428#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
429pub enum ViewChange {
430 /// Create a new view.
431 Create(View),
432 /// Drop an existing view.
433 Drop(QualifiedName),
434 /// Replace the SELECT body of a view.
435 ///
436 /// `compatible` is `true` when Postgres's `CREATE OR REPLACE VIEW` rules
437 /// are satisfied (same column names and types at the same indexes, with
438 /// new columns only appended at the end). When `compatible` is `false`,
439 /// the planner must `DROP` then re-`CREATE` the view (and rebuild its
440 /// dependents).
441 ReplaceBody {
442 /// The view as it should exist (source SQL).
443 source: View,
444 /// The view as it currently exists (live catalog).
445 catalog: View,
446 /// Whether `CREATE OR REPLACE VIEW` can be used (`true`) or a
447 /// `DROP` + `CREATE` cycle is required (`false`).
448 compatible: bool,
449 },
450 /// Change `WITH (security_barrier = ..., security_invoker = ...)` reloptions.
451 SetReloption {
452 /// View qname.
453 qname: QualifiedName,
454 /// Desired `security_barrier` value (`None` clears the option).
455 security_barrier: Option<bool>,
456 /// Desired `security_invoker` value (`None` clears the option).
457 security_invoker: Option<bool>,
458 },
459 /// Set (or clear) the view-level `COMMENT ON VIEW`.
460 SetComment {
461 /// View qname.
462 qname: QualifiedName,
463 /// New comment (`None` clears the comment).
464 comment: Option<String>,
465 },
466 /// Set (or clear) a `COMMENT ON COLUMN view.col`.
467 SetColumnComment {
468 /// View qname.
469 qname: QualifiedName,
470 /// Column name.
471 column: Identifier,
472 /// New comment (`None` clears the comment).
473 comment: Option<String>,
474 },
475}
476
477/// A structural change to a single materialized view.
478#[allow(clippy::large_enum_variant)]
479#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
480#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
481pub enum MvChange {
482 /// Create a new materialized view.
483 Create(MaterializedView),
484 /// Drop an existing materialized view.
485 ///
486 /// Unlike `ViewChange::Drop`, this is classified as `Safe` because
487 /// materialized views are derived data that can be recreated by refreshing.
488 Drop(QualifiedName),
489 /// Replace the SELECT body of a materialized view.
490 ///
491 /// Materialized views do not support `CREATE OR REPLACE`; the planner must
492 /// always `DROP` then `CREATE` the MV (and rebuild any indexes on it).
493 ReplaceBody {
494 /// The MV as it should exist (source SQL).
495 source: MaterializedView,
496 /// The MV as it currently exists (live catalog).
497 catalog: MaterializedView,
498 },
499 /// Set (or clear) the MV-level `COMMENT ON MATERIALIZED VIEW`.
500 SetComment {
501 /// MV qname.
502 qname: QualifiedName,
503 /// New comment (`None` clears the comment).
504 comment: Option<String>,
505 },
506 /// Set (or clear) a `COMMENT ON COLUMN mv.col`.
507 SetColumnComment {
508 /// MV qname.
509 qname: QualifiedName,
510 /// Column name.
511 column: Identifier,
512 /// New comment (`None` clears the comment).
513 comment: Option<String>,
514 },
515}
516
517/// A structural change to a single user-defined function.
518#[allow(clippy::large_enum_variant)]
519#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
520#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
521pub enum FunctionChange {
522 /// Create a new function.
523 Create(Function),
524 /// Drop an existing function by qualified name and normalized arg types.
525 Drop {
526 /// Qualified name of the function.
527 qname: QualifiedName,
528 /// Normalized argument types (IN/INOUT/VARIADIC only) used to
529 /// disambiguate overloads in the DROP FUNCTION statement.
530 args: NormalizedArgTypes,
531 },
532 /// Replace the function body and/or attributes using `CREATE OR REPLACE
533 /// FUNCTION`. Only valid when `function_can_or_replace` returns `true`.
534 CreateOrReplace(Function),
535 /// The function's return type or language changed in a way that PG's
536 /// `CREATE OR REPLACE FUNCTION` rejects. The planner must emit
537 /// `DROP FUNCTION … CASCADE` followed by `CREATE FUNCTION`.
538 ReplaceWithCascade {
539 /// The desired function (source).
540 source: Function,
541 /// The existing function (catalog / live database).
542 catalog: Function,
543 },
544 /// Set (or clear) `COMMENT ON FUNCTION`.
545 SetComment {
546 /// Qualified name of the function.
547 qname: QualifiedName,
548 /// Normalized argument types for disambiguation.
549 args: NormalizedArgTypes,
550 /// New comment (`None` clears the comment).
551 comment: Option<String>,
552 },
553}
554
555/// A structural change to a single user-defined procedure.
556#[allow(clippy::large_enum_variant)]
557#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
558#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
559pub enum ProcedureChange {
560 /// Create a new procedure.
561 Create(Procedure),
562 /// Drop an existing procedure by qualified name.
563 Drop(QualifiedName),
564 /// Replace the procedure body and/or attributes using `CREATE OR REPLACE
565 /// PROCEDURE`.
566 CreateOrReplace(Procedure),
567 /// Set (or clear) `COMMENT ON PROCEDURE`.
568 SetComment {
569 /// Qualified name of the procedure.
570 qname: QualifiedName,
571 /// New comment (`None` clears the comment).
572 comment: Option<String>,
573 },
574}
575
576/// Change to one extension. Pair-by-name semantics.
577#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
578#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
579pub enum ExtensionChange {
580 /// Install a new extension.
581 Create(Extension),
582 /// Drop an extension by name. Emits `DROP EXTENSION ... CASCADE`.
583 Drop(Identifier),
584 /// Bump extension version: `ALTER EXTENSION ... UPDATE TO 'v'`.
585 AlterUpdate {
586 /// Extension name.
587 name: Identifier,
588 /// New version to update to.
589 to_version: String,
590 },
591 /// Schema-changing replace (DROP CASCADE + CREATE).
592 ReplaceWithCascade(Extension),
593 /// Change the `COMMENT ON EXTENSION` text.
594 CommentOn {
595 /// Extension name.
596 name: Identifier,
597 /// New comment value (`None` clears the comment).
598 comment: Option<String>,
599 },
600}
601
602/// Change to one trigger. Pair-by-qname semantics; any structural
603/// difference emits `Replace`.
604#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
605#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
606pub enum TriggerChange {
607 /// Install a new trigger.
608 Create(Trigger),
609 /// Drop a trigger by qname (needs the table for `DROP TRIGGER name ON table`).
610 Drop {
611 /// Qualified name of the trigger.
612 qname: QualifiedName,
613 /// Owning table (needed for `DROP TRIGGER name ON table`).
614 table: QualifiedName,
615 },
616 /// Any structural change: drop + create.
617 Replace(Trigger),
618 /// Change the `COMMENT ON TRIGGER` text.
619 CommentOn {
620 /// Qualified name of the trigger.
621 qname: QualifiedName,
622 /// Owning table (needed for `COMMENT ON TRIGGER name ON table`).
623 table: QualifiedName,
624 /// New comment value (`None` clears the comment).
625 comment: Option<String>,
626 },
627}
628
629/// A change to a single event trigger.
630#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
631#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
632pub enum EventTriggerChange {
633 /// `CREATE EVENT TRIGGER ...`
634 Create(crate::ir::event_trigger::EventTrigger),
635 /// `DROP EVENT TRIGGER old; CREATE EVENT TRIGGER new;` — used when
636 /// `event`, `tag_filter`, or `function` differ (no in-place ALTER exists).
637 Replace {
638 /// As it exists in the target (live).
639 from: crate::ir::event_trigger::EventTrigger,
640 /// As it should exist in the source.
641 to: crate::ir::event_trigger::EventTrigger,
642 },
643 /// `DROP EVENT TRIGGER name;` — destructive.
644 Drop {
645 /// Event trigger name.
646 name: Identifier,
647 },
648 /// `ALTER EVENT TRIGGER name {ENABLE|DISABLE|ENABLE REPLICA|ENABLE ALWAYS};`
649 AlterEnable {
650 /// Event trigger name.
651 name: Identifier,
652 /// Desired fire state.
653 enabled: crate::ir::event_trigger::EventTriggerEnabled,
654 },
655 /// `ALTER EVENT TRIGGER name OWNER TO role;`
656 AlterOwner {
657 /// Event trigger name.
658 name: Identifier,
659 /// Desired owner.
660 owner: Identifier,
661 },
662 /// `COMMENT ON EVENT TRIGGER name IS '...'`
663 CommentOn {
664 /// Event trigger name.
665 name: Identifier,
666 /// New comment (`None` clears it).
667 comment: Option<String>,
668 },
669}
670
671/// A partition-membership change on a child table.
672///
673/// These changes are emitted by the differ when the `partition_of` field of a
674/// table changes. Wiring to SQL steps lands in PART9.
675#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
676#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
677pub enum TableChange {
678 /// Attach a child table to a parent partitioned table.
679 ///
680 /// Corresponds to `ALTER TABLE <parent> ATTACH PARTITION <child> <bounds>`.
681 AttachPartition {
682 /// The partitioned parent table.
683 parent: QualifiedName,
684 /// The child table being attached.
685 child: QualifiedName,
686 /// The partition bounds clause.
687 bounds: PartitionBounds,
688 },
689 /// Detach a child table from a parent partitioned table.
690 ///
691 /// Corresponds to `ALTER TABLE <parent> DETACH PARTITION <child>`.
692 DetachPartition {
693 /// The partitioned parent table.
694 parent: QualifiedName,
695 /// The child table being detached.
696 child: QualifiedName,
697 },
698}
699
700/// A structural change to a single publication.
701#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
702#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
703pub enum PublicationChange {
704 /// `CREATE PUBLICATION ...`
705 Create(crate::ir::publication::Publication),
706 /// `DROP PUBLICATION ...` — destructive.
707 Drop {
708 /// Publication name.
709 name: Identifier,
710 },
711 /// `DROP PUBLICATION old; CREATE PUBLICATION new;` — destructive; used
712 /// when the publication's scope mode switches (`AllTables` ↔ `Selective`).
713 Replace {
714 /// The publication as it exists in the target.
715 from: crate::ir::publication::Publication,
716 /// The publication as it should exist in the source.
717 to: crate::ir::publication::Publication,
718 },
719 /// `ALTER PUBLICATION p ADD TABLE x [(cols)] [WHERE (filter)]`
720 AddTable {
721 /// Publication name.
722 publication: Identifier,
723 /// The table entry to add.
724 table: crate::ir::publication::PublishedTable,
725 },
726 /// `ALTER PUBLICATION p DROP TABLE x`
727 DropTable {
728 /// Publication name.
729 publication: Identifier,
730 /// Qualified name of the table to drop.
731 qname: QualifiedName,
732 },
733 /// `ALTER PUBLICATION p SET TABLE x (cols) WHERE (filter)`
734 SetTable {
735 /// Publication name.
736 publication: Identifier,
737 /// The desired table entry state.
738 table: crate::ir::publication::PublishedTable,
739 },
740 /// `ALTER PUBLICATION p ADD TABLES IN SCHEMA s` (PG15+)
741 AddSchema {
742 /// Publication name.
743 publication: Identifier,
744 /// Schema to add.
745 schema: Identifier,
746 },
747 /// `ALTER PUBLICATION p DROP TABLES IN SCHEMA s` (PG15+)
748 DropSchema {
749 /// Publication name.
750 publication: Identifier,
751 /// Schema to drop.
752 schema: Identifier,
753 },
754 /// `ALTER PUBLICATION p SET (publish = '...')`
755 SetPublish {
756 /// Publication name.
757 publication: Identifier,
758 /// Desired publish-kinds bitset.
759 kinds: crate::ir::publication::PublishKinds,
760 },
761 /// `ALTER PUBLICATION p SET (publish_via_partition_root = ...)`
762 SetViaRoot {
763 /// Publication name.
764 publication: Identifier,
765 /// Desired value.
766 value: bool,
767 },
768 /// `COMMENT ON PUBLICATION p IS '...'`
769 CommentOn {
770 /// Publication name.
771 name: Identifier,
772 /// New comment value (`None` clears the comment).
773 comment: Option<String>,
774 },
775}
776
777/// A structural change to a single subscription.
778#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
779#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
780pub enum SubscriptionChange {
781 /// `CREATE SUBSCRIPTION ...`
782 Create(crate::ir::subscription::Subscription),
783 /// `DROP SUBSCRIPTION ...` — destructive.
784 Drop {
785 /// Subscription name.
786 name: Identifier,
787 },
788 /// `ALTER SUBSCRIPTION s CONNECTION '...'`
789 AlterConnection {
790 /// Subscription name.
791 name: Identifier,
792 /// New connection string (may contain `${VAR}` placeholders).
793 new_connection: String,
794 },
795 /// `ALTER SUBSCRIPTION s ADD PUBLICATION p`
796 AddPublication {
797 /// Subscription name.
798 name: Identifier,
799 /// Publication to add.
800 publication: Identifier,
801 },
802 /// `ALTER SUBSCRIPTION s DROP PUBLICATION p`
803 DropPublication {
804 /// Subscription name.
805 name: Identifier,
806 /// Publication to drop.
807 publication: Identifier,
808 },
809 /// `ALTER SUBSCRIPTION s SET (option = value, ...)` — sparse-delta.
810 ///
811 /// `create_slot` and `copy_data` are NEVER included (CREATE-only PG options).
812 SetOptions {
813 /// Subscription name.
814 name: Identifier,
815 /// Sparse options delta — only changed fields are `Some`.
816 options: crate::ir::subscription::SubscriptionOptions,
817 },
818 /// `COMMENT ON SUBSCRIPTION s IS '...'`
819 CommentOn {
820 /// Subscription name.
821 name: Identifier,
822 /// New comment value (`None` clears the comment).
823 comment: Option<String>,
824 },
825}
826
827/// A structural change to a single statistic.
828#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
829#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
830pub enum StatisticChange {
831 /// `CREATE STATISTICS ...`
832 Create(crate::ir::statistic::Statistic),
833 /// `DROP STATISTICS ...` — destructive.
834 Drop {
835 /// Schema-qualified statistic name.
836 qname: QualifiedName,
837 },
838 /// `DROP STATISTICS old; CREATE STATISTICS new;` — destructive; used
839 /// when columns / kinds / target table differ (PG has no in-place ALTER
840 /// for those fields).
841 Replace {
842 /// The statistic as it exists in the target.
843 from: crate::ir::statistic::Statistic,
844 /// The statistic as it should exist in the source.
845 to: crate::ir::statistic::Statistic,
846 },
847 /// `ALTER STATISTICS s SET STATISTICS n` — analyze target.
848 AlterSetTarget {
849 /// Schema-qualified statistic name.
850 qname: QualifiedName,
851 /// New statistics target value.
852 value: i32,
853 },
854 /// `COMMENT ON STATISTICS s IS '...'`
855 CommentOn {
856 /// Schema-qualified statistic name.
857 qname: QualifiedName,
858 /// New comment value (`None` clears the comment).
859 comment: Option<String>,
860 },
861}
862
863/// A structural change to a single collation.
864#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
865#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
866pub enum CollationChange {
867 /// `CREATE COLLATION ...`
868 Create(Collation),
869 /// `DROP COLLATION qname` — destructive.
870 ///
871 /// Emitted by [`diff_schemas`][crate::diff::schemas::diff_schemas] when
872 /// dropping a schema that contains collations: PG error 2BP01 fires if
873 /// `DROP SCHEMA X` executes while collations in X are still live.
874 ///
875 /// Not emitted by `diff_collations` directly — collations are lenient
876 /// there (no auto-drop for target-only collations; unmanaged drift
877 /// surfaces via the `unmanaged-collation` lint instead).
878 Drop {
879 /// Schema-qualified collation name.
880 qname: QualifiedName,
881 },
882 /// `ALTER COLLATION qname RENAME TO new_name`.
883 ///
884 /// Not emitted by the differ: rename intent is not structurally derivable
885 /// from name-mismatched-but-same-shape collations (the user could equally
886 /// have meant drop-old + create-new). This variant exists for the parser
887 /// and future explicit-rename use cases.
888 Rename {
889 /// Existing qname.
890 from: QualifiedName,
891 /// New unqualified name (same schema).
892 to: Identifier,
893 },
894 /// `DROP COLLATION old; CREATE COLLATION new;` — PG has no in-place
895 /// ALTER for provider / locale / deterministic.
896 Replace {
897 /// The collation as it exists in the target.
898 from: Collation,
899 /// The collation as it should exist in the source.
900 to: Collation,
901 },
902 /// `COMMENT ON COLLATION qname IS '...'`.
903 CommentOn {
904 /// Schema-qualified collation name.
905 qname: QualifiedName,
906 /// New comment (`None` clears).
907 comment: Option<String>,
908 },
909}
910
911#[cfg(test)]
912mod tests {
913 use super::*;
914 use crate::identifier::Identifier;
915 use crate::ir::column::Column;
916 use crate::ir::column_type::ColumnType;
917
918 fn id(s: &str) -> Identifier {
919 Identifier::from_unquoted(s).unwrap()
920 }
921
922 fn qn(schema: &str, name: &str) -> QualifiedName {
923 QualifiedName::new(id(schema), id(name))
924 }
925
926 fn table_users() -> Table {
927 Table {
928 qname: qn("app", "users"),
929 columns: vec![Column {
930 name: id("id"),
931 ty: ColumnType::BigInt,
932 nullable: false,
933 default: None,
934 identity: None,
935 generated: None,
936 collation: None,
937 storage: None,
938 compression: None,
939 comment: None,
940 }],
941 constraints: vec![],
942 partition_by: None,
943 partition_of: None,
944 comment: None,
945 owner: None,
946 grants: vec![],
947 rls_enabled: false,
948 rls_forced: false,
949 policies: vec![],
950 storage: crate::ir::reloptions::TableStorageOptions::default(),
951 access_method: None,
952 }
953 }
954
955 #[test]
956 fn create_table_entry_serde_round_trip() {
957 let entry = ChangeEntry {
958 change: Change::CreateTable(table_users()),
959 destructiveness: Destructiveness::Safe,
960 };
961 let json = serde_json::to_string(&entry).unwrap();
962 let back: ChangeEntry = serde_json::from_str(&json).unwrap();
963 assert_eq!(entry, back);
964 }
965
966 #[test]
967 fn drop_table_entry_serde_round_trip() {
968 let entry = ChangeEntry {
969 change: Change::DropTable {
970 qname: qn("app", "users"),
971 row_count_estimate: None,
972 },
973 destructiveness: Destructiveness::RequiresApprovalAndDataLossWarning {
974 reason: "drops table app.users".into(),
975 },
976 };
977 let json = serde_json::to_string(&entry).unwrap();
978 let back: ChangeEntry = serde_json::from_str(&json).unwrap();
979 assert_eq!(entry, back);
980 }
981
982 #[test]
983 fn equal_create_table_changes_compare_equal() {
984 let a = Change::CreateTable(table_users());
985 let b = Change::CreateTable(table_users());
986 assert_eq!(a, b);
987 }
988}