version_migrate/
lib.rs

1//! # version-migrate
2//!
3//! A library for explicit, type-safe schema versioning and migration.
4//!
5//! ## Features
6//!
7//! - **Type-safe migrations**: Define migrations between versions using traits
8//! - **Validation**: Automatic validation of migration paths (circular path detection, version ordering)
9//! - **Multi-format support**: Load from JSON, TOML, YAML, or any serde-compatible format
10//! - **Legacy data support**: Automatic fallback for data without version information
11//! - **Vec support**: Migrate collections of versioned entities
12//! - **Hierarchical structures**: Support for nested versioned entities
13//! - **Async migrations**: Optional async support for I/O-heavy migrations
14//!
15//! ## Basic Example
16//!
17//! ```ignore
18//! use version_migrate::{Versioned, MigratesTo, IntoDomain, Migrator};
19//! use serde::{Serialize, Deserialize};
20//!
21//! // Version 1.0.0
22//! #[derive(Serialize, Deserialize, Versioned)]
23//! #[versioned(version = "1.0.0")]
24//! struct TaskV1_0_0 {
25//!     id: String,
26//!     title: String,
27//! }
28//!
29//! // Version 1.1.0
30//! #[derive(Serialize, Deserialize, Versioned)]
31//! #[versioned(version = "1.1.0")]
32//! struct TaskV1_1_0 {
33//!     id: String,
34//!     title: String,
35//!     description: Option<String>,
36//! }
37//!
38//! // Domain model
39//! struct TaskEntity {
40//!     id: String,
41//!     title: String,
42//!     description: Option<String>,
43//! }
44//!
45//! impl MigratesTo<TaskV1_1_0> for TaskV1_0_0 {
46//!     fn migrate(self) -> TaskV1_1_0 {
47//!         TaskV1_1_0 {
48//!             id: self.id,
49//!             title: self.title,
50//!             description: None,
51//!         }
52//!     }
53//! }
54//!
55//! impl IntoDomain<TaskEntity> for TaskV1_1_0 {
56//!     fn into_domain(self) -> TaskEntity {
57//!         TaskEntity {
58//!             id: self.id,
59//!             title: self.title,
60//!             description: self.description,
61//!         }
62//!     }
63//! }
64//! ```
65//!
66//! ## Working with Collections (Vec)
67//!
68//! ```ignore
69//! // Save multiple versioned entities
70//! let tasks = vec![
71//!     TaskV1_0_0 { id: "1".into(), title: "Task 1".into() },
72//!     TaskV1_0_0 { id: "2".into(), title: "Task 2".into() },
73//! ];
74//! let json = migrator.save_vec(tasks)?;
75//!
76//! // Load and migrate multiple entities
77//! let domains: Vec<TaskEntity> = migrator.load_vec("task", &json)?;
78//! ```
79//!
80//! ## Legacy Data Support
81//!
82//! Handle data that was created before versioning was introduced:
83//!
84//! ```ignore
85//! // Legacy data without version information
86//! let legacy_json = r#"{"id": "task-1", "title": "Legacy Task"}"#;
87//!
88//! // Automatically treats legacy data as the first version and migrates
89//! let domain: TaskEntity = migrator.load_with_fallback("task", legacy_json)?;
90//!
91//! // Also works with properly versioned data
92//! let versioned_json = r#"{"version":"1.0.0","data":{"id":"task-1","title":"My Task"}}"#;
93//! let domain: TaskEntity = migrator.load_with_fallback("task", versioned_json)?;
94//! ```
95//!
96//! ## Hierarchical Structures
97//!
98//! For complex configurations with nested versioned entities:
99//!
100//! ```ignore
101//! #[derive(Serialize, Deserialize, Versioned)]
102//! #[versioned(version = "1.0.0")]
103//! struct ConfigV1 {
104//!     setting: SettingV1,
105//!     items: Vec<ItemV1>,
106//! }
107//!
108//! #[derive(Serialize, Deserialize, Versioned)]
109//! #[versioned(version = "2.0.0")]
110//! struct ConfigV2 {
111//!     setting: SettingV2,
112//!     items: Vec<ItemV2>,
113//! }
114//!
115//! impl MigratesTo<ConfigV2> for ConfigV1 {
116//!     fn migrate(self) -> ConfigV2 {
117//!         ConfigV2 {
118//!             // Migrate nested entities
119//!             setting: self.setting.migrate(),
120//!             items: self.items.into_iter()
121//!                 .map(|item| item.migrate())
122//!                 .collect(),
123//!         }
124//!     }
125//! }
126//! ```
127//!
128//! ## Design Philosophy
129//!
130//! This library follows the **explicit versioning** approach:
131//!
132//! - Each version has its own type (V1, V2, V3, etc.)
133//! - Migration logic is explicit and testable
134//! - Version changes are tracked in code
135//! - Root-level versioning ensures consistency
136//!
137//! This differs from ProtoBuf's "append-only" approach but allows for:
138//! - Schema refactoring and cleanup
139//! - Type-safe migration paths
140//! - Clear version history in code
141
142use serde::{Deserialize, Serialize};
143
144pub mod dir_storage;
145pub mod errors;
146mod migrator;
147pub mod paths;
148pub mod storage;
149
150// Re-export the derive macros
151pub use version_migrate_macro::Versioned;
152
153// Re-export Queryable derive macro (same name as trait is OK in Rust)
154#[doc(inline)]
155pub use version_migrate_macro::Queryable as DeriveQueryable;
156
157// Re-export VersionMigrate derive macro
158#[doc(inline)]
159pub use version_migrate_macro::VersionMigrate;
160/// Creates a migration path with simplified syntax.
161///
162/// This macro provides a concise way to define migration paths between versioned types.
163/// Use this when you need just the path without creating a Migrator instance.
164///
165/// # Syntax
166///
167/// Basic usage:
168/// ```ignore
169/// migrate_path!("entity", [V1, V2, V3])
170/// ```
171///
172/// With custom version/data keys:
173/// ```ignore
174/// migrate_path!("entity", [V1, V2, V3], version_key = "v", data_key = "d")
175/// ```
176///
177/// # Arguments
178///
179/// * `entity` - The entity name as a string literal (e.g., `"user"`, `"task"`)
180/// * `versions` - A list of version types in migration order (e.g., `[V1, V2, V3]`)
181/// * `version_key` - (Optional) Custom key for the version field (default: `"version"`)
182/// * `data_key` - (Optional) Custom key for the data field (default: `"data"`)
183///
184/// # Examples
185///
186/// ```ignore
187/// use version_migrate::{migrate_path, Migrator};
188///
189/// // Simple two-step migration
190/// let path = migrate_path!("task", [TaskV1, TaskV2]);
191///
192/// // Multi-step migration
193/// let path = migrate_path!("task", [TaskV1, TaskV2, TaskV3]);
194///
195/// // Many versions (arbitrary length supported)
196/// let path = migrate_path!("task", [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6]);
197///
198/// // With custom keys
199/// let path = migrate_path!("task", [TaskV1, TaskV2], version_key = "v", data_key = "d");
200///
201/// // Register with migrator
202/// let mut migrator = Migrator::new();
203/// migrator.register(path).unwrap();
204/// ```
205///
206/// # Generated Code
207///
208/// The macro expands to the equivalent builder pattern:
209/// ```ignore
210/// // migrate_path!("entity", [V1, V2])
211/// // expands to:
212/// Migrator::define("entity")
213///     .from::<V1>()
214///     .into::<V2>()
215/// ```
216#[macro_export]
217macro_rules! migrate_path {
218    // Basic: migrate_path!("entity", [V1, V2, V3, ...])
219    ($entity:expr, [$first:ty, $($rest:ty),+ $(,)?]) => {
220        $crate::migrator_vec_helper!($first; $($rest),+; $entity)
221    };
222
223    // With custom keys: migrate_path!("entity", [V1, V2, ...], version_key = "v", data_key = "d")
224    ($entity:expr, [$first:ty, $($rest:ty),+ $(,)?], version_key = $version_key:expr, data_key = $data_key:expr) => {
225        $crate::migrator_vec_helper_with_keys!($first; $($rest),+; $entity; $version_key; $data_key)
226    };
227}
228
229/// Helper macro for Vec notation without custom keys
230#[doc(hidden)]
231#[macro_export]
232macro_rules! migrator_vec_helper {
233    // Base case: two versions left
234    ($first:ty; $last:ty; $entity:expr) => {
235        $crate::Migrator::define($entity)
236            .from::<$first>()
237            .into::<$last>()
238    };
239
240    // Recursive case: more than two versions
241    ($first:ty; $second:ty, $($rest:ty),+; $entity:expr) => {
242        $crate::migrator_vec_build_steps!($first; $($rest),+; $entity; {
243            $crate::Migrator::define($entity).from::<$first>().step::<$second>()
244        })
245    };
246}
247
248/// Helper for building all steps, then applying final .into()
249#[doc(hidden)]
250#[macro_export]
251macro_rules! migrator_vec_build_steps {
252    // Final case: last version, call .into()
253    ($first:ty; $last:ty; $entity:expr; { $builder:expr }) => {
254        $builder.into::<$last>()
255    };
256
257    // Recursive case: add .step() and continue
258    ($first:ty; $current:ty, $($rest:ty),+; $entity:expr; { $builder:expr }) => {
259        $crate::migrator_vec_build_steps!($first; $($rest),+; $entity; {
260            $builder.step::<$current>()
261        })
262    };
263}
264
265/// Helper macro for Vec notation with custom keys
266#[doc(hidden)]
267#[macro_export]
268macro_rules! migrator_vec_helper_with_keys {
269    // Base case: two versions left
270    ($first:ty; $last:ty; $entity:expr; $version_key:expr; $data_key:expr) => {
271        $crate::Migrator::define($entity)
272            .with_keys($version_key, $data_key)
273            .from::<$first>()
274            .into::<$last>()
275    };
276
277    // Recursive case: more than two versions
278    ($first:ty; $second:ty, $($rest:ty),+; $entity:expr; $version_key:expr; $data_key:expr) => {
279        $crate::migrator_vec_build_steps_with_keys!($first; $($rest),+; $entity; $version_key; $data_key; {
280            $crate::Migrator::define($entity).with_keys($version_key, $data_key).from::<$first>().step::<$second>()
281        })
282    };
283}
284
285/// Helper for building all steps with custom keys, then applying final .into()
286#[doc(hidden)]
287#[macro_export]
288macro_rules! migrator_vec_build_steps_with_keys {
289    // Final case: last version, call .into()
290    ($first:ty; $last:ty; $entity:expr; $version_key:expr; $data_key:expr; { $builder:expr }) => {
291        $builder.into::<$last>()
292    };
293
294    // Recursive case: add .step() and continue
295    ($first:ty; $current:ty, $($rest:ty),+; $entity:expr; $version_key:expr; $data_key:expr; { $builder:expr }) => {
296        $crate::migrator_vec_build_steps_with_keys!($first; $($rest),+; $entity; $version_key; $data_key; {
297            $builder.step::<$current>()
298        })
299    };
300}
301
302/// Creates a fully initialized `Migrator` with registered migration paths.
303///
304/// This macro creates a `Migrator` instance and registers one or more migration paths,
305/// returning a ready-to-use migrator. This is the recommended way to create a migrator
306/// as it's more concise than manually calling `Migrator::new()` and `register()` for each path.
307///
308/// # Syntax
309///
310/// Single path:
311/// ```ignore
312/// migrator!("entity" => [V1, V2, V3])
313/// ```
314///
315/// Multiple paths:
316/// ```ignore
317/// migrator!(
318///     "task" => [TaskV1, TaskV2, TaskV3],
319///     "user" => [UserV1, UserV2]
320/// )
321/// ```
322///
323/// With custom keys:
324/// ```ignore
325/// migrator!(
326///     "task" => [TaskV1, TaskV2], version_key = "v", data_key = "d"
327/// )
328/// ```
329///
330/// # Examples
331///
332/// ```ignore
333/// use version_migrate::migrator;
334///
335/// // Single entity migration
336/// let migrator = migrator!("task" => [TaskV1, TaskV2, TaskV3]).unwrap();
337///
338/// // Multiple entities
339/// let migrator = migrator!(
340///     "task" => [TaskV1, TaskV2],
341///     "user" => [UserV1, UserV2]
342/// ).unwrap();
343///
344/// // Now ready to use
345/// let domain: TaskEntity = migrator.load("task", json_str)?;
346/// ```
347///
348/// # Returns
349///
350/// Returns `Result<Migrator, MigrationError>`. The migrator is ready to use if `Ok`.
351#[macro_export]
352macro_rules! migrator {
353    // Single path without custom keys
354    ($entity:expr => [$first:ty, $($rest:ty),+ $(,)?]) => {{
355        let mut migrator = $crate::Migrator::new();
356        let path = $crate::migrate_path!($entity, [$first, $($rest),+]);
357        migrator.register(path).map(|_| migrator)
358    }};
359
360    // Single path with custom keys
361    ($entity:expr => [$first:ty, $($rest:ty),+ $(,)?], version_key = $version_key:expr, data_key = $data_key:expr) => {{
362        let mut migrator = $crate::Migrator::new();
363        let path = $crate::migrate_path!($entity, [$first, $($rest),+], version_key = $version_key, data_key = $data_key);
364        migrator.register(path).map(|_| migrator)
365    }};
366
367    // Multiple paths without custom keys
368    ($($entity:expr => [$first:ty, $($rest:ty),+ $(,)?]),+ $(,)?) => {{
369        let mut migrator = $crate::Migrator::new();
370        $(
371            let path = $crate::migrate_path!($entity, [$first, $($rest),+]);
372            migrator.register(path)?;
373        )+
374        Ok::<$crate::Migrator, $crate::MigrationError>(migrator)
375    }};
376}
377
378// Re-export error types
379pub use errors::{IoOperationKind, MigrationError};
380
381// Re-export migrator types
382pub use migrator::{ConfigMigrator, MigrationPath, Migrator};
383
384// Re-export storage types
385pub use storage::{
386    AtomicWriteConfig, FileStorage, FileStorageStrategy, FormatStrategy, LoadBehavior,
387};
388
389// Re-export dir_storage types
390pub use dir_storage::{DirStorage, DirStorageStrategy, FilenameEncoding};
391
392#[cfg(feature = "async")]
393pub use dir_storage::AsyncDirStorage;
394
395// Re-export paths types
396pub use paths::{AppPaths, PathStrategy, PrefPath};
397
398// Re-export async-trait for user convenience
399#[cfg(feature = "async")]
400pub use async_trait::async_trait;
401
402/// A trait for versioned data schemas.
403///
404/// This trait marks a type as representing a specific version of a data schema.
405/// It should be derived using `#[derive(Versioned)]` along with the `#[versioned(version = "x.y.z")]` attribute.
406///
407/// # Custom Keys
408///
409/// You can customize the serialization keys:
410///
411/// ```ignore
412/// #[derive(Versioned)]
413/// #[versioned(
414///     version = "1.0.0",
415///     version_key = "schema_version",
416///     data_key = "payload"
417/// )]
418/// struct Task { ... }
419/// // Serializes to: {"schema_version":"1.0.0","payload":{...}}
420/// ```
421pub trait Versioned {
422    /// The semantic version of this schema.
423    const VERSION: &'static str;
424
425    /// The key name for the version field in serialized data.
426    /// Defaults to "version".
427    const VERSION_KEY: &'static str = "version";
428
429    /// The key name for the data field in serialized data.
430    /// Defaults to "data".
431    const DATA_KEY: &'static str = "data";
432}
433
434/// Defines explicit migration logic from one version to another.
435///
436/// Implementing this trait establishes a migration path from `Self` (the source version)
437/// to `T` (the target version).
438pub trait MigratesTo<T: Versioned>: Versioned {
439    /// Migrates from the current version to the target version.
440    fn migrate(self) -> T;
441}
442
443/// Converts a versioned DTO into the application's domain model.
444///
445/// This trait should be implemented on the latest version of a DTO to convert
446/// it into the clean, version-agnostic domain model.
447pub trait IntoDomain<D>: Versioned {
448    /// Converts this versioned data into the domain model.
449    fn into_domain(self) -> D;
450}
451
452/// Converts a domain model back into a versioned DTO.
453///
454/// This trait should be implemented on versioned DTOs to enable conversion
455/// from the domain model back to the versioned format for serialization.
456///
457/// # Example
458///
459/// ```ignore
460/// impl FromDomain<TaskEntity> for TaskV1_1_0 {
461///     fn from_domain(domain: TaskEntity) -> Self {
462///         TaskV1_1_0 {
463///             id: domain.id,
464///             title: domain.title,
465///             description: domain.description,
466///         }
467///     }
468/// }
469/// ```
470pub trait FromDomain<D>: Versioned + Serialize {
471    /// Converts a domain model into this versioned format.
472    fn from_domain(domain: D) -> Self;
473}
474
475/// Associates a domain entity with its latest versioned representation.
476///
477/// This trait enables automatic saving of domain entities using their latest version.
478/// It should typically be derived using the `#[version_migrate]` attribute macro.
479///
480/// # Example
481///
482/// ```ignore
483/// #[derive(Serialize, Deserialize)]
484/// #[version_migrate(entity = "task", latest = TaskV1_1_0)]
485/// struct TaskEntity {
486///     id: String,
487///     title: String,
488///     description: Option<String>,
489/// }
490///
491/// // Now you can save entities directly
492/// let entity = TaskEntity { ... };
493/// let json = migrator.save_entity(entity)?;
494/// ```
495pub trait LatestVersioned: Sized {
496    /// The latest versioned type for this entity.
497    type Latest: Versioned + Serialize + FromDomain<Self>;
498
499    /// The entity name used for migration paths.
500    const ENTITY_NAME: &'static str;
501
502    /// Whether this entity supports saving functionality.
503    /// When `false` (default), uses `into()` for read-only access.
504    /// When `true`, uses `into_with_save()` to enable domain entity saving.
505    const SAVE: bool = false;
506
507    /// Converts this domain entity into its latest versioned format.
508    fn to_latest(self) -> Self::Latest {
509        Self::Latest::from_domain(self)
510    }
511}
512
513/// Marks a domain type as queryable, associating it with an entity name.
514///
515/// This trait enables `ConfigMigrator` to automatically determine which entity
516/// path to use when querying or updating data.
517///
518/// # Example
519///
520/// ```ignore
521/// impl Queryable for TaskEntity {
522///     const ENTITY_NAME: &'static str = "task";
523/// }
524///
525/// let tasks: Vec<TaskEntity> = config.query("tasks")?;
526/// ```
527pub trait Queryable {
528    /// The entity name used to look up migration paths in the `Migrator`.
529    const ENTITY_NAME: &'static str;
530}
531
532/// Async version of `MigratesTo` for migrations requiring I/O operations.
533///
534/// Use this trait when migrations need to perform asynchronous operations
535/// such as database queries or API calls.
536#[cfg(feature = "async")]
537#[async_trait::async_trait]
538pub trait AsyncMigratesTo<T: Versioned>: Versioned + Send {
539    /// Asynchronously migrates from the current version to the target version.
540    ///
541    /// # Errors
542    ///
543    /// Returns `MigrationError` if the migration fails.
544    async fn migrate(self) -> Result<T, MigrationError>;
545}
546
547/// Async version of `IntoDomain` for domain conversions requiring I/O operations.
548///
549/// Use this trait when converting to the domain model requires asynchronous
550/// operations such as fetching additional data from external sources.
551#[cfg(feature = "async")]
552#[async_trait::async_trait]
553pub trait AsyncIntoDomain<D>: Versioned + Send {
554    /// Asynchronously converts this versioned data into the domain model.
555    ///
556    /// # Errors
557    ///
558    /// Returns `MigrationError` if the conversion fails.
559    async fn into_domain(self) -> Result<D, MigrationError>;
560}
561
562/// A wrapper for serialized data that includes explicit version information.
563///
564/// This struct is used for persistence to ensure that the version of the data
565/// is always stored alongside the data itself.
566#[derive(Serialize, Deserialize, Debug, Clone)]
567pub struct VersionedWrapper<T> {
568    /// The semantic version of the data.
569    pub version: String,
570    /// The actual data.
571    pub data: T,
572}
573
574impl<T> VersionedWrapper<T> {
575    /// Creates a new versioned wrapper with the specified version and data.
576    pub fn new(version: String, data: T) -> Self {
577        Self { version, data }
578    }
579}
580
581impl<T: Versioned> VersionedWrapper<T> {
582    /// Creates a wrapper from a versioned value, automatically extracting its version.
583    pub fn from_versioned(data: T) -> Self {
584        Self {
585            version: T::VERSION.to_string(),
586            data,
587        }
588    }
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
596    struct TestData {
597        value: String,
598    }
599
600    impl Versioned for TestData {
601        const VERSION: &'static str = "1.0.0";
602    }
603
604    #[test]
605    fn test_versioned_wrapper_from_versioned() {
606        let data = TestData {
607            value: "test".to_string(),
608        };
609        let wrapper = VersionedWrapper::from_versioned(data);
610
611        assert_eq!(wrapper.version, "1.0.0");
612        assert_eq!(wrapper.data.value, "test");
613    }
614
615    #[test]
616    fn test_versioned_wrapper_new() {
617        let data = TestData {
618            value: "manual".to_string(),
619        };
620        let wrapper = VersionedWrapper::new("2.0.0".to_string(), data);
621
622        assert_eq!(wrapper.version, "2.0.0");
623        assert_eq!(wrapper.data.value, "manual");
624    }
625
626    #[test]
627    fn test_versioned_wrapper_serialization() {
628        let data = TestData {
629            value: "serialize_test".to_string(),
630        };
631        let wrapper = VersionedWrapper::from_versioned(data);
632
633        // Serialize
634        let json = serde_json::to_string(&wrapper).expect("Serialization failed");
635
636        // Deserialize
637        let deserialized: VersionedWrapper<TestData> =
638            serde_json::from_str(&json).expect("Deserialization failed");
639
640        assert_eq!(deserialized.version, "1.0.0");
641        assert_eq!(deserialized.data.value, "serialize_test");
642    }
643
644    #[test]
645    fn test_versioned_wrapper_with_complex_data() {
646        #[derive(Serialize, Deserialize, Debug, PartialEq)]
647        struct ComplexData {
648            id: u64,
649            name: String,
650            tags: Vec<String>,
651            metadata: Option<String>,
652        }
653
654        impl Versioned for ComplexData {
655            const VERSION: &'static str = "3.2.1";
656        }
657
658        let data = ComplexData {
659            id: 42,
660            name: "complex".to_string(),
661            tags: vec!["tag1".to_string(), "tag2".to_string()],
662            metadata: Some("meta".to_string()),
663        };
664
665        let wrapper = VersionedWrapper::from_versioned(data);
666        assert_eq!(wrapper.version, "3.2.1");
667        assert_eq!(wrapper.data.id, 42);
668        assert_eq!(wrapper.data.tags.len(), 2);
669    }
670
671    #[test]
672    fn test_versioned_wrapper_clone() {
673        let data = TestData {
674            value: "clone_test".to_string(),
675        };
676        let wrapper = VersionedWrapper::from_versioned(data);
677        let cloned = wrapper.clone();
678
679        assert_eq!(cloned.version, wrapper.version);
680        assert_eq!(cloned.data.value, wrapper.data.value);
681    }
682
683    #[test]
684    fn test_versioned_wrapper_debug() {
685        let data = TestData {
686            value: "debug".to_string(),
687        };
688        let wrapper = VersionedWrapper::from_versioned(data);
689        let debug_str = format!("{:?}", wrapper);
690
691        assert!(debug_str.contains("1.0.0"));
692        assert!(debug_str.contains("debug"));
693    }
694}