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
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
//! MySQL-specific schema management implementation for RustF CLI
use crate::analyzer::OutputFormat;
use rust_embed::RustEmbed;
use rustf_schema::{Schema, SchemaError};
use std::collections::HashMap;
use std::path::Path;
use tokio::fs;
#[derive(RustEmbed)]
#[folder = "templates/"]
struct Templates;
/// Escape Rust reserved keywords by adding r# prefix
fn escape_rust_keyword(field_name: &str) -> String {
const RUST_KEYWORDS: &[&str] = &[
"type", "match", "if", "else", "while", "for", "loop", "fn", "let", "mut", "const",
"static", "struct", "enum", "trait", "impl", "mod", "use", "pub", "return", "break",
"continue", "true", "false", "self", "Self", "super", "crate", "in", "as", "where",
"async", "await", "dyn", "move", "ref", "macro", "union", "unsafe", "extern", "yield",
"try", "catch", "typeof",
];
if RUST_KEYWORDS.contains(&field_name) {
format!("r#{}", field_name)
} else {
field_name.to_string()
}
}
/// Check if a Rust type implements the Copy trait
/// Copy types can be safely returned by value from getters
fn is_copy_type(type_str: &str) -> bool {
matches!(
type_str,
"i8" | "i16"
| "i32"
| "i64"
| "i128"
| "u8"
| "u16"
| "u32"
| "u64"
| "u128"
| "f32"
| "f64"
| "bool"
| "chrono::DateTime<chrono::Utc>"
| "DateTime<Utc>"
| "chrono::NaiveDate"
| "NaiveDate"
| "chrono::NaiveTime"
| "NaiveTime"
)
}
/// Extract the inner type from Option<T>
/// Example: "Option<i32>" -> "i32"
fn extract_inner_type(option_type: &str) -> &str {
if let Some(inner) = option_type.strip_prefix("Option<") {
if let Some(without_bracket) = inner.strip_suffix(">") {
return without_bracket;
}
}
option_type
}
// Import the command structures from mod.rs
use crate::commands::schema::{
to_screaming_snake_case, GenerateTarget, SchemaAction, SchemaCommand,
};
/// Execute schema command for MySQL
pub async fn execute_schema_command(cmd: SchemaCommand) -> anyhow::Result<()> {
match cmd.action {
SchemaAction::Validate {
path,
check_generated,
} => {
validate_schema(&path, check_generated).await?;
}
SchemaAction::Analyze { path, format } => {
analyze_schema(&path, format).await?;
}
SchemaAction::Generate { target } => {
generate_code(target).await?;
}
SchemaAction::Watch {
path,
auto_generate,
} => {
watch_schema(&path, auto_generate).await?;
}
SchemaAction::CheckConsistency {
schema_path,
models_path,
} => {
check_consistency(&schema_path, &models_path).await?;
}
}
Ok(())
}
/// Validate schema files
async fn validate_schema(path: &Path, check_generated: bool) -> Result<(), SchemaError> {
println!("🔍 Validating schema in {:?}...", path);
if !path.exists() {
return Err(SchemaError::Io(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("Schema directory not found: {:?}", path),
)));
}
let schema = Schema::load_from_directory(path).await?;
println!("✅ Schema loaded successfully!");
if let Some(meta) = &schema.meta {
println!("📊 Database: {} (v{})", meta.database_name, meta.version);
}
println!("📋 Tables: {}", schema.tables.len());
println!("🔍 Validating schema consistency...");
// Use comprehensive validation to collect all errors
use rustf_schema::SchemaValidator;
let validation_result = SchemaValidator::validate_comprehensive(&schema)?;
if validation_result.has_errors() {
println!(
"❌ Schema validation failed with {} error(s):",
validation_result.errors.len()
);
for (i, error) in validation_result.errors.iter().enumerate() {
println!(" {}. {}", i + 1, error);
}
if validation_result.has_warnings() {
println!("⚠️ {} warning(s):", validation_result.warnings.len());
for (i, warning) in validation_result.warnings.iter().enumerate() {
println!(" {}. {}", i + 1, warning);
}
}
return validation_result.into_result();
} else if validation_result.has_warnings() {
println!(
"⚠️ Schema validation passed with {} warning(s):",
validation_result.warnings.len()
);
for (i, warning) in validation_result.warnings.iter().enumerate() {
println!(" {}. {}", i + 1, warning);
}
println!("✅ Schema validation completed!");
} else {
println!("✅ Schema validation passed!");
}
if check_generated {
println!("🔍 Checking generated code consistency...");
let models_path = Path::new("src/models");
if models_path.exists() {
let checksums = extract_generated_checksums(models_path).await?;
schema.validate_consistency(&checksums)?;
println!("✅ Generated code consistency check passed!");
} else {
println!("⚠️ No generated models found at {:?}", models_path);
}
}
println!("📈 Summary:");
println!(" • {} tables defined", schema.tables.len());
let total_fields: usize = schema.tables.values().map(|t| t.fields.len()).sum();
println!(" • {} total fields", total_fields);
let mut relation_count = 0;
for table in schema.tables.values() {
if let Some(belongs_to) = &table.relations.belongs_to {
relation_count += belongs_to.len();
}
if let Some(has_many) = &table.relations.has_many {
relation_count += has_many.len();
}
if let Some(has_one) = &table.relations.has_one {
relation_count += has_one.len();
}
if let Some(many_to_many) = &table.relations.many_to_many {
relation_count += many_to_many.len();
}
}
println!(" • {} relationships", relation_count);
Ok(())
}
/// Analyze schema structure
async fn analyze_schema(path: &Path, format: OutputFormat) -> Result<(), SchemaError> {
println!("🔍 Analyzing schema structure...");
let schema = Schema::load_from_directory(path).await?;
match format {
OutputFormat::Json => {
let json = serde_json::to_string_pretty(&schema)?;
println!("{}", json);
}
OutputFormat::Yaml => {
let yaml = serde_yaml::to_string(&schema)?;
println!("{}", yaml);
}
OutputFormat::Table => {
print_schema_table(&schema);
}
OutputFormat::Markdown => {
print_schema_markdown(&schema);
}
}
Ok(())
}
/// Generate code from schema
async fn generate_code(target: GenerateTarget) -> anyhow::Result<()> {
match target {
GenerateTarget::Models {
schema_path,
output,
force,
tables,
exclude,
} => {
generate_models(&schema_path, &output, force, tables, exclude).await?;
}
GenerateTarget::Sql {
schema_path,
output,
} => {
generate_sql_file(&schema_path, &output).await?;
}
}
Ok(())
}
/// Generate Rust model structs following RustF framework principles
async fn generate_models(
schema_path: &Path,
output_path: &Path,
force: bool,
tables_filter: Option<Vec<String>>,
exclude_filter: Option<Vec<String>>,
) -> anyhow::Result<()> {
// Create backup if forcing overwrite of existing models
if force && output_path.exists() && !crate::utils::backup::is_empty_directory(output_path)? {
use crate::utils::backup::BackupManager;
let backup_manager = BackupManager::new()?;
backup_manager.backup_directory(output_path, "models")?;
}
println!("🚀 Generating RustF models with base/wrapper pattern...");
println!("📂 Schema: {:?}", schema_path);
println!("📁 Output: {:?}", output_path);
// Check if this is likely a RustF project with models
let cargo_toml_path = output_path
.parent()
.and_then(|p| p.parent())
.map(|p| p.join("Cargo.toml"))
.filter(|p| p.exists());
if let Some(cargo_path) = cargo_toml_path {
let cargo_content = fs::read_to_string(&cargo_path).await.unwrap_or_default();
// Check if essential database dependencies are missing
if !cargo_content.contains("sqlx") {
println!("\n⚠️ WARNING: Database dependencies not detected in Cargo.toml");
println!(" Generated models will require these dependencies to compile.");
println!(" See instructions at the end of generation for details.\n");
}
}
let schema = Schema::load_from_directory(schema_path).await?;
// Create directory structure: models/base/ (no mod.rs files!)
let base_path = output_path.join("base");
if !output_path.exists() {
fs::create_dir_all(output_path).await?;
println!("📁 Created models directory: {:?}", output_path);
}
if !base_path.exists() {
fs::create_dir_all(&base_path).await?;
println!("📁 Created base directory: {:?}", base_path);
}
let mut generated_files = 0;
let mut wrapper_files = 0;
let schema_checksum = schema.checksum();
let generation_time = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
// Multi-database support: detect type per table, with fallbacks
fn detect_database_type(
table: &rustf_schema::Table,
meta: Option<&rustf_schema::SchemaMeta>,
) -> &'static str {
// 1. First: Check table's own database_type (supports multi-database)
if let Some(ref db_type) = table.database_type {
return match db_type.as_str() {
"mysql" => "MySql",
"postgres" | "postgresql" => "Postgres",
"sqlite" => "Sqlite",
_ => "Postgres", // Default fallback
};
}
// 2. Fallback: Check _meta.yaml for database information
if let Some(meta) = meta {
// Temporarily use description for type detection until schema is updated
if let Some(desc) = &meta.description {
if desc.contains("MySQL") || desc.contains("mysql") {
return "MySql";
} else if desc.contains("SQLite") || desc.contains("sqlite") {
return "Sqlite";
} else if desc.contains("PostgreSQL") || desc.contains("postgres") {
return "Postgres";
}
}
}
// 5. Final fallback
"Postgres"
}
// Filter tables based on --tables and --exclude options
let tables_to_generate: Vec<_> = schema
.tables
.iter()
.filter(|(_, table)| {
// Check if table should be included (using database table name)
if let Some(ref include_list) = tables_filter {
if !include_list
.iter()
.any(|t| t.eq_ignore_ascii_case(&table.table))
{
return false;
}
}
// Check if table should be excluded (using database table name)
if let Some(ref exclude_list) = exclude_filter {
if exclude_list
.iter()
.any(|t| t.eq_ignore_ascii_case(&table.table))
{
return false;
}
}
true
})
.collect();
if tables_to_generate.is_empty() {
println!("⚠️ No tables matched the filter criteria");
return Ok(());
}
println!(
"📊 Generating models for {} table(s)",
tables_to_generate.len()
);
for (_table_name, table) in tables_to_generate {
// Detect database type per table (supports multi-database scenarios)
let pool_type = detect_database_type(table, schema.meta.as_ref());
// 1. Generate base model: base/{table}.inc.rs (always overwritten)
let base_model_file = base_path.join(format!("{}.inc.rs", &table.table));
let base_code = generate_base_model_include_code(
table,
&schema,
&schema_checksum,
&generation_time,
pool_type,
)?;
fs::write(&base_model_file, base_code).await?;
println!(
"✅ Generated base include file: {}",
base_model_file.display()
);
generated_files += 1;
// 2. Generate wrapper model: {table}.rs (only if doesn't exist)
let wrapper_model_file = output_path.join(format!("{}.rs", &table.table));
if !wrapper_model_file.exists() || force {
let wrapper_code = generate_wrapper_model_include_code(table, pool_type)?;
fs::write(&wrapper_model_file, wrapper_code).await?;
println!(
"✅ Generated wrapper model: {}",
wrapper_model_file.display()
);
wrapper_files += 1;
} else {
println!(
"⚠️ Preserving existing business logic: {}",
wrapper_model_file.display()
);
}
}
// 3. Generate MODELS_README.md (always overwritten for latest guidelines)
let readme_file = output_path.join("MODELS_README.md");
let readme_content = generate_models_readme(&schema);
fs::write(&readme_file, readme_content).await?;
println!("✅ Generated documentation: {}", readme_file.display());
println!("🎉 Model generation completed!");
println!(
"📊 Generated {} base models and {} wrapper models",
generated_files, wrapper_files
);
println!("📝 Base models: Complete CRUD operations (will be overwritten)");
println!("🔧 Wrapper models: Add your business logic here (preserved)");
println!("⚠️ Only files in base/ will be overwritten on regeneration");
println!("📖 Read MODELS_README.md for detailed instructions");
// Check if we generated models with database dependencies
if generated_files > 0 {
println!("\n⚠️ IMPORTANT: Enable required dependencies in your Cargo.toml:");
println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
println!("# Required for database models:");
println!("sqlx = {{ version = \"0.8\", features = [\"runtime-tokio-rustls\", \"mysql\", \"postgres\", \"sqlite\", \"chrono\", \"rust_decimal\", \"uuid\"] }}");
println!("anyhow = \"1.0\"");
println!("chrono = {{ version = \"0.4\", features = [\"serde\"] }}");
println!("rust_decimal = {{ version = \"1.32\", features = [\"serde\"] }}");
println!("uuid = {{ version = \"1.0\", features = [\"v4\", \"serde\"] }}");
println!("\n💡 TIP: Adjust SQLx features based on your database:");
println!(" • MySQL: \"mysql\"");
println!(" • PostgreSQL: \"postgres\"");
println!(" • SQLite: \"sqlite\"");
println!("\n🔧 FOR COMPILATION: SQLx requires one of these options:");
println!(" 1. Set DATABASE_URL environment variable:");
println!(" export DATABASE_URL=\"mysql://user:pass@localhost/dbname\"");
println!(" 2. OR use offline mode (recommended for CI/CD):");
println!(" cargo sqlx prepare --database-url=\"your_db_url\"");
println!(" # This creates .sqlx/ directory with query metadata");
println!(" 3. OR disable compile-time checks (add to Cargo.toml):");
println!(" [env]");
println!(" SQLX_OFFLINE = \"true\"");
println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
}
Ok(())
}
/// Generate the full SQL schema (DDL) for all tables
async fn generate_sql_file(schema_path: &Path, output_path: &Path) -> anyhow::Result<()> {
println!("🚀 Generating SQL schema (DDL)...");
let schema = Schema::load_from_directory(schema_path).await?;
// Create output directory if it doesn't exist
if !output_path.exists() {
fs::create_dir_all(output_path).await?;
}
// Full schema snapshot (regenerated in place; track changes in git).
let sql_file = output_path.join("schema.sql");
let sql_code = super::sql_gen::generate_sql_schema(&schema, super::sql_gen::Dialect::MySql)?;
fs::write(&sql_file, sql_code).await?;
println!("✅ Generated {}", sql_file.display());
println!("🎉 SQL schema generated successfully!");
Ok(())
}
/// Watch schema files for changes
async fn watch_schema(path: &Path, auto_generate: bool) -> anyhow::Result<()> {
println!("👀 Watching schema directory: {:?}", path);
if auto_generate {
println!("🔄 Auto-generation enabled");
}
// This would use the existing file watcher from the CLI
// For now, just print a message
println!("⚠️ Watch mode not yet implemented");
println!("💡 Use 'rustf-cli watch' for file watching functionality");
Ok(())
}
/// Check consistency between schema and generated code
async fn check_consistency(schema_path: &Path, models_path: &Path) -> anyhow::Result<()> {
println!("🔍 Checking consistency between schema and generated code...");
println!("📂 Schema: {:?}", schema_path);
println!("📁 Models: {:?}", models_path);
let schema = Schema::load_from_directory(schema_path).await?;
if !models_path.exists() {
println!("❌ Models directory not found: {:?}", models_path);
println!("💡 Run 'rustf-cli schema generate models' to generate models");
return Ok(());
}
let generated_checksums = extract_generated_checksums(models_path).await?;
match schema.validate_consistency(&generated_checksums) {
Ok(()) => {
println!("✅ Schema and generated code are consistent!");
println!("📈 {} models validated", generated_checksums.len());
}
Err(SchemaError::Consistency(msg)) => {
println!("❌ Consistency check failed: {}", msg);
println!("💡 Run 'rustf-cli schema generate models --force' to regenerate models");
return Err(anyhow::anyhow!("Consistency check failed"));
}
Err(e) => return Err(e.into()),
}
Ok(())
}
/// Extract checksums from generated model files
async fn extract_generated_checksums(
models_path: &Path,
) -> Result<HashMap<String, String>, SchemaError> {
let mut checksums = HashMap::new();
// Look for generated files in the generated/ subfolder first
let generated_path = models_path.join("generated");
if generated_path.exists() {
let mut entries = fs::read_dir(&generated_path)
.await
.map_err(SchemaError::Io)?;
while let Some(entry) = entries.next_entry().await.map_err(SchemaError::Io)? {
let path = entry.path();
if path.extension().map_or(false, |ext| ext == "rs")
&& path.file_name().map_or(false, |name| name != "mod.rs")
{
let content = fs::read_to_string(&path).await.map_err(SchemaError::Io)?;
// Extract checksum from comment at top of file
if let Some(checksum_line) = content
.lines()
.find(|line| line.starts_with("// Schema checksum:"))
{
if let Some(checksum) = checksum_line.strip_prefix("// Schema checksum: ") {
// Extract table name from filename (remove _generated suffix)
if let Some(file_stem) = path.file_stem().and_then(|s| s.to_str()) {
let table_name =
file_stem.strip_suffix("_generated").unwrap_or(file_stem);
// Convert table name to model name (PascalCase)
let model_name = table_name
.split('_')
.map(|part| {
let mut chars = part.chars();
match chars.next() {
None => String::new(),
Some(first) => {
first.to_uppercase().collect::<String>()
+ chars.as_str()
}
}
})
.collect::<String>();
checksums.insert(model_name, checksum.trim().to_string());
}
}
}
}
}
} else {
// Fallback to old structure (flat files in models directory)
let mut entries = fs::read_dir(models_path).await.map_err(SchemaError::Io)?;
while let Some(entry) = entries.next_entry().await.map_err(SchemaError::Io)? {
let path = entry.path();
if path.extension().map_or(false, |ext| ext == "rs")
&& path.file_name().map_or(false, |name| name != "mod.rs")
{
let content = fs::read_to_string(&path).await.map_err(SchemaError::Io)?;
// Extract checksum from comment at top of file
if let Some(checksum_line) = content
.lines()
.find(|line| line.starts_with("// Schema checksum:"))
{
if let Some(checksum) = checksum_line.strip_prefix("// Schema checksum: ") {
// Extract table name from filename
if let Some(file_stem) = path.file_stem().and_then(|s| s.to_str()) {
// Convert table name back to model name (simple heuristic)
let model_name = file_stem
.split('_')
.map(|part| {
let mut chars = part.chars();
match chars.next() {
None => String::new(),
Some(first) => {
first.to_uppercase().collect::<String>()
+ chars.as_str()
}
}
})
.collect::<String>();
checksums.insert(model_name, checksum.trim().to_string());
}
}
}
}
}
}
Ok(checksums)
}
/// Generate complete model code with full CRUD operations (RustF style)
// removed unused function generate_complete_model_code
/// Generate manual model wrapper code (for business logic)
// removed unused function generate_manual_model_code
/// Generate Rust model code for a table (legacy function for compatibility)
// removed unused function generate_model_code
/// Print schema in table format
fn print_schema_table(schema: &Schema) {
if let Some(meta) = &schema.meta {
println!("📊 Database: {} (v{})", meta.database_name, meta.version);
if let Some(desc) = &meta.description {
println!("📝 Description: {}", desc);
}
println!();
}
for (table_name, table) in &schema.tables {
println!("📋 Table: {} ({})", table_name, table.table);
if let Some(desc) = &table.description {
println!(" Description: {}", desc);
}
println!(" Fields:");
for (field_name, field) in &table.fields {
let mut flags = Vec::new();
if field.constraints.primary_key == Some(true) {
flags.push("PK");
}
if field.constraints.unique == Some(true) {
flags.push("UNIQUE");
}
if field.constraints.required == Some(true) {
flags.push("NOT NULL");
}
let flags_str = if flags.is_empty() {
String::new()
} else {
format!(" ({})", flags.join(", "))
};
println!(
" • {}: {}{}",
field_name,
field.field_type.base_type(),
flags_str
);
if let Some(ai_hint) = &field.ai {
println!(" 💡 {}", ai_hint);
}
}
// Relations
if let Some(belongs_to) = &table.relations.belongs_to {
if !belongs_to.is_empty() {
println!(" Belongs to:");
for (rel_name, rel) in belongs_to {
println!(
" 👆 {}: {}.{} -> {}.{}",
rel_name, table.name, rel.local_field, rel.model, rel.foreign_field
);
}
}
}
if let Some(has_many) = &table.relations.has_many {
if !has_many.is_empty() {
println!(" Has many:");
for (rel_name, rel) in has_many {
println!(
" 👇 {}: {}.{} <- {}.{}",
rel_name, table.name, rel.local_field, rel.model, rel.foreign_field
);
}
}
}
println!();
}
}
/// Print schema in Markdown format
fn print_schema_markdown(schema: &Schema) {
println!("# Database Schema");
println!();
if let Some(meta) = &schema.meta {
println!("**Database:** {} v{}", meta.database_name, meta.version);
if let Some(desc) = &meta.description {
println!("**Description:** {}", desc);
}
println!();
}
for (table_name, table) in &schema.tables {
println!("## {}", table_name);
if let Some(desc) = &table.description {
println!("{}", desc);
println!();
}
if let Some(ai_context) = &table.ai_context {
println!("**AI Context:** {}", ai_context);
println!();
}
println!("**Table:** `{}`", table.table);
println!();
// Fields table
println!("| Field | Type | Constraints | Description |");
println!("|-------|------|-------------|-------------|");
for (field_name, field) in &table.fields {
let mut constraints = Vec::new();
if field.constraints.primary_key == Some(true) {
constraints.push("PK");
}
if field.constraints.unique == Some(true) {
constraints.push("UNIQUE");
}
if field.constraints.required == Some(true) {
constraints.push("NOT NULL");
}
let constraints_str = constraints.join(", ");
let description = field.ai.as_deref().unwrap_or("");
println!(
"| `{}` | `{}` | {} | {} |",
field_name,
field.field_type.base_type(),
constraints_str,
description
);
}
println!();
// Relations
if let Some(belongs_to) = &table.relations.belongs_to {
if !belongs_to.is_empty() {
println!("### Relations");
println!();
println!("**Belongs to:**");
for (rel_name, rel) in belongs_to {
println!(
"- `{}`: {}.{} → {}.{}",
rel_name, table.name, rel.local_field, rel.model, rel.foreign_field
);
}
println!();
}
}
if let Some(has_many) = &table.relations.has_many {
if !has_many.is_empty() {
println!("### Relations");
println!();
println!("**Has many:**");
for (rel_name, rel) in has_many {
println!(
"- `{}`: {}.{} ← {}.{}",
rel_name, table.name, rel.local_field, rel.model, rel.foreign_field
);
}
println!();
}
}
println!("---");
println!();
}
}
/// Process a template by replacing placeholders with values
fn process_template(content: &str, variables: &HashMap<String, String>) -> String {
let mut processed = content.to_string();
log::debug!("Processing template with {} variables", variables.len());
for (key, value) in variables {
let placeholder = format!("{{{{{}}}}}", key);
let display_value = if value.len() > 100 {
format!("{}...", &value[..100])
} else {
value.clone()
};
log::debug!(
"Replacing '{}' with '{}' (length: {})",
placeholder,
display_value,
value.len()
);
processed = processed.replace(&placeholder, value);
}
// Check for unreplaced variables
let remaining_vars = processed.matches("{{").count();
if remaining_vars > 0 {
log::warn!(
"Template still contains {} unreplaced variables",
remaining_vars
);
}
processed
}
/// Prepare template variables for base model generation
fn prepare_base_model_variables(
table: &rustf_schema::Table,
_schema: &Schema,
checksum: &str,
generation_time: &str,
pool_type: &str,
) -> HashMap<String, String> {
let mut vars = HashMap::new();
// Basic metadata
vars.insert("model_name".to_string(), table.name.clone());
vars.insert("table_name".to_string(), table.table.clone());
vars.insert("pool_type".to_string(), pool_type.to_string());
vars.insert("pool_getter".to_string(), "mysql_pool".to_string()); // MySQL specific pool getter
vars.insert("checksum".to_string(), checksum.to_string());
vars.insert("generation_time".to_string(), generation_time.to_string());
vars.insert("cli_version".to_string(), "0.1.0".to_string());
// Add table-level documentation
let mut table_doc = Vec::new();
log::debug!("Preparing table documentation for '{}'", table.name);
if let Some(ai_context) = &table.ai_context {
log::debug!("Found ai_context: '{}'", ai_context);
table_doc.push(ai_context.clone());
} else {
log::debug!("No ai_context found");
}
if let Some(description) = &table.description {
if !description.is_empty() {
log::debug!("Found description: '{}'", description);
table_doc.push(format!("Database: {}", description));
}
} else {
log::debug!("No description found");
}
let table_documentation = if table_doc.is_empty() {
"Auto-generated model from schema".to_string()
} else {
table_doc.join("\n/// ")
};
log::debug!("Final table documentation: '{}'", table_documentation);
vars.insert("table_documentation".to_string(), table_documentation);
// Sort fields alphabetically once for consistent ordering throughout generation
let mut sorted_fields: Vec<_> = table.fields.values().collect();
sorted_fields.sort_by(|a, b| a.name.cmp(&b.name));
log::debug!(
"Sorted fields order for {}: {:?}",
table.name,
sorted_fields.iter().map(|f| &f.name).collect::<Vec<_>>()
);
// Determine primary key field (detect early for use throughout generation)
let primary_key = table
.fields
.values()
.find(|f| f.constraints.primary_key.unwrap_or(false))
.map(|f| f.name.clone())
.unwrap_or_else(|| "id".to_string());
vars.insert("primary_key".to_string(), primary_key.clone());
// Determine ID type and whether this model has a primary key field
let has_primary_key = table
.fields
.values()
.any(|f| f.constraints.primary_key.unwrap_or(false));
let id_type = if let Some(pk_field) = table
.fields
.values()
.find(|f| f.constraints.primary_key.unwrap_or(false))
{
if let Some(ref lang_type) = pk_field.lang_type {
lang_type.clone()
} else {
match pk_field.field_type.base_type() {
"int" | "integer" => "i32",
"bigint" => "i64",
"string" => "String",
_ => "i32",
}
.to_string()
}
} else {
"i32".to_string() // Default type for models without primary key
};
vars.insert("id_type".to_string(), id_type.clone());
// Generate id method implementation based on whether primary key field exists
let id_method_impl = if has_primary_key {
// Use the primary key field name dynamically
let escaped_pk_field = escape_rust_keyword(&primary_key);
// Clone String IDs to avoid move out of borrowed content
if id_type == "String" {
format!(" self.{}.clone()", escaped_pk_field)
} else {
format!(" self.{}", escaped_pk_field)
}
} else {
" panic!(\"This model does not have a primary key field - it is likely a database view or composite entity\")".to_string()
};
vars.insert("id_method_impl".to_string(), id_method_impl);
// Generate imports
let mut imports = vec![
"#[allow(unused_imports)] use serde::{Deserialize, Serialize};".to_string(),
format!("#[allow(unused_imports)] use sqlx::{{Pool, {}}};", pool_type),
"#[allow(unused_imports)] use anyhow::Result;".to_string(),
];
// Check if we need chrono or other imports
let needs_datetime = table
.fields
.values()
.any(|f| matches!(f.field_type.base_type(), "timestamp" | "datetime"));
let needs_date = table
.fields
.values()
.any(|f| f.field_type.base_type() == "date");
let needs_time = table
.fields
.values()
.any(|f| f.field_type.base_type() == "time");
if needs_datetime || needs_date || needs_time {
let mut chrono_imports = vec![];
if needs_datetime {
chrono_imports.push("DateTime");
chrono_imports.push("Utc");
}
if needs_date {
chrono_imports.push("NaiveDate");
}
if needs_time {
chrono_imports.push("NaiveTime");
}
imports.push(format!("use chrono::{{{}}};", chrono_imports.join(", ")));
}
let needs_decimal = table
.fields
.values()
.any(|f| f.field_type.base_type() == "decimal");
if needs_decimal {
imports.push("use rust_decimal::Decimal;".to_string());
}
let needs_json = table
.fields
.values()
.any(|f| f.field_type.base_type() == "json");
if needs_json {
imports.push("use serde_json;".to_string());
}
let needs_uuid = table
.fields
.values()
.any(|f| f.field_type.base_type() == "uuid");
if needs_uuid {
imports.push("use uuid::Uuid;".to_string());
}
vars.insert("imports".to_string(), imports.join("\n"));
// NOTE: Field hints and validation rules are now accessed via CLI command:
// rustf-cli model-metadata <ModelName> --format json
// This eliminates runtime overhead while providing better AI development experience
// Generate struct fields with documentation
let mut struct_fields = Vec::new();
// Generate struct fields - documentation is handled elsewhere
for field in &sorted_fields {
let is_nullable = field.constraints.nullable.unwrap_or(false);
let rust_type = if let Some(ref lang_type) = field.lang_type {
lang_type.clone()
} else {
match field.field_type.base_type() {
// MySQL supports both signed and unsigned integers
"tinyint" => {
if is_nullable {
"Option<i8>"
} else {
"i8"
}
}
"smallint" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
}
"mediumint" | "int" | "integer" => {
if is_nullable {
"Option<i32>"
} else {
"i32"
}
}
"bigint" => {
if is_nullable {
"Option<i64>"
} else {
"i64"
}
}
// MySQL unsigned integers
"unsigned_tinyint" | "tinyint_unsigned" => {
if is_nullable {
"Option<u8>"
} else {
"u8"
}
}
"unsigned_smallint" | "smallint_unsigned" => {
if is_nullable {
"Option<u16>"
} else {
"u16"
}
}
"unsigned_int" | "unsigned_integer" | "int_unsigned" => {
if is_nullable {
"Option<u32>"
} else {
"u32"
}
}
"unsigned_bigint" | "bigint_unsigned" => {
if is_nullable {
"Option<u64>"
} else {
"u64"
}
}
// Floating point types
"float" => {
if is_nullable {
"Option<f32>"
} else {
"f32"
}
}
"double" | "real" => {
if is_nullable {
"Option<f64>"
} else {
"f64"
}
}
"decimal" | "numeric" => {
if is_nullable {
"Option<Decimal>"
} else {
"Decimal"
}
}
// Text types - MySQL has various text sizes
"varchar" | "char" | "string" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
"text" | "tinytext" | "mediumtext" | "longtext" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Boolean (MySQL often uses TINYINT(1))
"boolean" | "bool" => {
if is_nullable {
"Option<bool>"
} else {
"bool"
}
}
// Date/Time types
"timestamp" | "datetime" => {
if is_nullable {
"Option<DateTime<Utc>>"
} else {
"DateTime<Utc>"
}
}
"date" => {
if is_nullable {
"Option<NaiveDate>"
} else {
"NaiveDate"
}
}
"time" => {
if is_nullable {
"Option<NaiveTime>"
} else {
"NaiveTime"
}
}
"year" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
} // MySQL YEAR type
// Semantic types
"json" => {
if is_nullable {
"Option<serde_json::Value>"
} else {
"serde_json::Value"
}
}
"uuid" => {
if is_nullable {
"Option<Uuid>"
} else {
"Uuid"
}
}
"enum" | "set" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Binary
"binary" | "varbinary" | "blob" | "tinyblob" | "mediumblob" | "longblob" => {
if is_nullable {
"Option<Vec<u8>>"
} else {
"Vec<u8>"
}
}
// Default fallback
_ => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
}
.to_string()
};
let escaped_field_name = escape_rust_keyword(&field.name);
// Add field documentation from AI hints and other metadata
let mut field_doc = Vec::new();
// Add AI hint if present
if let Some(ai_hint) = &field.ai {
field_doc.push(format!(" /// {}", ai_hint));
}
// Database comments would be from the original DB schema (not available in Field struct yet)
// This could be added in the future when we extend the Field structure
// Add field type info
field_doc.push(format!(
" /// Type: {:?} ({})",
field.field_type, rust_type
));
// Add validation info
if field.constraints.required.unwrap_or(false) {
field_doc.push(" /// Required field".to_string());
}
if field.constraints.unique.unwrap_or(false) {
field_doc.push(" /// Unique constraint".to_string());
}
if field.constraints.primary_key.unwrap_or(false) {
field_doc.push(" /// Primary key".to_string());
}
// Add foreign key info
if let Some(fk) = &field.constraints.foreign_key {
field_doc.push(format!(" /// Foreign key: {}", fk));
}
let field_declaration = if field_doc.is_empty() {
format!(" pub {}: {},", escaped_field_name, rust_type)
} else {
format!(
"{}\n pub {}: {},",
field_doc.join("\n"),
escaped_field_name,
rust_type
)
};
struct_fields.push(field_declaration);
}
vars.insert("struct_fields".to_string(), struct_fields.join("\n"));
// Template compatibility - some templates use struct_fields_with_docs
vars.insert(
"struct_fields_with_docs".to_string(),
struct_fields.join("\n"),
);
// Generate type constants
let mut type_constants = Vec::new();
for field in &sorted_fields {
let is_nullable = field.constraints.nullable.unwrap_or(false);
let rust_type = if let Some(ref lang_type) = field.lang_type {
lang_type.clone()
} else {
match field.field_type.base_type() {
// MySQL supports both signed and unsigned integers
"tinyint" => {
if is_nullable {
"Option<i8>"
} else {
"i8"
}
}
"smallint" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
}
"mediumint" | "int" | "integer" => {
if is_nullable {
"Option<i32>"
} else {
"i32"
}
}
"bigint" => {
if is_nullable {
"Option<i64>"
} else {
"i64"
}
}
// MySQL unsigned integers
"unsigned_tinyint" | "tinyint_unsigned" => {
if is_nullable {
"Option<u8>"
} else {
"u8"
}
}
"unsigned_smallint" | "smallint_unsigned" => {
if is_nullable {
"Option<u16>"
} else {
"u16"
}
}
"unsigned_int" | "unsigned_integer" | "int_unsigned" => {
if is_nullable {
"Option<u32>"
} else {
"u32"
}
}
"unsigned_bigint" | "bigint_unsigned" => {
if is_nullable {
"Option<u64>"
} else {
"u64"
}
}
// Floating point types
"float" => {
if is_nullable {
"Option<f32>"
} else {
"f32"
}
}
"double" | "real" => {
if is_nullable {
"Option<f64>"
} else {
"f64"
}
}
"decimal" | "numeric" => {
if is_nullable {
"Option<Decimal>"
} else {
"Decimal"
}
}
// Text types - MySQL has various text sizes
"varchar" | "char" | "string" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
"text" | "tinytext" | "mediumtext" | "longtext" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Boolean (MySQL often uses TINYINT(1))
"boolean" | "bool" => {
if is_nullable {
"Option<bool>"
} else {
"bool"
}
}
// Date/Time types
"timestamp" | "datetime" => {
if is_nullable {
"Option<DateTime<Utc>>"
} else {
"DateTime<Utc>"
}
}
"date" => {
if is_nullable {
"Option<NaiveDate>"
} else {
"NaiveDate"
}
}
"time" => {
if is_nullable {
"Option<NaiveTime>"
} else {
"NaiveTime"
}
}
"year" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
} // MySQL YEAR type
// Semantic types
"json" => {
if is_nullable {
"Option<serde_json::Value>"
} else {
"serde_json::Value"
}
}
"uuid" => {
if is_nullable {
"Option<Uuid>"
} else {
"Uuid"
}
}
"enum" | "set" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Binary
"binary" | "varbinary" | "blob" | "tinyblob" | "mediumblob" | "longblob" => {
if is_nullable {
"Option<Vec<u8>>"
} else {
"Vec<u8>"
}
}
// Default fallback
_ => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
}
.to_string()
};
let escaped_field_name = escape_rust_keyword(&field.name);
type_constants.push(format!(
" pub type {} = {};",
escaped_field_name, rust_type
));
}
vars.insert("type_constants".to_string(), type_constants.join("\n"));
// Type imports for the Types module
let mut type_imports = Vec::new();
if needs_datetime || needs_date || needs_time {
let mut chrono_imports = vec![];
if needs_datetime {
chrono_imports.push("DateTime");
chrono_imports.push("Utc");
}
if needs_date {
chrono_imports.push("NaiveDate");
}
if needs_time {
chrono_imports.push("NaiveTime");
}
type_imports.push(format!(
" use chrono::{{{}}};",
chrono_imports.join(", ")
));
}
if needs_decimal {
type_imports.push(" use rust_decimal::Decimal;".to_string());
}
if needs_uuid {
type_imports.push(" use uuid::Uuid;".to_string());
}
vars.insert("type_imports".to_string(), type_imports.join("\n"));
// Generate column constants for type-safe queries
let mut column_constants = Vec::new();
for field in &sorted_fields {
let field_name = &field.name;
let const_name = to_screaming_snake_case(field_name);
column_constants.push(format!(
" pub const {}: &'static str = \"{}\";",
const_name, field_name
));
}
vars.insert("column_constants".to_string(), column_constants.join("\n"));
// Generate builder fields
let mut builder_fields = Vec::new();
for field in &sorted_fields {
let is_nullable = field.constraints.nullable.unwrap_or(false);
let is_auto = field.constraints.auto.is_some();
// Skip auto-generated fields (but keep non-auto ID fields like UUIDs)
if is_auto {
continue;
}
let rust_type = if let Some(ref lang_type) = field.lang_type {
lang_type.clone()
} else {
match field.field_type.base_type() {
// MySQL supports both signed and unsigned integers
"tinyint" => {
if is_nullable {
"Option<i8>"
} else {
"i8"
}
}
"smallint" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
}
"mediumint" | "int" | "integer" => {
if is_nullable {
"Option<i32>"
} else {
"i32"
}
}
"bigint" => {
if is_nullable {
"Option<i64>"
} else {
"i64"
}
}
// MySQL unsigned integers
"unsigned_tinyint" | "tinyint_unsigned" => {
if is_nullable {
"Option<u8>"
} else {
"u8"
}
}
"unsigned_smallint" | "smallint_unsigned" => {
if is_nullable {
"Option<u16>"
} else {
"u16"
}
}
"unsigned_int" | "unsigned_integer" | "int_unsigned" => {
if is_nullable {
"Option<u32>"
} else {
"u32"
}
}
"unsigned_bigint" | "bigint_unsigned" => {
if is_nullable {
"Option<u64>"
} else {
"u64"
}
}
// Floating point types
"float" => {
if is_nullable {
"Option<f32>"
} else {
"f32"
}
}
"double" | "real" => {
if is_nullable {
"Option<f64>"
} else {
"f64"
}
}
"decimal" | "numeric" => {
if is_nullable {
"Option<Decimal>"
} else {
"Decimal"
}
}
// Text types - MySQL has various text sizes
"varchar" | "char" | "string" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
"text" | "tinytext" | "mediumtext" | "longtext" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Boolean (MySQL often uses TINYINT(1))
"boolean" | "bool" => {
if is_nullable {
"Option<bool>"
} else {
"bool"
}
}
// Date/Time types
"timestamp" | "datetime" => {
if is_nullable {
"Option<DateTime<Utc>>"
} else {
"DateTime<Utc>"
}
}
"date" => {
if is_nullable {
"Option<NaiveDate>"
} else {
"NaiveDate"
}
}
"time" => {
if is_nullable {
"Option<NaiveTime>"
} else {
"NaiveTime"
}
}
"year" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
} // MySQL YEAR type
// Semantic types
"json" => {
if is_nullable {
"Option<serde_json::Value>"
} else {
"serde_json::Value"
}
}
"uuid" => {
if is_nullable {
"Option<Uuid>"
} else {
"Uuid"
}
}
"enum" | "set" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Binary
"binary" | "varbinary" | "blob" | "tinyblob" | "mediumblob" | "longblob" => {
if is_nullable {
"Option<Vec<u8>>"
} else {
"Vec<u8>"
}
}
// Default fallback
_ => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
}
.to_string()
};
let escaped_field_name = escape_rust_keyword(&field.name);
let _is_required = field.constraints.required.unwrap_or(false) && !is_nullable;
// For builder, wrap all fields in Option to allow incremental building
builder_fields.push(format!(
" {}: Option<{}>,",
escaped_field_name, rust_type
));
}
vars.insert("builder_fields".to_string(), builder_fields.join("\n"));
// Generate builder defaults
let mut builder_defaults = Vec::new();
for field in &sorted_fields {
let is_auto = field.constraints.auto.is_some();
if is_auto {
continue;
}
let escaped_field_name = escape_rust_keyword(&field.name);
builder_defaults.push(format!(" {}: None,", escaped_field_name));
}
vars.insert("builder_defaults".to_string(), builder_defaults.join("\n"));
// Generate builder methods
let mut builder_methods = Vec::new();
for field in &sorted_fields {
let is_auto = field.constraints.auto.is_some();
if is_auto {
continue;
}
let is_nullable = field.constraints.nullable.unwrap_or(false);
let rust_type = if let Some(ref lang_type) = field.lang_type {
lang_type.clone()
} else {
match field.field_type.base_type() {
// MySQL supports both signed and unsigned integers
"tinyint" => {
if is_nullable {
"Option<i8>"
} else {
"i8"
}
}
"smallint" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
}
"mediumint" | "int" | "integer" => {
if is_nullable {
"Option<i32>"
} else {
"i32"
}
}
"bigint" => {
if is_nullable {
"Option<i64>"
} else {
"i64"
}
}
// MySQL unsigned integers
"unsigned_tinyint" | "tinyint_unsigned" => {
if is_nullable {
"Option<u8>"
} else {
"u8"
}
}
"unsigned_smallint" | "smallint_unsigned" => {
if is_nullable {
"Option<u16>"
} else {
"u16"
}
}
"unsigned_int" | "unsigned_integer" | "int_unsigned" => {
if is_nullable {
"Option<u32>"
} else {
"u32"
}
}
"unsigned_bigint" | "bigint_unsigned" => {
if is_nullable {
"Option<u64>"
} else {
"u64"
}
}
// Floating point types
"float" => {
if is_nullable {
"Option<f32>"
} else {
"f32"
}
}
"double" | "real" => {
if is_nullable {
"Option<f64>"
} else {
"f64"
}
}
"decimal" | "numeric" => {
if is_nullable {
"Option<Decimal>"
} else {
"Decimal"
}
}
// Text types - MySQL has various text sizes
"varchar" | "char" | "string" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
"text" | "tinytext" | "mediumtext" | "longtext" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Boolean (MySQL often uses TINYINT(1))
"boolean" | "bool" => {
if is_nullable {
"Option<bool>"
} else {
"bool"
}
}
// Date/Time types
"timestamp" | "datetime" => {
if is_nullable {
"Option<DateTime<Utc>>"
} else {
"DateTime<Utc>"
}
}
"date" => {
if is_nullable {
"Option<NaiveDate>"
} else {
"NaiveDate"
}
}
"time" => {
if is_nullable {
"Option<NaiveTime>"
} else {
"NaiveTime"
}
}
"year" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
} // MySQL YEAR type
// Semantic types
"json" => {
if is_nullable {
"Option<serde_json::Value>"
} else {
"serde_json::Value"
}
}
"uuid" => {
if is_nullable {
"Option<Uuid>"
} else {
"Uuid"
}
}
"enum" | "set" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Binary
"binary" | "varbinary" | "blob" | "tinyblob" | "mediumblob" | "longblob" => {
if is_nullable {
"Option<Vec<u8>>"
} else {
"Vec<u8>"
}
}
// Default fallback
_ => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
}
.to_string()
};
let escaped_field_name = escape_rust_keyword(&field.name);
let field_doc = field.ai.as_deref().unwrap_or("Set this field");
// For String types in non-Option fields, use impl Into<String> for convenience
// For Option fields, handle Option<String> specially to use Option<String> directly
let (param_type, value_expr) = if rust_type == "Option<String>" {
// Optional String field - use Option<String> directly to allow None without type annotations
("Option<String>", "value")
} else if rust_type.starts_with("Option") {
// Other optional fields - accept the Option<T> type directly
(rust_type.as_str(), "value")
} else if rust_type.contains("String") {
// Non-nullable String field
("impl Into<String>", "value.into()")
} else {
// Non-nullable non-String field
(rust_type.as_str(), "value")
};
builder_methods.push(format!(
" /// {}\n pub fn {}(mut self, value: {}) -> Self {{\n self.{} = Some({});\n self\n }}",
field_doc, escaped_field_name, param_type, escaped_field_name, value_expr
));
}
vars.insert("builder_methods".to_string(), builder_methods.join("\n\n"));
// Generate builder validation helper method
let mut required_fields_checks = Vec::new();
let mut required_fields_names = Vec::new();
for field in &sorted_fields {
let is_auto = field.constraints.auto.is_some();
// Skip auto fields AND UUID primary key fields (which are auto-generated)
let is_uuid_pk = field.constraints.primary_key.unwrap_or(false) && field.field_type.base_type() == "uuid";
if is_auto || is_uuid_pk {
continue;
}
let is_nullable = field.constraints.nullable.unwrap_or(false);
let is_required = field.constraints.required.unwrap_or(false) && !is_nullable;
if is_required {
let escaped_field_name = escape_rust_keyword(&field.name);
required_fields_checks.push(format!(
" if self.{}.is_none() {{\n missing.push(\"{}\");\n }}",
escaped_field_name, field.name
));
required_fields_names.push(&field.name);
}
}
// Generate validate() method
let validate_method = if required_fields_names.is_empty() {
format!(
" /// Validate the builder has all required fields\n \
/// Returns Ok(()) if valid, or Err with list of missing fields\n \
pub fn validate(&self) -> Result<(), Vec<&'static str>> {{\n \
// No required fields to validate\n \
Ok(())\n \
}}"
)
} else {
format!(
" /// Validate the builder has all required fields\n \
/// Returns Ok(()) if valid, or Err with list of missing fields\n \
pub fn validate(&self) -> Result<(), Vec<&'static str>> {{\n \
let mut missing = Vec::new();\n \n{}\n \n \
if missing.is_empty() {{\n \
Ok(())\n \
}} else {{\n \
Err(missing)\n \
}}\n \
}}",
required_fields_checks.join("\n")
)
};
vars.insert("builder_validate_method".to_string(), validate_method);
// Generate builder validation for build() method
let builder_validation = if required_fields_names.is_empty() {
" // No required fields to validate".to_string()
} else {
format!(
" // Validate all required fields are present\n \
if let Err(missing) = self.validate() {{\n \
return Err(format!(\"Missing required fields: {{}}\", missing.join(\", \")));\n \
}}"
)
};
vars.insert("builder_validation".to_string(), builder_validation);
// Generate builder build implementation
let mut builder_build = Vec::new();
for field in &sorted_fields {
let is_auto = field.constraints.auto.is_some();
let escaped_field_name = escape_rust_keyword(&field.name);
if field.constraints.primary_key.unwrap_or(false) {
// Handle primary key field specially - usually auto-generated
// Check if it's a UUID field that needs special handling
let is_uuid = field.field_type.base_type() == "uuid";
if is_uuid {
builder_build.push(format!(
" {}: Uuid::new_v4(),",
escaped_field_name
));
} else if is_auto {
builder_build.push(format!(
" {}: Default::default(), // Auto-generated",
escaped_field_name
));
} else {
// For non-UUID, non-auto ID fields, use the value from the builder
builder_build.push(format!(
" {}: self.{}.unwrap(),",
escaped_field_name, escaped_field_name
));
}
} else if is_auto {
// Skip other auto fields in builder
builder_build.push(format!(
" {}: Default::default(), // Auto-generated",
escaped_field_name
));
} else {
let is_nullable = field.constraints.nullable.unwrap_or(false);
let is_required = field.constraints.required.unwrap_or(false) && !is_nullable;
if is_required {
builder_build.push(format!(
" {}: self.{}.unwrap(),",
escaped_field_name, escaped_field_name
));
} else if is_nullable {
// For nullable fields, builder has Option<Option<T>>, flatten to Option<T>
builder_build.push(format!(
" {}: self.{}.flatten(),",
escaped_field_name, escaped_field_name
));
} else {
builder_build.push(format!(
" {}: self.{}.unwrap_or_default(),",
escaped_field_name, escaped_field_name
));
}
}
}
// Add changed_fields and null_fields initialization
builder_build.push(" changed_fields: HashSet::new(),".to_string());
builder_build.push(" null_fields: HashSet::new(),".to_string());
vars.insert("builder_build".to_string(), builder_build.join("\n"));
// Generate create method
// Sort fields by name to ensure consistent parameter order
let mut non_auto_fields: Vec<_> = table
.fields
.values()
.filter(|f| !f.constraints.auto.is_some() && f.name != "id")
.collect();
non_auto_fields.sort_by(|a, b| a.name.cmp(&b.name));
// Generate insert field mapping for create_internal method
let mut insert_field_mappings = Vec::new();
for field in &sorted_fields {
// Skip auto-increment ID fields
if field.constraints.primary_key.unwrap_or(false) && field.constraints.auto.is_some() {
continue;
}
let escaped_field_name = escape_rust_keyword(&field.name);
let field_name = &field.name;
// Check if this is an array field
let is_array = field.field_type.base_type().starts_with("array");
if is_array {
// For array fields, convert Vec<T> to Vec<SqlValue> before wrapping in SqlValue::Array
let is_nullable = field.constraints.nullable.unwrap_or(false);
if is_nullable {
insert_field_mappings.push(format!(
" insert_data.insert(\"{}\".to_string(), model.{}.as_ref().map(|v| SqlValue::Array(v.iter().map(|item| SqlValue::from(item.clone())).collect())).unwrap_or(SqlValue::Null));",
field_name, escaped_field_name
));
} else {
insert_field_mappings.push(format!(
" insert_data.insert(\"{}\".to_string(), SqlValue::Array(model.{}.iter().map(|item| SqlValue::from(item.clone())).collect()));",
field_name, escaped_field_name
));
}
} else {
insert_field_mappings.push(format!(
" insert_data.insert(\"{}\".to_string(), SqlValue::from(model.{}));",
field_name, escaped_field_name
));
}
}
vars.insert(
"insert_field_mapping".to_string(),
insert_field_mappings.join("\n"),
);
// Determine database backend
let database_backend = match pool_type {
"MySql" => "DatabaseBackend::MySQL",
"Postgres" => "DatabaseBackend::Postgres",
"Sqlite" => "DatabaseBackend::SQLite",
_ => "DatabaseBackend::MySQL", // Default fallback
};
vars.insert("database_backend".to_string(), database_backend.to_string());
// Generate row conversion code for different database backends
let mut postgres_conversion = Vec::new();
let mut mysql_conversion = Vec::new();
let mut sqlite_conversion = Vec::new();
for field in &sorted_fields {
let field_name = &field.name;
// PostgreSQL conversion
postgres_conversion.push(format!(
" json_obj.insert(\"{}\".to_string(), \n serde_json::to_value(row.try_get::<_, _>(\"{}\")).unwrap_or(serde_json::Value::Null));",
field_name, field_name
));
// MySQL conversion
mysql_conversion.push(format!(
" json_obj.insert(\"{}\".to_string(), \n serde_json::to_value(row.try_get::<_, _>(\"{}\")).unwrap_or(serde_json::Value::Null));",
field_name, field_name
));
// SQLite conversion
sqlite_conversion.push(format!(
" json_obj.insert(\"{}\".to_string(), \n serde_json::to_value(row.try_get::<_, _>(\"{}\")).unwrap_or(serde_json::Value::Null));",
field_name, field_name
));
}
vars.insert(
"postgres_row_conversion".to_string(),
postgres_conversion.join("\n"),
);
vars.insert(
"mysql_row_conversion".to_string(),
mysql_conversion.join("\n"),
);
vars.insert(
"sqlite_row_conversion".to_string(),
sqlite_conversion.join("\n"),
);
// Generate FromRow implementations for each database type
let mut postgres_from_row = Vec::new();
let mut mysql_from_row = Vec::new();
let mut sqlite_from_row = Vec::new();
for field in &sorted_fields {
let escaped_field_name = escape_rust_keyword(&field.name);
let field_name = &field.name;
// PostgreSQL FromRow
postgres_from_row.push(format!(
" {}: row.try_get(\"{}\")?,",
escaped_field_name, field_name
));
// MySQL FromRow
mysql_from_row.push(format!(
" {}: row.try_get(\"{}\")?,",
escaped_field_name, field_name
));
// SQLite FromRow
sqlite_from_row.push(format!(
" {}: row.try_get(\"{}\")?,",
escaped_field_name, field_name
));
}
vars.insert(
"postgres_from_row".to_string(),
postgres_from_row.join("\n"),
);
vars.insert("mysql_from_row".to_string(), mysql_from_row.join("\n"));
vars.insert("sqlite_from_row".to_string(), sqlite_from_row.join("\n"));
// Generate conditional SQLite FromRow implementation
let sqlite_from_row_impl = if needs_decimal {
// Skip SQLite support for models with Decimal fields since rust_decimal doesn't support SQLite
"// SQLite FromRow implementation skipped: Table contains Decimal fields which are not supported by SQLite".to_string()
} else {
format!(
"impl sqlx::FromRow<'_, sqlx::sqlite::SqliteRow> for {}Base {{\n fn from_row(row: &sqlx::sqlite::SqliteRow) -> sqlx::Result<Self> {{\n use sqlx::Row;\n Ok(Self {{\n{}\n changed_fields: HashSet::new(),\n }})\n }}\n}}",
table.name,
sqlite_from_row.join("\n")
)
};
vars.insert(
"sqlite_from_row_impl".to_string(),
sqlite_from_row_impl.clone(),
);
// Build complete MySQL FromRow block (for MySQL-focused generation)
let mysql_fromrow_block = format!(
"impl sqlx::FromRow<'_, sqlx::mysql::MySqlRow> for {} {{\n fn from_row(row: &sqlx::mysql::MySqlRow) -> sqlx::Result<Self> {{\n use sqlx::Row;\n Ok(Self {{\n{}\n changed_fields: HashSet::new(),\n null_fields: HashSet::new(),\n }})\n }}\n}}",
table.name,
mysql_from_row.join("\n")
);
vars.insert("mysql_fromrow_block".to_string(), mysql_fromrow_block);
// For MySQL-only generation, PostgreSQL and SQLite blocks are empty
vars.insert("postgres_fromrow_block".to_string(), String::new());
vars.insert("sqlite_fromrow_block".to_string(), String::new());
// Generate conditional SQLite select support
let sqlite_select_support = if needs_decimal {
" return Err(anyhow::anyhow!(\"SQLite is not supported for this model: contains Decimal fields\"));"
} else {
" let results = sqlx::query_as::<_, Self>(sql)\n .fetch_all(pool)\n .await?;\n Ok(results)"
};
vars.insert(
"sqlite_select_support".to_string(),
sqlite_select_support.to_string(),
);
let sqlite_select_one_support = if needs_decimal {
" return Err(anyhow::anyhow!(\"SQLite is not supported for this model: contains Decimal fields\"));"
} else {
" let result = sqlx::query_as::<_, Self>(sql)\n .fetch_optional(pool)\n .await?;\n Ok(result)"
};
vars.insert(
"sqlite_select_one_support".to_string(),
sqlite_select_one_support.to_string(),
);
// Generate field setters with change tracking
let mut field_setters = Vec::new();
for field in &sorted_fields {
// Skip ID field - usually immutable
if field.constraints.primary_key.unwrap_or(false) {
continue;
}
let is_nullable = field.constraints.nullable.unwrap_or(false);
let rust_type = if let Some(ref lang_type) = field.lang_type {
lang_type.clone()
} else {
match field.field_type.base_type() {
// MySQL supports both signed and unsigned integers
"tinyint" => {
if is_nullable {
"Option<i8>"
} else {
"i8"
}
}
"smallint" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
}
"mediumint" | "int" | "integer" => {
if is_nullable {
"Option<i32>"
} else {
"i32"
}
}
"bigint" => {
if is_nullable {
"Option<i64>"
} else {
"i64"
}
}
// MySQL unsigned integers
"unsigned_tinyint" | "tinyint_unsigned" => {
if is_nullable {
"Option<u8>"
} else {
"u8"
}
}
"unsigned_smallint" | "smallint_unsigned" => {
if is_nullable {
"Option<u16>"
} else {
"u16"
}
}
"unsigned_int" | "unsigned_integer" | "int_unsigned" => {
if is_nullable {
"Option<u32>"
} else {
"u32"
}
}
"unsigned_bigint" | "bigint_unsigned" => {
if is_nullable {
"Option<u64>"
} else {
"u64"
}
}
// Floating point types
"float" => {
if is_nullable {
"Option<f32>"
} else {
"f32"
}
}
"double" | "real" => {
if is_nullable {
"Option<f64>"
} else {
"f64"
}
}
"decimal" | "numeric" => {
if is_nullable {
"Option<Decimal>"
} else {
"Decimal"
}
}
// Text types - MySQL has various text sizes
"varchar" | "char" | "string" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
"text" | "tinytext" | "mediumtext" | "longtext" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Boolean (MySQL often uses TINYINT(1))
"boolean" | "bool" => {
if is_nullable {
"Option<bool>"
} else {
"bool"
}
}
// Date/Time types
"timestamp" | "datetime" => {
if is_nullable {
"Option<DateTime<Utc>>"
} else {
"DateTime<Utc>"
}
}
"date" => {
if is_nullable {
"Option<NaiveDate>"
} else {
"NaiveDate"
}
}
"time" => {
if is_nullable {
"Option<NaiveTime>"
} else {
"NaiveTime"
}
}
"year" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
} // MySQL YEAR type
// Semantic types
"json" => {
if is_nullable {
"Option<serde_json::Value>"
} else {
"serde_json::Value"
}
}
"uuid" => {
if is_nullable {
"Option<Uuid>"
} else {
"Uuid"
}
}
"enum" | "set" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Binary
"binary" | "varbinary" | "blob" | "tinyblob" | "mediumblob" | "longblob" => {
if is_nullable {
"Option<Vec<u8>>"
} else {
"Vec<u8>"
}
}
// Default fallback
_ => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
}
.to_string()
};
let escaped_field_name = escape_rust_keyword(&field.name);
let default_doc = format!("Set the {} field", field.name);
let field_doc = field.ai.as_deref().unwrap_or(&default_doc);
// For String types, use Into trait for flexibility
let param_type = if rust_type.contains("String") && !rust_type.starts_with("Option") {
"impl Into<String>".to_string()
} else if rust_type == "Option<String>" {
"impl Into<String>".to_string()
} else {
rust_type.clone()
};
// Generate setter method
if rust_type.starts_with("Option<String>") {
// For Option<String>, use Option<String> directly to allow None without type annotations
field_setters.push(format!(
" /// {}\n pub fn set_{}(&mut self, value: Option<String>) {{\n self.{} = value;\n self.mark_changed(\"{}\", self.{}.is_none());\n }}",
field_doc, escaped_field_name, escaped_field_name, field.name, escaped_field_name
));
} else if rust_type.starts_with("Option") {
// For other Option types, accept Option<T> to allow setting to None
// Handle nested generics like Option<DateTime<Utc>>
let inner_type = if rust_type.starts_with("Option<") && rust_type.ends_with(">") {
&rust_type[7..rust_type.len() - 1]
} else {
rust_type.as_str()
};
field_setters.push(format!(
" /// {}\n pub fn set_{}(&mut self, value: Option<{}>) {{\n self.{} = value;\n self.mark_changed(\"{}\", self.{}.is_none());\n }}",
field_doc, escaped_field_name, inner_type, escaped_field_name, field.name, escaped_field_name
));
} else if rust_type.contains("String") {
field_setters.push(format!(
" /// {}\n pub fn set_{}(&mut self, value: {}) {{\n self.{} = value.into();\n self.mark_changed(\"{}\", false);\n }}",
field_doc, escaped_field_name, param_type, escaped_field_name, field.name
));
} else {
field_setters.push(format!(
" /// {}\n pub fn set_{}(&mut self, value: {}) {{\n self.{} = value;\n self.mark_changed(\"{}\", false);\n }}",
field_doc, escaped_field_name, param_type, escaped_field_name, field.name
));
}
}
vars.insert("field_setters".to_string(), field_setters.join("\n\n"));
// Generate field getters
let mut field_getters = Vec::new();
for field in &sorted_fields {
let is_nullable = field.constraints.nullable.unwrap_or(false);
let rust_type = if let Some(ref lang_type) = field.lang_type {
lang_type.clone()
} else {
match field.field_type.base_type() {
// MySQL supports both signed and unsigned integers
"tinyint" => {
if is_nullable {
"Option<i8>"
} else {
"i8"
}
}
"smallint" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
}
"mediumint" | "int" | "integer" => {
if is_nullable {
"Option<i32>"
} else {
"i32"
}
}
"bigint" => {
if is_nullable {
"Option<i64>"
} else {
"i64"
}
}
// MySQL unsigned integers
"unsigned_tinyint" | "tinyint_unsigned" => {
if is_nullable {
"Option<u8>"
} else {
"u8"
}
}
"unsigned_smallint" | "smallint_unsigned" => {
if is_nullable {
"Option<u16>"
} else {
"u16"
}
}
"unsigned_int" | "unsigned_integer" | "int_unsigned" => {
if is_nullable {
"Option<u32>"
} else {
"u32"
}
}
"unsigned_bigint" | "bigint_unsigned" => {
if is_nullable {
"Option<u64>"
} else {
"u64"
}
}
// Floating point types
"float" => {
if is_nullable {
"Option<f32>"
} else {
"f32"
}
}
"double" | "real" => {
if is_nullable {
"Option<f64>"
} else {
"f64"
}
}
"decimal" | "numeric" => {
if is_nullable {
"Option<Decimal>"
} else {
"Decimal"
}
}
// Text types - MySQL has various text sizes
"varchar" | "char" | "string" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
"text" | "tinytext" | "mediumtext" | "longtext" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Boolean (MySQL often uses TINYINT(1))
"boolean" | "bool" => {
if is_nullable {
"Option<bool>"
} else {
"bool"
}
}
// Date/Time types
"timestamp" | "datetime" => {
if is_nullable {
"Option<DateTime<Utc>>"
} else {
"DateTime<Utc>"
}
}
"date" => {
if is_nullable {
"Option<NaiveDate>"
} else {
"NaiveDate"
}
}
"time" => {
if is_nullable {
"Option<NaiveTime>"
} else {
"NaiveTime"
}
}
"year" => {
if is_nullable {
"Option<i16>"
} else {
"i16"
}
} // MySQL YEAR type
// Semantic types
"json" => {
if is_nullable {
"Option<serde_json::Value>"
} else {
"serde_json::Value"
}
}
"uuid" => {
if is_nullable {
"Option<Uuid>"
} else {
"Uuid"
}
}
"enum" | "set" => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
// Binary
"binary" | "varbinary" | "blob" | "tinyblob" | "mediumblob" | "longblob" => {
if is_nullable {
"Option<Vec<u8>>"
} else {
"Vec<u8>"
}
}
// Default fallback
_ => {
if is_nullable {
"Option<String>"
} else {
"String"
}
}
}
.to_string()
};
let escaped_field_name = escape_rust_keyword(&field.name);
// Generate getter method documentation
let field_doc = if let Some(ai_hint) = &field.ai {
format!(
"Get the {} field\n /// \n /// {}",
field.name, ai_hint
)
} else {
format!("Get the {} field", field.name)
};
// Generate getter method based on type
if rust_type.contains("String") && !rust_type.starts_with("Option") {
// For non-optional String, return &str to avoid cloning
field_getters.push(format!(
" /// {}\n pub fn {}(&self) -> &str {{\n &self.{}\n }}",
field_doc, escaped_field_name, escaped_field_name
));
} else if rust_type.starts_with("Option<String>") {
// For Option<String>, return Option<&str>
field_getters.push(format!(
" /// {}\n pub fn {}(&self) -> Option<&str> {{\n self.{}.as_deref()\n }}",
field_doc, escaped_field_name, escaped_field_name
));
} else if rust_type.starts_with("Option<") {
// For Option<T>, check if T is Copy
let inner_type = extract_inner_type(&rust_type);
if is_copy_type(inner_type) {
// For Option<Copy>, return by value (cheap copy)
// This makes unwrap_or() work naturally without .copied()
field_getters.push(format!(
" /// {}\n pub fn {}(&self) -> {} {{\n self.{}\n }}",
field_doc, escaped_field_name, rust_type, escaped_field_name
));
} else {
// For Option<NonCopy>, return reference
field_getters.push(format!(
" /// {}\n pub fn {}(&self) -> &{} {{\n &self.{}\n }}",
field_doc, escaped_field_name, rust_type, escaped_field_name
));
}
} else if rust_type.contains("Vec") || rust_type.contains("serde_json::Value") {
// For Vec and JSON values, return reference
field_getters.push(format!(
" /// {}\n pub fn {}(&self) -> &{} {{\n &self.{}\n }}",
field_doc, escaped_field_name, rust_type, escaped_field_name
));
} else {
// For primitive types, return by value (Copy trait)
field_getters.push(format!(
" /// {}\n pub fn {}(&self) -> {} {{\n self.{}\n }}",
field_doc, escaped_field_name, rust_type, escaped_field_name
));
}
}
vars.insert("field_getters".to_string(), field_getters.join("\n\n"));
// Generate get_field_value implementation
let mut get_field_cases = Vec::new();
for field in &sorted_fields {
let escaped_field_name = escape_rust_keyword(&field.name);
let field_name = &field.name;
// Check if this is an enum field
let is_enum = matches!(
field.field_type,
rustf_schema::types::FieldType::Enum { .. }
);
// Check if this is an array field
let is_array = field.field_type.base_type().starts_with("array");
if is_enum {
// For enum fields, check if it's optional
let is_nullable = field.constraints.nullable.unwrap_or(false);
if is_nullable {
// For optional enum fields, map the Option
get_field_cases.push(format!(
" \"{}\" => Ok(self.{}.clone().map(SqlValue::Enum).unwrap_or(SqlValue::Null)),",
field_name, escaped_field_name
));
} else {
// For required enum fields, use SqlValue::Enum directly
get_field_cases.push(format!(
" \"{}\" => Ok(SqlValue::Enum(self.{}.clone())),",
field_name, escaped_field_name
));
}
} else if is_array {
// For array fields, convert Vec<T> to Vec<SqlValue> before wrapping in SqlValue::Array
let is_nullable = field.constraints.nullable.unwrap_or(false);
if is_nullable {
get_field_cases.push(format!(
" \"{}\" => Ok(self.{}.clone().map(|v| SqlValue::Array(v.into_iter().map(SqlValue::from).collect())).unwrap_or(SqlValue::Null)),",
field_name, escaped_field_name
));
} else {
get_field_cases.push(format!(
" \"{}\" => Ok(SqlValue::Array(self.{}.clone().into_iter().map(SqlValue::from).collect())),",
field_name, escaped_field_name
));
}
} else {
// Regular fields use SqlValue::from
get_field_cases.push(format!(
" \"{}\" => Ok(SqlValue::from(self.{}.clone())),",
field_name, escaped_field_name
));
}
}
let get_field_value_impl = format!(
" match field_name {{\n{}\n _ => Err(anyhow::anyhow!(\"Unknown field: {{}}\", field_name)),\n }}",
get_field_cases.join("\n")
);
vars.insert("get_field_value_impl".to_string(), get_field_value_impl);
// For the include template, we need different variable names
vars.insert(
"get_field_value_match".to_string(),
get_field_cases.join("\n"),
);
// Determine primary key field (default to "id")
let primary_key = table
.fields
.values()
.find(|f| f.constraints.primary_key.unwrap_or(false))
.map(|f| f.name.clone())
.unwrap_or_else(|| "id".to_string());
vars.insert("primary_key".to_string(), primary_key);
// Generate FromRow implementations for each database type
let mut from_row_pg = Vec::new();
let mut from_row_mysql = Vec::new();
let mut from_row_sqlite = Vec::new();
for field in &sorted_fields {
let escaped_field_name = escape_rust_keyword(&field.name);
let field_name = &field.name;
// Generate field extraction for each database type
from_row_pg.push(format!(
" {}: row.try_get(\"{}\")?,",
escaped_field_name, field_name
));
from_row_mysql.push(format!(
" {}: row.try_get(\"{}\")?,",
escaped_field_name, field_name
));
from_row_sqlite.push(format!(
" {}: row.try_get(\"{}\")?,",
escaped_field_name, field_name
));
}
vars.insert("from_row_pg".to_string(), from_row_pg.join("\n"));
vars.insert("from_row_mysql".to_string(), from_row_mysql.join("\n"));
vars.insert("from_row_sqlite".to_string(), from_row_sqlite.join("\n"));
// Check if model has decimal fields (SQLite doesn't support Decimal type)
let needs_decimal = table
.fields
.values()
.any(|f| f.field_type.base_type() == "decimal");
// Generate conditional SQLite FromRow implementation
let sqlite_from_row_impl = if needs_decimal {
// Skip SQLite support for models with Decimal fields since rust_decimal doesn't support SQLite
"// SQLite FromRow implementation skipped: Table contains Decimal fields which are not supported by SQLite".to_string()
} else {
format!(
"impl sqlx::FromRow<'_, sqlx::sqlite::SqliteRow> for {} {{\n fn from_row(row: &sqlx::sqlite::SqliteRow) -> sqlx::Result<Self> {{\n use sqlx::Row;\n Ok(Self {{\n{}\n changed_fields: HashSet::new(),\n }})\n }}\n}}",
table.name, // This is correct - the struct is named after table.name without Base suffix
from_row_sqlite.join("\n")
)
};
vars.insert(
"sqlite_from_row_impl".to_string(),
sqlite_from_row_impl.clone(),
);
// Build complete MySQL FromRow block (for MySQL-focused generation)
let mysql_fromrow_block = format!(
"impl sqlx::FromRow<'_, sqlx::mysql::MySqlRow> for {} {{\n fn from_row(row: &sqlx::mysql::MySqlRow) -> sqlx::Result<Self> {{\n use sqlx::Row;\n Ok(Self {{\n{}\n changed_fields: HashSet::new(),\n null_fields: HashSet::new(),\n }})\n }}\n}}",
table.name,
from_row_mysql.join("\n")
);
vars.insert("mysql_fromrow_block".to_string(), mysql_fromrow_block);
// For MySQL-only generation, PostgreSQL and SQLite blocks are empty
vars.insert("postgres_fromrow_block".to_string(), String::new());
vars.insert("sqlite_fromrow_block".to_string(), String::new());
// Generate conditional SQLite select support
let sqlite_select_support = if needs_decimal {
" return Err(anyhow::anyhow!(\"SQLite is not supported for this model: contains Decimal fields\"));"
} else {
" let results = sqlx::query_as::<_, Self>(sql)\n .fetch_all(pool)\n .await?;\n Ok(results)"
};
vars.insert(
"sqlite_select_support".to_string(),
sqlite_select_support.to_string(),
);
let sqlite_select_one_support = if needs_decimal {
" return Err(anyhow::anyhow!(\"SQLite is not supported for this model: contains Decimal fields\"));"
} else {
" let result = sqlx::query_as::<_, Self>(sql)\n .fetch_optional(pool)\n .await?;\n Ok(result)"
};
vars.insert(
"sqlite_select_one_support".to_string(),
sqlite_select_one_support.to_string(),
);
// Collect enum fields and their values
let mut enum_fields = Vec::new();
let mut enum_constants = Vec::new();
let mut enum_converters = Vec::new();
for field in &sorted_fields {
if let rustf_schema::types::FieldType::Enum { values, .. } = &field.field_type {
enum_fields.push(field.name.clone());
// Generate constants for this enum field
for value in values {
let const_name = format!(
"{}_{}",
to_screaming_snake_case(&field.name),
to_screaming_snake_case(value)
);
enum_constants.push(format!(
" /// {} value for {} field\n pub const {}: &'static str = \"{}\";",
value, field.name, const_name, value
));
}
// Generate field-specific enum converter method (pass-through for MySQL)
// MySQL doesn't need type casting, but we provide the method for API consistency
enum_converters.push(format!(
" /// Convert a value to MySQL enum format for {} field\n /// \n /// # Example\n /// ```\n /// let value = {}::as_{}_enum(\"ACTIVE\");\n /// // Returns: \"ACTIVE\" (pass-through for MySQL)\n /// ```\n pub fn as_{}_enum(value: &str) -> String {{\n value.to_string()\n }}",
field.name, table.name, field.name, field.name
));
}
}
// Generate enum constants as part of the model impl block
// This makes them more discoverable for AI agents
if !enum_constants.is_empty() {
vars.insert(
"enum_constants_in_impl".to_string(),
enum_constants.join("\n"),
);
} else {
vars.insert("enum_constants_in_impl".to_string(), String::new());
}
// Add enum converter methods to template
if !enum_converters.is_empty() {
vars.insert("enum_converters".to_string(), enum_converters.join("\n\n"));
} else {
vars.insert("enum_converters".to_string(), String::new());
}
// Generate list of enum fields
let enum_fields_list =
if !enum_fields.is_empty() {
format!(
" /// List of fields that are enums\n pub const ENUM_FIELDS: &[&str] = &[{}];",
enum_fields.iter().map(|f| format!("\"{}\"", f)).collect::<Vec<_>>().join(", ")
)
} else {
" /// List of fields that are enums\n pub const ENUM_FIELDS: &[&str] = &[];"
.to_string()
};
vars.insert("enum_fields_list".to_string(), enum_fields_list);
// Generate insert field values mapping
let mut insert_field_values = Vec::new();
for field in &sorted_fields {
let escaped_field_name = escape_rust_keyword(&field.name);
let field_name = &field.name;
// Check if field has a default value or is auto-generated
let is_auto = field.constraints.auto.is_some();
if !is_auto {
// Check if this is an enum field
let is_enum = matches!(
&field.field_type,
rustf_schema::types::FieldType::Enum { .. }
);
// Check if this is an array field
let is_array = field.field_type.base_type().starts_with("array");
let value_expr = if is_enum {
// For enum fields, check if it's optional
let is_nullable = field.constraints.nullable.unwrap_or(false);
if is_nullable {
// For optional enum fields, map the Option
format!(
"model.{}.clone().map(SqlValue::Enum).unwrap_or(SqlValue::Null)",
escaped_field_name
)
} else {
// For required enum fields, use SqlValue::Enum directly
format!("SqlValue::Enum(model.{}.clone())", escaped_field_name)
}
} else if is_array {
// For array fields, convert Vec<T> to Vec<SqlValue> before wrapping in SqlValue::Array
let is_nullable = field.constraints.nullable.unwrap_or(false);
if is_nullable {
format!(
"model.{}.as_ref().map(|v| SqlValue::Array(v.iter().map(|item| SqlValue::from(item.clone())).collect())).unwrap_or(SqlValue::Null)",
escaped_field_name
)
} else {
format!(
"SqlValue::Array(model.{}.iter().map(|item| SqlValue::from(item.clone())).collect())",
escaped_field_name
)
}
} else {
// For other fields, use SqlValue::from
format!("SqlValue::from(model.{})", escaped_field_name)
};
insert_field_values.push(format!(
" insert_data.insert(\"{}\".to_string(), {});",
field_name, value_expr
));
}
}
vars.insert(
"insert_field_values".to_string(),
insert_field_values.join("\n"),
);
vars
}
/// Prepare template variables for wrapper model generation
fn prepare_wrapper_model_variables(
table: &rustf_schema::Table,
pool_type: &str,
) -> HashMap<String, String> {
let mut vars = HashMap::new();
// Basic metadata
vars.insert("model_name".to_string(), table.name.clone());
vars.insert("table_name".to_string(), table.table.clone());
vars.insert("pool_type".to_string(), pool_type.to_string());
// Sort fields alphabetically once for consistent ordering
let mut sorted_fields: Vec<_> = table.fields.values().collect();
sorted_fields.sort_by(|a, b| a.name.cmp(&b.name));
log::debug!(
"Sorted fields order for wrapper {}: {:?}",
table.name,
sorted_fields.iter().map(|f| &f.name).collect::<Vec<_>>()
);
// Generate the correct AnyDatabase variant with cloned pool
let any_database_variant = match pool_type {
"MySql" => "AnyDatabase::MySQL(pool.clone())",
"Postgres" => "AnyDatabase::Postgres(pool.clone())",
"Sqlite" => "AnyDatabase::SQLite(pool.clone())",
_ => "AnyDatabase::MySQL(pool.clone())", // Default fallback
};
vars.insert(
"any_database_variant".to_string(),
any_database_variant.to_string(),
);
// Determine primary key field (detect early for use throughout generation)
let primary_key = table
.fields
.values()
.find(|f| f.constraints.primary_key.unwrap_or(false))
.map(|f| f.name.clone())
.unwrap_or_else(|| "id".to_string());
vars.insert("primary_key".to_string(), primary_key.clone());
// Determine ID type and whether this model has a primary key field
let has_primary_key = table
.fields
.values()
.any(|f| f.constraints.primary_key.unwrap_or(false));
let id_type = if let Some(pk_field) = table
.fields
.values()
.find(|f| f.constraints.primary_key.unwrap_or(false))
{
if let Some(ref lang_type) = pk_field.lang_type {
lang_type.clone()
} else {
match pk_field.field_type.base_type() {
"int" | "integer" => "i32",
"bigint" => "i64",
"string" => "String",
_ => "i32",
}
.to_string()
}
} else {
"i32".to_string() // Default type for models without primary key
};
vars.insert("id_type".to_string(), id_type.clone());
// Generate id method implementation for wrapper
let id_method_impl = if has_primary_key {
// Use the primary key field name dynamically
let escaped_pk_field = escape_rust_keyword(&primary_key);
// Clone String IDs to avoid move out of borrowed content
if id_type == "String" {
format!(" self.base.{}.clone() ", escaped_pk_field)
} else {
format!(" self.base.{} ", escaped_pk_field)
}
} else {
" panic!(\"This model does not have a primary key field - it is likely a database view or composite entity\") ".to_string()
};
vars.insert("id_method_impl".to_string(), id_method_impl);
// Check if we need additional imports for the wrapper based on field types
let mut wrapper_imports = Vec::new();
let needs_datetime = table
.fields
.values()
.any(|f| matches!(f.field_type.base_type(), "timestamp" | "datetime"));
let needs_date = table
.fields
.values()
.any(|f| f.field_type.base_type() == "date");
let needs_time = table
.fields
.values()
.any(|f| f.field_type.base_type() == "time");
if needs_datetime || needs_date || needs_time {
let mut chrono_imports = vec![];
if needs_datetime {
chrono_imports.push("DateTime");
chrono_imports.push("Utc");
}
if needs_date {
chrono_imports.push("NaiveDate");
}
if needs_time {
chrono_imports.push("NaiveTime");
}
wrapper_imports.push(format!("use chrono::{{{}}};", chrono_imports.join(", ")));
}
let needs_decimal = table
.fields
.values()
.any(|f| f.field_type.base_type() == "decimal");
if needs_decimal {
wrapper_imports.push("use rust_decimal::Decimal;".to_string());
}
let needs_json = table
.fields
.values()
.any(|f| f.field_type.base_type() == "json");
if needs_json {
wrapper_imports.push("use serde_json;".to_string());
}
let needs_uuid = table
.fields
.values()
.any(|f| f.field_type.base_type() == "uuid");
if needs_uuid {
wrapper_imports.push("use uuid::Uuid;".to_string());
}
let wrapper_imports_str = if !wrapper_imports.is_empty() {
format!("\n{}", wrapper_imports.join("\n"))
} else {
String::new()
};
vars.insert("wrapper_imports".to_string(), wrapper_imports_str);
// No builder setter delegations needed - Deref handles it automatically!
vars.insert("builder_setter_delegations".to_string(), String::new());
// No longer need wrapper setters - Deref handles delegation automatically!
vars.insert("wrapper_setters".to_string(), String::new());
// No longer need field accessors - Deref handles delegation automatically!
// Empty field_accessors since Deref handles delegation
vars.insert("field_accessors".to_string(), String::new());
// Check if we should use macros for cleaner code
let use_macros = true; // Always use macros for new generation
vars.insert("use_macros".to_string(), use_macros.to_string());
// No longer generating create_method_wrapper - builder pattern is the way
vars
}
/// Generate base model include file using embedded template
fn generate_base_model_include_code(
table: &rustf_schema::Table,
schema: &Schema,
checksum: &str,
generation_time: &str,
pool_type: &str,
) -> anyhow::Result<String> {
// Get the include template
let template = Templates::get("models/base_model_include.rs.template")
.or_else(|| Templates::get("models/base_model.rs.template")) // Fallback to old template
.ok_or_else(|| anyhow::anyhow!("Base model template not found"))?;
let template_content = std::str::from_utf8(template.data.as_ref())?;
// Prepare variables
let variables =
prepare_base_model_variables(table, schema, checksum, generation_time, pool_type);
// Process template
let processed = process_template(template_content, &variables);
Ok(processed)
}
/// Generate wrapper model include code using embedded template
fn generate_wrapper_model_include_code(
table: &rustf_schema::Table,
pool_type: &str,
) -> anyhow::Result<String> {
// Get the include template
let template = Templates::get("models/wrapper_model_include.rs.template")
.or_else(|| Templates::get("models/wrapper_model.rs.template")) // Fallback to old template
.ok_or_else(|| anyhow::anyhow!("Wrapper model template not found"))?;
let template_content = std::str::from_utf8(template.data.as_ref())?;
// Prepare variables
let variables = prepare_wrapper_model_variables(table, pool_type);
// Process template
let processed = process_template(template_content, &variables);
Ok(processed)
}
/// Generate MODELS_README.md using embedded template
fn generate_models_readme_from_template(
generation_time: &str,
pool_type: &str,
) -> anyhow::Result<String> {
// Get the template
let template = Templates::get("readmes/models_README.md.template")
.ok_or_else(|| anyhow::anyhow!("Models README template not found"))?;
let template_content = std::str::from_utf8(template.data.as_ref())?;
// Prepare variables
let mut variables = HashMap::new();
variables.insert("generation_time".to_string(), generation_time.to_string());
variables.insert("cli_version".to_string(), "0.1.0".to_string());
variables.insert("pool_type".to_string(), pool_type.to_string());
// Process template
let processed = process_template(template_content, &variables);
Ok(processed)
}
/// Generate MODELS_README.md with comprehensive instructions (fallback)
fn generate_models_readme(_schema: &Schema) -> String {
let generation_time = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
// Try template first, fallback to inline if template fails
match generate_models_readme_from_template(&generation_time, "MySql") {
Ok(content) => content,
Err(_) => {
// Fallback inline version (simplified)
format!(
r#"# 📋 RustF Models Guide
## 🏗️ Directory Structure
```
src/models/
├── base/ # 🚫 NEVER EDIT - Generated code only
│ ├── user_base.rs # ⚠️ Overwritten on each generation
│ └── product_base.rs # ⚠️ Overwritten on each generation
├── user.rs # ✅ EDIT HERE - Business logic
├── product.rs # ✅ EDIT HERE - Business logic
└── MODELS_README.md # 📖 This file
```
## 🤖 Instructions for AI Agents
### ❌ NEVER DO:
- Edit files in `base/`
- Modify files with "AUTOMATICALLY GENERATED" header
- Import UserBase, ProductBase directly in the application
- Add business logic to base models
- Remove the `register()` function from wrappers
### ✅ ALWAYS DO:
- Edit wrapper models (user.rs, product.rs, etc.)
- Add business methods to wrapper structs
- Use composition: `struct User {{ base: UserBase }}`
- Preserve the `register()` function in each model
- Guide users to wrapper models for customization
- Use `self.base.field` to access DB fields
- Use `self.base.create()`, `.update()`, `.delete()` for DB operations
## 🔄 Development workflow
1. **Initial generation**: `rustf-cli schema generate models`
2. **Development**: Edit `user.rs` to add business logic
3. **Schema evolution**: Modify `schemas/users.yaml`
4. **Regeneration**: `rustf-cli schema generate models` (only `base/` is overwritten)
5. **Auto-discovery**: `auto_models!()` automatically finds wrappers
## 📊 File types
| Type | Location | Editable | Description |
|------|----------|----------|-------------|
| Base | `base/*_base.rs` | ❌ No | Generated CRUD models |
| Wrapper | `*.rs` | ✅ Yes | Business logic |
| Schema | `schemas/*.yaml` | ✅ Yes | DB definition |
## 🚨 Important rules
- **Never import directly** base models in the application
- **Always use** wrappers (User, Product, etc.)
- **Preserve** the `register()` function for auto_models!()
- **Composition** rather than inheritance: `User {{ base: UserBase }}`
---
### 📚 Generated at {} by RustF CLI v0.1.0
"#,
generation_time
)
}
}
}
/// Simple compilation validation for generated models
///
/// This creates a temporary Rust file and runs `cargo check` to ensure
/// the generated code compiles without errors.
#[allow(dead_code)]
fn validate_generated_model_compilation(model_name: &str, code: &str) -> anyhow::Result<()> {
use std::fs;
use std::process::Command;
use tempfile::NamedTempFile;
// Create a temporary Rust file
let temp_file = NamedTempFile::new()?;
let temp_path = temp_file.path();
// Write the generated code to temp file
fs::write(temp_path, code)?;
// Run cargo check on the file (basic syntax validation)
let output = Command::new("rustc")
.arg("--edition")
.arg("2021")
.arg("--crate-type")
.arg("lib")
.arg("--check-cfg")
.arg("cfg()")
.arg(temp_path)
.output();
match output {
Ok(result) => {
if !result.status.success() {
let stderr = String::from_utf8_lossy(&result.stderr);
eprintln!(
"⚠️ Compilation validation failed for model '{}':",
model_name
);
eprintln!("{}", stderr);
// Don't fail the generation, just warn
println!("🔍 Generated code saved to: {:?} for debugging", temp_path);
return Err(anyhow::anyhow!(
"Model '{}' has compilation errors. Check the generated code.",
model_name
));
}
println!(
"✅ Compilation validation passed for model '{}'",
model_name
);
Ok(())
}
Err(e) => {
// rustc not available, skip validation
println!(
"⚠️ Skipping compilation validation (rustc not found): {}",
e
);
Ok(())
}
}
}