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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
//! Migration manager and builder pattern for defining type-safe migration paths.
use crate::errors::MigrationError;
use crate::forward::{ForwardContext, Forwardable};
use crate::{IntoDomain, MigratesTo, Versioned};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::collections::HashMap;
use std::marker::PhantomData;
type MigrationFn =
Box<dyn Fn(serde_json::Value) -> Result<serde_json::Value, MigrationError> + Send + Sync>;
/// Type-erased function for saving domain entities
type DomainSaveFn =
Box<dyn Fn(serde_json::Value, &str, &str) -> Result<String, MigrationError> + Send + Sync>;
type DomainSaveFlatFn =
Box<dyn Fn(serde_json::Value, &str) -> Result<String, MigrationError> + Send + Sync>;
/// A registered migration path for a specific entity type.
struct EntityMigrationPath {
/// Maps version -> migration function to next version
steps: HashMap<String, MigrationFn>,
/// The final conversion to domain model
finalize:
Box<dyn Fn(serde_json::Value) -> Result<serde_json::Value, MigrationError> + Send + Sync>,
/// Ordered list of versions in the migration path
versions: Vec<String>,
/// The key name for version field in serialized data
version_key: String,
/// The key name for data field in serialized data
data_key: String,
}
/// Type-erased functions for saving domain entities by entity name
struct DomainSavers {
save_fn: DomainSaveFn,
save_flat_fn: DomainSaveFlatFn,
}
/// The migration manager that orchestrates all migrations.
pub struct Migrator {
paths: HashMap<String, EntityMigrationPath>,
default_version_key: Option<String>,
default_data_key: Option<String>,
domain_savers: HashMap<String, DomainSavers>,
}
impl Migrator {
/// Creates a new, empty migrator.
pub fn new() -> Self {
Self {
paths: HashMap::new(),
default_version_key: None,
default_data_key: None,
domain_savers: HashMap::new(),
}
}
/// Gets the latest version for a given entity.
///
/// # Returns
///
/// The latest version string if the entity is registered, `None` otherwise.
pub fn get_latest_version(&self, entity: &str) -> Option<&str> {
self.paths
.get(entity)
.and_then(|path| path.versions.last())
.map(|v| v.as_str())
}
/// Creates a builder for configuring the migrator.
///
/// # Example
///
/// ```ignore
/// let migrator = Migrator::builder()
/// .default_version_key("schema_version")
/// .default_data_key("payload")
/// .build();
/// ```
pub fn builder() -> MigratorBuilder {
MigratorBuilder::new()
}
/// Starts defining a migration path for an entity.
pub fn define(entity: &str) -> MigrationPathBuilder<Start> {
MigrationPathBuilder::new(entity.to_string())
}
/// Registers a migration path with validation.
///
/// This method validates the migration path before registering it:
/// - Checks for circular migration paths
/// - Validates version ordering follows semver rules
///
/// # Errors
///
/// Returns an error if validation fails.
pub fn register<D>(&mut self, path: MigrationPath<D>) -> Result<(), MigrationError> {
Self::validate_migration_path(&path.entity, &path.versions)?;
// Resolve key priority: Path custom > Migrator default > EntityPath (trait constants)
let version_key = path
.custom_version_key
.or_else(|| self.default_version_key.clone())
.unwrap_or_else(|| path.inner.version_key.clone());
let data_key = path
.custom_data_key
.or_else(|| self.default_data_key.clone())
.unwrap_or_else(|| path.inner.data_key.clone());
let entity_name = path.entity.clone();
let final_path = EntityMigrationPath {
steps: path.inner.steps,
finalize: path.inner.finalize,
versions: path.versions,
version_key,
data_key,
};
self.paths.insert(path.entity, final_path);
// Register domain savers if available
if let (Some(save_fn), Some(save_flat_fn)) = (path.save_fn, path.save_flat_fn) {
self.domain_savers.insert(
entity_name,
DomainSavers {
save_fn,
save_flat_fn,
},
);
}
Ok(())
}
/// Validates a migration path for correctness.
fn validate_migration_path(entity: &str, versions: &[String]) -> Result<(), MigrationError> {
// Check for circular paths
Self::check_circular_path(entity, versions)?;
// Check version ordering
Self::check_version_ordering(entity, versions)?;
Ok(())
}
/// Checks if there are any circular dependencies in the migration path.
fn check_circular_path(entity: &str, versions: &[String]) -> Result<(), MigrationError> {
let mut seen = std::collections::HashSet::new();
for version in versions {
if !seen.insert(version) {
// Found a duplicate - circular path detected
let path = versions.join(" -> ");
return Err(MigrationError::CircularMigrationPath {
entity: entity.to_string(),
path,
});
}
}
Ok(())
}
/// Checks if versions are ordered according to semver rules.
fn check_version_ordering(entity: &str, versions: &[String]) -> Result<(), MigrationError> {
for i in 0..versions.len().saturating_sub(1) {
let current = &versions[i];
let next = &versions[i + 1];
// Parse versions
let current_ver = semver::Version::parse(current).map_err(|e| {
MigrationError::DeserializationError(format!("Invalid semver '{}': {}", current, e))
})?;
let next_ver = semver::Version::parse(next).map_err(|e| {
MigrationError::DeserializationError(format!("Invalid semver '{}': {}", next, e))
})?;
// Check that next version is greater than current
if next_ver <= current_ver {
return Err(MigrationError::InvalidVersionOrder {
entity: entity.to_string(),
from: current.clone(),
to: next.clone(),
});
}
}
Ok(())
}
/// Loads and migrates data from any serde-compatible format.
///
/// This is the generic version that accepts any type implementing `Serialize`.
/// For JSON strings, use the convenience method `load` instead.
///
/// # Arguments
///
/// * `entity` - The entity name used when registering the migration path
/// * `data` - Versioned data in any serde-compatible format (e.g., `toml::Value`, `serde_json::Value`)
///
/// # Returns
///
/// The migrated data as the domain model type
///
/// # Errors
///
/// Returns an error if:
/// - The data cannot be converted to the internal format
/// - The entity is not registered
/// - A migration step fails
///
/// # Example
///
/// ```ignore
/// // Load from TOML
/// let toml_data: toml::Value = toml::from_str(toml_str)?;
/// let domain: TaskEntity = migrator.load_from("task", toml_data)?;
///
/// // Load from JSON Value
/// let json_data: serde_json::Value = serde_json::from_str(json_str)?;
/// let domain: TaskEntity = migrator.load_from("task", json_data)?;
/// ```
pub fn load_from<D, T>(&self, entity: &str, data: T) -> Result<D, MigrationError>
where
D: DeserializeOwned,
T: Serialize,
{
// Convert the input data to serde_json::Value for internal processing
let value = serde_json::to_value(data).map_err(|e| {
MigrationError::DeserializationError(format!(
"Failed to convert input data to internal format: {}",
e
))
})?;
// Get the migration path for this entity
let path = self
.paths
.get(entity)
.ok_or_else(|| MigrationError::EntityNotFound(entity.to_string()))?;
let version_key = &path.version_key;
let data_key = &path.data_key;
// Extract version and data using custom keys
let obj = value.as_object().ok_or_else(|| {
MigrationError::DeserializationError(
"Expected object with version and data fields".to_string(),
)
})?;
let current_version = obj
.get(version_key)
.and_then(|v| v.as_str())
.ok_or_else(|| {
MigrationError::DeserializationError(format!(
"Missing or invalid '{}' field",
version_key
))
})?
.to_string();
let mut current_data = obj
.get(data_key)
.ok_or_else(|| {
MigrationError::DeserializationError(format!("Missing '{}' field", data_key))
})?
.clone();
let mut current_version = current_version;
// Apply migration steps until we reach a version with no further steps
while let Some(migrate_fn) = path.steps.get(¤t_version) {
// Migration function returns raw value, no wrapping
current_data = migrate_fn(current_data.clone())?;
// Update version to the next step
// Find the next version in the path
match path.versions.iter().position(|v| v == ¤t_version) {
Some(idx) if idx + 1 < path.versions.len() => {
current_version = path.versions[idx + 1].clone();
}
_ => break,
}
}
// Finalize into domain model
let domain_value = (path.finalize)(current_data)?;
serde_json::from_value(domain_value).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to convert to domain: {}", e))
})
}
/// Loads and migrates data from a JSON string.
///
/// This is a convenience method for the common case of loading from JSON.
/// For other formats, use `load_from` instead.
///
/// # Arguments
///
/// * `entity` - The entity name used when registering the migration path
/// * `json` - A JSON string containing versioned data
///
/// # Returns
///
/// The migrated data as the domain model type
///
/// # Errors
///
/// Returns an error if:
/// - The JSON cannot be parsed
/// - The entity is not registered
/// - A migration step fails
///
/// # Example
///
/// ```ignore
/// let json = r#"{"version":"1.0.0","data":{"id":"task-1","title":"My Task"}}"#;
/// let domain: TaskEntity = migrator.load("task", json)?;
/// ```
pub fn load<D: DeserializeOwned>(&self, entity: &str, json: &str) -> Result<D, MigrationError> {
let data: serde_json::Value = serde_json::from_str(json).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to parse JSON: {}", e))
})?;
self.load_from(entity, data)
}
/// Loads and migrates data from any serde-compatible format with fallback for legacy data.
///
/// This method attempts to load data as versioned first. If version field is missing,
/// it treats the data as version 0 (the first version in the migration chain).
///
/// # Arguments
///
/// * `entity` - The entity name used when registering the migration path
/// * `data` - Data that may or may not have version information
///
/// # Returns
///
/// The migrated data as the domain model type
///
/// # Errors
///
/// Returns an error if:
/// - The data cannot be converted to the internal format
/// - The entity is not registered
/// - A migration step fails
///
/// # Example
///
/// ```ignore
/// // Works with versioned data
/// let versioned_json = r#"{"version":"1.0.0","data":{"id":"task-1","title":"My Task"}}"#;
/// let domain: TaskEntity = migrator.load_with_fallback("task", versioned_json)?;
///
/// // Works with legacy data (no version field) - treats as V1
/// let legacy_json = r#"{"id":"task-1","title":"My Task"}"#;
/// let domain: TaskEntity = migrator.load_with_fallback("task", legacy_json)?;
/// ```
pub fn load_from_with_fallback<D, T>(&self, entity: &str, data: T) -> Result<D, MigrationError>
where
D: DeserializeOwned,
T: Serialize,
{
// Convert the input data to serde_json::Value for internal processing
let value = serde_json::to_value(data).map_err(|e| {
MigrationError::DeserializationError(format!(
"Failed to convert input data to internal format: {}",
e
))
})?;
// Get the migration path for this entity
let path = self
.paths
.get(entity)
.ok_or_else(|| MigrationError::EntityNotFound(entity.to_string()))?;
let version_key = &path.version_key;
let data_key = &path.data_key;
// Try to extract version and data using custom keys
let (current_version, current_data) = if let Some(obj) = value.as_object() {
if let Some(version_value) = obj.get(version_key) {
if let Some(version_str) = version_value.as_str() {
// Versioned data format
let data = obj
.get(data_key)
.ok_or_else(|| {
MigrationError::DeserializationError(format!(
"Missing '{}' field",
data_key
))
})?
.clone();
(version_str.to_string(), data)
} else {
// Version field exists but is not a string - fallback to first version
if path.versions.is_empty() {
return Err(MigrationError::DeserializationError(
"No migration versions defined for fallback".to_string(),
));
}
(path.versions[0].clone(), value)
}
} else {
// No version field - fallback to first version
if path.versions.is_empty() {
return Err(MigrationError::DeserializationError(
"No migration versions defined for fallback".to_string(),
));
}
(path.versions[0].clone(), value)
}
} else {
return Err(MigrationError::DeserializationError(
"Expected object format for versioned data".to_string(),
));
};
let mut current_version = current_version;
let mut current_data = current_data;
// Apply migration steps until we reach a version with no further steps
while let Some(migrate_fn) = path.steps.get(¤t_version) {
// Migration function returns raw value, no wrapping
current_data = migrate_fn(current_data.clone())?;
// Update version to the next step
// Find the next version in the path
match path.versions.iter().position(|v| v == ¤t_version) {
Some(idx) if idx + 1 < path.versions.len() => {
current_version = path.versions[idx + 1].clone();
}
_ => break,
}
}
// Finalize into domain model
let domain_value = (path.finalize)(current_data)?;
serde_json::from_value(domain_value).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to convert to domain: {}", e))
})
}
/// Loads and migrates data from a JSON string with fallback for legacy data.
///
/// This is a convenience method for `load_from_with_fallback` that accepts JSON strings.
///
/// # Arguments
///
/// * `entity` - The entity name used when registering the migration path
/// * `json` - A JSON string that may or may not contain version information
///
/// # Returns
///
/// The migrated data as the domain model type
///
/// # Errors
///
/// Returns an error if:
/// - The JSON cannot be parsed
/// - The entity is not registered
/// - A migration step fails
///
/// # Example
///
/// ```ignore
/// // Works with versioned data
/// let versioned_json = r#"{"version":"1.0.0","data":{"id":"task-1","title":"My Task"}}"#;
/// let domain: TaskEntity = migrator.load_with_fallback("task", versioned_json)?;
///
/// // Works with legacy data (no version field) - treats as V1
/// let legacy_json = r#"{"id":"task-1","title":"My Task"}"#;
/// let domain: TaskEntity = migrator.load_with_fallback("task", legacy_json)?;
/// ```
pub fn load_with_fallback<D: DeserializeOwned>(
&self,
entity: &str,
json: &str,
) -> Result<D, MigrationError> {
let data: serde_json::Value = serde_json::from_str(json).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to parse JSON: {}", e))
})?;
self.load_from_with_fallback(entity, data)
}
/// Loads and migrates data from a flat format JSON string.
///
/// This is a convenience method for loading from flat format JSON where the version
/// field is at the same level as the data fields.
///
/// # Arguments
///
/// * `entity` - The entity name used when registering the migration path
/// * `json` - A JSON string containing versioned data in flat format
///
/// # Returns
///
/// The migrated data as the domain model type
///
/// # Errors
///
/// Returns an error if:
/// - The JSON cannot be parsed
/// - The entity is not registered
/// - A migration step fails
///
/// # Example
///
/// ```ignore
/// let json = r#"{"version":"1.0.0","id":"task-1","title":"My Task"}"#;
/// let domain: TaskEntity = migrator.load_flat("task", json)?;
/// ```
pub fn load_flat<D: DeserializeOwned>(
&self,
entity: &str,
json: &str,
) -> Result<D, MigrationError> {
let data: serde_json::Value = serde_json::from_str(json).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to parse JSON: {}", e))
})?;
self.load_flat_from(entity, data)
}
/// Loads and migrates data from any serde-compatible format in flat format.
///
/// This method expects the version field to be at the same level as the data fields.
/// It uses the registered migration path's runtime-configured keys (respecting the
/// Path > Migrator > Trait priority).
///
/// # Arguments
///
/// * `entity` - The entity name used when registering the migration path
/// * `value` - A serde-compatible value containing versioned data in flat format
///
/// # Returns
///
/// The migrated data as the domain model type
///
/// # Errors
///
/// Returns an error if:
/// - The entity is not registered
/// - The data format is invalid
/// - A migration step fails
///
/// # Example
///
/// ```ignore
/// let toml_value: toml::Value = toml::from_str(toml_str)?;
/// let domain: TaskEntity = migrator.load_flat_from("task", toml_value)?;
/// ```
pub fn load_flat_from<D, T>(&self, entity: &str, value: T) -> Result<D, MigrationError>
where
D: DeserializeOwned,
T: Serialize,
{
let path = self
.paths
.get(entity)
.ok_or_else(|| MigrationError::EntityNotFound(entity.to_string()))?;
let version_key = &path.version_key;
// Convert to serde_json::Value for manipulation
let mut value = serde_json::to_value(value).map_err(|e| {
MigrationError::SerializationError(format!("Failed to convert input: {}", e))
})?;
// Extract version from the flat structure
let obj = value.as_object_mut().ok_or_else(|| {
MigrationError::DeserializationError(
"Expected object with version field at top level".to_string(),
)
})?;
let current_version = obj
.remove(version_key)
.ok_or_else(|| {
MigrationError::DeserializationError(format!(
"Missing '{}' field in flat format",
version_key
))
})?
.as_str()
.ok_or_else(|| {
MigrationError::DeserializationError(format!(
"Invalid '{}' field type",
version_key
))
})?
.to_string();
// Now obj contains only data fields (version has been removed)
let mut current_data = serde_json::Value::Object(obj.clone());
let mut current_version = current_version;
// Apply migration steps until we reach a version with no further steps
while let Some(migrate_fn) = path.steps.get(¤t_version) {
// Migration function returns raw value, no wrapping
current_data = migrate_fn(current_data.clone())?;
// Update version to the next step
match path.versions.iter().position(|v| v == ¤t_version) {
Some(idx) if idx + 1 < path.versions.len() => {
current_version = path.versions[idx + 1].clone();
}
_ => break,
}
}
// Finalize into domain model
let domain_value = (path.finalize)(current_data)?;
serde_json::from_value(domain_value).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to convert to domain: {}", e))
})
}
/// Saves versioned data to a JSON string.
///
/// This method wraps the provided data with its version information and serializes
/// it to JSON format. The resulting JSON can later be loaded and migrated using
/// the `load` method.
///
/// # Arguments
///
/// * `data` - The versioned data to save
///
/// # Returns
///
/// A JSON string with the format: `{"version":"x.y.z","data":{...}}`
///
/// # Errors
///
/// Returns `SerializationError` if the data cannot be serialized to JSON.
///
/// # Example
///
/// ```ignore
/// let task = TaskV1_0_0 {
/// id: "task-1".to_string(),
/// title: "My Task".to_string(),
/// };
///
/// let migrator = Migrator::new();
/// let json = migrator.save(task)?;
/// // json: {"version":"1.0.0","data":{"id":"task-1","title":"My Task"}}
/// ```
pub fn save<T: Versioned + Serialize>(&self, data: T) -> Result<String, MigrationError> {
// Use custom keys from the type's Versioned trait
let version_key = T::VERSION_KEY;
let data_key = T::DATA_KEY;
// Serialize the data
let data_value = serde_json::to_value(&data).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize data: {}", e))
})?;
// Build the wrapper with custom keys
let mut map = serde_json::Map::new();
map.insert(
version_key.to_string(),
serde_json::Value::String(T::VERSION.to_string()),
);
map.insert(data_key.to_string(), data_value);
serde_json::to_string(&map).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize wrapper: {}", e))
})
}
/// Saves versioned data to a JSON string in flat format.
///
/// Unlike `save()`, this method produces a flat JSON structure where the version
/// field is at the same level as the data fields, not wrapped in a separate object.
///
/// # Arguments
///
/// * `data` - The versioned data to save
///
/// # Returns
///
/// A JSON string with the format: `{"version":"x.y.z","field1":"value1",...}`
///
/// # Errors
///
/// Returns `SerializationError` if the data cannot be serialized to JSON.
///
/// # Example
///
/// ```ignore
/// let task = TaskV1_0_0 {
/// id: "task-1".to_string(),
/// title: "My Task".to_string(),
/// };
///
/// let migrator = Migrator::new();
/// let json = migrator.save_flat(task)?;
/// // json: {"version":"1.0.0","id":"task-1","title":"My Task"}
/// ```
pub fn save_flat<T: Versioned + Serialize>(&self, data: T) -> Result<String, MigrationError> {
let version_key = T::VERSION_KEY;
// Serialize the data to a JSON object
let mut data_value = serde_json::to_value(&data).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize data: {}", e))
})?;
// Ensure it's an object so we can add the version field
let obj = data_value.as_object_mut().ok_or_else(|| {
MigrationError::SerializationError(
"Data must serialize to a JSON object for flat format".to_string(),
)
})?;
// Add the version field to the same level as data fields
obj.insert(
version_key.to_string(),
serde_json::Value::String(T::VERSION.to_string()),
);
serde_json::to_string(&obj).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize flat format: {}", e))
})
}
/// Loads and migrates multiple entities from any serde-compatible format.
///
/// This is the generic version that accepts any type implementing `Serialize`.
/// For JSON arrays, use the convenience method `load_vec` instead.
///
/// # Arguments
///
/// * `entity` - The entity name used when registering the migration path
/// * `data` - Array of versioned data in any serde-compatible format
///
/// # Returns
///
/// A vector of migrated data as domain model types
///
/// # Errors
///
/// Returns an error if:
/// - The data cannot be converted to the internal format
/// - The entity is not registered
/// - Any migration step fails
///
/// # Example
///
/// ```ignore
/// // Load from TOML array
/// let toml_array: Vec<toml::Value> = /* ... */;
/// let domains: Vec<TaskEntity> = migrator.load_vec_from("task", toml_array)?;
///
/// // Load from JSON Value array
/// let json_array: Vec<serde_json::Value> = /* ... */;
/// let domains: Vec<TaskEntity> = migrator.load_vec_from("task", json_array)?;
/// ```
pub fn load_vec_from<D, T>(&self, entity: &str, data: Vec<T>) -> Result<Vec<D>, MigrationError>
where
D: DeserializeOwned,
T: Serialize,
{
data.into_iter()
.map(|item| self.load_from(entity, item))
.collect()
}
/// Loads and migrates multiple entities from a JSON array string.
///
/// This is a convenience method for the common case of loading from a JSON array.
/// For other formats, use `load_vec_from` instead.
///
/// # Arguments
///
/// * `entity` - The entity name used when registering the migration path
/// * `json` - A JSON array string containing versioned data
///
/// # Returns
///
/// A vector of migrated data as domain model types
///
/// # Errors
///
/// Returns an error if:
/// - The JSON cannot be parsed
/// - The entity is not registered
/// - Any migration step fails
///
/// # Example
///
/// ```ignore
/// let json = r#"[
/// {"version":"1.0.0","data":{"id":"task-1","title":"Task 1"}},
/// {"version":"1.0.0","data":{"id":"task-2","title":"Task 2"}}
/// ]"#;
/// let domains: Vec<TaskEntity> = migrator.load_vec("task", json)?;
/// ```
pub fn load_vec<D: DeserializeOwned>(
&self,
entity: &str,
json: &str,
) -> Result<Vec<D>, MigrationError> {
let data: Vec<serde_json::Value> = serde_json::from_str(json).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to parse JSON array: {}", e))
})?;
self.load_vec_from(entity, data)
}
/// Loads and migrates multiple entities from a flat format JSON array string.
///
/// This is a convenience method for loading from a JSON array where each element
/// has the version field at the same level as the data fields.
///
/// # Arguments
///
/// * `entity` - The entity name used when registering the migration path
/// * `json` - A JSON array string containing versioned data in flat format
///
/// # Returns
///
/// A vector of migrated data as domain model types
///
/// # Errors
///
/// Returns an error if:
/// - The JSON cannot be parsed
/// - The entity is not registered
/// - Any migration step fails
///
/// # Example
///
/// ```ignore
/// let json = r#"[
/// {"version":"1.0.0","id":"task-1","title":"Task 1"},
/// {"version":"1.0.0","id":"task-2","title":"Task 2"}
/// ]"#;
/// let domains: Vec<TaskEntity> = migrator.load_vec_flat("task", json)?;
/// ```
pub fn load_vec_flat<D: DeserializeOwned>(
&self,
entity: &str,
json: &str,
) -> Result<Vec<D>, MigrationError> {
let data: Vec<serde_json::Value> = serde_json::from_str(json).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to parse JSON array: {}", e))
})?;
self.load_vec_flat_from(entity, data)
}
/// Loads and migrates multiple entities from any serde-compatible format in flat format.
///
/// This method expects each element to have the version field at the same level
/// as the data fields. It uses the registered migration path's runtime-configured
/// keys (respecting the Path > Migrator > Trait priority).
///
/// # Arguments
///
/// * `entity` - The entity name used when registering the migration path
/// * `data` - Vector of serde-compatible values in flat format
///
/// # Returns
///
/// A vector of migrated data as domain model types
///
/// # Errors
///
/// Returns an error if:
/// - The entity is not registered
/// - The data format is invalid
/// - Any migration step fails
///
/// # Example
///
/// ```ignore
/// let toml_array: Vec<toml::Value> = /* ... */;
/// let domains: Vec<TaskEntity> = migrator.load_vec_flat_from("task", toml_array)?;
/// ```
pub fn load_vec_flat_from<D, T>(
&self,
entity: &str,
data: Vec<T>,
) -> Result<Vec<D>, MigrationError>
where
D: DeserializeOwned,
T: Serialize,
{
data.into_iter()
.map(|item| self.load_flat_from(entity, item))
.collect()
}
/// Saves multiple versioned entities to a JSON array string.
///
/// This method wraps each item with its version information and serializes
/// them as a JSON array. The resulting JSON can later be loaded and migrated
/// using the `load_vec` method.
///
/// # Arguments
///
/// * `data` - Vector of versioned data to save
///
/// # Returns
///
/// A JSON array string where each element has the format: `{"version":"x.y.z","data":{...}}`
///
/// # Errors
///
/// Returns `SerializationError` if the data cannot be serialized to JSON.
///
/// # Example
///
/// ```ignore
/// let tasks = vec![
/// TaskV1_0_0 {
/// id: "task-1".to_string(),
/// title: "Task 1".to_string(),
/// },
/// TaskV1_0_0 {
/// id: "task-2".to_string(),
/// title: "Task 2".to_string(),
/// },
/// ];
///
/// let migrator = Migrator::new();
/// let json = migrator.save_vec(tasks)?;
/// // json: [{"version":"1.0.0","data":{"id":"task-1",...}}, ...]
/// ```
pub fn save_vec<T: Versioned + Serialize>(
&self,
data: Vec<T>,
) -> Result<String, MigrationError> {
let version_key = T::VERSION_KEY;
let data_key = T::DATA_KEY;
let wrappers: Result<Vec<serde_json::Value>, MigrationError> = data
.into_iter()
.map(|item| {
let data_value = serde_json::to_value(&item).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize item: {}", e))
})?;
let mut map = serde_json::Map::new();
map.insert(
version_key.to_string(),
serde_json::Value::String(T::VERSION.to_string()),
);
map.insert(data_key.to_string(), data_value);
Ok(serde_json::Value::Object(map))
})
.collect();
serde_json::to_string(&wrappers?).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize data array: {}", e))
})
}
/// Saves multiple versioned entities to a JSON array string in flat format.
///
/// This method serializes each item with the version field at the same level
/// as the data fields, not wrapped in a separate object.
///
/// # Arguments
///
/// * `data` - Vector of versioned data to save
///
/// # Returns
///
/// A JSON array string where each element has the format: `{"version":"x.y.z","field1":"value1",...}`
///
/// # Errors
///
/// Returns `SerializationError` if the data cannot be serialized to JSON.
///
/// # Example
///
/// ```ignore
/// let tasks = vec![
/// TaskV1_0_0 {
/// id: "task-1".to_string(),
/// title: "Task 1".to_string(),
/// },
/// TaskV1_0_0 {
/// id: "task-2".to_string(),
/// title: "Task 2".to_string(),
/// },
/// ];
///
/// let migrator = Migrator::new();
/// let json = migrator.save_vec_flat(tasks)?;
/// // json: [{"version":"1.0.0","id":"task-1",...}, ...]
/// ```
pub fn save_vec_flat<T: Versioned + Serialize>(
&self,
data: Vec<T>,
) -> Result<String, MigrationError> {
let version_key = T::VERSION_KEY;
let flat_items: Result<Vec<serde_json::Value>, MigrationError> = data
.into_iter()
.map(|item| {
let mut data_value = serde_json::to_value(&item).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize item: {}", e))
})?;
let obj = data_value.as_object_mut().ok_or_else(|| {
MigrationError::SerializationError(
"Data must serialize to a JSON object for flat format".to_string(),
)
})?;
// Add version field at the same level
obj.insert(
version_key.to_string(),
serde_json::Value::String(T::VERSION.to_string()),
);
Ok(serde_json::Value::Object(obj.clone()))
})
.collect();
serde_json::to_string(&flat_items?).map_err(|e| {
MigrationError::SerializationError(format!(
"Failed to serialize flat data array: {}",
e
))
})
}
// =========================================================================
// Forward Compatibility API
// =========================================================================
/// Loads data with forward compatibility support.
///
/// This method allows loading data from versions that don't exist in the current
/// codebase yet. Unknown versions are deserialized using the latest known schema,
/// and unknown fields are preserved for later saving.
///
/// # ⚠️ Requirements
///
/// Forward compatibility assumes **additive-only schema changes**:
///
/// - ✅ Field additions (future version has new fields) → OK, unknown fields preserved
/// - ❌ Field deletions → Deserialization will fail
/// - ❌ Field type changes → Data corruption
/// - ❌ Field semantic changes → Logic bugs
///
/// # Arguments
///
/// * `entity` - The entity name used when registering the migration path
/// * `json` - A JSON string containing versioned data
///
/// # Returns
///
/// A `Forwardable<D>` wrapper containing the domain model and context for preserving
/// unknown fields when saving.
///
/// # Example
///
/// ```ignore
/// // Data from a future version (2.0.0) that doesn't exist in code yet
/// let json = r#"{"version":"2.0.0","data":{"id":"1","title":"Task","new_field":"value"}}"#;
///
/// // Load with forward compatibility (V1 is the latest known version)
/// let mut task: Forwardable<TaskEntity> = migrator.load_forward("task", json)?;
///
/// // Check if it was a lossy load
/// if task.was_lossy() {
/// eprintln!("Warning: Loaded from unknown version {}", task.original_version());
/// }
///
/// // Modify the data
/// task.title = "Updated".to_string();
///
/// // Save preserving unknown fields and original version
/// let saved = migrator.save_forward(&task)?;
/// // → {"version":"2.0.0","data":{"id":"1","title":"Updated","new_field":"value"}}
/// ```
pub fn load_forward<D: DeserializeOwned>(
&self,
entity: &str,
json: &str,
) -> Result<Forwardable<D>, MigrationError> {
let value: serde_json::Value = serde_json::from_str(json).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to parse JSON: {}", e))
})?;
self.load_forward_from(entity, value, false)
}
/// Loads data with forward compatibility support from flat format.
///
/// Same as `load_forward` but expects flat format where version is at the same
/// level as data fields.
///
/// # Example
///
/// ```ignore
/// let json = r#"{"version":"2.0.0","id":"1","title":"Task","new_field":"value"}"#;
/// let task: Forwardable<TaskEntity> = migrator.load_forward_flat("task", json)?;
/// ```
pub fn load_forward_flat<D: DeserializeOwned>(
&self,
entity: &str,
json: &str,
) -> Result<Forwardable<D>, MigrationError> {
let value: serde_json::Value = serde_json::from_str(json).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to parse JSON: {}", e))
})?;
self.load_forward_from(entity, value, true)
}
/// Internal implementation for forward-compatible loading.
fn load_forward_from<D: DeserializeOwned>(
&self,
entity: &str,
value: serde_json::Value,
is_flat: bool,
) -> Result<Forwardable<D>, MigrationError> {
let path = self
.paths
.get(entity)
.ok_or_else(|| MigrationError::EntityNotFound(entity.to_string()))?;
let version_key = &path.version_key;
let data_key = &path.data_key;
let obj = value.as_object().ok_or_else(|| {
MigrationError::DeserializationError("Expected JSON object".to_string())
})?;
// Extract version
let original_version = obj
.get(version_key)
.and_then(|v| v.as_str())
.ok_or_else(|| {
MigrationError::DeserializationError(format!(
"Missing or invalid '{}' field",
version_key
))
})?
.to_string();
// Extract data (handling both wrapped and flat formats)
let (data_value, all_fields) = if is_flat {
// Flat format: data fields are at the same level as version
let mut fields = obj.clone();
fields.remove(version_key);
(serde_json::Value::Object(fields.clone()), fields)
} else {
// Wrapped format: data is in a separate field
let data = obj
.get(data_key)
.ok_or_else(|| {
MigrationError::DeserializationError(format!("Missing '{}' field", data_key))
})?
.clone();
let fields = data
.as_object()
.cloned()
.unwrap_or_else(serde_json::Map::new);
(data, fields)
};
// Check if version is known
let is_known_version = path.versions.contains(&original_version);
let was_lossy = !is_known_version;
// Determine which version to use for deserialization
let target_version = if is_known_version {
original_version.clone()
} else {
// Use the latest known version for unknown versions
path.versions.last().cloned().ok_or_else(|| {
MigrationError::DeserializationError(
"No versions registered for entity".to_string(),
)
})?
};
// Apply migrations if needed (from known version to latest)
let mut current_data = data_value.clone();
let mut current_version = if is_known_version {
original_version.clone()
} else {
// For unknown versions, skip migration and deserialize directly
target_version.clone()
};
if is_known_version {
// Apply migration steps
while let Some(migrate_fn) = path.steps.get(¤t_version) {
current_data = migrate_fn(current_data)?;
match path.versions.iter().position(|v| v == ¤t_version) {
Some(idx) if idx + 1 < path.versions.len() => {
current_version = path.versions[idx + 1].clone();
}
_ => break,
}
}
}
// Finalize into domain model
let domain_value = (path.finalize)(current_data)?;
// Deserialize to domain type
let domain: D = serde_json::from_value(domain_value.clone()).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to deserialize domain: {}", e))
})?;
// Calculate unknown fields (fields in original data but not in domain)
let domain_obj = domain_value
.as_object()
.cloned()
.unwrap_or_else(serde_json::Map::new);
let mut unknown_fields = serde_json::Map::new();
for (key, value) in all_fields {
if !domain_obj.contains_key(&key) {
unknown_fields.insert(key, value);
}
}
let ctx = ForwardContext::new(
original_version,
unknown_fields,
was_lossy,
version_key.clone(),
data_key.clone(),
is_flat,
);
Ok(Forwardable::new(domain, ctx))
}
/// Saves data preserving forward compatibility information.
///
/// This method saves the domain data while preserving unknown fields from the
/// original data and maintaining the original version number.
///
/// # Arguments
///
/// * `data` - A `Forwardable<D>` wrapper containing domain data and context
///
/// # Returns
///
/// A JSON string with preserved unknown fields and original version.
///
/// # Example
///
/// ```ignore
/// let mut task: Forwardable<TaskEntity> = migrator.load_forward("task", json)?;
/// task.title = "Updated".to_string();
/// let saved = migrator.save_forward(&task)?;
/// ```
pub fn save_forward<D: Serialize>(
&self,
data: &Forwardable<D>,
) -> Result<String, MigrationError> {
let ctx = data.context();
// Serialize the domain data
let mut domain_value = serde_json::to_value(&data.inner).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize domain: {}", e))
})?;
// Merge unknown fields back
if let Some(obj) = domain_value.as_object_mut() {
for (key, value) in ctx.unknown_fields.iter() {
if !obj.contains_key(key) {
obj.insert(key.clone(), value.clone());
}
}
}
// Build output based on original format
if ctx.was_flat {
// Flat format
let obj = domain_value.as_object_mut().ok_or_else(|| {
MigrationError::SerializationError(
"Domain must serialize to object for flat format".to_string(),
)
})?;
obj.insert(
ctx.version_key.clone(),
serde_json::Value::String(ctx.original_version.clone()),
);
serde_json::to_string(&obj).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize: {}", e))
})
} else {
// Wrapped format
let mut wrapper = serde_json::Map::new();
wrapper.insert(
ctx.version_key.clone(),
serde_json::Value::String(ctx.original_version.clone()),
);
wrapper.insert(ctx.data_key.clone(), domain_value);
serde_json::to_string(&wrapper).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize: {}", e))
})
}
}
/// Saves a domain entity to a JSON string using its latest versioned format.
///
/// This method automatically converts the domain entity to its latest version
/// and saves it with version information.
///
/// # Arguments
///
/// * `entity` - The domain entity to save (must implement `LatestVersioned`)
///
/// # Returns
///
/// A JSON string with the format: `{"version":"x.y.z","data":{...}}`
///
/// # Errors
///
/// Returns `SerializationError` if the entity cannot be serialized to JSON.
///
/// # Example
///
/// ```ignore
/// #[version_migrate(entity = "task", latest = TaskV1_1_0)]
/// struct TaskEntity {
/// id: String,
/// title: String,
/// description: Option<String>,
/// }
///
/// let entity = TaskEntity {
/// id: "task-1".to_string(),
/// title: "My Task".to_string(),
/// description: Some("Description".to_string()),
/// };
///
/// let migrator = Migrator::new();
/// let json = migrator.save_entity(entity)?;
/// // Automatically saved with latest version (1.1.0)
/// ```
pub fn save_entity<E: crate::LatestVersioned>(
&self,
entity: E,
) -> Result<String, MigrationError> {
let latest = entity.to_latest();
self.save(latest)
}
/// Saves a domain entity to a JSON string in flat format using its latest versioned format.
///
/// This method automatically converts the domain entity to its latest version
/// and saves it with the version field at the same level as data fields.
///
/// # Arguments
///
/// * `entity` - The domain entity to save (must implement `LatestVersioned`)
///
/// # Returns
///
/// A JSON string with the format: `{"version":"x.y.z","field1":"value1",...}`
///
/// # Errors
///
/// Returns `SerializationError` if the entity cannot be serialized to JSON.
///
/// # Example
///
/// ```ignore
/// #[version_migrate(entity = "task", latest = TaskV1_1_0)]
/// struct TaskEntity {
/// id: String,
/// title: String,
/// description: Option<String>,
/// }
///
/// let entity = TaskEntity {
/// id: "task-1".to_string(),
/// title: "My Task".to_string(),
/// description: Some("Description".to_string()),
/// };
///
/// let migrator = Migrator::new();
/// let json = migrator.save_entity_flat(entity)?;
/// // json: {"version":"1.1.0","id":"task-1","title":"My Task",...}
/// ```
pub fn save_entity_flat<E: crate::LatestVersioned>(
&self,
entity: E,
) -> Result<String, MigrationError> {
let latest = entity.to_latest();
self.save_flat(latest)
}
/// Saves multiple domain entities to a JSON array string using their latest versioned format.
///
/// This method automatically converts each domain entity to its latest version
/// and saves them as a JSON array.
///
/// # Arguments
///
/// * `entities` - Vector of domain entities to save
///
/// # Returns
///
/// A JSON array string where each element has the format: `{"version":"x.y.z","data":{...}}`
///
/// # Errors
///
/// Returns `SerializationError` if the entities cannot be serialized to JSON.
///
/// # Example
///
/// ```ignore
/// let entities = vec![
/// TaskEntity { id: "1".into(), title: "Task 1".into(), description: None },
/// TaskEntity { id: "2".into(), title: "Task 2".into(), description: None },
/// ];
///
/// let json = migrator.save_entity_vec(entities)?;
/// ```
pub fn save_entity_vec<E: crate::LatestVersioned>(
&self,
entities: Vec<E>,
) -> Result<String, MigrationError> {
let versioned: Vec<E::Latest> = entities.into_iter().map(|e| e.to_latest()).collect();
self.save_vec(versioned)
}
/// Saves multiple domain entities to a JSON array string in flat format using their latest versioned format.
///
/// This method automatically converts each domain entity to its latest version
/// and saves them with version fields at the same level as data fields.
///
/// # Arguments
///
/// * `entities` - Vector of domain entities to save
///
/// # Returns
///
/// A JSON array string where each element has the format: `{"version":"x.y.z","field1":"value1",...}`
///
/// # Errors
///
/// Returns `SerializationError` if the entities cannot be serialized to JSON.
///
/// # Example
///
/// ```ignore
/// let entities = vec![
/// TaskEntity { id: "1".into(), title: "Task 1".into(), description: None },
/// TaskEntity { id: "2".into(), title: "Task 2".into(), description: None },
/// ];
///
/// let json = migrator.save_entity_vec_flat(entities)?;
/// ```
pub fn save_entity_vec_flat<E: crate::LatestVersioned>(
&self,
entities: Vec<E>,
) -> Result<String, MigrationError> {
let versioned: Vec<E::Latest> = entities.into_iter().map(|e| e.to_latest()).collect();
self.save_vec_flat(versioned)
}
/// Saves a domain entity to a JSON string using its latest versioned format, by entity name.
///
/// This method works without requiring the `VersionMigrate` macro on the entity type.
/// Instead, it uses the save function registered during `register()` via `into_with_save()`.
///
/// # Arguments
///
/// * `entity_name` - The entity name used when registering the migration path
/// * `entity` - The domain entity to save (must be Serialize)
///
/// # Returns
///
/// A JSON string with the format: `{"version":"x.y.z","data":{...}}`
///
/// # Errors
///
/// Returns `MigrationPathNotDefined` if the entity is not registered with save support.
/// Returns `SerializationError` if the entity cannot be serialized.
///
/// # Example
///
/// ```ignore
/// impl FromDomain<TaskEntity> for TaskV1_1_0 {
/// fn from_domain(entity: TaskEntity) -> Self { ... }
/// }
///
/// let path = Migrator::define("task")
/// .from::<TaskV1_0_0>()
/// .step::<TaskV1_1_0>()
/// .into_with_save::<TaskEntity>();
///
/// migrator.register(path)?;
///
/// let entity = TaskEntity { ... };
/// let json = migrator.save_domain("task", entity)?;
/// // → {"version":"1.1.0","data":{"id":"1","title":"My Task",...}}
/// ```
pub fn save_domain<T: Serialize>(
&self,
entity_name: &str,
entity: T,
) -> Result<String, MigrationError> {
let saver = self.domain_savers.get(entity_name).ok_or_else(|| {
MigrationError::EntityNotFound(format!(
"Entity '{}' is not registered with domain save support. Use into_with_save() when defining the migration path.",
entity_name
))
})?;
// Get version/data keys from registered path
let path = self.paths.get(entity_name).ok_or_else(|| {
MigrationError::EntityNotFound(format!("Entity '{}' is not registered", entity_name))
})?;
let domain_value = serde_json::to_value(entity).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize entity: {}", e))
})?;
(saver.save_fn)(domain_value, &path.version_key, &path.data_key)
}
/// Saves a domain entity to a JSON string in flat format using its latest versioned format, by entity name.
///
/// This method works without requiring the `VersionMigrate` macro on the entity type.
/// The version field is placed at the same level as data fields.
///
/// # Arguments
///
/// * `entity_name` - The entity name used when registering the migration path
/// * `entity` - The domain entity to save (must be Serialize)
///
/// # Returns
///
/// A JSON string with the format: `{"version":"x.y.z","field1":"value1",...}`
///
/// # Errors
///
/// Returns `MigrationPathNotDefined` if the entity is not registered with save support.
/// Returns `SerializationError` if the entity cannot be serialized.
///
/// # Example
///
/// ```ignore
/// let json = migrator.save_domain_flat("task", entity)?;
/// // → {"version":"1.1.0","id":"1","title":"My Task",...}
/// ```
pub fn save_domain_flat<T: Serialize>(
&self,
entity_name: &str,
entity: T,
) -> Result<String, MigrationError> {
let saver = self.domain_savers.get(entity_name).ok_or_else(|| {
MigrationError::EntityNotFound(format!(
"Entity '{}' is not registered with domain save support. Use into_with_save() when defining the migration path.",
entity_name
))
})?;
// Get version key from registered path
let path = self.paths.get(entity_name).ok_or_else(|| {
MigrationError::EntityNotFound(format!("Entity '{}' is not registered", entity_name))
})?;
let domain_value = serde_json::to_value(entity).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize entity: {}", e))
})?;
(saver.save_flat_fn)(domain_value, &path.version_key)
}
}
impl Default for Migrator {
fn default() -> Self {
Self::new()
}
}
/// Builder for configuring a `Migrator` with default settings.
pub struct MigratorBuilder {
default_version_key: Option<String>,
default_data_key: Option<String>,
}
impl MigratorBuilder {
pub(crate) fn new() -> Self {
Self {
default_version_key: None,
default_data_key: None,
}
}
/// Sets the default version key for all entities.
///
/// This key will be used unless overridden by:
/// - The entity's `MigrationPath` via `with_keys()`
/// - The type's `Versioned` trait constants
pub fn default_version_key(mut self, key: impl Into<String>) -> Self {
self.default_version_key = Some(key.into());
self
}
/// Sets the default data key for all entities.
///
/// This key will be used unless overridden by:
/// - The entity's `MigrationPath` via `with_keys()`
/// - The type's `Versioned` trait constants
pub fn default_data_key(mut self, key: impl Into<String>) -> Self {
self.default_data_key = Some(key.into());
self
}
/// Builds the `Migrator` with the configured defaults.
pub fn build(self) -> Migrator {
Migrator {
paths: HashMap::new(),
default_version_key: self.default_version_key,
default_data_key: self.default_data_key,
domain_savers: HashMap::new(),
}
}
}
/// Marker type for builder state: start
pub struct Start;
/// Marker type for builder state: has a starting version
pub struct HasFrom<V>(PhantomData<V>);
/// Marker type for builder state: has intermediate steps
pub struct HasSteps<V>(PhantomData<V>);
/// Builder for defining migration paths.
pub struct MigrationPathBuilder<State> {
entity: String,
steps: HashMap<String, MigrationFn>,
versions: Vec<String>,
version_key: String,
data_key: String,
custom_version_key: Option<String>,
custom_data_key: Option<String>,
_state: PhantomData<State>,
}
impl MigrationPathBuilder<Start> {
fn new(entity: String) -> Self {
Self {
entity,
steps: HashMap::new(),
versions: Vec::new(),
version_key: String::from("version"),
data_key: String::from("data"),
custom_version_key: None,
custom_data_key: None,
_state: PhantomData,
}
}
/// Overrides the version and data keys for this migration path.
///
/// This takes precedence over both the Migrator's defaults and the type's trait constants.
///
/// # Example
///
/// ```ignore
/// Migrator::define("task")
/// .with_keys("custom_version", "custom_data")
/// .from::<TaskV1>()
/// .into::<TaskDomain>();
/// ```
pub fn with_keys(
mut self,
version_key: impl Into<String>,
data_key: impl Into<String>,
) -> Self {
self.custom_version_key = Some(version_key.into());
self.custom_data_key = Some(data_key.into());
self
}
/// Sets the starting version for migrations.
pub fn from<V: Versioned + DeserializeOwned>(self) -> MigrationPathBuilder<HasFrom<V>> {
let mut versions = self.versions;
versions.push(V::VERSION.to_string());
MigrationPathBuilder {
entity: self.entity,
steps: self.steps,
versions,
version_key: V::VERSION_KEY.to_string(),
data_key: V::DATA_KEY.to_string(),
custom_version_key: self.custom_version_key,
custom_data_key: self.custom_data_key,
_state: PhantomData,
}
}
}
impl<V> MigrationPathBuilder<HasFrom<V>>
where
V: Versioned + DeserializeOwned,
{
/// Adds a migration step to the next version.
pub fn step<Next>(mut self) -> MigrationPathBuilder<HasSteps<Next>>
where
V: MigratesTo<Next>,
Next: Versioned + DeserializeOwned + Serialize,
{
let from_version = V::VERSION.to_string();
let migration_fn: MigrationFn = Box::new(move |value| {
let from_value: V = serde_json::from_value(value).map_err(|e| {
MigrationError::DeserializationError(format!(
"Failed to deserialize version {}: {}",
V::VERSION,
e
))
})?;
let to_value = from_value.migrate();
// Return the raw migrated value without wrapping
serde_json::to_value(&to_value).map_err(|e| MigrationError::MigrationStepFailed {
from: V::VERSION.to_string(),
to: Next::VERSION.to_string(),
error: e.to_string(),
})
});
self.steps.insert(from_version, migration_fn);
self.versions.push(Next::VERSION.to_string());
MigrationPathBuilder {
entity: self.entity,
steps: self.steps,
versions: self.versions,
version_key: self.version_key,
data_key: self.data_key,
custom_version_key: self.custom_version_key,
custom_data_key: self.custom_data_key,
_state: PhantomData,
}
}
/// Finalizes the migration path with conversion to domain model.
pub fn into<D: DeserializeOwned + Serialize>(self) -> MigrationPath<D>
where
V: IntoDomain<D>,
{
let finalize: Box<
dyn Fn(serde_json::Value) -> Result<serde_json::Value, MigrationError> + Send + Sync,
> = Box::new(move |value| {
let versioned: V = serde_json::from_value(value).map_err(|e| {
MigrationError::DeserializationError(format!(
"Failed to deserialize final version: {}",
e
))
})?;
let domain = versioned.into_domain();
serde_json::to_value(domain).map_err(|e| MigrationError::MigrationStepFailed {
from: V::VERSION.to_string(),
to: "domain".to_string(),
error: e.to_string(),
})
});
MigrationPath {
entity: self.entity,
inner: EntityMigrationPath {
steps: self.steps,
finalize,
versions: self.versions.clone(),
version_key: self.version_key,
data_key: self.data_key,
},
versions: self.versions,
custom_version_key: self.custom_version_key,
custom_data_key: self.custom_data_key,
save_fn: None,
save_flat_fn: None,
_phantom: PhantomData,
}
}
/// Finalizes the migration path with conversion to domain model and enables domain entity saving.
///
/// This variant registers save functions that allow saving domain entities directly by entity name,
/// without needing the `VersionMigrate` macro on the entity type.
///
/// # Requirements
///
/// The latest versioned type (V) must implement `FromDomain<D>` to convert domain entities
/// back to the versioned format for saving.
///
/// # Example
///
/// ```ignore
/// impl FromDomain<TaskEntity> for TaskV1_1_0 {
/// fn from_domain(entity: TaskEntity) -> Self {
/// TaskV1_1_0 {
/// id: entity.id,
/// title: entity.title,
/// description: entity.description,
/// }
/// }
/// }
///
/// let path = Migrator::define("task")
/// .from::<TaskV1_0_0>()
/// .step::<TaskV1_1_0>()
/// .into_with_save::<TaskEntity>();
///
/// migrator.register(path)?;
///
/// // Now you can save by entity name
/// let entity = TaskEntity { ... };
/// let json = migrator.save_domain("task", entity)?;
/// ```
pub fn into_with_save<D: DeserializeOwned + Serialize>(self) -> MigrationPath<D>
where
V: IntoDomain<D> + crate::FromDomain<D>,
{
let finalize: Box<
dyn Fn(serde_json::Value) -> Result<serde_json::Value, MigrationError> + Send + Sync,
> = Box::new(move |value| {
let versioned: V = serde_json::from_value(value).map_err(|e| {
MigrationError::DeserializationError(format!(
"Failed to deserialize final version: {}",
e
))
})?;
let domain = versioned.into_domain();
serde_json::to_value(domain).map_err(|e| MigrationError::MigrationStepFailed {
from: V::VERSION.to_string(),
to: "domain".to_string(),
error: e.to_string(),
})
});
// Create save function for domain entities
let version = V::VERSION;
let save_fn: DomainSaveFn = Box::new(move |domain_value, vkey, dkey| {
let domain: D = serde_json::from_value(domain_value).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to deserialize domain: {}", e))
})?;
let latest = V::from_domain(domain);
let data_value = serde_json::to_value(&latest).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize latest: {}", e))
})?;
let mut map = serde_json::Map::new();
map.insert(
vkey.to_string(),
serde_json::Value::String(version.to_string()),
);
map.insert(dkey.to_string(), data_value);
serde_json::to_string(&map).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize wrapper: {}", e))
})
});
let save_flat_fn: DomainSaveFlatFn = Box::new(move |domain_value, vkey| {
let domain: D = serde_json::from_value(domain_value).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to deserialize domain: {}", e))
})?;
let latest = V::from_domain(domain);
let mut data_value = serde_json::to_value(&latest).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize latest: {}", e))
})?;
let obj = data_value.as_object_mut().ok_or_else(|| {
MigrationError::SerializationError(
"Data must serialize to a JSON object for flat format".to_string(),
)
})?;
obj.insert(
vkey.to_string(),
serde_json::Value::String(version.to_string()),
);
serde_json::to_string(&obj).map_err(|e| {
MigrationError::SerializationError(format!(
"Failed to serialize flat format: {}",
e
))
})
});
MigrationPath {
entity: self.entity,
inner: EntityMigrationPath {
steps: self.steps,
finalize,
versions: self.versions.clone(),
version_key: self.version_key,
data_key: self.data_key,
},
versions: self.versions,
custom_version_key: self.custom_version_key,
custom_data_key: self.custom_data_key,
save_fn: Some(save_fn),
save_flat_fn: Some(save_flat_fn),
_phantom: PhantomData,
}
}
}
impl<V> MigrationPathBuilder<HasSteps<V>>
where
V: Versioned + DeserializeOwned,
{
/// Adds another migration step.
pub fn step<Next>(mut self) -> MigrationPathBuilder<HasSteps<Next>>
where
V: MigratesTo<Next>,
Next: Versioned + DeserializeOwned + Serialize,
{
let from_version = V::VERSION.to_string();
let migration_fn: MigrationFn = Box::new(move |value| {
let from_value: V = serde_json::from_value(value).map_err(|e| {
MigrationError::DeserializationError(format!(
"Failed to deserialize version {}: {}",
V::VERSION,
e
))
})?;
let to_value = from_value.migrate();
// Return the raw migrated value without wrapping
serde_json::to_value(&to_value).map_err(|e| MigrationError::MigrationStepFailed {
from: V::VERSION.to_string(),
to: Next::VERSION.to_string(),
error: e.to_string(),
})
});
self.steps.insert(from_version, migration_fn);
self.versions.push(Next::VERSION.to_string());
MigrationPathBuilder {
entity: self.entity,
steps: self.steps,
versions: self.versions,
version_key: self.version_key,
data_key: self.data_key,
custom_version_key: self.custom_version_key,
custom_data_key: self.custom_data_key,
_state: PhantomData,
}
}
/// Finalizes the migration path with conversion to domain model.
pub fn into<D: DeserializeOwned + Serialize>(self) -> MigrationPath<D>
where
V: IntoDomain<D>,
{
let finalize: Box<
dyn Fn(serde_json::Value) -> Result<serde_json::Value, MigrationError> + Send + Sync,
> = Box::new(move |value| {
let versioned: V = serde_json::from_value(value).map_err(|e| {
MigrationError::DeserializationError(format!(
"Failed to deserialize final version: {}",
e
))
})?;
let domain = versioned.into_domain();
serde_json::to_value(domain).map_err(|e| MigrationError::MigrationStepFailed {
from: V::VERSION.to_string(),
to: "domain".to_string(),
error: e.to_string(),
})
});
MigrationPath {
entity: self.entity,
inner: EntityMigrationPath {
steps: self.steps,
finalize,
versions: self.versions.clone(),
version_key: self.version_key,
data_key: self.data_key,
},
versions: self.versions,
custom_version_key: self.custom_version_key,
custom_data_key: self.custom_data_key,
save_fn: None,
save_flat_fn: None,
_phantom: PhantomData,
}
}
/// Finalizes the migration path with conversion to domain model and enables domain entity saving.
///
/// See `MigrationPathBuilder<HasFrom<V>>::into_with_save` for details.
pub fn into_with_save<D: DeserializeOwned + Serialize>(self) -> MigrationPath<D>
where
V: IntoDomain<D> + crate::FromDomain<D>,
{
let finalize: Box<
dyn Fn(serde_json::Value) -> Result<serde_json::Value, MigrationError> + Send + Sync,
> = Box::new(move |value| {
let versioned: V = serde_json::from_value(value).map_err(|e| {
MigrationError::DeserializationError(format!(
"Failed to deserialize final version: {}",
e
))
})?;
let domain = versioned.into_domain();
serde_json::to_value(domain).map_err(|e| MigrationError::MigrationStepFailed {
from: V::VERSION.to_string(),
to: "domain".to_string(),
error: e.to_string(),
})
});
// Create save function for domain entities
let version = V::VERSION;
let save_fn: DomainSaveFn = Box::new(move |domain_value, vkey, dkey| {
let domain: D = serde_json::from_value(domain_value).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to deserialize domain: {}", e))
})?;
let latest = V::from_domain(domain);
let data_value = serde_json::to_value(&latest).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize latest: {}", e))
})?;
let mut map = serde_json::Map::new();
map.insert(
vkey.to_string(),
serde_json::Value::String(version.to_string()),
);
map.insert(dkey.to_string(), data_value);
serde_json::to_string(&map).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize wrapper: {}", e))
})
});
let save_flat_fn: DomainSaveFlatFn = Box::new(move |domain_value, vkey| {
let domain: D = serde_json::from_value(domain_value).map_err(|e| {
MigrationError::DeserializationError(format!("Failed to deserialize domain: {}", e))
})?;
let latest = V::from_domain(domain);
let mut data_value = serde_json::to_value(&latest).map_err(|e| {
MigrationError::SerializationError(format!("Failed to serialize latest: {}", e))
})?;
let obj = data_value.as_object_mut().ok_or_else(|| {
MigrationError::SerializationError(
"Data must serialize to a JSON object for flat format".to_string(),
)
})?;
obj.insert(
vkey.to_string(),
serde_json::Value::String(version.to_string()),
);
serde_json::to_string(&obj).map_err(|e| {
MigrationError::SerializationError(format!(
"Failed to serialize flat format: {}",
e
))
})
});
MigrationPath {
entity: self.entity,
inner: EntityMigrationPath {
steps: self.steps,
finalize,
versions: self.versions.clone(),
version_key: self.version_key,
data_key: self.data_key,
},
versions: self.versions,
custom_version_key: self.custom_version_key,
custom_data_key: self.custom_data_key,
save_fn: Some(save_fn),
save_flat_fn: Some(save_flat_fn),
_phantom: PhantomData,
}
}
}
/// A complete migration path from versioned DTOs to a domain model.
pub struct MigrationPath<D> {
entity: String,
inner: EntityMigrationPath,
/// List of versions in the migration path for validation
versions: Vec<String>,
/// Custom version key override (takes precedence over Migrator defaults)
custom_version_key: Option<String>,
/// Custom data key override (takes precedence over Migrator defaults)
custom_data_key: Option<String>,
/// Function to save domain entities (if FromDomain is implemented)
save_fn: Option<DomainSaveFn>,
/// Function to save domain entities in flat format (if FromDomain is implemented)
save_flat_fn: Option<DomainSaveFlatFn>,
_phantom: PhantomData<D>,
}
/// A wrapper around JSON data that provides convenient query and update methods
/// for partial updates with automatic migration.
///
/// `ConfigMigrator` holds a JSON object and allows you to query specific keys,
/// automatically migrating versioned data to domain entities, and update them
/// with the latest version.
///
/// # Example
///
/// ```ignore
/// // config.json:
/// // {
/// // "app_name": "MyApp",
/// // "tasks": [
/// // {"version": "1.0.0", "id": "1", "title": "Task 1"},
/// // {"version": "2.0.0", "id": "2", "title": "Task 2", "description": "New"}
/// // ]
/// // }
///
/// let config_json = fs::read_to_string("config.json")?;
/// let mut config = ConfigMigrator::from(&config_json, migrator)?;
///
/// // Query tasks (automatically migrates all versions to TaskEntity)
/// let mut tasks: Vec<TaskEntity> = config.query("tasks")?;
///
/// // Update tasks
/// tasks[0].title = "Updated Task".to_string();
///
/// // Save back with latest version
/// config.update("tasks", tasks)?;
///
/// // Write to file
/// fs::write("config.json", config.to_string()?)?;
/// ```
pub struct ConfigMigrator {
root: serde_json::Value,
migrator: Migrator,
}
impl ConfigMigrator {
/// Creates a new `ConfigMigrator` from a JSON string and a `Migrator`.
///
/// # Errors
///
/// Returns `MigrationError::DeserializationError` if the JSON is invalid.
pub fn from(json: &str, migrator: Migrator) -> Result<Self, MigrationError> {
let root = serde_json::from_str(json)
.map_err(|e| MigrationError::DeserializationError(e.to_string()))?;
Ok(Self { root, migrator })
}
/// Queries a specific key from the JSON object and returns the data as domain entities.
///
/// This method automatically migrates all versioned data to the latest version
/// and converts them to domain entities.
///
/// # Type Parameters
///
/// - `T`: Must implement `Queryable` to provide the entity name, and `Deserialize` for deserialization.
///
/// # Errors
///
/// - Returns `MigrationError::DeserializationError` if the key doesn't contain a valid array.
/// - Returns migration errors if the data cannot be migrated.
///
/// # Example
///
/// ```ignore
/// let tasks: Vec<TaskEntity> = config.query("tasks")?;
/// ```
pub fn query<T>(&self, key: &str) -> Result<Vec<T>, MigrationError>
where
T: crate::Queryable + for<'de> serde::Deserialize<'de>,
{
let value = &self.root[key];
if value.is_null() {
return Ok(Vec::new());
}
if !value.is_array() {
return Err(MigrationError::DeserializationError(format!(
"Key '{}' does not contain an array",
key
)));
}
match value.as_array() {
Some(array) => self
.migrator
.load_vec_flat_from(T::ENTITY_NAME, array.to_vec()),
None => Err(MigrationError::DeserializationError(format!(
"Key '{}' is not an array",
key
))),
}
}
/// Updates a specific key in the JSON object with new domain entities.
///
/// This method serializes the entities with the latest version (automatically
/// determined from the `Queryable` trait) and updates the JSON object in place.
///
/// # Type Parameters
///
/// - `T`: Must implement `Serialize` and `Queryable`.
///
/// # Errors
///
/// - Returns `MigrationError::EntityNotFound` if the entity is not registered.
/// - Returns serialization errors if the data cannot be serialized.
///
/// # Example
///
/// ```ignore
/// // Version is automatically determined from the entity's migration path
/// config.update("tasks", updated_tasks)?;
/// ```
pub fn update<T>(&mut self, key: &str, data: Vec<T>) -> Result<(), MigrationError>
where
T: serde::Serialize + crate::Queryable,
{
let entity_name = T::ENTITY_NAME;
let latest_version = self
.migrator
.get_latest_version(entity_name)
.ok_or_else(|| MigrationError::EntityNotFound(entity_name.to_string()))?;
// Serialize each item with version field
let items: Vec<serde_json::Value> = data
.into_iter()
.map(|item| {
let mut obj = serde_json::to_value(&item)
.map_err(|e| MigrationError::SerializationError(e.to_string()))?;
if let Some(obj_map) = obj.as_object_mut() {
obj_map.insert(
"version".to_string(),
serde_json::Value::String(latest_version.to_string()),
);
}
Ok(obj)
})
.collect::<Result<Vec<_>, MigrationError>>()?;
self.root[key] = serde_json::Value::Array(items);
Ok(())
}
/// Converts the entire JSON object back to a pretty-printed string.
///
/// # Errors
///
/// Returns `MigrationError::SerializationError` if serialization fails.
pub fn to_string(&self) -> Result<String, MigrationError> {
serde_json::to_string_pretty(&self.root)
.map_err(|e| MigrationError::SerializationError(e.to_string()))
}
/// Converts the entire JSON object to a compact string.
///
/// # Errors
///
/// Returns `MigrationError::SerializationError` if serialization fails.
pub fn to_string_compact(&self) -> Result<String, MigrationError> {
serde_json::to_string(&self.root)
.map_err(|e| MigrationError::SerializationError(e.to_string()))
}
/// Returns a reference to the underlying JSON value.
pub fn as_value(&self) -> &serde_json::Value {
&self.root
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{IntoDomain, MigratesTo, Versioned, VersionedWrapper};
use serde::{Deserialize, Serialize};
// Test data structures
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct V1 {
value: String,
}
impl Versioned for V1 {
const VERSION: &'static str = "1.0.0";
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct V2 {
value: String,
count: u32,
}
impl Versioned for V2 {
const VERSION: &'static str = "2.0.0";
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct V3 {
value: String,
count: u32,
enabled: bool,
}
impl Versioned for V3 {
const VERSION: &'static str = "3.0.0";
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Domain {
value: String,
count: u32,
enabled: bool,
}
impl MigratesTo<V2> for V1 {
fn migrate(self) -> V2 {
V2 {
value: self.value,
count: 0,
}
}
}
impl MigratesTo<V3> for V2 {
fn migrate(self) -> V3 {
V3 {
value: self.value,
count: self.count,
enabled: true,
}
}
}
impl IntoDomain<Domain> for V3 {
fn into_domain(self) -> Domain {
Domain {
value: self.value,
count: self.count,
enabled: self.enabled,
}
}
}
#[test]
fn test_migrator_new() {
let migrator = Migrator::new();
assert_eq!(migrator.paths.len(), 0);
}
#[test]
fn test_migrator_default() {
let migrator = Migrator::default();
assert_eq!(migrator.paths.len(), 0);
}
#[test]
fn test_single_step_migration() {
let path = Migrator::define("test")
.from::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
let v2 = V2 {
value: "test".to_string(),
count: 42,
};
let wrapper = VersionedWrapper::from_versioned(v2);
let json = serde_json::to_string(&wrapper).unwrap();
let result: Domain = migrator.load("test", &json).unwrap();
assert_eq!(result.value, "test");
assert_eq!(result.count, 42);
assert!(result.enabled);
}
#[test]
fn test_multi_step_migration() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
let v1 = V1 {
value: "multi_step".to_string(),
};
let wrapper = VersionedWrapper::from_versioned(v1);
let json = serde_json::to_string(&wrapper).unwrap();
let result: Domain = migrator.load("test", &json).unwrap();
assert_eq!(result.value, "multi_step");
assert_eq!(result.count, 0);
assert!(result.enabled);
}
#[test]
fn test_no_migration_needed() {
let path = Migrator::define("test").from::<V3>().into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
let v3 = V3 {
value: "latest".to_string(),
count: 100,
enabled: false,
};
let wrapper = VersionedWrapper::from_versioned(v3);
let json = serde_json::to_string(&wrapper).unwrap();
let result: Domain = migrator.load("test", &json).unwrap();
assert_eq!(result.value, "latest");
assert_eq!(result.count, 100);
assert!(!result.enabled);
}
#[test]
fn test_entity_not_found() {
let migrator = Migrator::new();
let v1 = V1 {
value: "test".to_string(),
};
let wrapper = VersionedWrapper::from_versioned(v1);
let json = serde_json::to_string(&wrapper).unwrap();
let result: Result<Domain, MigrationError> = migrator.load("unknown", &json);
assert!(matches!(result, Err(MigrationError::EntityNotFound(_))));
if let Err(MigrationError::EntityNotFound(entity)) = result {
assert_eq!(entity, "unknown");
}
}
#[test]
fn test_invalid_json() {
let path = Migrator::define("test").from::<V3>().into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
let invalid_json = "{ invalid json }";
let result: Result<Domain, MigrationError> = migrator.load("test", invalid_json);
assert!(matches!(
result,
Err(MigrationError::DeserializationError(_))
));
}
#[test]
fn test_multiple_entities() {
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct OtherDomain {
value: String,
}
impl IntoDomain<OtherDomain> for V1 {
fn into_domain(self) -> OtherDomain {
OtherDomain { value: self.value }
}
}
let path1 = Migrator::define("entity1")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let path2 = Migrator::define("entity2")
.from::<V1>()
.into::<OtherDomain>();
let mut migrator = Migrator::new();
migrator.register(path1).unwrap();
migrator.register(path2).unwrap();
// Test entity1
let v1 = V1 {
value: "entity1".to_string(),
};
let wrapper = VersionedWrapper::from_versioned(v1);
let json = serde_json::to_string(&wrapper).unwrap();
let result: Domain = migrator.load("entity1", &json).unwrap();
assert_eq!(result.value, "entity1");
// Test entity2
let v1 = V1 {
value: "entity2".to_string(),
};
let wrapper = VersionedWrapper::from_versioned(v1);
let json = serde_json::to_string(&wrapper).unwrap();
let result: OtherDomain = migrator.load("entity2", &json).unwrap();
assert_eq!(result.value, "entity2");
}
#[test]
fn test_save() {
let migrator = Migrator::new();
let v1 = V1 {
value: "test_save".to_string(),
};
let json = migrator.save(v1).unwrap();
// Verify JSON contains version and data
assert!(json.contains("\"version\""));
assert!(json.contains("\"1.0.0\""));
assert!(json.contains("\"data\""));
assert!(json.contains("\"test_save\""));
// Verify it can be parsed back
let parsed: VersionedWrapper<serde_json::Value> = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.version, "1.0.0");
}
#[test]
fn test_save_and_load_roundtrip() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Save V1 data
let v1 = V1 {
value: "roundtrip".to_string(),
};
let json = migrator.save(v1).unwrap();
// Load and migrate to Domain
let domain: Domain = migrator.load("test", &json).unwrap();
assert_eq!(domain.value, "roundtrip");
assert_eq!(domain.count, 0); // Default from V1->V2 migration
assert!(domain.enabled); // Default from V2->V3 migration
}
#[test]
fn test_save_latest_version() {
let migrator = Migrator::new();
let v3 = V3 {
value: "latest".to_string(),
count: 42,
enabled: false,
};
let json = migrator.save(v3).unwrap();
// Verify the JSON structure
assert!(json.contains("\"version\":\"3.0.0\""));
assert!(json.contains("\"value\":\"latest\""));
assert!(json.contains("\"count\":42"));
assert!(json.contains("\"enabled\":false"));
}
#[test]
fn test_save_pretty() {
let migrator = Migrator::new();
let v2 = V2 {
value: "pretty".to_string(),
count: 10,
};
let json = migrator.save(v2).unwrap();
// Should be compact JSON (not pretty-printed)
assert!(!json.contains('\n'));
assert!(json.contains("\"version\":\"2.0.0\""));
}
#[test]
fn test_validation_invalid_version_order() {
// Manually construct a path with invalid version ordering
let entity = "test".to_string();
let versions = vec!["2.0.0".to_string(), "1.0.0".to_string()]; // Wrong order
let result = Migrator::validate_migration_path(&entity, &versions);
assert!(matches!(
result,
Err(MigrationError::InvalidVersionOrder { .. })
));
if let Err(MigrationError::InvalidVersionOrder {
entity: e,
from,
to,
}) = result
{
assert_eq!(e, "test");
assert_eq!(from, "2.0.0");
assert_eq!(to, "1.0.0");
}
}
#[test]
fn test_validation_circular_path() {
// Manually construct a path with circular reference
let entity = "test".to_string();
let versions = vec![
"1.0.0".to_string(),
"2.0.0".to_string(),
"1.0.0".to_string(), // Circular!
];
let result = Migrator::validate_migration_path(&entity, &versions);
assert!(matches!(
result,
Err(MigrationError::CircularMigrationPath { .. })
));
if let Err(MigrationError::CircularMigrationPath { entity: e, path }) = result {
assert_eq!(e, "test");
assert!(path.contains("1.0.0"));
assert!(path.contains("2.0.0"));
}
}
#[test]
fn test_validation_valid_path() {
// Valid migration path
let entity = "test".to_string();
let versions = vec![
"1.0.0".to_string(),
"1.1.0".to_string(),
"2.0.0".to_string(),
];
let result = Migrator::validate_migration_path(&entity, &versions);
assert!(result.is_ok());
}
#[test]
fn test_validation_empty_path() {
// Empty path should be valid
let entity = "test".to_string();
let versions = vec![];
let result = Migrator::validate_migration_path(&entity, &versions);
assert!(result.is_ok());
}
#[test]
fn test_validation_single_version() {
// Single version path should be valid (no steps, just final conversion)
let entity = "test".to_string();
let versions = vec!["1.0.0".to_string()];
let result = Migrator::validate_migration_path(&entity, &versions);
assert!(result.is_ok());
}
// Tests for Vec operations
#[test]
fn test_save_vec_and_load_vec() {
let migrator = Migrator::new();
// Save multiple V1 items
let items = vec![
V1 {
value: "item1".to_string(),
},
V1 {
value: "item2".to_string(),
},
V1 {
value: "item3".to_string(),
},
];
let json = migrator.save_vec(items).unwrap();
// Verify JSON array format
assert!(json.starts_with('['));
assert!(json.ends_with(']'));
assert!(json.contains("\"version\":\"1.0.0\""));
assert!(json.contains("item1"));
assert!(json.contains("item2"));
assert!(json.contains("item3"));
// Setup migration path
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Load and migrate the array
let domains: Vec<Domain> = migrator.load_vec("test", &json).unwrap();
assert_eq!(domains.len(), 3);
assert_eq!(domains[0].value, "item1");
assert_eq!(domains[1].value, "item2");
assert_eq!(domains[2].value, "item3");
// All should have default values from migration
for domain in &domains {
assert_eq!(domain.count, 0);
assert!(domain.enabled);
}
}
#[test]
fn test_load_vec_empty_array() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
let json = "[]";
let domains: Vec<Domain> = migrator.load_vec("test", json).unwrap();
assert_eq!(domains.len(), 0);
}
#[test]
fn test_load_vec_mixed_versions() {
// Setup migration path
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// JSON with mixed versions
let json = r#"[
{"version":"1.0.0","data":{"value":"v1-item"}},
{"version":"2.0.0","data":{"value":"v2-item","count":42}},
{"version":"3.0.0","data":{"value":"v3-item","count":99,"enabled":false}}
]"#;
let domains: Vec<Domain> = migrator.load_vec("test", json).unwrap();
assert_eq!(domains.len(), 3);
// V1 item migrated to domain
assert_eq!(domains[0].value, "v1-item");
assert_eq!(domains[0].count, 0);
assert!(domains[0].enabled);
// V2 item migrated to domain
assert_eq!(domains[1].value, "v2-item");
assert_eq!(domains[1].count, 42);
assert!(domains[1].enabled);
// V3 item converted to domain
assert_eq!(domains[2].value, "v3-item");
assert_eq!(domains[2].count, 99);
assert!(!domains[2].enabled);
}
#[test]
fn test_load_vec_from_json_values() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Create Vec<serde_json::Value> directly
let values: Vec<serde_json::Value> = vec![
serde_json::json!({"version":"1.0.0","data":{"value":"direct1"}}),
serde_json::json!({"version":"1.0.0","data":{"value":"direct2"}}),
];
let domains: Vec<Domain> = migrator.load_vec_from("test", values).unwrap();
assert_eq!(domains.len(), 2);
assert_eq!(domains[0].value, "direct1");
assert_eq!(domains[1].value, "direct2");
}
#[test]
fn test_save_vec_empty() {
let migrator = Migrator::new();
let empty: Vec<V1> = vec![];
let json = migrator.save_vec(empty).unwrap();
assert_eq!(json, "[]");
}
#[test]
fn test_load_vec_invalid_json() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
let invalid_json = "{ not an array }";
let result: Result<Vec<Domain>, MigrationError> = migrator.load_vec("test", invalid_json);
assert!(matches!(
result,
Err(MigrationError::DeserializationError(_))
));
}
#[test]
fn test_load_vec_entity_not_found() {
let migrator = Migrator::new();
let json = r#"[{"version":"1.0.0","data":{"value":"test"}}]"#;
let result: Result<Vec<Domain>, MigrationError> = migrator.load_vec("unknown", json);
assert!(matches!(result, Err(MigrationError::EntityNotFound(_))));
}
#[test]
fn test_save_vec_latest_version() {
let migrator = Migrator::new();
let items = vec![
V3 {
value: "latest1".to_string(),
count: 10,
enabled: true,
},
V3 {
value: "latest2".to_string(),
count: 20,
enabled: false,
},
];
let json = migrator.save_vec(items).unwrap();
// Verify structure
assert!(json.contains("\"version\":\"3.0.0\""));
assert!(json.contains("latest1"));
assert!(json.contains("latest2"));
assert!(json.contains("\"count\":10"));
assert!(json.contains("\"count\":20"));
}
#[test]
fn test_load_with_fallback_versioned_data() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Test with properly versioned data
let versioned_json = r#"{"version":"1.0.0","data":{"value":"versioned_test"}}"#;
let result: Domain = migrator.load_with_fallback("test", versioned_json).unwrap();
assert_eq!(result.value, "versioned_test");
assert_eq!(result.count, 0); // Default from V1->V2 migration
assert!(result.enabled); // Default from V2->V3 migration
}
#[test]
fn test_load_with_fallback_legacy_data() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Test with legacy data (no version field) - should treat as V1
let legacy_json = r#"{"value":"legacy_test"}"#;
let result: Domain = migrator.load_with_fallback("test", legacy_json).unwrap();
assert_eq!(result.value, "legacy_test");
assert_eq!(result.count, 0); // Default from V1->V2 migration
assert!(result.enabled); // Default from V2->V3 migration
}
#[test]
fn test_load_with_fallback_mixed_formats() {
let path = Migrator::define("test")
.from::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Test with legacy data that matches V2 format
let legacy_v2_json = r#"{"value":"legacy_v2","count":42}"#;
let result: Domain = migrator.load_with_fallback("test", legacy_v2_json).unwrap();
assert_eq!(result.value, "legacy_v2");
assert_eq!(result.count, 42);
assert!(result.enabled); // Default from V2->V3 migration
// Test with versioned data
let versioned_json = r#"{"version":"2.0.0","data":{"value":"versioned_v2","count":99}}"#;
let result2: Domain = migrator.load_with_fallback("test", versioned_json).unwrap();
assert_eq!(result2.value, "versioned_v2");
assert_eq!(result2.count, 99);
assert!(result2.enabled);
}
#[test]
fn test_load_from_with_fallback_toml_value() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Simulate loading from TOML or other format
let data = serde_json::json!({"value": "from_toml"});
let result: Domain = migrator.load_from_with_fallback("test", data).unwrap();
assert_eq!(result.value, "from_toml");
assert_eq!(result.count, 0);
assert!(result.enabled);
}
#[test]
fn test_load_with_fallback_no_migration_path() {
let migrator = Migrator::new();
let legacy_json = r#"{"value":"test"}"#;
let result: Result<Domain, MigrationError> =
migrator.load_with_fallback("unknown", legacy_json);
assert!(matches!(result, Err(MigrationError::EntityNotFound(_))));
}
#[test]
fn test_load_with_fallback_empty_migration_path() {
// Register entity with no migration steps (direct conversion)
let path = Migrator::define("test").from::<V3>().into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Legacy data should still work with direct conversion
let legacy_json = r#"{"value":"direct","count":10,"enabled":false}"#;
let result: Domain = migrator.load_with_fallback("test", legacy_json).unwrap();
assert_eq!(result.value, "direct");
assert_eq!(result.count, 10);
assert!(!result.enabled);
}
#[test]
fn test_load_with_fallback_invalid_json() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
let invalid_json = "{ invalid json }";
let result: Result<Domain, MigrationError> =
migrator.load_with_fallback("test", invalid_json);
assert!(matches!(
result,
Err(MigrationError::DeserializationError(_))
));
}
#[test]
fn test_load_with_fallback_non_object_data() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Array instead of object
let array_json = r#"["not", "an", "object"]"#;
let result: Result<Domain, MigrationError> =
migrator.load_with_fallback("test", array_json);
assert!(matches!(
result,
Err(MigrationError::DeserializationError(_))
));
}
#[test]
fn test_invalid_semver_version() {
// Test with invalid semver format in a migration chain
// Note: Validation only runs when there are 2+ versions to compare
#[derive(Serialize, Deserialize, Debug)]
struct BadV1 {
value: String,
}
impl Versioned for BadV1 {
const VERSION: &'static str = "not-a-semver";
}
impl MigratesTo<V2> for BadV1 {
fn migrate(self) -> V2 {
V2 {
value: self.value,
count: 0,
}
}
}
// Two versions triggers version ordering check
let path = Migrator::define("bad")
.from::<BadV1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
let result = migrator.register(path);
// Should fail due to invalid semver in version ordering check
assert!(matches!(
result,
Err(MigrationError::DeserializationError(_))
));
}
#[test]
fn test_load_from_with_toml_value() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Create a toml::Value directly
let toml_str = r#"
version = "1.0.0"
[data]
value = "from_toml"
"#;
let toml_value: toml::Value = toml::from_str(toml_str).unwrap();
let result: Domain = migrator.load_from("test", toml_value).unwrap();
assert_eq!(result.value, "from_toml");
assert_eq!(result.count, 0);
assert!(result.enabled);
}
#[test]
fn test_load_from_missing_version_field() {
let path = Migrator::define("test").from::<V3>().into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// JSON object without version field
let json_value: serde_json::Value = serde_json::json!({
"data": {"value": "test", "count": 1, "enabled": true}
});
let result: Result<Domain, MigrationError> = migrator.load_from("test", json_value);
assert!(matches!(
result,
Err(MigrationError::DeserializationError(_))
));
}
#[test]
fn test_load_from_missing_data_field() {
let path = Migrator::define("test").from::<V3>().into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// JSON object without data field
let json_value: serde_json::Value = serde_json::json!({
"version": "3.0.0"
});
let result: Result<Domain, MigrationError> = migrator.load_from("test", json_value);
assert!(matches!(
result,
Err(MigrationError::DeserializationError(_))
));
}
#[test]
fn test_load_from_non_object() {
let path = Migrator::define("test").from::<V3>().into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Not an object
let json_value: serde_json::Value = serde_json::json!("just a string");
let result: Result<Domain, MigrationError> = migrator.load_from("test", json_value);
assert!(matches!(
result,
Err(MigrationError::DeserializationError(_))
));
}
#[test]
fn test_load_from_invalid_domain_conversion() {
#[derive(Serialize, Deserialize, Debug)]
struct StrictDomain {
required_field: String,
}
impl IntoDomain<StrictDomain> for V3 {
fn into_domain(self) -> StrictDomain {
StrictDomain {
required_field: self.value,
}
}
}
let path = Migrator::define("strict")
.from::<V3>()
.into::<StrictDomain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// V3 data that will fail to convert to StrictDomain due to field name mismatch
// The finalize function creates StrictDomain but serde expects different field
let json = r#"{"version":"3.0.0","data":{"value":"test","count":1,"enabled":true}}"#;
// This should work because IntoDomain converts correctly
let result: Result<StrictDomain, MigrationError> = migrator.load("strict", json);
assert!(result.is_ok());
assert_eq!(result.unwrap().required_field, "test");
}
#[test]
fn test_save_flat_and_load_flat() {
let path = Migrator::define("test").from::<V3>().into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
let v3 = V3 {
value: "flat_test".to_string(),
count: 99,
enabled: true,
};
let json = migrator.save_flat(v3).unwrap();
// Verify flat format (version at same level as data)
assert!(json.contains("\"version\":\"3.0.0\""));
assert!(json.contains("\"value\":\"flat_test\""));
assert!(!json.contains("\"data\":"));
// Load back
let result: Domain = migrator.load_flat("test", &json).unwrap();
assert_eq!(result.value, "flat_test");
assert_eq!(result.count, 99);
assert!(result.enabled);
}
#[test]
fn test_load_from_with_fallback_version_not_string() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Version field is a number, not a string - should fallback to V1
let json_value: serde_json::Value = serde_json::json!({
"version": 100,
"value": "fallback_test"
});
let result: Domain = migrator
.load_from_with_fallback("test", json_value)
.unwrap();
assert_eq!(result.value, "fallback_test");
assert_eq!(result.count, 0); // Default from V1->V2 migration
assert!(result.enabled); // Default from V2->V3 migration
}
#[test]
fn test_load_from_with_fallback_missing_data_field() {
let path = Migrator::define("test")
.from::<V1>()
.step::<V2>()
.step::<V3>()
.into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Has version string but missing data field
let json_value: serde_json::Value = serde_json::json!({
"version": "1.0.0"
});
let result: Result<Domain, MigrationError> =
migrator.load_from_with_fallback("test", json_value);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
matches!(err, MigrationError::DeserializationError(ref msg) if msg.contains("data")),
"Expected DeserializationError about missing data field, got: {:?}",
err
);
}
#[test]
fn test_register_second_version_invalid_semver() {
// BadV2 has invalid semver format
#[derive(Serialize, Deserialize, Debug)]
struct BadV2 {
value: String,
count: u32,
}
impl Versioned for BadV2 {
const VERSION: &'static str = "not-a-version"; // Invalid semver
}
impl MigratesTo<BadV2> for V1 {
fn migrate(self) -> BadV2 {
BadV2 {
value: self.value,
count: 0,
}
}
}
impl IntoDomain<Domain> for BadV2 {
fn into_domain(self) -> Domain {
Domain {
value: self.value,
count: self.count,
enabled: false,
}
}
}
let path = Migrator::define("test")
.from::<V1>()
.step::<BadV2>()
.into::<Domain>();
let mut migrator = Migrator::new();
let result = migrator.register(path);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
matches!(err, MigrationError::DeserializationError(ref msg) if msg.contains("not-a-version")),
"Expected error about invalid semver 'not-a-version', got: {:?}",
err
);
}
#[test]
fn test_load_from_with_fallback_non_object() {
let path = Migrator::define("test").from::<V3>().into::<Domain>();
let mut migrator = Migrator::new();
migrator.register(path).unwrap();
// Array instead of object
let json_value: serde_json::Value = serde_json::json!([1, 2, 3]);
let result: Result<Domain, MigrationError> =
migrator.load_from_with_fallback("test", json_value);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
matches!(err, MigrationError::DeserializationError(ref msg) if msg.contains("object")),
"Expected DeserializationError about object format, got: {:?}",
err
);
}
}