reinhardt-db 0.1.1

Django-style database layer for Reinhardt framework
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
//! Filesystem-based migration repository
//!
//! Persists migrations as `.rs` files on disk.

use super::{Migration, MigrationError, MigrationRepository, Result};
use crate::migrations::ast_parser;
use async_trait::async_trait;
use quote::quote;
use std::path::{Path, PathBuf};
use syn::parse_quote;

/// Repository that persists migrations as `.rs` files
///
/// This repository writes migrations to disk in the format:
/// ```rust,no_run
/// // <app_label>/migrations/<name>.rs
/// use reinhardt_db::migrations::Migration;
/// // use reinhardt::db::migrations::prelude::*;
/// // use reinhardt::db::migrations::FieldType;
///
/// pub fn migration() -> Migration {
///     Migration::new("0001_initial", "app")
/// }
/// ```
pub struct FilesystemRepository {
	/// Root directory for migration files
	root_dir: PathBuf,
}

impl FilesystemRepository {
	/// Create a new FilesystemRepository
	///
	/// # Arguments
	///
	/// * `root_dir` - Root directory where migration files will be stored
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_db::migrations::FilesystemRepository;
	/// let repo = FilesystemRepository::new("./migrations");
	/// ```
	pub fn new<P: AsRef<Path>>(root_dir: P) -> Self {
		Self {
			root_dir: root_dir.as_ref().to_path_buf(),
		}
	}

	/// Validate that a path component does not contain traversal sequences.
	///
	/// Rejects components containing `..`, path separators, or null bytes
	/// to prevent directory traversal attacks that could escape the
	/// migration root directory.
	fn validate_path_component(component: &str, label: &str) -> Result<()> {
		if component.is_empty() {
			return Err(MigrationError::PathTraversal(format!(
				"{} cannot be empty",
				label
			)));
		}

		// Reject path traversal sequences
		if component.contains("..") {
			return Err(MigrationError::PathTraversal(format!(
				"{} contains path traversal sequence '..': {}",
				label, component
			)));
		}

		// Reject path separators (both Unix and Windows)
		if component.contains('/') || component.contains('\\') {
			return Err(MigrationError::PathTraversal(format!(
				"{} contains path separator: {}",
				label, component
			)));
		}

		// Reject null bytes
		if component.contains('\0') {
			return Err(MigrationError::PathTraversal(format!(
				"{} contains null byte: {}",
				label, component
			)));
		}

		Ok(())
	}

	/// Get the path for a migration file
	///
	/// Returns: `<root_dir>/<app_label>/<name>.rs`
	///
	/// Validates that `app_label` and `name` do not contain path traversal
	/// sequences before constructing the path.
	fn migration_path(&self, app_label: &str, name: &str) -> Result<PathBuf> {
		Self::validate_path_component(app_label, "App label")?;
		Self::validate_path_component(name, "Migration name")?;

		let path = self.root_dir.join(app_label).join(format!("{}.rs", name));

		// Final safety check: if both paths can be canonicalized (i.e., exist on disk),
		// verify the resolved path stays within root_dir.
		// When directories don't exist yet (e.g., during save), the component-level
		// validation above is sufficient to prevent traversal.
		if let (Ok(canonical_root), Some(parent)) = (self.root_dir.canonicalize(), path.parent())
			&& let Ok(canonical_parent) = parent.canonicalize()
			&& !canonical_parent.starts_with(&canonical_root)
		{
			return Err(MigrationError::PathTraversal(format!(
				"Resolved path escapes migration root directory: {}",
				path.display()
			)));
		}

		Ok(path)
	}

	/// Generate Rust code for a migration file
	fn generate_migration_code(&self, migration: &Migration) -> Result<String> {
		// Build dependencies vector (tuple elements need .to_string() for String type)
		let deps: Vec<_> = migration
			.dependencies
			.iter()
			.map(|(app, name)| {
				quote! { (#app.to_string(), #name.to_string()) }
			})
			.collect();

		// Build replaces vector (tuple elements need .to_string() for String type)
		let replaces: Vec<_> = migration
			.replaces
			.iter()
			.map(|(app, name)| {
				quote! { (#app.to_string(), #name.to_string()) }
			})
			.collect();

		let app_label = &migration.app_label;
		let name = &migration.name;
		let atomic = migration.atomic;
		let state_only = migration.state_only;
		let database_only = migration.database_only;

		// Build initial field token
		let initial_tokens = match migration.initial {
			Some(true) => quote! { Some(true) },
			Some(false) => quote! { Some(false) },
			None => quote! { None },
		};

		// Generate operation code
		let ops_tokens = migration.operations.iter();
		let operations_code = quote! { vec![#(#ops_tokens),*] };

		// Generate full migration file
		let file: syn::File = parse_quote! {
			use reinhardt::db::migrations::prelude::*;
			use reinhardt::db::migrations::FieldType;

			pub fn migration() -> Migration {
				Migration {
					app_label: #app_label.to_string(),
					name: #name.to_string(),
					operations: #operations_code,
					dependencies: vec![#(#deps),*],
					atomic: #atomic,
					replaces: vec![#(#replaces),*],
					initial: #initial_tokens,
					state_only: #state_only,
					database_only: #database_only,
					swappable_dependencies: vec![],
					optional_dependencies: vec![],
				}
			}
		};

		// Format with prettyplease first, then apply rustfmt
		let prettyplease_output = prettyplease::unparse(&file);
		let formatted = Self::format_with_rustfmt(&prettyplease_output)?;
		Ok(formatted)
	}

	/// Format code with rustfmt, applying project's rustfmt.toml settings (hard_tabs = true)
	///
	/// Falls back to prettyplease output if rustfmt is not available or fails.
	fn format_with_rustfmt(code: &str) -> Result<String> {
		use std::io::Write;
		use std::process::{Command, Stdio};

		// Try to run rustfmt
		let child = Command::new("rustfmt")
			.arg("--edition=2024")
			.stdin(Stdio::piped())
			.stdout(Stdio::piped())
			.stderr(Stdio::piped())
			.spawn();

		match child {
			Ok(mut child_process) => {
				// Write code to stdin
				if let Some(stdin) = child_process.stdin.as_mut() {
					stdin.write_all(code.as_bytes()).map_err(|e| {
						MigrationError::IoError(std::io::Error::other(format!(
							"Failed to write to rustfmt stdin: {}",
							e
						)))
					})?;
				}

				// Get formatted output
				let output = child_process.wait_with_output().map_err(|e| {
					MigrationError::IoError(std::io::Error::other(format!(
						"Failed to read rustfmt output: {}",
						e
					)))
				})?;

				if output.status.success() {
					String::from_utf8(output.stdout).map_err(|e| {
						MigrationError::IoError(std::io::Error::other(format!(
							"Invalid UTF-8 from rustfmt: {}",
							e
						)))
					})
				} else {
					// rustfmt failed, fallback to prettyplease output
					eprintln!("Warning: rustfmt failed, using prettyplease output");
					Ok(code.to_string())
				}
			}
			Err(_) => {
				// rustfmt not available, use prettyplease output
				eprintln!("Warning: rustfmt not found, using prettyplease output (space-indented)");
				Ok(code.to_string())
			}
		}
	}

	/// Check if two migrations have identical operations
	///
	/// Returns true if the operations vectors are equal.
	fn has_identical_operations(&self, m1: &Migration, m2: &Migration) -> bool {
		m1.operations == m2.operations
	}
}

#[async_trait]
impl MigrationRepository for FilesystemRepository {
	async fn save(&mut self, migration: &Migration) -> Result<()> {
		let path = self.migration_path(&migration.app_label, &migration.name)?;

		// Check if migration file already exists to prevent overwriting
		if tokio::fs::try_exists(&path).await.unwrap_or(false) {
			return Err(MigrationError::IoError(std::io::Error::other(format!(
				"Migration file already exists: {}. \
				If you want to replace it, please delete the existing file first.",
				path.display()
			))));
		}

		// Check for duplicate operations with existing migrations.
		// Skip for migrations with empty operations (e.g., merge migrations)
		// since empty-vs-empty comparison is never a meaningful duplicate signal.
		// The file-exists check above already prevents actual overwrites.
		if !migration.operations.is_empty() {
			let existing_migrations = self.list(&migration.app_label).await?;
			for existing in &existing_migrations {
				if self.has_identical_operations(existing, migration) {
					return Err(MigrationError::DuplicateOperations(format!(
						"Migration '{}' has identical operations to existing migration '{}'. \
						This usually indicates a problem with from_state construction. \
						The existing migration was created at the same location and performs \
						the same database changes.",
						migration.name, existing.name
					)));
				}
			}
		}

		// Create parent directories
		if let Some(parent) = path.parent() {
			tokio::fs::create_dir_all(parent).await.map_err(|e| {
				MigrationError::IoError(std::io::Error::other(format!(
					"Failed to create directory {}: {}",
					parent.display(),
					e
				)))
			})?;
		}

		// Generate migration code
		let code = self.generate_migration_code(migration)?;

		// Write to file
		tokio::fs::write(&path, code).await.map_err(|e| {
			MigrationError::IoError(std::io::Error::other(format!(
				"Failed to write {}: {}",
				path.display(),
				e
			)))
		})?;

		Ok(())
	}

	async fn get(&self, app_label: &str, name: &str) -> Result<Migration> {
		let path = self.migration_path(app_label, name)?;

		if !path.exists() {
			return Err(MigrationError::NotFound(format!("{}.{}", app_label, name)));
		}

		// Read and parse file
		let content = tokio::fs::read_to_string(&path).await.map_err(|e| {
			MigrationError::IoError(std::io::Error::other(format!(
				"Failed to read {}: {}",
				path.display(),
				e
			)))
		})?;

		// Parse with syn
		let ast: syn::File = syn::parse_file(&content).map_err(|e| {
			MigrationError::InvalidMigration(format!("Failed to parse {}: {}", path.display(), e))
		})?;

		// Extract migration data from AST using ast_parser utility
		ast_parser::extract_migration_metadata(&ast, app_label, name)
	}

	async fn list(&self, app_label: &str) -> Result<Vec<Migration>> {
		Self::validate_path_component(app_label, "App label")?;
		let migrations_dir = self.root_dir.join(app_label);

		if !migrations_dir.exists() {
			return Ok(vec![]);
		}

		let mut migrations = Vec::new();

		// Read directory
		let mut entries = tokio::fs::read_dir(&migrations_dir).await.map_err(|e| {
			MigrationError::IoError(std::io::Error::other(format!(
				"Failed to read directory {}: {}",
				migrations_dir.display(),
				e
			)))
		})?;

		while let Some(entry) = entries.next_entry().await.map_err(|e| {
			MigrationError::IoError(std::io::Error::other(format!(
				"Failed to read directory entry: {}",
				e
			)))
		})? {
			let path = entry.path();

			// Skip non-.rs files
			if path.extension().and_then(|s| s.to_str()) != Some("rs") {
				continue;
			}

			// Extract name from filename
			if let Some(name) = path.file_stem().and_then(|s| s.to_str()) {
				// Get migration
				match self.get(app_label, name).await {
					Ok(migration) => migrations.push(migration),
					Err(e) => {
						eprintln!("Warning: Failed to load migration {}: {}", name, e);
					}
				}
			}
		}

		Ok(migrations)
	}

	async fn delete(&mut self, app_label: &str, name: &str) -> Result<()> {
		let path = self.migration_path(app_label, name)?;

		if !path.exists() {
			return Err(MigrationError::NotFound(format!("{}.{}", app_label, name)));
		}

		tokio::fs::remove_file(&path).await.map_err(|e| {
			MigrationError::IoError(std::io::Error::other(format!(
				"Failed to delete {}: {}",
				path.display(),
				e
			)))
		})?;

		Ok(())
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::migrations::fields::FieldType;
	use crate::migrations::operations::{ColumnDefinition, Operation};
	use rstest::rstest;
	use serial_test::serial;
	use tempfile::TempDir;

	/// Creates a test migration with a unique CreateTable operation based on the migration name.
	/// This ensures each migration has distinct operations to avoid duplicate detection errors.
	fn create_test_migration(app_label: &str, name: &str) -> Migration {
		let mut migration = Migration::new(name, app_label);

		// Create a unique table name derived from the migration name
		let table_name = format!("table_{}", name.replace('-', "_"));
		migration.operations.push(Operation::CreateTable {
			name: table_name,
			columns: vec![ColumnDefinition::new("id", FieldType::Integer)],
			constraints: vec![],
			without_rowid: None,
			partition: None,
			interleave_in_parent: None,
		});

		migration
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_new() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();

		// Act
		let repo = FilesystemRepository::new(temp_dir.path());

		// Assert
		assert_eq!(repo.root_dir, temp_dir.path());
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_save() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let mut repo = FilesystemRepository::new(temp_dir.path());
		let migration = create_test_migration("polls", "0001_initial");

		// Act
		repo.save(&migration).await.unwrap();

		// Assert
		let path = repo.migration_path("polls", "0001_initial").unwrap();
		assert!(tokio::fs::try_exists(&path).await.unwrap());

		let content = tokio::fs::read_to_string(&path).await.unwrap();
		assert!(content.contains("pub fn migration() -> Migration"));
		assert!(content.contains("app_label: \"polls\""));
		assert!(content.contains("name: \"0001_initial\""));
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_get() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let mut repo = FilesystemRepository::new(temp_dir.path());
		let migration = create_test_migration("polls", "0001_initial");
		repo.save(&migration).await.unwrap();

		// Act
		let retrieved = repo.get("polls", "0001_initial").await.unwrap();

		// Assert
		assert_eq!(retrieved.app_label, "polls");
		assert_eq!(retrieved.name, "0001_initial");
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_get_not_found() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let repo = FilesystemRepository::new(temp_dir.path());

		// Act
		let result = repo.get("polls", "0001_initial").await;

		// Assert
		assert!(result.is_err());
		assert!(matches!(result.unwrap_err(), MigrationError::NotFound(_)));
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_list() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let mut repo = FilesystemRepository::new(temp_dir.path());
		repo.save(&create_test_migration("polls", "0001_initial"))
			.await
			.unwrap();
		repo.save(&create_test_migration("polls", "0002_add_field"))
			.await
			.unwrap();

		// Act
		let migrations = repo.list("polls").await.unwrap();

		// Assert
		assert_eq!(migrations.len(), 2);
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_list_empty() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let repo = FilesystemRepository::new(temp_dir.path());

		// Act
		let migrations = repo.list("polls").await.unwrap();

		// Assert
		assert_eq!(migrations.len(), 0);
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_delete() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let mut repo = FilesystemRepository::new(temp_dir.path());
		let migration = create_test_migration("polls", "0001_initial");
		repo.save(&migration).await.unwrap();
		let path = repo.migration_path("polls", "0001_initial").unwrap();
		assert!(tokio::fs::try_exists(&path).await.unwrap());

		// Act
		repo.delete("polls", "0001_initial").await.unwrap();

		// Assert
		assert!(!tokio::fs::try_exists(&path).await.unwrap());
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_delete_not_found() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let mut repo = FilesystemRepository::new(temp_dir.path());

		// Act
		let result = repo.delete("polls", "0001_initial").await;

		// Assert
		assert!(result.is_err());
		assert!(matches!(result.unwrap_err(), MigrationError::NotFound(_)));
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_save_with_dependencies() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let mut repo = FilesystemRepository::new(temp_dir.path());
		let migration =
			Migration::new("0002_add_field", "polls").add_dependency("polls", "0001_initial");

		// Act
		repo.save(&migration).await.unwrap();

		// Assert
		let path = repo.migration_path("polls", "0002_add_field").unwrap();
		let content = tokio::fs::read_to_string(&path).await.unwrap();
		assert!(content.contains("dependencies"));
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_save_prevents_overwrite() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let mut repo = FilesystemRepository::new(temp_dir.path());
		let migration = create_test_migration("polls", "0001_initial");
		repo.save(&migration).await.unwrap();
		let path = repo.migration_path("polls", "0001_initial").unwrap();
		assert!(tokio::fs::try_exists(&path).await.unwrap());

		// Act
		let duplicate_migration = create_test_migration("polls", "0001_initial");
		let result = repo.save(&duplicate_migration).await;

		// Assert
		assert!(result.is_err());
		let err = result.unwrap_err();
		assert!(matches!(err, MigrationError::IoError(_)));
		assert!(err.to_string().contains("already exists"));
	}

	#[rstest]
	#[case("../etc", "0001_initial", "App label")]
	#[case("polls", "../secret", "Migration name")]
	#[case("../../root", "0001_initial", "App label")]
	#[case("polls", "../../etc/passwd", "Migration name")]
	fn test_path_traversal_rejected(
		#[case] app_label: &str,
		#[case] name: &str,
		#[case] expected_label: &str,
	) {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let repo = FilesystemRepository::new(temp_dir.path());

		// Act
		let result = repo.migration_path(app_label, name);

		// Assert
		assert!(result.is_err(), "Path traversal should be rejected");
		let err = result.unwrap_err();
		assert!(matches!(err, MigrationError::PathTraversal(_)));
		assert!(
			err.to_string().contains(expected_label),
			"Error should mention '{}', got: {}",
			expected_label,
			err
		);
	}

	#[rstest]
	#[case("polls/subdir", "0001_initial")]
	#[case("polls\\subdir", "0001_initial")]
	#[case("polls", "name/with/slashes")]
	fn test_path_separator_rejected(#[case] app_label: &str, #[case] name: &str) {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let repo = FilesystemRepository::new(temp_dir.path());

		// Act
		let result = repo.migration_path(app_label, name);

		// Assert
		assert!(result.is_err(), "Path separators should be rejected");
		assert!(matches!(
			result.unwrap_err(),
			MigrationError::PathTraversal(_)
		));
	}

	#[rstest]
	#[case("polls\0evil", "0001_initial")]
	#[case("polls", "0001\0evil")]
	fn test_null_byte_rejected(#[case] app_label: &str, #[case] name: &str) {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let repo = FilesystemRepository::new(temp_dir.path());

		// Act
		let result = repo.migration_path(app_label, name);

		// Assert
		assert!(result.is_err(), "Null bytes should be rejected");
		assert!(matches!(
			result.unwrap_err(),
			MigrationError::PathTraversal(_)
		));
	}

	#[rstest]
	#[case("", "0001_initial")]
	#[case("polls", "")]
	fn test_empty_component_rejected(#[case] app_label: &str, #[case] name: &str) {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let repo = FilesystemRepository::new(temp_dir.path());

		// Act
		let result = repo.migration_path(app_label, name);

		// Assert
		assert!(result.is_err(), "Empty components should be rejected");
		assert!(matches!(
			result.unwrap_err(),
			MigrationError::PathTraversal(_)
		));
	}

	#[rstest]
	fn test_valid_path_accepted() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let repo = FilesystemRepository::new(temp_dir.path());

		// Act
		let result = repo.migration_path("polls", "0001_initial");

		// Assert
		assert!(result.is_ok(), "Valid path should be accepted");
		let path = result.unwrap();
		assert!(path.starts_with(temp_dir.path()));
		assert!(path.ends_with("0001_initial.rs"));
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_save_rejects_traversal_in_app_label() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let mut repo = FilesystemRepository::new(temp_dir.path());
		let migration = create_test_migration("../etc", "0001_initial");

		// Act
		let result = repo.save(&migration).await;

		// Assert
		assert!(result.is_err());
		assert!(matches!(
			result.unwrap_err(),
			MigrationError::PathTraversal(_)
		));
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_list_rejects_traversal_in_app_label() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let repo = FilesystemRepository::new(temp_dir.path());

		// Act
		let result = repo.list("../etc").await;

		// Assert
		assert!(result.is_err());
		assert!(matches!(
			result.unwrap_err(),
			MigrationError::PathTraversal(_)
		));
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_save_with_initial_true() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let mut repo = FilesystemRepository::new(temp_dir.path());
		let mut migration = create_test_migration("polls", "0001_initial_true");
		migration.initial = Some(true);

		// Act
		repo.save(&migration).await.unwrap();

		// Assert - verify generated code contains initial: Some(true)
		let path = repo.migration_path("polls", "0001_initial_true").unwrap();
		let content = tokio::fs::read_to_string(&path).await.unwrap();
		assert!(
			content.contains("Some(true)"),
			"Generated code should contain Some(true), got: {}",
			content
		);

		// Assert - round-trip: get() parses back the same initial value
		let retrieved = repo.get("polls", "0001_initial_true").await.unwrap();
		assert_eq!(retrieved.initial, Some(true));
	}

	#[rstest]
	#[tokio::test]
	#[serial(filesystem_repository)]
	async fn test_filesystem_repository_save_with_initial_false() {
		// Arrange
		let temp_dir = TempDir::new().unwrap();
		let mut repo = FilesystemRepository::new(temp_dir.path());
		let mut migration = create_test_migration("polls", "0001_initial_false");
		migration.initial = Some(false);

		// Act
		repo.save(&migration).await.unwrap();

		// Assert - verify generated code contains initial: Some(false)
		let path = repo.migration_path("polls", "0001_initial_false").unwrap();
		let content = tokio::fs::read_to_string(&path).await.unwrap();
		assert!(
			content.contains("Some(false)"),
			"Generated code should contain Some(false), got: {}",
			content
		);

		// Assert - round-trip: get() parses back the same initial value
		let retrieved = repo.get("polls", "0001_initial_false").await.unwrap();
		assert_eq!(retrieved.initial, Some(false));
	}
}