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//! - **Vec support**: Migrate collections of versioned entities
11//! - **Hierarchical structures**: Support for nested versioned entities
12//! - **Async migrations**: Optional async support for I/O-heavy migrations
13//!
14//! ## Basic Example
15//!
16//! ```ignore
17//! use version_migrate::{Versioned, MigratesTo, IntoDomain, Migrator};
18//! use serde::{Serialize, Deserialize};
19//!
20//! // Version 1.0.0
21//! #[derive(Serialize, Deserialize, Versioned)]
22//! #[versioned(version = "1.0.0")]
23//! struct TaskV1_0_0 {
24//! id: String,
25//! title: String,
26//! }
27//!
28//! // Version 1.1.0
29//! #[derive(Serialize, Deserialize, Versioned)]
30//! #[versioned(version = "1.1.0")]
31//! struct TaskV1_1_0 {
32//! id: String,
33//! title: String,
34//! description: Option<String>,
35//! }
36//!
37//! // Domain model
38//! struct TaskEntity {
39//! id: String,
40//! title: String,
41//! description: Option<String>,
42//! }
43//!
44//! impl MigratesTo<TaskV1_1_0> for TaskV1_0_0 {
45//! fn migrate(self) -> TaskV1_1_0 {
46//! TaskV1_1_0 {
47//! id: self.id,
48//! title: self.title,
49//! description: None,
50//! }
51//! }
52//! }
53//!
54//! impl IntoDomain<TaskEntity> for TaskV1_1_0 {
55//! fn into_domain(self) -> TaskEntity {
56//! TaskEntity {
57//! id: self.id,
58//! title: self.title,
59//! description: self.description,
60//! }
61//! }
62//! }
63//! ```
64//!
65//! ## Working with Collections (Vec)
66//!
67//! ```ignore
68//! // Save multiple versioned entities
69//! let tasks = vec![
70//! TaskV1_0_0 { id: "1".into(), title: "Task 1".into() },
71//! TaskV1_0_0 { id: "2".into(), title: "Task 2".into() },
72//! ];
73//! let json = migrator.save_vec(tasks)?;
74//!
75//! // Load and migrate multiple entities
76//! let domains: Vec<TaskEntity> = migrator.load_vec("task", &json)?;
77//! ```
78//!
79//! ## Hierarchical Structures
80//!
81//! For complex configurations with nested versioned entities:
82//!
83//! ```ignore
84//! #[derive(Serialize, Deserialize, Versioned)]
85//! #[versioned(version = "1.0.0")]
86//! struct ConfigV1 {
87//! setting: SettingV1,
88//! items: Vec<ItemV1>,
89//! }
90//!
91//! #[derive(Serialize, Deserialize, Versioned)]
92//! #[versioned(version = "2.0.0")]
93//! struct ConfigV2 {
94//! setting: SettingV2,
95//! items: Vec<ItemV2>,
96//! }
97//!
98//! impl MigratesTo<ConfigV2> for ConfigV1 {
99//! fn migrate(self) -> ConfigV2 {
100//! ConfigV2 {
101//! // Migrate nested entities
102//! setting: self.setting.migrate(),
103//! items: self.items.into_iter()
104//! .map(|item| item.migrate())
105//! .collect(),
106//! }
107//! }
108//! }
109//! ```
110//!
111//! ## Design Philosophy
112//!
113//! This library follows the **explicit versioning** approach:
114//!
115//! - Each version has its own type (V1, V2, V3, etc.)
116//! - Migration logic is explicit and testable
117//! - Version changes are tracked in code
118//! - Root-level versioning ensures consistency
119//!
120//! This differs from ProtoBuf's "append-only" approach but allows for:
121//! - Schema refactoring and cleanup
122//! - Type-safe migration paths
123//! - Clear version history in code
124
125use serde::{Deserialize, Serialize};
126
127pub mod errors;
128mod migrator;
129pub mod paths;
130pub mod storage;
131
132// Re-export the derive macros
133pub use version_migrate_macro::Versioned;
134
135// Re-export Queryable derive macro (same name as trait is OK in Rust)
136#[doc(inline)]
137pub use version_migrate_macro::Queryable as DeriveQueryable;
138
139// Re-export error types
140pub use errors::MigrationError;
141
142// Re-export migrator types
143pub use migrator::{ConfigMigrator, MigrationPath, Migrator};
144
145// Re-export storage types
146pub use storage::{
147 AtomicWriteConfig, FileStorage, FileStorageStrategy, FormatStrategy, LoadBehavior,
148};
149
150// Re-export paths types
151pub use paths::{AppPaths, PathStrategy};
152
153// Re-export async-trait for user convenience
154pub use async_trait::async_trait;
155
156/// A trait for versioned data schemas.
157///
158/// This trait marks a type as representing a specific version of a data schema.
159/// It should be derived using `#[derive(Versioned)]` along with the `#[versioned(version = "x.y.z")]` attribute.
160///
161/// # Custom Keys
162///
163/// You can customize the serialization keys:
164///
165/// ```ignore
166/// #[derive(Versioned)]
167/// #[versioned(
168/// version = "1.0.0",
169/// version_key = "schema_version",
170/// data_key = "payload"
171/// )]
172/// struct Task { ... }
173/// // Serializes to: {"schema_version":"1.0.0","payload":{...}}
174/// ```
175pub trait Versioned {
176 /// The semantic version of this schema.
177 const VERSION: &'static str;
178
179 /// The key name for the version field in serialized data.
180 /// Defaults to "version".
181 const VERSION_KEY: &'static str = "version";
182
183 /// The key name for the data field in serialized data.
184 /// Defaults to "data".
185 const DATA_KEY: &'static str = "data";
186}
187
188/// Defines explicit migration logic from one version to another.
189///
190/// Implementing this trait establishes a migration path from `Self` (the source version)
191/// to `T` (the target version).
192pub trait MigratesTo<T: Versioned>: Versioned {
193 /// Migrates from the current version to the target version.
194 fn migrate(self) -> T;
195}
196
197/// Converts a versioned DTO into the application's domain model.
198///
199/// This trait should be implemented on the latest version of a DTO to convert
200/// it into the clean, version-agnostic domain model.
201pub trait IntoDomain<D>: Versioned {
202 /// Converts this versioned data into the domain model.
203 fn into_domain(self) -> D;
204}
205
206/// Marks a domain type as queryable, associating it with an entity name.
207///
208/// This trait enables `ConfigMigrator` to automatically determine which entity
209/// path to use when querying or updating data.
210///
211/// # Example
212///
213/// ```ignore
214/// impl Queryable for TaskEntity {
215/// const ENTITY_NAME: &'static str = "task";
216/// }
217///
218/// let tasks: Vec<TaskEntity> = config.query("tasks")?;
219/// ```
220pub trait Queryable {
221 /// The entity name used to look up migration paths in the `Migrator`.
222 const ENTITY_NAME: &'static str;
223}
224
225/// Async version of `MigratesTo` for migrations requiring I/O operations.
226///
227/// Use this trait when migrations need to perform asynchronous operations
228/// such as database queries or API calls.
229#[async_trait::async_trait]
230pub trait AsyncMigratesTo<T: Versioned>: Versioned + Send {
231 /// Asynchronously migrates from the current version to the target version.
232 ///
233 /// # Errors
234 ///
235 /// Returns `MigrationError` if the migration fails.
236 async fn migrate(self) -> Result<T, MigrationError>;
237}
238
239/// Async version of `IntoDomain` for domain conversions requiring I/O operations.
240///
241/// Use this trait when converting to the domain model requires asynchronous
242/// operations such as fetching additional data from external sources.
243#[async_trait::async_trait]
244pub trait AsyncIntoDomain<D>: Versioned + Send {
245 /// Asynchronously converts this versioned data into the domain model.
246 ///
247 /// # Errors
248 ///
249 /// Returns `MigrationError` if the conversion fails.
250 async fn into_domain(self) -> Result<D, MigrationError>;
251}
252
253/// A wrapper for serialized data that includes explicit version information.
254///
255/// This struct is used for persistence to ensure that the version of the data
256/// is always stored alongside the data itself.
257#[derive(Serialize, Deserialize, Debug, Clone)]
258pub struct VersionedWrapper<T> {
259 /// The semantic version of the data.
260 pub version: String,
261 /// The actual data.
262 pub data: T,
263}
264
265impl<T> VersionedWrapper<T> {
266 /// Creates a new versioned wrapper with the specified version and data.
267 pub fn new(version: String, data: T) -> Self {
268 Self { version, data }
269 }
270}
271
272impl<T: Versioned> VersionedWrapper<T> {
273 /// Creates a wrapper from a versioned value, automatically extracting its version.
274 pub fn from_versioned(data: T) -> Self {
275 Self {
276 version: T::VERSION.to_string(),
277 data,
278 }
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285
286 #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
287 struct TestData {
288 value: String,
289 }
290
291 impl Versioned for TestData {
292 const VERSION: &'static str = "1.0.0";
293 }
294
295 #[test]
296 fn test_versioned_wrapper_from_versioned() {
297 let data = TestData {
298 value: "test".to_string(),
299 };
300 let wrapper = VersionedWrapper::from_versioned(data);
301
302 assert_eq!(wrapper.version, "1.0.0");
303 assert_eq!(wrapper.data.value, "test");
304 }
305
306 #[test]
307 fn test_versioned_wrapper_new() {
308 let data = TestData {
309 value: "manual".to_string(),
310 };
311 let wrapper = VersionedWrapper::new("2.0.0".to_string(), data);
312
313 assert_eq!(wrapper.version, "2.0.0");
314 assert_eq!(wrapper.data.value, "manual");
315 }
316
317 #[test]
318 fn test_versioned_wrapper_serialization() {
319 let data = TestData {
320 value: "serialize_test".to_string(),
321 };
322 let wrapper = VersionedWrapper::from_versioned(data);
323
324 // Serialize
325 let json = serde_json::to_string(&wrapper).expect("Serialization failed");
326
327 // Deserialize
328 let deserialized: VersionedWrapper<TestData> =
329 serde_json::from_str(&json).expect("Deserialization failed");
330
331 assert_eq!(deserialized.version, "1.0.0");
332 assert_eq!(deserialized.data.value, "serialize_test");
333 }
334
335 #[test]
336 fn test_versioned_wrapper_with_complex_data() {
337 #[derive(Serialize, Deserialize, Debug, PartialEq)]
338 struct ComplexData {
339 id: u64,
340 name: String,
341 tags: Vec<String>,
342 metadata: Option<String>,
343 }
344
345 impl Versioned for ComplexData {
346 const VERSION: &'static str = "3.2.1";
347 }
348
349 let data = ComplexData {
350 id: 42,
351 name: "complex".to_string(),
352 tags: vec!["tag1".to_string(), "tag2".to_string()],
353 metadata: Some("meta".to_string()),
354 };
355
356 let wrapper = VersionedWrapper::from_versioned(data);
357 assert_eq!(wrapper.version, "3.2.1");
358 assert_eq!(wrapper.data.id, 42);
359 assert_eq!(wrapper.data.tags.len(), 2);
360 }
361
362 #[test]
363 fn test_versioned_wrapper_clone() {
364 let data = TestData {
365 value: "clone_test".to_string(),
366 };
367 let wrapper = VersionedWrapper::from_versioned(data);
368 let cloned = wrapper.clone();
369
370 assert_eq!(cloned.version, wrapper.version);
371 assert_eq!(cloned.data.value, wrapper.data.value);
372 }
373
374 #[test]
375 fn test_versioned_wrapper_debug() {
376 let data = TestData {
377 value: "debug".to_string(),
378 };
379 let wrapper = VersionedWrapper::from_versioned(data);
380 let debug_str = format!("{:?}", wrapper);
381
382 assert!(debug_str.contains("1.0.0"));
383 assert!(debug_str.contains("debug"));
384 }
385}