vespertide-core 0.2.1

Data models for tables, columns, constraints, indexes, and migration actions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
mod display;
mod narrowing_strategy;
mod prefix;
mod remap_mapping_serde;

use crate::schema::{ColumnDef, ColumnName, ColumnType, TableConstraint, TableName};
pub use narrowing_strategy::NarrowingStrategy;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// A single versioned migration, grouping a set of [`MigrationAction`]s under a version number.
///
/// Migration plans are auto-generated by `vespertide revision` and stored as JSON or YAML files
/// in the `migrations/` directory. **Never create or edit these files manually.**
///
/// The `version` field is a monotonically increasing integer. The `id` is a UUID that guards
/// against accidental plan substitution when the same version number appears in two different
/// migration histories.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub struct MigrationPlan {
    /// Unique identifier for this migration (UUID format).
    /// Defaults to empty string for backward compatibility with old migration files.
    #[serde(default)]
    pub id: String,
    /// Human-readable description of what this migration does (from `-m "message"`).
    pub comment: Option<String>,
    /// ISO 8601 timestamp of when the migration file was generated.
    #[serde(default)]
    pub created_at: Option<String>,
    /// Monotonically increasing version number, starting at 1.
    pub version: u32,
    /// Ordered list of schema changes to apply in this migration.
    pub actions: Vec<MigrationAction>,
}

/// A single schema change produced by the planner and consumed by the SQL generator.
///
/// The planner emits a `Vec<MigrationAction>` when diffing two schemas. The SQL generator
/// (`vespertide-query`) translates each action into backend-specific DDL statements.
///
/// Prefer typed actions over [`MigrationAction::RawSql`]. Raw SQL is an emergency escape hatch:
/// it is not portable across backends and is skipped during baseline replay, which means the
/// planner cannot reason about it.
///
/// This enum is `#[non_exhaustive]`: new variants may be added in future releases.
/// Downstream `match` expressions should include a wildcard arm.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum MigrationAction {
    /// Create a new table with the given columns and constraints (`CREATE TABLE`).
    CreateTable {
        table: TableName,
        columns: Vec<ColumnDef>,
        constraints: Vec<TableConstraint>,
    },
    /// Drop an existing table and all its data (`DROP TABLE`).
    DeleteTable { table: TableName },
    /// Add a new column to an existing table (`ALTER TABLE ... ADD COLUMN`).
    AddColumn {
        table: TableName,
        column: Box<ColumnDef>,
        /// Optional fill value to backfill existing rows when adding NOT NULL without default.
        fill_with: Option<String>,
    },
    /// Rename a column in an existing table (`ALTER TABLE ... RENAME COLUMN`).
    RenameColumn {
        table: TableName,
        from: ColumnName,
        to: ColumnName,
    },
    /// Remove a column from an existing table (`ALTER TABLE ... DROP COLUMN`).
    DeleteColumn {
        table: TableName,
        column: ColumnName,
    },
    /// Change the SQL type of an existing column (`ALTER TABLE ... ALTER COLUMN ... TYPE`).
    ModifyColumnType {
        table: TableName,
        column: ColumnName,
        new_type: ColumnType,
        /// Mapping of removed enum values to replacement values for safe enum value removal.
        /// e.g., `{"cancelled": "'pending'"}` generates an `UPDATE` before the type change.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        fill_with: Option<BTreeMap<String, String>>,
        /// Strategy for transforming existing rows that would violate a *narrowed* new type
        /// (smaller VARCHAR length, lower NUMERIC scale, smaller integer size, etc.) so the
        /// `ALTER COLUMN TYPE` cannot fail. When `None`, the SQL generator emits a plain ALTER —
        /// safe only when the user has independently verified no row violates the new type
        /// (typically prompted by the `vespertide revision` type-narrowing select UI).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        narrowing_strategy: Option<NarrowingStrategy>,
        /// `IANA` timezone name (e.g. `"Asia/Seoul"`) or numeric UTC offset (e.g. `"+09:00"`)
        /// used when converting between `timestamp` and `timestamptz`. Required for safe
        /// migration on `PostgreSQL` where the conversion is non-trivial; ignored on `MySQL`
        /// and `SQLite` where vespertide maps both `timestamp` and `timestamptz` to the same
        /// underlying type. Validated by the CLI `revision` prompt against a 30-name
        /// whitelist plus numeric offset format `±HH:MM`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timezone: Option<String>,
    },
    /// Change whether a column accepts `NULL` values.
    ModifyColumnNullable {
        table: TableName,
        column: ColumnName,
        nullable: bool,
        /// Required when changing from nullable to non-nullable to backfill existing NULL values.
        fill_with: Option<String>,
        /// When true, rows with NULL values in the column are deleted instead of backfilled.
        /// Mutually exclusive with `fill_with`. Useful for FK columns where a valid fill value
        /// may not exist.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        delete_null_rows: Option<bool>,
    },
    /// Change or remove the default value of a column.
    ModifyColumnDefault {
        table: TableName,
        column: ColumnName,
        /// The new default value, or `None` to remove the default.
        new_default: Option<String>,
        /// **F15 fault gate — backfill existing rows.**
        ///
        /// `ALTER TABLE ... SET DEFAULT ...` only affects *new* rows. When
        /// the user wants every existing row updated to the new default in
        /// the same migration (the common "I want consistency right now"
        /// intent), the CLI's `revision` prompt captures that choice and
        /// stores the desired value here. The SQL generator then emits an
        /// `UPDATE table SET col = <value>` immediately after the ALTER.
        ///
        /// `None` (default, wire-format identical to v0.2.0) → skip the
        /// backfill: existing rows keep their current values. The action
        /// behaves exactly as before this field existed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        backfill: Option<String>,
    },
    /// Change or remove the comment on a column.
    ModifyColumnComment {
        table: TableName,
        column: ColumnName,
        /// The new comment, or `None` to remove the comment.
        new_comment: Option<String>,
    },
    /// Add a constraint (primary key, unique, foreign key, check, or index) to a table.
    ///
    /// F2 duplicate-handling strategy lives on the `Unique` variant of
    /// [`TableConstraint`] itself (see `TableConstraint::Unique.strategy`),
    /// not here — the strategy is intrinsic to a particular unique
    /// constraint, regardless of whether it is added, replaced, or shipped
    /// inside a `CreateTable`.
    AddConstraint {
        table: TableName,
        constraint: TableConstraint,
    },
    /// Remove a constraint from a table.
    RemoveConstraint {
        table: TableName,
        constraint: TableConstraint,
    },
    /// Atomically replace one constraint with another (e.g. when columns in a composite key change).
    ReplaceConstraint {
        table: TableName,
        from: TableConstraint,
        to: TableConstraint,
    },
    /// Remap stored integer values of an integer-backed enum column.
    ///
    /// Emitted when the user changes the `value` of an existing integer
    /// enum variant in the model (e.g. `medium: 5 → 10`). Because integer
    /// enums are stored as plain `INTEGER` in the database, the DB itself
    /// cannot detect the drift; if Vespertide stayed silent the ORM mapping
    /// would silently re-interpret existing rows. The SQL generator turns
    /// this action into a single atomic `UPDATE table SET col = CASE WHEN
    /// col = old THEN new ... END WHERE col IN (...)` that re-stamps every
    /// affected row before the new ORM mapping takes effect.
    ///
    /// `mapping` is a `BTreeMap<i64, i64>` keyed on the *old* value, so the
    /// type system guarantees a single replacement per source value.
    /// Canonical JSON wire format is `{"5": 10, "100": 20}` (string keys
    /// are how JSON represents map keys; serde transparently parses them
    /// back to `i64`). For backward compatibility the legacy array form
    /// `[[5, 10], [100, 20]]` is still accepted on read — see
    /// `remap_mapping_serde` for the details. The map iterates in
    /// `old_value` order at emit time so snapshots stay deterministic.
    /// Variants whose name AND value are unchanged are absent; variants
    /// added or removed (no name overlap on either side) are also absent
    /// — those need a separate migration action.
    RemapEnumValues {
        table: TableName,
        column: ColumnName,
        #[serde(with = "remap_mapping_serde")]
        #[cfg_attr(feature = "schema", schemars(with = "BTreeMap<String, i64>"))]
        mapping: BTreeMap<i64, i64>,
    },
    /// Rename a table (`ALTER TABLE ... RENAME TO`).
    RenameTable { from: TableName, to: TableName },
    /// Execute a raw SQL statement verbatim.
    ///
    /// **Emergency escape hatch only.** Raw SQL is not portable across backends and is invisible
    /// to baseline replay, so the planner cannot reason about schema state after this action.
    /// Use typed actions whenever possible.
    RawSql { sql: String },
}

impl MigrationAction {
    /// Returns the primary table this action affects, if any.
    /// Returns None for actions that don't bind to a single table (e.g. `RawSql`).
    #[must_use]
    pub fn table_name(&self) -> Option<&str> {
        match self {
            Self::CreateTable { table, .. }
            | Self::DeleteTable { table }
            | Self::AddColumn { table, .. }
            | Self::DeleteColumn { table, .. }
            | Self::RenameColumn { table, .. }
            | Self::ModifyColumnType { table, .. }
            | Self::ModifyColumnNullable { table, .. }
            | Self::ModifyColumnDefault { table, .. }
            | Self::ModifyColumnComment { table, .. }
            | Self::AddConstraint { table, .. }
            | Self::RemoveConstraint { table, .. }
            | Self::ReplaceConstraint { table, .. }
            | Self::RemapEnumValues { table, .. } => Some(table.as_str()),
            Self::RenameTable { from, .. } => Some(from.as_str()),
            Self::RawSql { .. } => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{ReferenceAction, SimpleColumnType};
    use rstest::rstest;

    fn default_column() -> ColumnDef {
        ColumnDef::new("email", ColumnType::Simple(SimpleColumnType::Text), true)
    }

    fn idx(name: Option<&str>, cols: &[&str]) -> TableConstraint {
        TableConstraint::Index {
            name: name.map(Into::into),
            columns: cols.iter().map(|c| (*c).into()).collect(),
        }
    }
    fn pk_id() -> TableConstraint {
        TableConstraint::PrimaryKey {
            auto_increment: false,
            columns: vec!["id".into()],
            strategy: crate::PrimaryKeyAdditionStrategy::default(),
        }
    }
    fn pk_id_auto() -> TableConstraint {
        TableConstraint::PrimaryKey {
            auto_increment: true,
            columns: vec!["id".into()],
            strategy: crate::PrimaryKeyAdditionStrategy::default(),
        }
    }
    fn uq_email(name: Option<&str>) -> TableConstraint {
        TableConstraint::Unique {
            name: name.map(Into::into),
            columns: vec!["email".into()],
            strategy: crate::schema::UniqueConstraintStrategy::DeleteDuplicates {
                keep: crate::schema::KeepPolicy::First,
            },
        }
    }
    fn fk_user(name: Option<&str>, on_delete: Option<ReferenceAction>) -> TableConstraint {
        TableConstraint::ForeignKey {
            name: name.map(Into::into),
            columns: vec!["user_id".into()],
            ref_table: "users".into(),
            ref_columns: vec!["id".into()],
            on_delete,
            on_update: None,
            orphan_strategy: crate::ForeignKeyOrphanStrategy::default(),
        }
    }
    fn chk(name: &str, expr: &str) -> TableConstraint {
        TableConstraint::Check {
            name: name.into(),
            expr: expr.into(),
            strategy: crate::CheckViolationStrategy::default(),
        }
    }
    fn idx_email(name: Option<&str>) -> TableConstraint {
        idx(name, &["email"])
    }

    #[test]
    fn migration_action_wire_format_round_trip() {
        let canonical = r#"{"type":"create_table","table":"user","columns":[],"constraints":[]}"#;
        let parsed: MigrationAction = serde_json::from_str(canonical).expect("parse");
        let reserialized = serde_json::to_string(&parsed).expect("serialize");

        assert_eq!(
            reserialized, canonical,
            "wire format MUST be byte-identical"
        );
    }

    #[test]
    fn migration_action_rename_column_wire_format() {
        let canonical = r#"{"type":"rename_column","table":"orders","from":"old","to":"new"}"#;
        let parsed: MigrationAction = serde_json::from_str(canonical).expect("parse");
        let reserialized = serde_json::to_string(&parsed).expect("serialize");

        assert_eq!(reserialized, canonical);
    }

    #[test]
    fn migration_plan_real_example_round_trip() {
        let plan_json =
            include_str!("../../../../examples/app/migrations/0001_init.vespertide.json");
        let parsed: MigrationPlan =
            serde_json::from_str(plan_json).expect("real migration plan parses");
        let reserialized = serde_json::to_string(&parsed).expect("serialize");
        let reparsed: MigrationPlan = serde_json::from_str(&reserialized).expect("round-trip");

        assert_eq!(
            parsed, reparsed,
            "semantic content preserved across round-trip"
        );
    }

    #[rstest]
    #[case::create_table(
        MigrationAction::CreateTable {
            table: "users".into(),
            columns: vec![],
            constraints: vec![],
        },
        "CreateTable: users"
    )]
    #[case::delete_table(
        MigrationAction::DeleteTable {
            table: "users".into(),
        },
        "DeleteTable: users"
    )]
    #[case::add_column(
        MigrationAction::AddColumn {
            table: "users".into(),
            column: Box::new(default_column()),
            fill_with: None,
        },
        "AddColumn: users.email"
    )]
    #[case::rename_column(
        MigrationAction::RenameColumn {
            table: "users".into(),
            from: "old_name".into(),
            to: "new_name".into(),
        },
        "RenameColumn: users.old_name -> new_name"
    )]
    #[case::delete_column(
        MigrationAction::DeleteColumn {
            table: "users".into(),
            column: "email".into(),
        },
        "DeleteColumn: users.email"
    )]
    #[case::modify_column_type(
        MigrationAction::ModifyColumnType {
            table: "users".into(),
            column: "age".into(),
            new_type: ColumnType::Simple(SimpleColumnType::Integer),
            fill_with: None,
            narrowing_strategy: None,
            timezone: None,
        },
        "ModifyColumnType: users.age"
    )]
    #[case::add_constraint_index_with_name(
        MigrationAction::AddConstraint { table: "users".into(), constraint: idx_email(Some("ix_users__email")) },
        "AddConstraint: users.ix_users__email (INDEX)"
    )]
    #[case::add_constraint_index_without_name(
        MigrationAction::AddConstraint { table: "users".into(), constraint: idx_email(None) },
        "AddConstraint: users.INDEX"
    )]
    #[case::remove_constraint_index_with_name(
        MigrationAction::RemoveConstraint { table: "users".into(), constraint: idx_email(Some("ix_users__email")) },
        "RemoveConstraint: users.ix_users__email (INDEX)"
    )]
    #[case::remove_constraint_index_without_name(
        MigrationAction::RemoveConstraint { table: "users".into(), constraint: idx_email(None) },
        "RemoveConstraint: users.INDEX"
    )]
    #[case::rename_table(
        MigrationAction::RenameTable {
            from: "old_table".into(),
            to: "new_table".into(),
        },
        "RenameTable: old_table -> new_table"
    )]
    fn test_display_basic_actions(#[case] action: MigrationAction, #[case] expected: &str) {
        assert_eq!(action.to_string(), expected);
    }

    #[test]
    fn test_display_raw_sql_truncates_unicode_without_panicking() {
        let sql = "COMMENT ON COLUMN 한국어테이블.이름 IS '日本語 café 📊';".repeat(3);
        let action = MigrationAction::RawSql { sql };

        let display = action.to_string();

        assert!(display.starts_with("RawSql: COMMENT ON COLUMN 한국어테이블"));
        assert!(display.ends_with("..."));
    }

    #[rstest]
    #[case::create_table(
        MigrationAction::CreateTable {
            table: "users".into(),
            columns: vec![],
            constraints: vec![],
        },
        Some("users")
    )]
    #[case::rename_table(
        MigrationAction::RenameTable {
            from: "old_users".into(),
            to: "users".into(),
        },
        Some("old_users")
    )]
    #[case::raw_sql(MigrationAction::RawSql { sql: "SELECT 1".into() }, None)]
    fn test_table_name(#[case] action: MigrationAction, #[case] expected: Option<&str>) {
        assert_eq!(action.table_name(), expected);
    }

    #[rstest]
    #[case::add_constraint_primary_key(
        MigrationAction::AddConstraint { table: "users".into(), constraint: pk_id() },
        "AddConstraint: users.PRIMARY KEY"
    )]
    #[case::add_constraint_unique_with_name(
        MigrationAction::AddConstraint { table: "users".into(), constraint: uq_email(Some("uq_email")) },
        "AddConstraint: users.uq_email (UNIQUE)"
    )]
    #[case::add_constraint_unique_without_name(
        MigrationAction::AddConstraint { table: "users".into(), constraint: uq_email(None) },
        "AddConstraint: users.UNIQUE"
    )]
    #[case::add_constraint_foreign_key_with_name(
        MigrationAction::AddConstraint { table: "posts".into(), constraint: fk_user(Some("fk_user"), Some(ReferenceAction::Cascade)) },
        "AddConstraint: posts.fk_user (FOREIGN KEY)"
    )]
    #[case::add_constraint_foreign_key_without_name(
        MigrationAction::AddConstraint { table: "posts".into(), constraint: fk_user(None, None) },
        "AddConstraint: posts.FOREIGN KEY"
    )]
    #[case::add_constraint_check(
        MigrationAction::AddConstraint { table: "users".into(), constraint: chk("chk_age", "age > 0") },
        "AddConstraint: users.chk_age (CHECK)"
    )]
    fn test_display_add_constraint(#[case] action: MigrationAction, #[case] expected: &str) {
        assert_eq!(action.to_string(), expected);
    }

    #[rstest]
    #[case::remove_constraint_primary_key(
        MigrationAction::RemoveConstraint { table: "users".into(), constraint: pk_id() },
        "RemoveConstraint: users.PRIMARY KEY"
    )]
    #[case::remove_constraint_unique_with_name(
        MigrationAction::RemoveConstraint { table: "users".into(), constraint: uq_email(Some("uq_email")) },
        "RemoveConstraint: users.uq_email (UNIQUE)"
    )]
    #[case::remove_constraint_unique_without_name(
        MigrationAction::RemoveConstraint { table: "users".into(), constraint: uq_email(None) },
        "RemoveConstraint: users.UNIQUE"
    )]
    #[case::remove_constraint_foreign_key_with_name(
        MigrationAction::RemoveConstraint { table: "posts".into(), constraint: fk_user(Some("fk_user"), None) },
        "RemoveConstraint: posts.fk_user (FOREIGN KEY)"
    )]
    #[case::remove_constraint_foreign_key_without_name(
        MigrationAction::RemoveConstraint { table: "posts".into(), constraint: fk_user(None, None) },
        "RemoveConstraint: posts.FOREIGN KEY"
    )]
    #[case::remove_constraint_check(
        MigrationAction::RemoveConstraint { table: "users".into(), constraint: chk("chk_age", "age > 0") },
        "RemoveConstraint: users.chk_age (CHECK)"
    )]
    fn test_display_remove_constraint(#[case] action: MigrationAction, #[case] expected: &str) {
        assert_eq!(action.to_string(), expected);
    }

    #[rstest]
    #[case::raw_sql_short(
        MigrationAction::RawSql {
            sql: "SELECT 1".into(),
        },
        "RawSql: SELECT 1"
    )]
    fn test_display_raw_sql_short(#[case] action: MigrationAction, #[case] expected: &str) {
        assert_eq!(action.to_string(), expected);
    }

    #[test]
    fn test_display_raw_sql_long() {
        let action = MigrationAction::RawSql {
            sql:
                "SELECT * FROM users WHERE id = 1 AND name = 'test' AND email = 'test@example.com'"
                    .into(),
        };
        let result = action.to_string();
        assert!(result.starts_with("RawSql: "));
        assert!(result.ends_with("..."));
        assert!(result.len() > 10);
    }

    #[rstest]
    #[case::modify_column_nullable_to_not_null(
        MigrationAction::ModifyColumnNullable {
            table: "users".into(),
            column: "email".into(),
            nullable: false,
            fill_with: None,
            delete_null_rows: None,
        },
        "ModifyColumnNullable: users.email -> NOT NULL"
    )]
    #[case::modify_column_nullable_to_null(
        MigrationAction::ModifyColumnNullable {
            table: "users".into(),
            column: "email".into(),
            nullable: true,
            fill_with: None,
            delete_null_rows: None,
        },
        "ModifyColumnNullable: users.email -> NULL"
    )]
    fn test_display_modify_column_nullable(
        #[case] action: MigrationAction,
        #[case] expected: &str,
    ) {
        assert_eq!(action.to_string(), expected);
    }

    #[rstest]
    #[case::modify_column_default_set(
        MigrationAction::ModifyColumnDefault {
            table: "users".into(),
            column: "status".into(),
            new_default: Some("'active'".into()),
            backfill: None,
        },
        "ModifyColumnDefault: users.status -> 'active'"
    )]
    #[case::modify_column_default_drop(
        MigrationAction::ModifyColumnDefault {
            table: "users".into(),
            column: "status".into(),
            new_default: None,
            backfill: None,
        },
        "ModifyColumnDefault: users.status -> (none)"
    )]
    fn test_display_modify_column_default(#[case] action: MigrationAction, #[case] expected: &str) {
        assert_eq!(action.to_string(), expected);
    }

    #[rstest]
    #[case::modify_column_comment_set(
        MigrationAction::ModifyColumnComment {
            table: "users".into(),
            column: "email".into(),
            new_comment: Some("User email address".into()),
        },
        "ModifyColumnComment: users.email -> 'User email address'"
    )]
    #[case::modify_column_comment_drop(
        MigrationAction::ModifyColumnComment {
            table: "users".into(),
            column: "email".into(),
            new_comment: None,
        },
        "ModifyColumnComment: users.email -> (none)"
    )]
    fn test_display_modify_column_comment(#[case] action: MigrationAction, #[case] expected: &str) {
        assert_eq!(action.to_string(), expected);
    }

    #[test]
    fn test_display_modify_column_comment_long() {
        // Test truncation for long comments (> 30 chars)
        let action = MigrationAction::ModifyColumnComment {
            table: "users".into(),
            column: "email".into(),
            new_comment: Some(
                "This is a very long comment that should be truncated in display".into(),
            ),
        };
        let result = action.to_string();
        assert!(result.contains("..."));
        assert!(result.contains("This is a very long comment"));
        // Should be truncated at 27 chars + "..."
        assert!(!result.contains("truncated in display"));
    }

    // Tests for with_prefix
    #[test]
    fn test_action_with_prefix_create_table() {
        let action = MigrationAction::CreateTable {
            table: "users".into(),
            columns: vec![default_column()],
            constraints: vec![TableConstraint::ForeignKey {
                name: Some("fk_org".into()),
                columns: vec!["org_id".into()],
                ref_table: "organizations".into(),
                ref_columns: vec!["id".into()],
                on_delete: None,
                on_update: None,
                orphan_strategy: crate::ForeignKeyOrphanStrategy::default(),
            }],
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::CreateTable {
            table, constraints, ..
        } = prefixed
        {
            assert_eq!(table.as_str(), "myapp_users");
            if let TableConstraint::ForeignKey { ref_table, .. } = &constraints[0] {
                assert_eq!(ref_table.as_str(), "myapp_organizations");
            }
        } else {
            panic!("Expected CreateTable");
        }
    }

    #[test]
    fn test_action_with_prefix_delete_table() {
        let action = MigrationAction::DeleteTable {
            table: "users".into(),
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::DeleteTable { table } = prefixed {
            assert_eq!(table.as_str(), "myapp_users");
        } else {
            panic!("Expected DeleteTable");
        }
    }

    #[test]
    fn test_action_with_prefix_add_column() {
        let action = MigrationAction::AddColumn {
            table: "users".into(),
            column: Box::new(default_column()),
            fill_with: None,
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::AddColumn { table, .. } = prefixed {
            assert_eq!(table.as_str(), "myapp_users");
        } else {
            panic!("Expected AddColumn");
        }
    }

    #[test]
    fn test_action_with_prefix_rename_table() {
        let action = MigrationAction::RenameTable {
            from: "old_table".into(),
            to: "new_table".into(),
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::RenameTable { from, to } = prefixed {
            assert_eq!(from.as_str(), "myapp_old_table");
            assert_eq!(to.as_str(), "myapp_new_table");
        } else {
            panic!("Expected RenameTable");
        }
    }

    #[test]
    fn test_action_with_prefix_raw_sql_unchanged() {
        let action = MigrationAction::RawSql {
            sql: "SELECT * FROM users".into(),
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::RawSql { sql } = prefixed {
            // RawSql is not modified - user is responsible for table names
            assert_eq!(sql, "SELECT * FROM users");
        } else {
            panic!("Expected RawSql");
        }
    }

    #[test]
    fn test_action_with_prefix_empty_prefix() {
        let action = MigrationAction::CreateTable {
            table: "users".into(),
            columns: vec![],
            constraints: vec![],
        };
        let prefixed = action.clone().with_prefix("");
        if let MigrationAction::CreateTable { table, .. } = prefixed {
            assert_eq!(table.as_str(), "users");
        }
    }

    #[test]
    fn test_migration_plan_with_prefix() {
        let plan = MigrationPlan {
            id: String::new(),
            comment: Some("test".into()),
            created_at: None,
            version: 1,
            actions: vec![
                MigrationAction::CreateTable {
                    table: "users".into(),
                    columns: vec![],
                    constraints: vec![],
                },
                MigrationAction::CreateTable {
                    table: "posts".into(),
                    columns: vec![],
                    constraints: vec![fk_user(Some("fk_user"), None)],
                },
            ],
        };
        let prefixed = plan.with_prefix("myapp_");
        assert_eq!(prefixed.actions.len(), 2);

        if let MigrationAction::CreateTable { table, .. } = &prefixed.actions[0] {
            assert_eq!(table.as_str(), "myapp_users");
        }
        if let MigrationAction::CreateTable {
            table, constraints, ..
        } = &prefixed.actions[1]
        {
            assert_eq!(table.as_str(), "myapp_posts");
            if let TableConstraint::ForeignKey { ref_table, .. } = &constraints[0] {
                assert_eq!(ref_table.as_str(), "myapp_users");
            }
        }
    }

    #[test]
    fn test_action_with_prefix_rename_column() {
        let action = MigrationAction::RenameColumn {
            table: "users".into(),
            from: "name".into(),
            to: "full_name".into(),
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::RenameColumn { table, from, to } = prefixed {
            assert_eq!(table.as_str(), "myapp_users");
            assert_eq!(from.as_str(), "name");
            assert_eq!(to.as_str(), "full_name");
        } else {
            panic!("Expected RenameColumn");
        }
    }

    #[test]
    fn test_action_with_prefix_delete_column() {
        let action = MigrationAction::DeleteColumn {
            table: "users".into(),
            column: "old_field".into(),
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::DeleteColumn { table, column } = prefixed {
            assert_eq!(table.as_str(), "myapp_users");
            assert_eq!(column.as_str(), "old_field");
        } else {
            panic!("Expected DeleteColumn");
        }
    }

    #[test]
    fn test_action_with_prefix_modify_column_type() {
        let action = MigrationAction::ModifyColumnType {
            table: "users".into(),
            column: "age".into(),
            new_type: ColumnType::Simple(SimpleColumnType::BigInt),
            fill_with: None,
            narrowing_strategy: None,
            timezone: None,
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::ModifyColumnType {
            table,
            column,
            new_type,
            fill_with,
            ..
        } = prefixed
        {
            assert_eq!(table.as_str(), "myapp_users");
            assert_eq!(column.as_str(), "age");
            assert!(matches!(
                new_type,
                ColumnType::Simple(SimpleColumnType::BigInt)
            ));
            assert_eq!(fill_with, None);
        } else {
            panic!("Expected ModifyColumnType");
        }
    }

    #[test]
    fn test_action_with_prefix_modify_column_nullable() {
        let action = MigrationAction::ModifyColumnNullable {
            table: "users".into(),
            column: "email".into(),
            nullable: false,
            fill_with: Some("default@example.com".into()),
            delete_null_rows: None,
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::ModifyColumnNullable {
            table,
            column,
            nullable,
            fill_with,
            delete_null_rows,
        } = prefixed
        {
            assert_eq!(table.as_str(), "myapp_users");
            assert_eq!(column.as_str(), "email");
            assert!(!nullable);
            assert_eq!(fill_with, Some("default@example.com".into()));
            assert_eq!(delete_null_rows, None);
        } else {
            panic!("Expected ModifyColumnNullable");
        }
    }

    #[test]
    fn test_action_with_prefix_modify_column_default() {
        let action = MigrationAction::ModifyColumnDefault {
            table: "users".into(),
            column: "status".into(),
            new_default: Some("active".into()),
            backfill: None,
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::ModifyColumnDefault {
            table,
            column,
            new_default,
            ..
        } = prefixed
        {
            assert_eq!(table.as_str(), "myapp_users");
            assert_eq!(column.as_str(), "status");
            assert_eq!(new_default, Some("active".into()));
        } else {
            panic!("Expected ModifyColumnDefault");
        }
    }

    #[test]
    fn test_action_with_prefix_modify_column_comment() {
        let action = MigrationAction::ModifyColumnComment {
            table: "users".into(),
            column: "bio".into(),
            new_comment: Some("User biography".into()),
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::ModifyColumnComment {
            table,
            column,
            new_comment,
        } = prefixed
        {
            assert_eq!(table.as_str(), "myapp_users");
            assert_eq!(column.as_str(), "bio");
            assert_eq!(new_comment, Some("User biography".into()));
        } else {
            panic!("Expected ModifyColumnComment");
        }
    }

    #[test]
    fn test_action_with_prefix_add_constraint() {
        let action = MigrationAction::AddConstraint {
            table: "posts".into(),
            constraint: fk_user(Some("fk_user"), None),
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::AddConstraint { table, constraint } = prefixed {
            assert_eq!(table.as_str(), "myapp_posts");
            if let TableConstraint::ForeignKey { ref_table, .. } = constraint {
                assert_eq!(ref_table.as_str(), "myapp_users");
            } else {
                panic!("Expected ForeignKey constraint");
            }
        } else {
            panic!("Expected AddConstraint");
        }
    }

    #[test]
    fn test_action_with_prefix_remove_constraint() {
        let action = MigrationAction::RemoveConstraint {
            table: "posts".into(),
            constraint: fk_user(Some("fk_user"), None),
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::RemoveConstraint { table, constraint } = prefixed {
            assert_eq!(table.as_str(), "myapp_posts");
            if let TableConstraint::ForeignKey { ref_table, .. } = constraint {
                assert_eq!(ref_table.as_str(), "myapp_users");
            } else {
                panic!("Expected ForeignKey constraint");
            }
        } else {
            panic!("Expected RemoveConstraint");
        }
    }

    #[rstest]
    #[case::replace_constraint_primary_key(
        MigrationAction::ReplaceConstraint { table: "users".into(), from: pk_id(), to: pk_id_auto() },
        "ReplaceConstraint: users.PRIMARY KEY"
    )]
    #[case::replace_constraint_unique_with_name(
        MigrationAction::ReplaceConstraint { table: "users".into(), from: uq_email(None), to: uq_email(Some("uq_email")) },
        "ReplaceConstraint: users.uq_email (UNIQUE)"
    )]
    #[case::replace_constraint_unique_without_name(
        MigrationAction::ReplaceConstraint { table: "users".into(), from: uq_email(Some("uq_email")), to: uq_email(None) },
        "ReplaceConstraint: users.UNIQUE"
    )]
    #[case::replace_constraint_foreign_key_with_name(
        MigrationAction::ReplaceConstraint { table: "posts".into(), from: fk_user(None, None), to: fk_user(Some("fk_user"), None) },
        "ReplaceConstraint: posts.fk_user (FOREIGN KEY)"
    )]
    #[case::replace_constraint_foreign_key_without_name(
        MigrationAction::ReplaceConstraint { table: "posts".into(), from: fk_user(Some("fk_user"), None), to: fk_user(None, None) },
        "ReplaceConstraint: posts.FOREIGN KEY"
    )]
    #[case::replace_constraint_check(
        MigrationAction::ReplaceConstraint { table: "users".into(), from: chk("chk_age", "age > 0"), to: chk("chk_age", "age >= 0") },
        "ReplaceConstraint: users.chk_age (CHECK)"
    )]
    #[case::replace_constraint_index_with_name(
        MigrationAction::ReplaceConstraint { table: "users".into(), from: idx_email(None), to: idx_email(Some("ix_users__email")) },
        "ReplaceConstraint: users.ix_users__email (INDEX)"
    )]
    #[case::replace_constraint_index_without_name(
        MigrationAction::ReplaceConstraint { table: "users".into(), from: idx_email(Some("ix_users__email")), to: idx_email(None) },
        "ReplaceConstraint: users.INDEX"
    )]
    fn test_display_replace_constraint(#[case] action: MigrationAction, #[case] expected: &str) {
        assert_eq!(action.to_string(), expected);
    }

    #[test]
    fn test_action_with_prefix_replace_constraint() {
        let action = MigrationAction::ReplaceConstraint {
            table: "posts".into(),
            from: fk_user(Some("fk_user"), Some(ReferenceAction::Cascade)),
            to: fk_user(Some("fk_user"), Some(ReferenceAction::SetNull)),
        };
        let prefixed = action.with_prefix("myapp_");
        if let MigrationAction::ReplaceConstraint { table, from, to } = prefixed {
            assert_eq!(table.as_str(), "myapp_posts");
            if let TableConstraint::ForeignKey { ref_table, .. } = from {
                assert_eq!(ref_table.as_str(), "myapp_users");
            } else {
                panic!("Expected ForeignKey constraint in from");
            }
            if let TableConstraint::ForeignKey { ref_table, .. } = to {
                assert_eq!(ref_table.as_str(), "myapp_users");
            } else {
                panic!("Expected ForeignKey constraint in to");
            }
        } else {
            panic!("Expected ReplaceConstraint");
        }
    }
}