vespertide-loader 0.1.58

Loads migrations and models from filesystem
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
use std::env;
use std::fs;
use std::path::PathBuf;

use anyhow::{Context, Result};
use vespertide_config::VespertideConfig;
use vespertide_core::MigrationPlan;
use vespertide_planner::validate_migration_plan;

/// Load all migration plans from the migrations directory, sorted by version.
pub fn load_migrations(config: &VespertideConfig) -> Result<Vec<MigrationPlan>> {
    let migrations_dir = config.migrations_dir();
    if !migrations_dir.exists() {
        return Ok(Vec::new());
    }

    let mut plans = Vec::new();
    let entries = fs::read_dir(migrations_dir).context("read migrations directory")?;

    for entry in entries {
        let entry = entry.context("read directory entry")?;
        let path = entry.path();
        if path.is_file() {
            let ext = path.extension().and_then(|s| s.to_str());
            if ext == Some("json") || ext == Some("yaml") || ext == Some("yml") {
                let content = fs::read_to_string(&path)
                    .with_context(|| format!("read migration file: {}", path.display()))?;

                let plan: MigrationPlan = if ext == Some("json") {
                    serde_json::from_str(&content)
                        .with_context(|| format!("parse migration: {}", path.display()))?
                } else {
                    serde_yaml::from_str(&content)
                        .with_context(|| format!("parse migration: {}", path.display()))?
                };

                // Validate the migration plan
                validate_migration_plan(&plan)
                    .with_context(|| format!("validate migration: {}", path.display()))?;

                plans.push(plan);
            }
        }
    }

    // Sort by version number
    plans.sort_by_key(|p| p.version);
    Ok(plans)
}

/// Load migrations from a specific directory (for compile-time use in macros).
pub fn load_migrations_from_dir(
    project_root: Option<PathBuf>,
) -> Result<Vec<MigrationPlan>, Box<dyn std::error::Error>> {
    // Locate project root from CARGO_MANIFEST_DIR or use provided path
    let project_root = if let Some(root) = project_root {
        root
    } else {
        let manifest_dir = env::var("CARGO_MANIFEST_DIR")
            .map_err(|_| "CARGO_MANIFEST_DIR environment variable not set")?;
        PathBuf::from(manifest_dir)
    };

    // Read vespertide.json or use defaults
    let config = crate::config::load_config_or_default(Some(project_root.clone()))
        .map_err(|e| format!("Failed to load config: {}", e))?;

    // Read migrations directory
    let migrations_dir = project_root.join(config.migrations_dir());
    if !migrations_dir.exists() {
        return Ok(Vec::new());
    }

    let mut plans = Vec::new();
    let entries = fs::read_dir(&migrations_dir)
        .map_err(|e| format!("Failed to read migrations directory: {}", e))?;

    for entry in entries {
        let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?;
        let path = entry.path();
        if path.is_file() {
            let ext = path.extension().and_then(|s| s.to_str());
            if ext == Some("json") || ext == Some("yaml") || ext == Some("yml") {
                let content = fs::read_to_string(&path)
                    .context(format!("Failed to read migration file {}", path.display()))?;

                let plan: MigrationPlan = if ext == Some("json") {
                    serde_json::from_str(&content).map_err(|e| {
                        format!("Failed to parse JSON migration {}: {}", path.display(), e)
                    })?
                } else {
                    serde_yaml::from_str(&content).map_err(|e| {
                        format!("Failed to parse YAML migration {}: {}", path.display(), e)
                    })?
                };

                plans.push(plan);
            }
        }
    }

    // Sort by version
    plans.sort_by_key(|p| p.version);
    Ok(plans)
}

/// Load migrations at compile time (for macro use).
pub fn load_migrations_at_compile_time() -> Result<Vec<MigrationPlan>, Box<dyn std::error::Error>> {
    load_migrations_from_dir(None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;
    use std::env;
    use std::fs;
    use tempfile::TempDir;

    struct CwdGuard {
        original: PathBuf,
    }

    impl CwdGuard {
        fn new(dir: &PathBuf) -> Self {
            let original = env::current_dir().unwrap();
            env::set_current_dir(dir).unwrap();
            Self { original }
        }
    }

    impl Drop for CwdGuard {
        fn drop(&mut self) {
            let _ = env::set_current_dir(&self.original);
        }
    }

    fn write_config(dir: &std::path::Path) {
        let cfg = VespertideConfig::default();
        let text = serde_json::to_string_pretty(&cfg).unwrap();
        fs::write(dir.join("vespertide.json"), text).unwrap();
    }

    #[test]
    #[serial]
    fn test_load_migrations_returns_empty_when_no_migrations_dir() {
        let temp_dir = TempDir::new().unwrap();
        let _guard = CwdGuard::new(&temp_dir.path().to_path_buf());
        write_config(temp_dir.path());

        let result = load_migrations(&VespertideConfig::default()).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    #[serial]
    fn test_load_migrations_reads_json_and_sorts_versions() {
        let temp_dir = TempDir::new().unwrap();
        let _guard = CwdGuard::new(&temp_dir.path().to_path_buf());
        write_config(temp_dir.path());
        fs::create_dir_all("migrations").unwrap();
        fs::write(
            "migrations/0002_second.json",
            r#"{"version": 2, "actions": []}"#,
        )
        .unwrap();
        fs::write(
            "migrations/0001_first.json",
            r#"{"version": 1, "actions": []}"#,
        )
        .unwrap();

        let plans = load_migrations(&VespertideConfig::default()).unwrap();
        assert_eq!(
            plans.iter().map(|plan| plan.version).collect::<Vec<_>>(),
            vec![1, 2]
        );
    }

    #[test]
    fn test_load_migrations_from_dir_with_no_migrations_dir() {
        let temp_dir = TempDir::new().unwrap();
        let result = load_migrations_from_dir(Some(temp_dir.path().to_path_buf()));
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 0);
    }

    #[test]
    fn test_load_migrations_from_dir_with_empty_migrations_dir() {
        let temp_dir = TempDir::new().unwrap();
        let migrations_dir = temp_dir.path().join("migrations");
        fs::create_dir_all(&migrations_dir).unwrap();

        let result = load_migrations_from_dir(Some(temp_dir.path().to_path_buf()));
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 0);
    }

    #[test]
    fn test_load_migrations_from_dir_with_json_migration() {
        let temp_dir = TempDir::new().unwrap();
        let migrations_dir = temp_dir.path().join("migrations");
        fs::create_dir_all(&migrations_dir).unwrap();

        let migration_content = r#"{
            "version": 1,
            "actions": [
                {
                    "type": "create_table",
                    "table": "users",
                    "columns": [
                        {
                            "name": "id",
                            "type": "integer",
                            "nullable": false
                        }
                    ],
                    "constraints": []
                }
            ]
        }"#;

        fs::write(migrations_dir.join("0001_test.json"), migration_content).unwrap();

        let result = load_migrations_from_dir(Some(temp_dir.path().to_path_buf()));
        assert!(result.is_ok());
        let plans = result.unwrap();
        assert_eq!(plans.len(), 1);
        assert_eq!(plans[0].version, 1);
    }

    #[test]
    fn test_load_migrations_from_dir_sorts_by_version() {
        let temp_dir = TempDir::new().unwrap();
        let migrations_dir = temp_dir.path().join("migrations");
        fs::create_dir_all(&migrations_dir).unwrap();

        let migration1 = r#"{"version": 2, "actions": []}"#;
        let migration2 = r#"{"version": 1, "actions": []}"#;
        let migration3 = r#"{"version": 3, "actions": []}"#;

        fs::write(migrations_dir.join("0002_second.json"), migration1).unwrap();
        fs::write(migrations_dir.join("0001_first.json"), migration2).unwrap();
        fs::write(migrations_dir.join("0003_third.json"), migration3).unwrap();

        let result = load_migrations_from_dir(Some(temp_dir.path().to_path_buf()));
        assert!(result.is_ok());
        let plans = result.unwrap();
        assert_eq!(plans.len(), 3);
        assert_eq!(plans[0].version, 1);
        assert_eq!(plans[1].version, 2);
        assert_eq!(plans[2].version, 3);
    }

    #[test]
    fn test_load_migrations_from_dir_with_yaml_migration() {
        let temp_dir = TempDir::new().unwrap();
        let migrations_dir = temp_dir.path().join("migrations");
        fs::create_dir_all(&migrations_dir).unwrap();

        let migration_content = r#"---
version: 1
actions:
  - type: create_table
    table: users
    columns:
      - name: id
        type: integer
        nullable: false
    constraints: []
"#;

        fs::write(migrations_dir.join("0001_test.yaml"), migration_content).unwrap();

        let result = load_migrations_from_dir(Some(temp_dir.path().to_path_buf()));
        assert!(result.is_ok());
        let plans = result.unwrap();
        assert_eq!(plans.len(), 1);
        assert_eq!(plans[0].version, 1);
    }

    #[test]
    fn test_load_migrations_from_dir_with_yml_migration() {
        let temp_dir = TempDir::new().unwrap();
        let migrations_dir = temp_dir.path().join("migrations");
        fs::create_dir_all(&migrations_dir).unwrap();

        let migration_content = r#"---
version: 1
actions:
  - type: create_table
    table: users
    columns:
      - name: id
        type: integer
        nullable: false
    constraints: []
"#;

        fs::write(migrations_dir.join("0001_test.yml"), migration_content).unwrap();

        let result = load_migrations_from_dir(Some(temp_dir.path().to_path_buf()));
        assert!(result.is_ok());
        let plans = result.unwrap();
        assert_eq!(plans.len(), 1);
        assert_eq!(plans[0].version, 1);
    }

    #[test]
    #[serial]
    fn test_load_migrations_reads_yaml_for_runtime_loader() {
        let temp_dir = TempDir::new().unwrap();
        let _guard = CwdGuard::new(&temp_dir.path().to_path_buf());
        write_config(temp_dir.path());
        fs::create_dir_all("migrations").unwrap();

        let migration_content = r#"---
version: 1
actions:
  - type: create_table
    table: users
    columns:
      - name: id
        type: integer
        nullable: false
    constraints: []
"#;
        fs::write("migrations/0001_test.yaml", migration_content).unwrap();

        let plans = load_migrations(&VespertideConfig::default()).unwrap();
        assert_eq!(plans.len(), 1);
        assert_eq!(plans[0].version, 1);
    }

    #[test]
    fn test_load_migrations_from_dir_with_invalid_json() {
        let temp_dir = TempDir::new().unwrap();
        let migrations_dir = temp_dir.path().join("migrations");
        fs::create_dir_all(&migrations_dir).unwrap();

        let invalid_json = r#"{"version": 1, "actions": [invalid]}"#;
        fs::write(migrations_dir.join("0001_invalid.json"), invalid_json).unwrap();

        let result = load_migrations_from_dir(Some(temp_dir.path().to_path_buf()));
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Failed to parse JSON migration"));
    }

    #[test]
    fn test_load_migrations_from_dir_with_invalid_yaml() {
        let temp_dir = TempDir::new().unwrap();
        let migrations_dir = temp_dir.path().join("migrations");
        fs::create_dir_all(&migrations_dir).unwrap();

        let invalid_yaml = r#"---
version: 1
actions:
  - invalid: [syntax
"#;
        fs::write(migrations_dir.join("0001_invalid.yaml"), invalid_yaml).unwrap();

        let result = load_migrations_from_dir(Some(temp_dir.path().to_path_buf()));
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Failed to parse YAML migration"));
    }

    #[test]
    fn test_load_migrations_from_dir_with_unreadable_file() {
        // Note: Testing file read errors (line 85) is extremely difficult in unit tests
        // because it requires actual I/O errors like:
        // - Disk failures
        // - Permission issues
        // - File locks from other processes
        // - Network filesystem issues
        //
        // The error handling code path at line 85 exists and will be executed
        // in real-world scenarios when file read errors occur.
        // The format! macro and error message construction are tested through
        // other error paths (invalid JSON/YAML parsing).
        //
        // For now, we verify the function works correctly with valid files.
        let temp_dir = TempDir::new().unwrap();
        let migrations_dir = temp_dir.path().join("migrations");
        fs::create_dir_all(&migrations_dir).unwrap();

        let file_path = migrations_dir.join("0001_test.json");
        fs::write(&file_path, r#"{"version": 1, "actions": []}"#).unwrap();

        let result = load_migrations_from_dir(Some(temp_dir.path().to_path_buf()));
        assert!(result.is_ok());
    }

    #[test]
    #[serial]
    fn test_load_migrations_from_dir_without_project_root() {
        // Save the original value
        let original = env::var("CARGO_MANIFEST_DIR").ok();

        // Remove CARGO_MANIFEST_DIR to test the error path
        // Note: remove_var is unsafe in multi-threaded environments,
        // but serial_test ensures tests run sequentially
        unsafe {
            env::remove_var("CARGO_MANIFEST_DIR");
        }

        let result = load_migrations_from_dir(None);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("CARGO_MANIFEST_DIR environment variable not set"));

        // Restore the original value if it existed
        if let Some(val) = original {
            unsafe {
                env::set_var("CARGO_MANIFEST_DIR", val);
            }
        }
    }

    #[test]
    fn test_load_migrations_at_compile_time() {
        // This function just calls load_migrations_from_dir(None)
        // We can't easily test it without CARGO_MANIFEST_DIR, but we can verify
        // it doesn't panic
        let result = load_migrations_at_compile_time();
        // This might succeed if CARGO_MANIFEST_DIR is set (like in cargo test)
        // or fail if it's not set
        // Either way, we're testing the code path
        let _ = result;
    }
}