waypoint-core 0.4.0

Lightweight, Flyway-compatible SQL migration library for PostgreSQL and MySQL
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
//! Migration file parsing, scanning, and types.
//!
//! Supports versioned (`V{version}__{desc}.sql`) and repeatable (`R__{desc}.sql`) migrations.

use std::cmp::Ordering;
use std::fmt;
use std::sync::LazyLock;

use regex_lite::Regex;

use crate::checksum::calculate_checksum;
use crate::directive::{self, MigrationDirectives};
use crate::error::{Result, WaypointError};
use crate::hooks;

static VERSIONED_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^V([\d._]+)__(.+)$").unwrap());
static UNDO_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^U([\d._]+)__(.+)$").unwrap());
static REPEATABLE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^R__(.+)$").unwrap());

/// A parsed migration version, supporting dotted numeric segments (e.g., "1.2.3").
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct MigrationVersion {
    /// Parsed numeric segments of the version (e.g., `[1, 2, 3]` for `"1.2.3"`).
    pub segments: Vec<u64>,
    /// Original version string as it appeared in the filename.
    pub raw: String,
}

impl MigrationVersion {
    /// Parse a version string like `"1.2.3"` or `"1_2"` into segments.
    pub fn parse(raw: &str) -> Result<Self> {
        if raw.is_empty() {
            return Err(WaypointError::MigrationParseError(
                "Version string is empty".to_string(),
            ));
        }

        // Support both "." and "_" as segment separators
        let segments: std::result::Result<Vec<u64>, _> =
            raw.split(['.', '_']).map(|s| s.parse::<u64>()).collect();

        let segments = segments.map_err(|e| {
            WaypointError::MigrationParseError(format!(
                "Invalid version segment in '{}': {}",
                raw, e
            ))
        })?;

        Ok(MigrationVersion {
            segments,
            raw: raw.to_string(),
        })
    }
}

impl Ord for MigrationVersion {
    fn cmp(&self, other: &Self) -> Ordering {
        let max_len = self.segments.len().max(other.segments.len());
        for i in 0..max_len {
            let a = self.segments.get(i).copied().unwrap_or(0);
            let b = other.segments.get(i).copied().unwrap_or(0);
            match a.cmp(&b) {
                Ordering::Equal => continue,
                ord => return ord,
            }
        }
        Ordering::Equal
    }
}

impl PartialOrd for MigrationVersion {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

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

/// The type of a migration (for display/serialization).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MigrationType {
    /// V{version}__{description}.sql
    Versioned,
    /// R__{description}.sql
    Repeatable,
    /// U{version}__{description}.sql
    Undo,
}

impl fmt::Display for MigrationType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MigrationType::Versioned => write!(f, "SQL"),
            MigrationType::Repeatable => write!(f, "SQL_REPEATABLE"),
            MigrationType::Undo => write!(f, "UNDO_SQL"),
        }
    }
}

/// Type-safe encoding of the migration variant.
///
/// Versioned migrations always have a version; repeatable migrations never do.
/// This eliminates the `Option<MigrationVersion>` + `MigrationType` redundancy.
#[derive(Debug, Clone)]
pub enum MigrationKind {
    /// A versioned migration with an associated version number.
    Versioned(MigrationVersion),
    /// A repeatable migration that is re-applied whenever its checksum changes.
    Repeatable,
    /// An undo migration that reverses a specific versioned migration.
    Undo(MigrationVersion),
}

/// A migration file discovered on disk.
#[derive(Debug, Clone)]
pub struct ResolvedMigration {
    /// Whether this is a versioned, repeatable, or undo migration (with version if applicable).
    pub kind: MigrationKind,
    /// Human-readable description extracted from the filename.
    pub description: String,
    /// Original filename of the migration script (e.g., `V1__Create_users.sql`).
    pub script: String,
    /// CRC32 checksum of the migration SQL content.
    pub checksum: i32,
    /// Raw SQL content of the migration file.
    pub sql: String,
    /// Parsed directives from SQL comments (e.g., `@depends`, `@environment`).
    pub directives: MigrationDirectives,
}

impl ResolvedMigration {
    /// Get the version if this is a versioned or undo migration.
    pub fn version(&self) -> Option<&MigrationVersion> {
        match &self.kind {
            MigrationKind::Versioned(v) | MigrationKind::Undo(v) => Some(v),
            MigrationKind::Repeatable => None,
        }
    }

    /// Get the migration type for display/serialization.
    pub fn migration_type(&self) -> MigrationType {
        match &self.kind {
            MigrationKind::Versioned(_) => MigrationType::Versioned,
            MigrationKind::Repeatable => MigrationType::Repeatable,
            MigrationKind::Undo(_) => MigrationType::Undo,
        }
    }

    /// Whether this is a versioned migration.
    pub fn is_versioned(&self) -> bool {
        matches!(&self.kind, MigrationKind::Versioned(_))
    }

    /// Whether this is an undo migration.
    pub fn is_undo(&self) -> bool {
        matches!(&self.kind, MigrationKind::Undo(_))
    }
}

/// Parse a migration filename into its components.
///
/// Expected patterns:
///   V{version}__{description}.sql  — versioned migration
///   R__{description}.sql           — repeatable migration
pub fn parse_migration_filename(filename: &str) -> Result<(MigrationKind, String)> {
    // Strip .sql extension
    let stem = filename.strip_suffix(".sql").ok_or_else(|| {
        WaypointError::MigrationParseError(format!(
            "Migration file '{}' does not have .sql extension",
            filename
        ))
    })?;

    if let Some(caps) = VERSIONED_RE.captures(stem) {
        let version_str = caps.get(1).unwrap().as_str();
        let description = caps.get(2).unwrap().as_str().replace('_', " ");
        let version = MigrationVersion::parse(version_str)?;
        Ok((MigrationKind::Versioned(version), description))
    } else if let Some(caps) = UNDO_RE.captures(stem) {
        let version_str = caps.get(1).unwrap().as_str();
        let description = caps.get(2).unwrap().as_str().replace('_', " ");
        let version = MigrationVersion::parse(version_str)?;
        Ok((MigrationKind::Undo(version), description))
    } else if let Some(caps) = REPEATABLE_RE.captures(stem) {
        let description = caps.get(1).unwrap().as_str().replace('_', " ");
        Ok((MigrationKind::Repeatable, description))
    } else {
        Err(WaypointError::MigrationParseError(format!(
            "Migration file '{}' does not match V{{version}}__{{description}}.sql, U{{version}}__{{description}}.sql, or R__{{description}}.sql pattern",
            filename
        )))
    }
}

/// Scan migration locations for SQL files and parse them into ResolvedMigrations.
pub fn scan_migrations(locations: &[std::path::PathBuf]) -> Result<Vec<ResolvedMigration>> {
    let mut migrations = Vec::new();

    for location in locations {
        if !location.exists() {
            log::warn!("Migration location does not exist: {}", location.display());
            continue;
        }

        let entries = std::fs::read_dir(location).map_err(|e| {
            WaypointError::IoError(std::io::Error::new(
                e.kind(),
                format!(
                    "Failed to read migration directory '{}': {}",
                    location.display(),
                    e
                ),
            ))
        })?;

        for entry in entries {
            let entry = entry?;
            let path = entry.path();

            if !path.is_file() {
                continue;
            }

            let filename = match path.file_name().and_then(|n| n.to_str()) {
                Some(name) => name.to_string(),
                None => continue,
            };

            // Skip non-SQL files
            if !filename.ends_with(".sql") {
                continue;
            }

            // Skip hook callback files
            if hooks::is_hook_file(&filename) {
                continue;
            }

            // Skip files that don't start with V, U, or R
            if !filename.starts_with('V')
                && !filename.starts_with('U')
                && !filename.starts_with('R')
            {
                continue;
            }

            let (kind, description) = match parse_migration_filename(&filename) {
                Ok(result) => result,
                Err(e) => {
                    log::warn!("Skipping malformed migration file '{}': {}", filename, e);
                    continue;
                }
            };
            let sql = std::fs::read_to_string(&path)?;
            let checksum = calculate_checksum(&sql);
            let directives = directive::parse_directives(&sql);

            migrations.push(ResolvedMigration {
                kind,
                description,
                script: filename,
                checksum,
                sql,
                directives,
            });
        }
    }

    // Sort: versioned by version, then undo by version, then repeatable by description
    migrations.sort_by(|a, b| {
        // Order groups: Versioned first, then Undo, then Repeatable
        fn group_order(kind: &MigrationKind) -> u8 {
            match kind {
                MigrationKind::Versioned(_) => 0,
                MigrationKind::Undo(_) => 1,
                MigrationKind::Repeatable => 2,
            }
        }
        let ga = group_order(&a.kind);
        let gb = group_order(&b.kind);
        if ga != gb {
            return ga.cmp(&gb);
        }
        match (&a.kind, &b.kind) {
            (MigrationKind::Versioned(va), MigrationKind::Versioned(vb)) => va.cmp(vb),
            (MigrationKind::Undo(va), MigrationKind::Undo(vb)) => va.cmp(vb),
            (MigrationKind::Repeatable, MigrationKind::Repeatable) => {
                a.description.cmp(&b.description)
            }
            _ => Ordering::Equal,
        }
    });

    // Detect duplicate versions
    let mut seen_versions: std::collections::HashSet<String> = std::collections::HashSet::new();
    for m in &migrations {
        if let Some(v) = m.version() {
            let prefix = if m.is_versioned() { "V" } else { "U" };
            let key = format!("{}{}", prefix, v.raw);
            if !seen_versions.insert(key) {
                return Err(WaypointError::ValidationFailed(format!(
                    "Duplicate migration version '{}' found in file '{}'. Each version must be unique.",
                    v.raw, m.script
                )));
            }
        }
    }

    Ok(migrations)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_version_parsing() {
        let v = MigrationVersion::parse("1").unwrap();
        assert_eq!(v.segments, vec![1]);

        let v = MigrationVersion::parse("1.2.3").unwrap();
        assert_eq!(v.segments, vec![1, 2, 3]);

        let v = MigrationVersion::parse("1_2_3").unwrap();
        assert_eq!(v.segments, vec![1, 2, 3]);
    }

    #[test]
    fn test_version_ordering() {
        let v1 = MigrationVersion::parse("1").unwrap();
        let v2 = MigrationVersion::parse("2").unwrap();
        let v1_9 = MigrationVersion::parse("1.9").unwrap();
        let v1_10 = MigrationVersion::parse("1.10").unwrap();
        let v1_2 = MigrationVersion::parse("1.2").unwrap();
        let v1_2_0 = MigrationVersion::parse("1.2.0").unwrap();

        assert!(v1 < v2);
        assert!(v1_9 < v1_10); // Numeric, not string comparison
        assert!(v1_2 < v1_9);
        assert_eq!(v1_2.cmp(&v1_2_0), Ordering::Equal); // Trailing zeros are equal
    }

    #[test]
    fn test_version_parse_error() {
        assert!(MigrationVersion::parse("").is_err());
        assert!(MigrationVersion::parse("abc").is_err());
    }

    #[test]
    fn test_parse_versioned_filename() {
        let (kind, desc) = parse_migration_filename("V1__Create_users.sql").unwrap();
        match kind {
            MigrationKind::Versioned(v) => assert_eq!(v.segments, vec![1]),
            _ => panic!("Expected Versioned"),
        }
        assert_eq!(desc, "Create users");
    }

    #[test]
    fn test_parse_versioned_dotted_version() {
        let (kind, desc) = parse_migration_filename("V1.2.3__Add_column.sql").unwrap();
        match kind {
            MigrationKind::Versioned(v) => assert_eq!(v.segments, vec![1, 2, 3]),
            _ => panic!("Expected Versioned"),
        }
        assert_eq!(desc, "Add column");
    }

    #[test]
    fn test_parse_repeatable_filename() {
        let (kind, desc) = parse_migration_filename("R__Create_user_view.sql").unwrap();
        assert!(matches!(kind, MigrationKind::Repeatable));
        assert_eq!(desc, "Create user view");
    }

    #[test]
    fn test_parse_invalid_filename() {
        assert!(parse_migration_filename("random.sql").is_err());
        assert!(parse_migration_filename("V1_missing_separator.sql").is_err());
        assert!(parse_migration_filename("V1__no_ext").is_err());
    }

    #[test]
    fn test_parse_undo_filename() {
        let (kind, desc) = parse_migration_filename("U1__Create_users.sql").unwrap();
        match kind {
            MigrationKind::Undo(v) => assert_eq!(v.segments, vec![1]),
            _ => panic!("Expected Undo"),
        }
        assert_eq!(desc, "Create users");
    }

    #[test]
    fn test_parse_undo_dotted_version() {
        let (kind, desc) = parse_migration_filename("U1.2.3__Add_column.sql").unwrap();
        match kind {
            MigrationKind::Undo(v) => assert_eq!(v.segments, vec![1, 2, 3]),
            _ => panic!("Expected Undo"),
        }
        assert_eq!(desc, "Add column");
    }

    #[test]
    fn test_malformed_filename_is_skipped() {
        // This tests the parse function itself
        assert!(parse_migration_filename("random.sql").is_err());
        assert!(parse_migration_filename("V1_missing_separator.sql").is_err());
    }

    #[test]
    fn test_undo_is_undo() {
        let m = ResolvedMigration {
            kind: MigrationKind::Undo(MigrationVersion::parse("1").unwrap()),
            description: "test".to_string(),
            script: "U1__test.sql".to_string(),
            checksum: 0,
            sql: String::new(),
            directives: MigrationDirectives::default(),
        };
        assert!(m.is_undo());
        assert!(!m.is_versioned());
        assert_eq!(m.migration_type(), MigrationType::Undo);
        assert_eq!(m.migration_type().to_string(), "UNDO_SQL");
    }
}