drizzle-migrations 0.1.14

Migration infrastructure for drizzle-rs
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
//! Core traits for type-safe migration infrastructure
//!
//! This module provides idiomatic Rust traits replacing TypeScript patterns:
//! - `Version` - Type-safe version markers with const NUMBER
//! - `Upgradable` - Trait for upgrading snapshots between versions
//! - `Entity` - Trait for DDL entities with const KIND
//! - `EntityKind` - Enum replacing string `entity_type` discrimination

use std::fmt;
use std::hash::Hash;
use std::marker::PhantomData;

// Import dialect-specific types for associated type definitions
use crate::postgres::{
    PostgresDDL, PostgresSnapshot, ddl::PostgresEntity, statements::PostgresGenerator,
};
use crate::sqlite::{SQLiteDDL, SQLiteSnapshot, ddl::SqliteEntity, statements::SqliteGenerator};

// =============================================================================
// Version System
// =============================================================================

/// Type-safe version marker trait.
///
/// Each schema version is represented as a zero-sized type implementing this trait.
/// The version number is available at compile time via the associated constant.
pub trait Version: Copy + Clone + Default + 'static {
    /// The version number (5, 6, 7, 8, etc.)
    const NUMBER: u32;
}

/// Helper to get version as string at runtime
#[must_use]
pub fn version_str<V: Version>() -> String {
    V::NUMBER.to_string()
}

/// Version 5 marker
#[derive(Copy, Clone, Default, Debug)]
pub struct V5;
impl Version for V5 {
    const NUMBER: u32 = 5;
}

/// Version 6 marker
#[derive(Copy, Clone, Default, Debug)]
pub struct V6;
impl Version for V6 {
    const NUMBER: u32 = 6;
}

/// Version 7 marker
#[derive(Copy, Clone, Default, Debug)]
pub struct V7;
impl Version for V7 {
    const NUMBER: u32 = 7;
}

/// Version 8 marker
#[derive(Copy, Clone, Default, Debug)]
pub struct V8;
impl Version for V8 {
    const NUMBER: u32 = 8;
}

/// Latest version aliases per dialect
pub type SqliteLatest = V7;
pub type PostgresLatest = V8;
pub type MysqlLatest = V5;

// =============================================================================
// Upgradable Trait
// =============================================================================

/// Trait for upgrading a snapshot from one version to another.
///
/// Implementations are provided for each dialect's version transitions.
/// The trait is generic over the snapshot type `S`, source version `From`,
/// and target version `To`.
///
/// # Example
/// ```rust
/// # let _ = r####"
/// impl Upgradable<V5, V6> for SqliteSnapshot<V5> {
///     type Output = SqliteSnapshot<V6>;
///     type Error = UpgradeError;
///
///     fn upgrade(self) -> Result<Self::Output, Self::Error> {
///         // Transform v5 -> v6
///     }
/// }
/// # "####;
/// ```
pub trait Upgradable<From: Version, To: Version> {
    /// The output snapshot type (same shape, different version)
    type Output;
    /// Error type for upgrade failures
    type Error;

    /// Perform the upgrade transformation
    ///
    /// # Errors
    ///
    /// Returns the implementation's [`Self::Error`] if the upgrade
    /// transformation fails (e.g., due to an unsupported input format or a
    /// corrupted snapshot).
    fn upgrade(self) -> Result<Self::Output, Self::Error>;
}

/// Type-safe upgrade function that only compiles for valid upgrade paths.
///
/// This function leverages the `CanUpgrade` trait to enforce at compile time
/// that the specified dialect supports the given version transition.
///
/// # Example
/// ```rust
/// # let _ = r####"
/// use drizzle_migrations::{Sqlite, V5, V7, CanUpgrade, Versioned};
///
/// // This compiles because Sqlite: CanUpgrade<V5, V7>
/// fn upgrade_sqlite_snapshot<D>(data: Versioned<MyData, V5>) -> Versioned<MyData, V7>
/// where
///     D: CanUpgrade<V5, V7>,
/// {
///     // Perform the upgrade
///     Versioned::new(data.into_inner())
/// }
/// # "####;
/// ```
#[inline]
pub const fn assert_can_upgrade<D, From, To>()
where
    D: CanUpgrade<From, To>,
    From: Version,
    To: Version,
{
    // This function exists to provide a clear compile-time error
    // when an invalid upgrade path is attempted.
}

// =============================================================================
// Entity System
// =============================================================================

/// Entity kind discriminator enum.
///
/// Replaces string-based `entity_type` fields with a proper enum.
/// Uses `#[repr(u8)]` for efficient storage and comparison.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum EntityKind {
    // Schema-level entities
    Schema = 0,
    Enum = 1,
    Sequence = 2,
    Role = 3,

    // Table-level entities
    Table = 10,
    Column = 11,
    Index = 12,
    ForeignKey = 13,
    PrimaryKey = 14,
    UniqueConstraint = 15,
    CheckConstraint = 16,

    // Other entities
    Policy = 20,
    View = 21,
}

impl EntityKind {
    /// Get the string representation for JSON serialization compatibility
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Schema => "schemas",
            Self::Enum => "enums",
            Self::Sequence => "sequences",
            Self::Role => "roles",
            Self::Table => "tables",
            Self::Column => "columns",
            Self::Index => "indexes",
            Self::ForeignKey => "fks",
            Self::PrimaryKey => "pks",
            Self::UniqueConstraint => "uniques",
            Self::CheckConstraint => "checks",
            Self::Policy => "policies",
            Self::View => "views",
        }
    }

    /// Parse from string (for deserialization)
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "schemas" => Some(Self::Schema),
            "enums" => Some(Self::Enum),
            "sequences" => Some(Self::Sequence),
            "roles" => Some(Self::Role),
            "tables" => Some(Self::Table),
            "columns" => Some(Self::Column),
            "indexes" => Some(Self::Index),
            "fks" => Some(Self::ForeignKey),
            "pks" => Some(Self::PrimaryKey),
            "uniques" => Some(Self::UniqueConstraint),
            "checks" => Some(Self::CheckConstraint),
            "policies" => Some(Self::Policy),
            "views" => Some(Self::View),
            _ => None,
        }
    }
}

impl std::str::FromStr for EntityKind {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s).ok_or(())
    }
}

impl fmt::Display for EntityKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Entity key types for unique identification
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum EntityKey {
    /// Simple name (e.g., table name, schema name)
    Simple(String),
    /// Two-part key (e.g., table.column)
    Composite2(String, String),
    /// Three-part key (e.g., schema.table.column for `PostgreSQL`)
    Composite3(String, String, String),
}

impl EntityKey {
    pub fn simple(name: impl Into<String>) -> Self {
        Self::Simple(name.into())
    }

    pub fn composite2(a: impl Into<String>, b: impl Into<String>) -> Self {
        Self::Composite2(a.into(), b.into())
    }

    pub fn composite3(a: impl Into<String>, b: impl Into<String>, c: impl Into<String>) -> Self {
        Self::Composite3(a.into(), b.into(), c.into())
    }
}

/// Trait for DDL entities.
///
/// All DDL entity types (Table, Column, Index, etc.) implement this trait.
/// The `KIND` constant enables compile-time entity type discrimination.
pub trait Entity: Clone + PartialEq {
    /// The entity kind (discriminator)
    const KIND: EntityKind;

    /// Get the unique key for this entity
    fn key(&self) -> EntityKey;

    /// Get the parent entity key (if this entity belongs to a parent)
    fn parent_key(&self) -> Option<EntityKey> {
        None
    }
}

// =============================================================================
// Versioned Snapshot
// =============================================================================

/// A snapshot with compile-time version tracking.
///
/// Wraps snapshot data with a phantom type parameter for the version.
/// This enables type-safe upgrade chains and prevents accidental version mixing.
#[derive(Clone, Debug)]
pub struct Versioned<Data, V: Version> {
    /// The actual snapshot data
    pub data: Data,
    /// Phantom marker for version
    _version: PhantomData<V>,
}

impl<Data, V: Version> Versioned<Data, V> {
    /// Create a new versioned wrapper
    pub const fn new(data: Data) -> Self {
        Self {
            data,
            _version: PhantomData,
        }
    }

    /// Get the version number
    #[must_use]
    pub const fn version() -> u32 {
        V::NUMBER
    }

    /// Get the version as a string
    #[must_use]
    pub fn version_str() -> String {
        version_str::<V>()
    }

    /// Unwrap to get the inner data
    pub fn into_inner(self) -> Data {
        self.data
    }
}

// =============================================================================
// Dialect Trait
// =============================================================================

/// Trait representing a database dialect.
///
/// This trait uses associated types to provide compile-time type safety across
/// dialect-specific operations. Both `MinVersion` and `LatestVersion` are
/// associated types implementing `Version`, enabling const operations.
///
/// # Example
/// ```rust
/// # let _ = r####"
/// fn process<D: Dialect>() {
///     // All const at compile time
///     const MIN: u32 = D::MinVersion::NUMBER;
///     const LATEST: u32 = D::LatestVersion::NUMBER;
///     println!("Processing {} (v{} to v{})", D::NAME, MIN, LATEST);
/// }
/// # "####;
/// ```
pub trait Dialect: Sized + 'static {
    /// Display name of the dialect
    const NAME: &'static str;

    /// Minimum supported snapshot version (as a type)
    type MinVersion: Version;

    /// Latest/current snapshot version (as a type)
    type LatestVersion: Version;

    /// Dialect-specific snapshot type
    type Snapshot: Clone + Default + std::fmt::Debug;

    /// Dialect-specific DDL collection type
    type DDL: Clone + Default + std::fmt::Debug;

    /// Dialect-specific entity enum (e.g., `SqliteEntity`, `PostgresEntity`)
    type Entity: Clone + std::fmt::Debug + PartialEq;

    /// Dialect-specific SQL generator
    type Generator: Default;

    /// Check if a version number is supported
    #[inline]
    #[must_use]
    fn is_supported_version(version: u32) -> bool {
        version >= Self::MinVersion::NUMBER && version <= Self::LatestVersion::NUMBER
    }

    /// Check if a version is the latest
    #[inline]
    #[must_use]
    fn is_latest_version(version: u32) -> bool {
        version == Self::LatestVersion::NUMBER
    }

    /// Check if a version needs upgrade
    #[inline]
    #[must_use]
    fn needs_upgrade_from(version: u32) -> bool {
        version < Self::LatestVersion::NUMBER && version >= Self::MinVersion::NUMBER
    }

    /// Diff two snapshots and generate SQL migration statements
    fn diff_and_generate(
        prev: &Self::Snapshot,
        cur: &Self::Snapshot,
        breakpoints: bool,
    ) -> MigrationResult;
}

/// Marker trait for compile-time upgrade path validation.
///
/// Implement this trait to declare that a dialect supports upgrading from
/// version `From` to version `To`. The compiler will enforce that only
/// valid upgrade paths are used.
///
/// # Example
/// ```rust
/// # let _ = r####"
/// // Declare SQLite can upgrade V5 -> V6
/// impl CanUpgrade<V5, V6> for Sqlite {}
/// impl CanUpgrade<V6, V7> for Sqlite {}
///
/// // This function only compiles if the upgrade is valid
/// fn upgrade<D, From, To>(data: Versioned<Data, From>) -> Versioned<Data, To>
/// where
///     D: Dialect + CanUpgrade<From, To>,
///     From: Version,
///     To: Version,
/// {
///     // ...
/// }
/// # "####;
/// ```
pub trait CanUpgrade<From: Version, To: Version>: Dialect {}

// =============================================================================
// Dialect Operations Trait
// =============================================================================

/// Migration result from diffing two snapshots
#[derive(Debug, Clone)]
pub struct MigrationResult {
    /// Generated SQL statements
    pub sql_statements: Vec<String>,
    /// Whether there are any changes
    pub has_changes: bool,
}

impl MigrationResult {
    /// Create an empty result (no changes)
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            sql_statements: Vec::new(),
            has_changes: false,
        }
    }

    /// Create a result with changes
    #[must_use]
    pub const fn with_changes(sql_statements: Vec<String>) -> Self {
        let has_changes = !sql_statements.is_empty();
        Self {
            sql_statements,
            has_changes,
        }
    }
}

/// `SQLite` dialect marker type
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Sqlite;

impl Sqlite {
    /// Minimum supported snapshot version (inherent alias)
    pub const MIN_VERSION: u32 = V5::NUMBER;
    /// Latest snapshot version (inherent alias)
    pub const LATEST_VERSION: u32 = V7::NUMBER;
}

impl Dialect for Sqlite {
    const NAME: &'static str = "sqlite";
    type MinVersion = V5;
    type LatestVersion = V7;
    type Snapshot = SQLiteSnapshot;
    type DDL = SQLiteDDL;
    type Entity = SqliteEntity;
    type Generator = SqliteGenerator;

    fn diff_and_generate(
        prev: &Self::Snapshot,
        cur: &Self::Snapshot,
        breakpoints: bool,
    ) -> MigrationResult {
        let diff = crate::sqlite::diff_snapshots(prev, cur);
        if !diff.has_changes() {
            return MigrationResult::empty();
        }
        let generator = SqliteGenerator::new().with_breakpoints(breakpoints);
        let sql = generator.generate_migration(&diff);
        MigrationResult::with_changes(sql)
    }
}

// Declare valid SQLite upgrade paths
impl CanUpgrade<V5, V6> for Sqlite {}
impl CanUpgrade<V6, V7> for Sqlite {}
// Transitive: V5 -> V7 requires going through V6
impl CanUpgrade<V5, V7> for Sqlite {}

/// `PostgreSQL` dialect marker type
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Postgres;

impl Postgres {
    /// Minimum supported snapshot version (inherent alias)
    pub const MIN_VERSION: u32 = V5::NUMBER;
    /// Latest snapshot version (inherent alias)
    pub const LATEST_VERSION: u32 = V8::NUMBER;
}

impl Dialect for Postgres {
    const NAME: &'static str = "postgresql";
    type MinVersion = V5;
    type LatestVersion = V8;
    type Snapshot = PostgresSnapshot;
    type DDL = PostgresDDL;
    type Entity = PostgresEntity;
    type Generator = PostgresGenerator;

    fn diff_and_generate(
        prev: &Self::Snapshot,
        cur: &Self::Snapshot,
        breakpoints: bool,
    ) -> MigrationResult {
        let diff = crate::postgres::diff_snapshots(&prev.ddl, &cur.ddl);
        if !diff.has_changes() {
            return MigrationResult::empty();
        }
        let generator = PostgresGenerator::new().with_breakpoints(breakpoints);
        let sql = generator.generate(&diff.diffs);
        MigrationResult::with_changes(sql)
    }
}

// Declare valid PostgreSQL upgrade paths
impl CanUpgrade<V5, V6> for Postgres {}
impl CanUpgrade<V6, V7> for Postgres {}
impl CanUpgrade<V7, V8> for Postgres {}
// Transitive paths
impl CanUpgrade<V5, V7> for Postgres {}
impl CanUpgrade<V5, V8> for Postgres {}
impl CanUpgrade<V6, V8> for Postgres {}

/// `MySQL` dialect marker type
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Mysql;

impl Mysql {
    /// Minimum supported snapshot version (inherent alias)
    pub const MIN_VERSION: u32 = V5::NUMBER;
    /// Latest snapshot version (inherent alias)
    pub const LATEST_VERSION: u32 = V5::NUMBER;
}

impl Dialect for Mysql {
    const NAME: &'static str = "mysql";
    type MinVersion = V5;
    type LatestVersion = V5;
    // MySQL not yet implemented - use placeholder types
    type Snapshot = ();
    type DDL = ();
    type Entity = ();
    type Generator = ();

    fn diff_and_generate(
        _prev: &Self::Snapshot,
        _cur: &Self::Snapshot,
        _breakpoints: bool,
    ) -> MigrationResult {
        unimplemented!("MySQL migrations not yet supported")
    }
}
// No upgrade paths for MySQL - already at latest

// =============================================================================
// Diff Types
// =============================================================================

/// Diff operation type
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DiffType {
    Create,
    Drop,
    Alter,
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;

    #[test]
    fn test_version_numbers() {
        assert_eq!(V5::NUMBER, 5);
        assert_eq!(V6::NUMBER, 6);
        assert_eq!(V7::NUMBER, 7);
        assert_eq!(V8::NUMBER, 8);
    }

    #[test]
    fn test_version_str() {
        assert_eq!(version_str::<V5>(), "5");
        assert_eq!(version_str::<V7>(), "7");
    }

    #[test]
    fn test_entity_kind_str() {
        assert_eq!(EntityKind::Table.as_str(), "tables");
        assert_eq!(EntityKind::Column.as_str(), "columns");
        assert_eq!(EntityKind::ForeignKey.as_str(), "fks");
    }

    #[test]
    fn test_entity_kind_parse() {
        assert_eq!(EntityKind::from_str("tables"), Ok(EntityKind::Table));
        assert_eq!(EntityKind::from_str("columns"), Ok(EntityKind::Column));
        assert_eq!(EntityKind::from_str("invalid"), Err(()));
    }

    #[test]
    fn test_versioned_snapshot() {
        #[derive(Clone, Debug)]
        struct TestData {
            value: i32,
        }

        let versioned: Versioned<TestData, V7> = Versioned::new(TestData { value: 42 });
        assert_eq!(Versioned::<TestData, V7>::version(), 7);
        assert_eq!(versioned.data.value, 42);
    }

    #[test]
    fn test_dialect_version_info() {
        // SQLite: V5 to V7 - using inherent consts (no trait needed)
        assert_eq!(Sqlite::MIN_VERSION, 5);
        assert_eq!(Sqlite::LATEST_VERSION, 7);

        // PostgreSQL: V5 to V8
        assert_eq!(Postgres::MIN_VERSION, 5);
        assert_eq!(Postgres::LATEST_VERSION, 8);

        // MySQL: V5 only
        assert_eq!(Mysql::MIN_VERSION, 5);
        assert_eq!(Mysql::LATEST_VERSION, 5);
    }

    #[test]
    fn test_dialect_version_checks() {
        // SQLite checks
        assert!(Sqlite::is_supported_version(5));
        assert!(Sqlite::is_supported_version(6));
        assert!(Sqlite::is_supported_version(7));
        assert!(!Sqlite::is_supported_version(4));
        assert!(!Sqlite::is_supported_version(8));

        assert!(Sqlite::needs_upgrade_from(5));
        assert!(Sqlite::needs_upgrade_from(6));
        assert!(!Sqlite::needs_upgrade_from(7));

        assert!(!Sqlite::is_latest_version(5));
        assert!(Sqlite::is_latest_version(7));
    }

    #[test]
    fn test_can_upgrade_compiles() {
        // These calls verify that the CanUpgrade impls exist
        // If they don't, this test won't compile
        assert_can_upgrade::<Sqlite, V5, V6>();
        assert_can_upgrade::<Sqlite, V6, V7>();
        assert_can_upgrade::<Sqlite, V5, V7>(); // Transitive

        assert_can_upgrade::<Postgres, V5, V6>();
        assert_can_upgrade::<Postgres, V6, V7>();
        assert_can_upgrade::<Postgres, V7, V8>();
        assert_can_upgrade::<Postgres, V5, V8>(); // Transitive
    }

    // This test demonstrates a compile-time error if uncommented:
    // #[test]
    // fn test_invalid_upgrade_fails() {
    //     // This would fail to compile because Sqlite doesn't impl CanUpgrade<V5, V8>
    //     assert_can_upgrade::<Sqlite, V5, V8>();
    // }
}