waypoint-core 0.8.1

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
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
//! Parse `-- waypoint:*` comment directives from SQL file headers.
//!
//! Directives appear as SQL comments at the top of migration files:
//! ```sql
//! -- waypoint:env dev,staging
//! -- waypoint:depends V3,V5
//! CREATE TABLE ...
//! ```

/// Parsed directives from a migration file header.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MigrationDirectives {
    /// Dependencies: `-- waypoint:depends V3,V5` (V prefix is stripped)
    pub depends: Vec<String>,
    /// Environment tags: `-- waypoint:env dev,staging`
    pub env: Vec<String>,
    /// Preconditions: `-- waypoint:require table_exists("users")`
    pub require: Vec<String>,
    /// Postconditions: `-- waypoint:ensure column_exists("users", "email")`
    pub ensure: Vec<String>,
    /// Safety override: `-- waypoint:safety-override` bypasses DANGER blocks
    pub safety_override: bool,
}

/// Scope of an inline lint suppression.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum LintIgnoreScope {
    /// `-- waypoint:lint-ignore` — applies to the next statement only.
    NextStatement,
    /// `-- waypoint:lint-ignore-file` — applies to the whole file.
    File,
}

impl std::fmt::Display for LintIgnoreScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LintIgnoreScope::NextStatement => write!(f, "statement"),
            LintIgnoreScope::File => write!(f, "file"),
        }
    }
}

/// An inline `-- waypoint:lint-ignore[-file]` directive.
///
/// ```sql
/// -- waypoint:lint-ignore E001 reason="backfilled by the ceremony writer"
/// ALTER TABLE t ADD COLUMN c int NOT NULL;
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintIgnoreDirective {
    /// Whether this suppresses the next statement or the whole file.
    pub scope: LintIgnoreScope,
    /// Rule IDs named by the directive, uppercased. Never empty for a valid
    /// directive; an empty list means the directive named no rules.
    pub rules: Vec<String>,
    /// The mandatory `reason=...` value, if one was supplied.
    pub reason: Option<String>,
    /// 1-based line number of the directive.
    pub line: usize,
    /// Byte offset of the start of the directive's line.
    pub offset: usize,
}

/// Parse every `-- waypoint:lint-ignore[-file]` directive in a migration file.
///
/// Unlike the header directives, these may appear anywhere in the file, but
/// only on lines that contain nothing but the comment — a trailing comment on
/// a line of SQL is ignored, because its scope would be ambiguous.
pub fn parse_lint_ignores(sql: &str) -> Vec<LintIgnoreDirective> {
    let mut out = Vec::new();
    let mut offset = 0usize;

    // split('\n') rather than lines() so byte offsets stay exact on CRLF input.
    for (idx, line) in sql.split('\n').enumerate() {
        let line_offset = offset;
        offset += line.len() + 1;

        let trimmed = line.trim();
        let Some(body) = trimmed.strip_prefix("--") else {
            continue;
        };
        let body = body.trim();

        let (scope, rest) =
            if let Some(rest) = strip_directive_prefix(body, "waypoint:lint-ignore-file") {
                (LintIgnoreScope::File, rest)
            } else if let Some(rest) = strip_directive_prefix(body, "waypoint:lint-ignore") {
                (LintIgnoreScope::NextStatement, rest)
            } else {
                continue;
            };

        let (rules_part, reason) = split_reason(rest);
        let rules = rules_part
            .split([',', ' ', '\t'])
            .map(|r| r.trim())
            .filter(|r| !r.is_empty())
            .map(|r| r.to_uppercase())
            .collect();

        out.push(LintIgnoreDirective {
            scope,
            rules,
            reason,
            line: idx + 1,
            offset: line_offset,
        });
    }

    out
}

/// Split a directive tail into its rule list and its `reason=` value.
///
/// The reason runs to the end of the line and may be quoted with `"` or `'`.
fn split_reason(rest: &str) -> (&str, Option<String>) {
    let lower = rest.to_lowercase();
    let Some(pos) = lower.find("reason") else {
        return (rest, None);
    };
    // Require `reason` to be a standalone word followed by `=` or `:`.
    let after = rest[pos + "reason".len()..].trim_start();
    let Some(value) = after.strip_prefix('=').or_else(|| after.strip_prefix(':')) else {
        return (rest, None);
    };
    let value = value.trim();
    let value = value
        .strip_prefix('"')
        .and_then(|v| v.strip_suffix('"'))
        .or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
        .unwrap_or(value)
        .trim();

    let reason = if value.is_empty() {
        None
    } else {
        Some(value.to_string())
    };
    (&rest[..pos], reason)
}

/// Strip a directive prefix, ensuring the prefix is followed by whitespace or end of string.
/// This prevents prefix collisions like "waypoint:env" matching "waypoint:environment".
fn strip_directive_prefix<'a>(line: &'a str, prefix: &str) -> Option<&'a str> {
    if let Some(rest) = line.strip_prefix(prefix) {
        if rest.is_empty() || rest.starts_with(char::is_whitespace) {
            Some(rest.trim())
        } else {
            None
        }
    } else {
        None
    }
}

/// Parse `-- waypoint:*` directives from SQL content.
///
/// Only parses comment lines (`--`) at the top of the file.
/// Stops at the first non-empty, non-comment line.
pub fn parse_directives(sql: &str) -> MigrationDirectives {
    let mut directives = MigrationDirectives::default();

    for line in sql.lines() {
        let trimmed = line.trim();

        // Skip empty lines at the top
        if trimmed.is_empty() {
            continue;
        }

        // Only process SQL comment lines
        if !trimmed.starts_with("--") {
            break;
        }

        let comment_body = trimmed.strip_prefix("--").unwrap().trim();

        if let Some(value) = strip_directive_prefix(comment_body, "waypoint:depends") {
            for item in value.split(',') {
                let item = item.trim();
                if !item.is_empty() {
                    // Strip optional V prefix
                    let version = item.strip_prefix('V').unwrap_or(item);
                    directives.depends.push(version.to_string());
                }
            }
        } else if let Some(value) = strip_directive_prefix(comment_body, "waypoint:env") {
            for item in value.split(',') {
                let item = item.trim();
                if !item.is_empty() {
                    directives.env.push(item.to_string());
                }
            }
        } else if let Some(value) = strip_directive_prefix(comment_body, "waypoint:require") {
            if !value.is_empty() {
                directives.require.push(value.to_string());
            }
        } else if let Some(value) = strip_directive_prefix(comment_body, "waypoint:ensure") {
            if !value.is_empty() {
                directives.ensure.push(value.to_string());
            }
        } else if comment_body.trim() == "waypoint:safety-override" {
            directives.safety_override = true;
        } else if let Some(unknown) = unrecognised_directive(comment_body) {
            // A misspelled directive used to be indistinguishable from an
            // ordinary comment. `-- waypoint:requires table_exists("x")` — the
            // plural is an easy slip — silently dropped the precondition, and
            // the migration then ran without the guard the author wrote.
            log::warn!(
                "Unrecognised directive '-- waypoint:{}' — this line is being treated as an \
                 ordinary comment and has no effect. Known directives: depends, env, require, \
                 ensure, safety-override, lint-ignore, lint-ignore-file.",
                unknown
            );
        }
    }

    directives
}

/// The directive name in `comment_body`, if it looks like a `waypoint:`
/// directive but is not one we know.
///
/// Returns `None` for ordinary comments and for the `lint-ignore` family, which
/// [`parse_lint_ignores`] handles in its own pass over the file.
fn unrecognised_directive(comment_body: &str) -> Option<&str> {
    let name = comment_body.strip_prefix("waypoint:")?;
    let head = name
        .split_whitespace()
        .next()
        .unwrap_or(name)
        .trim_end_matches(':');
    if head.is_empty() || matches!(head, "lint-ignore" | "lint-ignore-file") {
        return None;
    }
    Some(head)
}

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

    #[test]
    fn test_parse_env_directive() {
        let sql = "-- waypoint:env dev,staging\nCREATE TABLE foo();";
        let d = parse_directives(sql);
        assert_eq!(d.env, vec!["dev", "staging"]);
        assert!(d.depends.is_empty());
    }

    #[test]
    fn test_parse_depends_directive() {
        let sql = "-- waypoint:depends V3,V5\nCREATE TABLE foo();";
        let d = parse_directives(sql);
        assert_eq!(d.depends, vec!["3", "5"]);
        assert!(d.env.is_empty());
    }

    #[test]
    fn test_parse_depends_without_v_prefix() {
        let sql = "-- waypoint:depends 3,5\nCREATE TABLE foo();";
        let d = parse_directives(sql);
        assert_eq!(d.depends, vec!["3", "5"]);
    }

    #[test]
    fn test_parse_multiple_directives() {
        let sql = "-- waypoint:env dev\n-- waypoint:depends V1,V2\nCREATE TABLE foo();";
        let d = parse_directives(sql);
        assert_eq!(d.env, vec!["dev"]);
        assert_eq!(d.depends, vec!["1", "2"]);
    }

    #[test]
    fn test_stops_at_non_comment_line() {
        let sql = "-- waypoint:env dev\nCREATE TABLE foo();\n-- waypoint:env prod\n";
        let d = parse_directives(sql);
        assert_eq!(d.env, vec!["dev"]);
    }

    #[test]
    fn test_empty_sql() {
        let d = parse_directives("");
        assert!(d.env.is_empty());
        assert!(d.depends.is_empty());
    }

    #[test]
    fn test_no_directives() {
        let sql = "-- Regular comment\nCREATE TABLE foo();";
        let d = parse_directives(sql);
        assert!(d.env.is_empty());
        assert!(d.depends.is_empty());
    }

    #[test]
    fn test_skips_leading_blank_lines() {
        let sql = "\n\n-- waypoint:env prod\nCREATE TABLE foo();";
        let d = parse_directives(sql);
        assert_eq!(d.env, vec!["prod"]);
    }

    #[test]
    fn test_whitespace_in_values() {
        let sql = "-- waypoint:env  dev , staging , prod \nCREATE TABLE foo();";
        let d = parse_directives(sql);
        assert_eq!(d.env, vec!["dev", "staging", "prod"]);
    }

    #[test]
    fn test_no_env_runs_everywhere() {
        let d = MigrationDirectives::default();
        assert!(d.env.is_empty());
    }

    #[test]
    fn test_parse_require_directive() {
        let sql = "-- waypoint:require table_exists(\"users\")\nCREATE TABLE foo();";
        let d = parse_directives(sql);
        assert_eq!(d.require, vec!["table_exists(\"users\")"]);
    }

    #[test]
    fn test_parse_ensure_directive() {
        let sql = "-- waypoint:ensure column_exists(\"users\", \"email\")\nALTER TABLE users ADD COLUMN email TEXT;";
        let d = parse_directives(sql);
        assert_eq!(d.ensure, vec!["column_exists(\"users\", \"email\")"]);
    }

    #[test]
    fn test_parse_multiple_guards() {
        let sql = "-- waypoint:require table_exists(\"users\")\n-- waypoint:require NOT column_exists(\"users\", \"email\")\n-- waypoint:ensure column_exists(\"users\", \"email\")\nALTER TABLE users ADD COLUMN email TEXT;";
        let d = parse_directives(sql);
        assert_eq!(d.require.len(), 2);
        assert_eq!(d.ensure.len(), 1);
    }

    #[test]
    fn test_parse_lint_ignore_next_statement() {
        let sql = "-- waypoint:lint-ignore E001 reason=\"empty table at deploy time\"\nALTER TABLE t ADD COLUMN a int NOT NULL;";
        let d = parse_lint_ignores(sql);
        assert_eq!(d.len(), 1);
        assert_eq!(d[0].scope, LintIgnoreScope::NextStatement);
        assert_eq!(d[0].rules, vec!["E001"]);
        assert_eq!(d[0].reason.as_deref(), Some("empty table at deploy time"));
        assert_eq!(d[0].line, 1);
        assert_eq!(d[0].offset, 0);
    }

    #[test]
    fn test_parse_lint_ignore_file_scope_and_multiple_rules() {
        let sql = "-- header\n-- waypoint:lint-ignore-file E001,W004 reason=legacy migration\nDROP TABLE t;";
        let d = parse_lint_ignores(sql);
        assert_eq!(d.len(), 1);
        assert_eq!(d[0].scope, LintIgnoreScope::File);
        assert_eq!(d[0].rules, vec!["E001", "W004"]);
        assert_eq!(d[0].reason.as_deref(), Some("legacy migration"));
        assert_eq!(d[0].line, 2);
    }

    #[test]
    fn test_parse_lint_ignore_without_reason() {
        let d = parse_lint_ignores("-- waypoint:lint-ignore E001\nSELECT 1;");
        assert_eq!(d.len(), 1);
        assert!(d[0].reason.is_none());
        assert_eq!(d[0].rules, vec!["E001"]);
    }

    #[test]
    fn test_parse_lint_ignore_without_rules() {
        let d = parse_lint_ignores("-- waypoint:lint-ignore reason=because\nSELECT 1;");
        assert_eq!(d.len(), 1);
        assert!(d[0].rules.is_empty());
        assert_eq!(d[0].reason.as_deref(), Some("because"));
    }

    #[test]
    fn test_parse_lint_ignore_offsets_are_exact() {
        let sql = "SELECT 1;\n-- waypoint:lint-ignore E001 reason=x\nSELECT 2;";
        let d = parse_lint_ignores(sql);
        assert_eq!(d[0].line, 2);
        assert_eq!(&sql[d[0].offset..d[0].offset + 2], "--");
    }

    #[test]
    fn test_trailing_comment_is_not_a_directive() {
        // Scope would be ambiguous, so only comment-only lines count.
        let d = parse_lint_ignores("SELECT 1; -- waypoint:lint-ignore E001 reason=x\n");
        assert!(d.is_empty());
    }

    #[test]
    fn test_lint_ignore_prefix_does_not_collide() {
        let d = parse_lint_ignores("-- waypoint:lint-ignore-file E001 reason=x\n");
        assert_eq!(d[0].scope, LintIgnoreScope::File);
        assert_eq!(d[0].rules, vec!["E001"]);
    }

    #[test]
    fn test_parse_safety_override() {
        let sql = "-- waypoint:safety-override\nALTER TABLE large_table ADD COLUMN foo TEXT;";
        let d = parse_directives(sql);
        assert!(d.safety_override);
    }

    #[test]
    fn test_safety_override_default_false() {
        let sql = "CREATE TABLE foo();";
        let d = parse_directives(sql);
        assert!(!d.safety_override);
    }

    #[test]
    fn test_env_prefix_does_not_match_ensure() {
        let sql = "-- waypoint:ensure column_exists(\"users\", \"email\")\nALTER TABLE users ADD COLUMN email TEXT;";
        let d = parse_directives(sql);
        // Should be parsed as ensure, not env
        assert!(d.env.is_empty());
        assert_eq!(d.ensure.len(), 1);
    }

    #[test]
    fn test_directive_prefix_boundary() {
        // "waypoint:environment" should NOT match "waypoint:env"
        let sql = "-- waypoint:environment prod\nCREATE TABLE foo();";
        let d = parse_directives(sql);
        // Should NOT be parsed as env directive since "waypoint:environment" != "waypoint:env"
        assert!(d.env.is_empty());
    }

    #[test]
    fn test_parse_empty_depends() {
        let sql = "-- waypoint:depends\nCREATE TABLE foo();";
        let d = parse_directives(sql);
        assert!(d.depends.is_empty());
    }

    #[test]
    fn test_parse_empty_env() {
        let sql = "-- waypoint:env\nCREATE TABLE foo();";
        let d = parse_directives(sql);
        assert!(d.env.is_empty());
    }

    #[test]
    fn test_parse_require_with_special_chars() {
        let sql = "-- waypoint:require table_exists(\"my-table\")\nCREATE TABLE foo();";
        let d = parse_directives(sql);
        assert_eq!(d.require, vec!["table_exists(\"my-table\")"]);
    }

    #[test]
    fn test_unrecognised_directive_detects_typos_but_not_ordinary_comments() {
        // Typos in directive names used to be silently indistinguishable from
        // a plain comment, so a mistyped `require` dropped the precondition.
        assert_eq!(
            unrecognised_directive("waypoint:requires foo()"),
            Some("requires")
        );
        assert_eq!(
            unrecognised_directive("waypoint:saftey-override"),
            Some("saftey-override")
        );
        assert_eq!(
            unrecognised_directive("waypoint:ensures x"),
            Some("ensures")
        );

        // Known directives and ordinary comments are not flagged.
        assert_eq!(
            unrecognised_directive("waypoint:lint-ignore E001 reason=\"x\""),
            None
        );
        assert_eq!(
            unrecognised_directive("waypoint:lint-ignore-file E001 reason=\"x\""),
            None
        );
        assert_eq!(unrecognised_directive("just a normal comment"), None);
        assert_eq!(unrecognised_directive("waypoint is a tool"), None);
    }

    #[test]
    fn test_known_directives_still_parse_and_are_not_warned_about() {
        let sql = "-- waypoint:require table_exists(\"a\")\n\
                   -- waypoint:ensure table_exists(\"b\")\n\
                   -- waypoint:env prod\n\
                   -- waypoint:depends V1\n\
                   -- waypoint:safety-override\n\
                   SELECT 1;";
        let d = parse_directives(sql);
        assert_eq!(d.require.len(), 1);
        assert_eq!(d.ensure.len(), 1);
        assert_eq!(d.env, vec!["prod"]);
        assert_eq!(d.depends, vec!["1"]);
        assert!(d.safety_override);
        // None of these should look unrecognised.
        for body in [
            "waypoint:require x",
            "waypoint:ensure x",
            "waypoint:env prod",
            "waypoint:depends V1",
            "waypoint:safety-override",
        ] {
            let head = unrecognised_directive(body);
            assert!(
                matches!(
                    head,
                    Some("require" | "ensure" | "env" | "depends" | "safety-override")
                ),
                "known directive {body:?} classified as {head:?}"
            );
        }
    }
}