version-migrate 0.20.0

Explicit, type-safe schema versioning and migration for Rust
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
use serde::{Deserialize, Serialize};
use version_migrate::{migrate_path, IntoDomain, MigratesTo, Migrator, Versioned};

// Define test versions V1 through V10
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TaskV1 {
    id: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TaskV2 {
    id: String,
    title: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TaskV3 {
    id: String,
    title: String,
    description: Option<String>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TaskV4 {
    id: String,
    title: String,
    description: Option<String>,
    status: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TaskV5 {
    id: String,
    title: String,
    description: Option<String>,
    status: String,
    priority: i32,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TaskV6 {
    id: String,
    title: String,
    description: Option<String>,
    status: String,
    priority: i32,
    tags: Vec<String>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TaskV7 {
    id: String,
    title: String,
    description: Option<String>,
    status: String,
    priority: i32,
    tags: Vec<String>,
    due_date: Option<String>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TaskV8 {
    id: String,
    title: String,
    description: Option<String>,
    status: String,
    priority: i32,
    tags: Vec<String>,
    due_date: Option<String>,
    assignee: Option<String>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TaskV9 {
    id: String,
    title: String,
    description: Option<String>,
    status: String,
    priority: i32,
    tags: Vec<String>,
    due_date: Option<String>,
    assignee: Option<String>,
    created_at: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TaskV10 {
    id: String,
    title: String,
    description: Option<String>,
    status: String,
    priority: i32,
    tags: Vec<String>,
    due_date: Option<String>,
    assignee: Option<String>,
    created_at: String,
    updated_at: String,
}

// Domain model
#[derive(Debug, PartialEq)]
struct TaskEntity {
    id: String,
    title: String,
    description: Option<String>,
    status: String,
    priority: i32,
    tags: Vec<String>,
    due_date: Option<String>,
    assignee: Option<String>,
    created_at: String,
    updated_at: String,
}

// Implement Versioned for all versions
impl Versioned for TaskV1 {
    const VERSION: &'static str = "1.0.0";
}

impl Versioned for TaskV2 {
    const VERSION: &'static str = "2.0.0";
}

impl Versioned for TaskV3 {
    const VERSION: &'static str = "3.0.0";
}

impl Versioned for TaskV4 {
    const VERSION: &'static str = "4.0.0";
}

impl Versioned for TaskV5 {
    const VERSION: &'static str = "5.0.0";
}

impl Versioned for TaskV6 {
    const VERSION: &'static str = "6.0.0";
}

impl Versioned for TaskV7 {
    const VERSION: &'static str = "7.0.0";
}

impl Versioned for TaskV8 {
    const VERSION: &'static str = "8.0.0";
}

impl Versioned for TaskV9 {
    const VERSION: &'static str = "9.0.0";
}

impl Versioned for TaskV10 {
    const VERSION: &'static str = "10.0.0";
}

// Implement migration chain
impl MigratesTo<TaskV2> for TaskV1 {
    fn migrate(self) -> TaskV2 {
        TaskV2 {
            id: self.id,
            title: "Untitled".to_string(),
        }
    }
}

impl MigratesTo<TaskV3> for TaskV2 {
    fn migrate(self) -> TaskV3 {
        TaskV3 {
            id: self.id,
            title: self.title,
            description: None,
        }
    }
}

impl MigratesTo<TaskV4> for TaskV3 {
    fn migrate(self) -> TaskV4 {
        TaskV4 {
            id: self.id,
            title: self.title,
            description: self.description,
            status: "open".to_string(),
        }
    }
}

impl MigratesTo<TaskV5> for TaskV4 {
    fn migrate(self) -> TaskV5 {
        TaskV5 {
            id: self.id,
            title: self.title,
            description: self.description,
            status: self.status,
            priority: 0,
        }
    }
}

impl MigratesTo<TaskV6> for TaskV5 {
    fn migrate(self) -> TaskV6 {
        TaskV6 {
            id: self.id,
            title: self.title,
            description: self.description,
            status: self.status,
            priority: self.priority,
            tags: vec![],
        }
    }
}

impl MigratesTo<TaskV7> for TaskV6 {
    fn migrate(self) -> TaskV7 {
        TaskV7 {
            id: self.id,
            title: self.title,
            description: self.description,
            status: self.status,
            priority: self.priority,
            tags: self.tags,
            due_date: None,
        }
    }
}

impl MigratesTo<TaskV8> for TaskV7 {
    fn migrate(self) -> TaskV8 {
        TaskV8 {
            id: self.id,
            title: self.title,
            description: self.description,
            status: self.status,
            priority: self.priority,
            tags: self.tags,
            due_date: self.due_date,
            assignee: None,
        }
    }
}

impl MigratesTo<TaskV9> for TaskV8 {
    fn migrate(self) -> TaskV9 {
        TaskV9 {
            id: self.id,
            title: self.title,
            description: self.description,
            status: self.status,
            priority: self.priority,
            tags: self.tags,
            due_date: self.due_date,
            assignee: self.assignee,
            created_at: "2023-01-01T00:00:00Z".to_string(),
        }
    }
}

impl MigratesTo<TaskV10> for TaskV9 {
    fn migrate(self) -> TaskV10 {
        TaskV10 {
            id: self.id,
            title: self.title,
            description: self.description,
            status: self.status,
            priority: self.priority,
            tags: self.tags,
            due_date: self.due_date,
            assignee: self.assignee,
            created_at: self.created_at,
            updated_at: "2023-01-01T00:00:00Z".to_string(),
        }
    }
}

// Implement IntoDomain for each version to all subsequent versions and TaskEntity
impl IntoDomain<TaskV2> for TaskV1 {
    fn into_domain(self) -> TaskV2 {
        self.migrate()
    }
}

impl IntoDomain<TaskV3> for TaskV2 {
    fn into_domain(self) -> TaskV3 {
        self.migrate()
    }
}

impl IntoDomain<TaskV4> for TaskV3 {
    fn into_domain(self) -> TaskV4 {
        self.migrate()
    }
}

impl IntoDomain<TaskV5> for TaskV4 {
    fn into_domain(self) -> TaskV5 {
        self.migrate()
    }
}

impl IntoDomain<TaskV6> for TaskV5 {
    fn into_domain(self) -> TaskV6 {
        self.migrate()
    }
}

impl IntoDomain<TaskV7> for TaskV6 {
    fn into_domain(self) -> TaskV7 {
        self.migrate()
    }
}

impl IntoDomain<TaskV8> for TaskV7 {
    fn into_domain(self) -> TaskV8 {
        self.migrate()
    }
}

impl IntoDomain<TaskV9> for TaskV8 {
    fn into_domain(self) -> TaskV9 {
        self.migrate()
    }
}

impl IntoDomain<TaskV10> for TaskV9 {
    fn into_domain(self) -> TaskV10 {
        self.migrate()
    }
}

// Implement IntoDomain<TaskEntity> for intermediate versions through full migration chain
impl IntoDomain<TaskEntity> for TaskV5 {
    fn into_domain(self) -> TaskEntity {
        // V5 -> V6 -> V7 -> V8 -> V9 -> V10 -> TaskEntity
        self.migrate()
            .migrate()
            .migrate()
            .migrate()
            .migrate()
            .into_domain()
    }
}

impl IntoDomain<TaskEntity> for TaskV10 {
    fn into_domain(self) -> TaskEntity {
        TaskEntity {
            id: self.id,
            title: self.title,
            description: self.description,
            status: self.status,
            priority: self.priority,
            tags: self.tags,
            due_date: self.due_date,
            assignee: self.assignee,
            created_at: self.created_at,
            updated_at: self.updated_at,
        }
    }
}

// Add Serialize/Deserialize to TaskEntity
impl Serialize for TaskEntity {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("TaskEntity", 10)?;
        state.serialize_field("id", &self.id)?;
        state.serialize_field("title", &self.title)?;
        state.serialize_field("description", &self.description)?;
        state.serialize_field("status", &self.status)?;
        state.serialize_field("priority", &self.priority)?;
        state.serialize_field("tags", &self.tags)?;
        state.serialize_field("due_date", &self.due_date)?;
        state.serialize_field("assignee", &self.assignee)?;
        state.serialize_field("created_at", &self.created_at)?;
        state.serialize_field("updated_at", &self.updated_at)?;
        state.end()
    }
}

impl<'de> Deserialize<'de> for TaskEntity {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(field_identifier, rename_all = "snake_case")]
        enum Field {
            Id,
            Title,
            Description,
            Status,
            Priority,
            Tags,
            DueDate,
            Assignee,
            CreatedAt,
            UpdatedAt,
        }

        struct TaskEntityVisitor;

        impl<'de> serde::de::Visitor<'de> for TaskEntityVisitor {
            type Value = TaskEntity;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("struct TaskEntity")
            }

            fn visit_map<V>(self, mut map: V) -> Result<TaskEntity, V::Error>
            where
                V: serde::de::MapAccess<'de>,
            {
                let mut id = None;
                let mut title = None;
                let mut description = None;
                let mut status = None;
                let mut priority = None;
                let mut tags = None;
                let mut due_date = None;
                let mut assignee = None;
                let mut created_at = None;
                let mut updated_at = None;

                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Id => {
                            if id.is_some() {
                                return Err(serde::de::Error::duplicate_field("id"));
                            }
                            id = Some(map.next_value()?);
                        }
                        Field::Title => {
                            if title.is_some() {
                                return Err(serde::de::Error::duplicate_field("title"));
                            }
                            title = Some(map.next_value()?);
                        }
                        Field::Description => {
                            if description.is_some() {
                                return Err(serde::de::Error::duplicate_field("description"));
                            }
                            description = Some(map.next_value()?);
                        }
                        Field::Status => {
                            if status.is_some() {
                                return Err(serde::de::Error::duplicate_field("status"));
                            }
                            status = Some(map.next_value()?);
                        }
                        Field::Priority => {
                            if priority.is_some() {
                                return Err(serde::de::Error::duplicate_field("priority"));
                            }
                            priority = Some(map.next_value()?);
                        }
                        Field::Tags => {
                            if tags.is_some() {
                                return Err(serde::de::Error::duplicate_field("tags"));
                            }
                            tags = Some(map.next_value()?);
                        }
                        Field::DueDate => {
                            if due_date.is_some() {
                                return Err(serde::de::Error::duplicate_field("due_date"));
                            }
                            due_date = Some(map.next_value()?);
                        }
                        Field::Assignee => {
                            if assignee.is_some() {
                                return Err(serde::de::Error::duplicate_field("assignee"));
                            }
                            assignee = Some(map.next_value()?);
                        }
                        Field::CreatedAt => {
                            if created_at.is_some() {
                                return Err(serde::de::Error::duplicate_field("created_at"));
                            }
                            created_at = Some(map.next_value()?);
                        }
                        Field::UpdatedAt => {
                            if updated_at.is_some() {
                                return Err(serde::de::Error::duplicate_field("updated_at"));
                            }
                            updated_at = Some(map.next_value()?);
                        }
                    }
                }

                let id = id.ok_or_else(|| serde::de::Error::missing_field("id"))?;
                let title = title.ok_or_else(|| serde::de::Error::missing_field("title"))?;
                let description =
                    description.ok_or_else(|| serde::de::Error::missing_field("description"))?;
                let status = status.ok_or_else(|| serde::de::Error::missing_field("status"))?;
                let priority =
                    priority.ok_or_else(|| serde::de::Error::missing_field("priority"))?;
                let tags = tags.ok_or_else(|| serde::de::Error::missing_field("tags"))?;
                let due_date =
                    due_date.ok_or_else(|| serde::de::Error::missing_field("due_date"))?;
                let assignee =
                    assignee.ok_or_else(|| serde::de::Error::missing_field("assignee"))?;
                let created_at =
                    created_at.ok_or_else(|| serde::de::Error::missing_field("created_at"))?;
                let updated_at =
                    updated_at.ok_or_else(|| serde::de::Error::missing_field("updated_at"))?;

                Ok(TaskEntity {
                    id,
                    title,
                    description,
                    status,
                    priority,
                    tags,
                    due_date,
                    assignee,
                    created_at,
                    updated_at,
                })
            }
        }

        const FIELDS: &[&str] = &[
            "id",
            "title",
            "description",
            "status",
            "priority",
            "tags",
            "due_date",
            "assignee",
            "created_at",
            "updated_at",
        ];
        deserializer.deserialize_struct("TaskEntity", FIELDS, TaskEntityVisitor)
    }
}

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

    #[test]
    fn test_vec_notation_6_versions() {
        let path = migrate_path!("task", [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskEntity]);
        let mut migrator = Migrator::new();
        migrator.register(path).unwrap();

        let original = TaskV1 {
            id: "task-1".to_string(),
        };
        let json = migrator.save(original).unwrap();

        // Should migrate through V5 and convert to domain
        let result: TaskEntity = migrator.load("task", &json).unwrap();
        assert_eq!(result.id, "task-1");
        assert_eq!(result.title, "Untitled");
        assert_eq!(result.tags, Vec::<String>::new());
    }

    #[test]
    fn test_vec_notation_7_versions() {
        let path = migrate_path!(
            "task",
            [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6, TaskV7]
        );
        let mut migrator = Migrator::new();
        migrator.register(path).unwrap();

        let original = TaskV1 {
            id: "task-1".to_string(),
        };
        let json = migrator.save(original).unwrap();

        let result: TaskV7 = migrator.load("task", &json).unwrap();
        assert_eq!(result.id, "task-1");
        assert_eq!(result.due_date, None);
    }

    #[test]
    fn test_vec_notation_8_versions() {
        let path = migrate_path!(
            "task",
            [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6, TaskV7, TaskV8]
        );
        let mut migrator = Migrator::new();
        migrator.register(path).unwrap();

        let original = TaskV1 {
            id: "task-1".to_string(),
        };
        let json = migrator.save(original).unwrap();

        let result: TaskV8 = migrator.load("task", &json).unwrap();
        assert_eq!(result.id, "task-1");
        assert_eq!(result.assignee, None);
    }

    #[test]
    fn test_vec_notation_9_versions() {
        let path = migrate_path!(
            "task",
            [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6, TaskV7, TaskV8, TaskV9]
        );
        let mut migrator = Migrator::new();
        migrator.register(path).unwrap();

        let original = TaskV1 {
            id: "task-1".to_string(),
        };
        let json = migrator.save(original).unwrap();

        let result: TaskV9 = migrator.load("task", &json).unwrap();
        assert_eq!(result.id, "task-1");
        assert_eq!(result.created_at, "2023-01-01T00:00:00Z");
    }

    #[test]
    fn test_vec_notation_10_versions() {
        let path = migrate_path!(
            "task",
            [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6, TaskV7, TaskV8, TaskV9, TaskV10]
        );
        let mut migrator = Migrator::new();
        migrator.register(path).unwrap();

        let original = TaskV1 {
            id: "task-1".to_string(),
        };
        let json = migrator.save(original).unwrap();

        let result: TaskEntity = migrator.load("task", &json).unwrap();
        assert_eq!(result.id, "task-1");
        assert_eq!(result.title, "Untitled");
        assert_eq!(result.created_at, "2023-01-01T00:00:00Z");
        assert_eq!(result.updated_at, "2023-01-01T00:00:00Z");
    }

    #[test]
    fn test_vec_notation_with_default_keys() {
        // Test that vec notation works with standard versioned types
        let path = migrate_path!(
            "task",
            [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6, TaskV7]
        );
        let mut migrator = Migrator::new();
        migrator.register(path).unwrap();

        let original = TaskV1 {
            id: "task-custom".to_string(),
        };
        let json = migrator.save(original).unwrap();

        // Check that default keys are used
        assert!(json.contains("\"version\""));
        assert!(json.contains("\"data\""));

        let result: TaskV7 = migrator.load("task", &json).unwrap();
        assert_eq!(result.id, "task-custom");
    }

    #[test]
    fn test_middle_version_migration() {
        let path = migrate_path!(
            "task",
            [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6, TaskV7, TaskV8]
        );
        let mut migrator = Migrator::new();
        migrator.register(path).unwrap();

        // Start from middle version
        let original = TaskV4 {
            id: "task-mid".to_string(),
            title: "Middle Task".to_string(),
            description: Some("From V4".to_string()),
            status: "in-progress".to_string(),
        };
        let json = migrator.save(original).unwrap();

        let result: TaskV8 = migrator.load("task", &json).unwrap();
        assert_eq!(result.id, "task-mid");
        assert_eq!(result.title, "Middle Task");
        assert_eq!(result.description, Some("From V4".to_string()));
        assert_eq!(result.status, "in-progress");
        assert_eq!(result.priority, 0); // Added in V5
        assert_eq!(result.tags, Vec::<String>::new()); // Added in V6
        assert_eq!(result.due_date, None); // Added in V7
        assert_eq!(result.assignee, None); // Added in V8
    }

    #[test]
    fn test_compile_time_vec_syntax() {
        // These should all compile successfully
        let _path1 = migrate_path!("two", [TaskV1, TaskV2]);
        let _path2 = migrate_path!("three", [TaskV1, TaskV2, TaskV3]);
        let _path3 = migrate_path!("four", [TaskV1, TaskV2, TaskV3, TaskV4]);
        let _path4 = migrate_path!("five", [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5]);
        let _path5 = migrate_path!("six", [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6]);
        let _path6 = migrate_path!(
            "seven",
            [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6, TaskV7]
        );
        let _path7 = migrate_path!(
            "eight",
            [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6, TaskV7, TaskV8]
        );
        let _path8 = migrate_path!(
            "nine",
            [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6, TaskV7, TaskV8, TaskV9]
        );
        let _path9 = migrate_path!(
            "ten",
            [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6, TaskV7, TaskV8, TaskV9, TaskV10]
        );

        // With custom keys
        let _path_custom = migrate_path!(
            "custom",
            [TaskV1, TaskV2, TaskV3, TaskV4, TaskV5, TaskV6, TaskV7],
            version_key = "version",
            data_key = "data"
        );
    }
}