autumn-cli 0.10.0

CLI tool for the Autumn web framework
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
//! `autumn generate migration` — emit a Diesel migration directory only.
//!
//! Inspects the migration name to decide whether to emit empty SQL files
//! (for hand-edited migrations), `ALTER TABLE … ADD COLUMN` (when the name
//! starts with `Add…To…`), or `ALTER TABLE … DROP COLUMN` (when it starts
//! with `Remove…From…`).

use std::path::Path;

use super::dsl::parse_fields;
use super::emit::Plan;
use super::naming::pascal_to_snake;
use super::schema_edit::{
    MigrationShape, add_columns_down_sql_for, add_columns_up_sql_for, add_search_down_sql_for,
    add_search_up_sql_for, detect_migration_shape, encrypt_columns_down_sql,
    encrypt_columns_up_sql, parse_model_search_config_for_table, remove_columns_down_sql_for,
    remove_columns_up_sql_for, singularize,
};
use super::{GenerateError, detect_backend, ensure_project_root};

fn collect_rs_files_recursive(dir: &Path, candidates: &mut Vec<std::path::PathBuf>) {
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                collect_rs_files_recursive(&path, candidates);
            } else if path.is_file()
                && path.extension().is_some_and(|ext| ext == "rs")
                && !candidates.contains(&path)
            {
                candidates.push(path);
            }
        }
    }
}

/// Compute the file actions for `autumn generate migration`.
///
/// # Errors
/// Project layout, name, and DSL errors surface here.
#[allow(dead_code)]
pub fn plan_migration(
    project_root: &Path,
    name: &str,
    field_tokens: &[String],
    timestamp: &str,
) -> Result<Plan, GenerateError> {
    plan_migration_with_options(project_root, name, field_tokens, timestamp, &[])
}

/// [`plan_migration`], plus `--unique FIELD` flags (issue #1032) — mirrors
/// the DSL's inline `:unique` modifier, which already works via
/// [`parse_fields`] alone (no options struct needed, unlike `generate
/// model`/`scaffold`'s `ModelOptions`).
///
/// # Errors
/// Project layout, name, DSL, and unknown-field errors surface here.
#[allow(
    clippy::too_many_lines,
    reason = "a linear match over the migration shapes (add/remove/encrypt/search \
              columns), each arm emitting its own up/down SQL; splitting an arm out \
              would not make any single shape clearer"
)]
pub fn plan_migration_with_options(
    project_root: &Path,
    name: &str,
    field_tokens: &[String],
    timestamp: &str,
    uniques: &[String],
) -> Result<Plan, GenerateError> {
    ensure_project_root(project_root)?;
    super::model::validate_resource_name(name)?;
    let mut fields = parse_fields(field_tokens)?;
    super::model::apply_unique_flags(&mut fields, uniques)?;
    // Issue #1340: `generate migration` emits SQL and nothing else — it never
    // writes a model file, so there is nowhere for the `#[encrypted(...)]`
    // attribute to land. Accepting `{encrypted}` here would add an ordinary
    // plaintext column while the author believes they declared encryption:
    // precisely the silent failure this DSL token exists to eliminate. Point at
    // the two generators that do wire the attribute, and at the existing
    // `Encrypt<Column>On<Table>` shape for converting a column that already
    // exists.
    if let Some(field) = fields.iter().find(|f| f.is_encrypted()) {
        return Err(GenerateError::InvalidField {
            token: field.name.clone(),
            reason: format!(
                "the `encrypted` modifier is not supported by `generate migration`: this \
                 command emits SQL only, so the `#[encrypted]` attribute would never reach a \
                 model and the column would silently be plaintext. Declare the column with \
                 `autumn generate model`/`autumn generate scaffold` \
                 (`{}:String{{encrypted}}`), or convert an existing plaintext column with \
                 `autumn generate migration Encrypt{}On<Table>`, which emits the documented \
                 offline backfill.",
                field.name,
                super::naming::pascal(&field.name),
            ),
        });
    }
    // Issue #1384: same reasoning as `{encrypted}` above, and the same silent
    // failure. `generate migration` emits SQL only, so the `#[translatable]`
    // attribute — and the `Translated` field type that carries every bit of the
    // behaviour — would never reach a model. The column would be added as
    // `TEXT NOT NULL DEFAULT '{}'` while the model kept reading it as a plain
    // `String`, so the app would render raw JSON where the author believed they
    // had declared per-locale content.
    //
    // Refusing here also closes the `--unique` hole by construction: the flag is
    // folded in above by `apply_unique_flags`, after `parse_field`'s own
    // `:unique` cross-check has already run, so `--unique` on a translatable
    // column would otherwise have emitted a UNIQUE index over the whole JSON
    // container — precisely what the inline spelling refuses.
    if let Some(field) = fields.iter().find(|f| f.is_translatable()) {
        return Err(GenerateError::InvalidField {
            token: field.name.clone(),
            reason: format!(
                "the `translatable` modifier is not supported by `generate migration`: this \
                 command emits SQL only, so the `#[translatable]` attribute and the \
                 `autumn_web::i18n::Translated` field type would never reach a model, and the \
                 app would read the per-locale JSON container as a plain string. Declare the \
                 column with `autumn generate model` (`{}:String{{translatable}}`), which emits \
                 the model, the schema entry, the migration and the `i18n` feature together.",
                field.name
            ),
        });
    }
    // Determine the target app's database backend so the emitted ALTER TABLE
    // DDL is backend-aware (SQLite foundation, issue #1614).
    let backend = detect_backend(project_root);

    // The directory uses snake_case (`add_title_to_posts`) but the shape is
    // detected from the original PascalCase form because the keywords `To`
    // and `From` only have an unambiguous meaning at PascalCase chunk
    // boundaries.
    let dir_name = format!("{timestamp}_{}", snake_or_pascal_to_snake(name));
    let migration_dir = project_root.join("migrations").join(&dir_name);

    let mut plan = Plan::new(project_root);

    let shape = detect_migration_shape(&pascalish(name));
    let (up, down) = match shape {
        MigrationShape::AddColumns { ref table } if !fields.is_empty() => {
            // A `references` field here gets the same target-model warning /
            // UUID-PK error as `generate model`/`generate scaffold` (issue
            // #1026) — otherwise the same DSL token gives inconsistent
            // feedback depending only on which subcommand declared it.
            // `own_id_type` is `None`: this shape only `ALTER TABLE`s an
            // *existing* table, so its actual primary-key type isn't tracked
            // anywhere the generator can see — a self-reference here is left
            // unvalidated rather than guessed at.
            super::model::check_reference_targets(&mut plan, project_root, &fields, table, None)?;
            // Issue #1318: a `lock_version` token means optimistic locking here
            // too — `add_columns_up_sql_for` gives it the `DEFAULT 0` the
            // DB-managed column needs — so validate it exactly as `generate
            // model`/`generate scaffold` do. Scoped to the ADD shape on
            // purpose: a REMOVE migration names a column that already exists,
            // and dropping a legacy `lock_version` whose name now collides with
            // the magic one is a legitimate (indeed, the recommended) thing to
            // do. Its rollback re-adds the column with the type the user
            // supplied, so rejecting `RemoveLockVersionFromPosts
            // lock_version:String` would block the very escape hatch the other
            // error messages point at.
            super::model::validate_lock_version_field(&fields, &[])?;
            // The same standing guard `generate model`/`scaffold` carries: a
            // field kind with no working diesel SQLite conversion would leak an
            // uncompilable column into the app. Every kind converts as of #1924
            // (AC #4).
            if backend == autumn_web::config::DatabaseBackend::Sqlite {
                super::reject_sqlite_unsupported_field_kinds(&fields)?;
            }
            // `src/schema.rs`'s current content, so a `unique` field being
            // added here can't pick an index name that coincidentally
            // collides with a plain index on some other, already-existing
            // column from an earlier migration this one has no other way to
            // see (issue #1032 review follow-up). Empty string (no
            // collision-check widening) if the file doesn't exist yet.
            let existing_schema =
                std::fs::read_to_string(project_root.join("src/schema.rs")).unwrap_or_default();
            (
                add_columns_up_sql_for(backend, table, &fields, &existing_schema)?,
                add_columns_down_sql_for(backend, table, &fields, &existing_schema),
            )
        }
        MigrationShape::RemoveColumns { ref table } if !fields.is_empty() => {
            // `remove_columns_down_sql`'s rollback restores the FK
            // constraint/index for a `references` field (issue #1026), so it
            // needs the same UUID-PK guard as `AddColumns` — otherwise a
            // target with a UUID primary key still produces a `down.sql`
            // that fails to apply on rollback.
            super::model::check_reference_targets(&mut plan, project_root, &fields, table, None)?;
            // The rollback (`down.sql`) re-adds the removed columns via
            // `ALTER TABLE … ADD COLUMN …`, so a field kind with no working
            // diesel SQLite conversion would still leak into generated DDL —
            // reject it up front, matching the AddColumns path (AC #4, #1924).
            if backend == autumn_web::config::DatabaseBackend::Sqlite {
                super::reject_sqlite_unsupported_field_kinds(&fields)?;
            }
            let existing_schema =
                std::fs::read_to_string(project_root.join("src/schema.rs")).unwrap_or_default();
            // SQLite refuses `DROP COLUMN` while an index names the column.
            // Recover the table's prior indexes so the up path drops them first
            // (#1906). Postgres cascades the drop and needs none of this.
            let prior_indexes = if backend == autumn_web::config::DatabaseBackend::Sqlite {
                let columns: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect();
                super::prior_index::scan_prior_indexes(
                    &project_root.join("migrations"),
                    table,
                    &columns,
                )
                .map_err(GenerateError::Config)?
            } else {
                Vec::new()
            };
            (
                remove_columns_up_sql_for(
                    backend,
                    table,
                    &fields,
                    &existing_schema,
                    &prior_indexes,
                ),
                remove_columns_down_sql_for(
                    backend,
                    table,
                    &fields,
                    &existing_schema,
                    &prior_indexes,
                )?,
            )
        }
        MigrationShape::EncryptColumns {
            ref table,
            ref columns,
        } => (
            encrypt_columns_up_sql(table, columns),
            encrypt_columns_down_sql(table, columns),
        ),
        MigrationShape::AddSearch { ref table } => {
            // Full-text search is backend-aware (issue #1910): Postgres emits a
            // `tsvector` generated column + GIN index; SQLite emits an
            // external-content FTS5 virtual table + maintenance triggers (see
            // `add_search_up_sql_for`). Neither leaks DDL that breaks the other
            // backend, so `--search` now works on both.
            let singular = singularize(table);

            // Collect all potential model file candidates in order of preference
            let mut candidates = Vec::new();

            let first_cand = project_root
                .join("src/models")
                .join(format!("{singular}.rs"));
            if first_cand.exists() {
                candidates.push(first_cand);
            }

            let second_cand = project_root.join("src/models.rs");
            if second_cand.exists() {
                candidates.push(second_cand);
            }

            let models_dir = project_root.join("src/models");
            let mut other_candidates = Vec::new();
            collect_rs_files_recursive(&models_dir, &mut other_candidates);
            other_candidates.sort();

            for path in other_candidates {
                if !candidates.contains(&path) {
                    candidates.push(path);
                }
            }

            let mut found_config = None;
            let mut tried_files = Vec::new();

            for path in candidates {
                if let Ok(content) = std::fs::read_to_string(&path) {
                    if let Some((language, fts_fields)) =
                        parse_model_search_config_for_table(&content, table)
                    {
                        found_config = Some((path, language, fts_fields));
                        break;
                    }
                    tried_files.push(path);
                }
            }

            let Some((_path, language, fts_fields)) = found_config else {
                if tried_files.is_empty() {
                    return Err(GenerateError::Config(format!(
                        "Missing model files for table '{table}'. Expected src/models/{singular}.rs or src/models.rs."
                    )));
                }
                let files_str = tried_files
                    .iter()
                    .map(|p| p.to_string_lossy().to_string())
                    .collect::<Vec<_>>()
                    .join(", ");
                return Err(GenerateError::Config(format!(
                    "No #[searchable] fields configured for table '{table}' in any of the checked files: [{files_str}]"
                )));
            };

            (
                add_search_up_sql_for(backend, table, &language, &fts_fields)?,
                add_search_down_sql_for(backend, table),
            )
        }
        _ => (String::new(), String::new()),
    };

    plan.create(migration_dir.join("up.sql"), up);
    plan.create(migration_dir.join("down.sql"), down);
    Ok(plan)
}

/// Fallback destroy-only plan for `autumn destroy migration <name>` when
/// [`plan_migration_with_options`] can't be recomputed — e.g. an
/// `AddSearchTo<Table>` migration whose model file (or its `#[searchable]`
/// config) is already gone by the time destroy runs, a common cleanup order
/// like deleting/destroying the model first (issue #1048 PR review).
/// `plan_migration_with_options` needs that config to render the right SQL,
/// which is meaningless (and an error) once it's gone.
///
/// Locates the migration directory by suffix only — the same
/// `{timestamp}_{suffix}` naming [`plan_migration_with_options`] uses, which
/// is all [`Plan::revert`] actually needs to find it (destroy always
/// recomputes a fresh timestamp anyway, so exact SQL content was never
/// load-bearing for *locating* the directory). Its expected content is
/// unknowable without re-deriving the search config, so `up.sql`/`down.sql`
/// are recorded with an empty placeholder — real content (never empty)
/// always counts as diverged, so they're only removed with `--force`,
/// exactly like [`super::admin::plan_admin_destroy_fallback`].
///
/// # Errors
/// Returns [`GenerateError`] when `project_root` isn't a valid project, or
/// `name` fails validation.
pub fn plan_migration_destroy_fallback(
    project_root: &Path,
    name: &str,
    timestamp: &str,
) -> Result<Plan, GenerateError> {
    ensure_project_root(project_root)?;
    super::model::validate_resource_name(name)?;

    let dir_name = format!("{timestamp}_{}", snake_or_pascal_to_snake(name));
    let migration_dir = project_root.join("migrations").join(&dir_name);
    let mut plan = Plan::new(project_root);
    plan.create(migration_dir.join("up.sql"), String::new());
    plan.create(migration_dir.join("down.sql"), String::new());
    Ok(plan)
}

/// Convert a name like `AddTitleToPosts` → `add_title_to_posts`, while
/// leaving an already-snake-case name untouched.
fn snake_or_pascal_to_snake(name: &str) -> String {
    if name.contains('_') || !name.chars().any(char::is_uppercase) {
        name.to_ascii_lowercase()
    } else {
        pascal_to_snake(name)
    }
}

/// Re-shape a possibly-snake-case name back to `PascalCase` so
/// [`detect_migration_shape`] sees the chunk boundaries it expects.
fn pascalish(name: &str) -> String {
    if name.contains('_') {
        super::naming::snake_to_pascal(name)
    } else {
        name.to_owned()
    }
}

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

    /// #1384 (Codex round 4): `generate migration` emits SQL only, so a
    /// `{translatable}` column would arrive without the `#[translatable]`
    /// attribute or the `Translated` field type — the app would read the JSON
    /// container as a plain string. Same silent failure `{encrypted}` refuses.
    #[test]
    fn migration_rejects_a_translatable_field() {
        let tmp = project();
        let err = plan_migration(
            tmp.path(),
            "AddTitleToPosts",
            &["title:String{translatable}".into()],
            "20260427000000",
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("translatable"), "{err}");
        assert!(err.contains("generate model"), "{err}");
    }

    /// The refusal also closes the `--unique` hole: the flag is applied after
    /// `parse_field`'s own `:unique` cross-check has run, so without it
    /// `--unique` would emit a UNIQUE index over the whole JSON container.
    #[test]
    fn migration_rejects_a_translatable_field_flagged_unique() {
        let tmp = project();
        let err = plan_migration_with_options(
            tmp.path(),
            "AddTitleToPosts",
            &["title:String{translatable}".into()],
            "20260427000000",
            &["title".to_owned()],
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("translatable"), "{err}");
    }
    use crate::generate::Flags;
    use crate::generate::emit::Action;
    use std::fs;
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn project() -> TempDir {
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join("Cargo.toml"), "[package]\nname=\"x\"\n").unwrap();
        tmp
    }

    #[test]
    fn empty_migration_when_no_keyword_match() {
        let tmp = project();
        let plan = plan_migration(tmp.path(), "BackfillSomething", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let dir = tmp
            .path()
            .join("migrations/20260427000000_backfill_something");
        let up = fs::read_to_string(dir.join("up.sql")).unwrap();
        let down = fs::read_to_string(dir.join("down.sql")).unwrap();
        assert!(up.is_empty());
        assert!(down.is_empty());
    }

    #[test]
    fn generate_then_destroy_migration_round_trips_to_original_project_state() {
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                ("AUTUMN_DATABASE__URL", None::<&str>),
                ("DATABASE_URL", None::<&str>),
            ],
            || {
                let tmp = project();
                let plan = plan_migration(
                    tmp.path(),
                    "AddTitleToPosts",
                    &["title:String".into()],
                    "20260427000000",
                )
                .unwrap();
                plan.execute(Flags::default()).unwrap();
                let dir = tmp
                    .path()
                    .join("migrations/20260427000000_add_title_to_posts");
                assert!(dir.exists());

                // Destroy recomputes the plan with a FRESH timestamp; the
                // real on-disk directory must still be found by suffix.
                let destroy_plan = plan_migration(
                    tmp.path(),
                    "AddTitleToPosts",
                    &["title:String".into()],
                    "99999999999999",
                )
                .unwrap();
                destroy_plan.revert(Flags::default()).unwrap();

                assert!(!dir.exists());
                assert!(
                    fs::read_dir(tmp.path().join("migrations"))
                        .map_or(true, |mut d| d.next().is_none())
                );
            },
        );
    }

    #[test]
    fn destroy_migration_refuses_directory_with_unplanned_file_unless_forced() {
        // issue #1048 PR review: a developer may drop a README.md or an
        // auxiliary fixture alongside the generated up.sql/down.sql. Destroy
        // must treat that extra file as divergence rather than silently
        // sweeping it up with `remove_dir_all`.
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                ("AUTUMN_DATABASE__URL", None::<&str>),
                ("DATABASE_URL", None::<&str>),
            ],
            || {
                let tmp = project();
                let plan = plan_migration(
                    tmp.path(),
                    "AddTitleToPosts",
                    &["title:String".into()],
                    "20260427000000",
                )
                .unwrap();
                plan.execute(Flags::default()).unwrap();
                let dir = tmp
                    .path()
                    .join("migrations/20260427000000_add_title_to_posts");
                assert!(dir.exists());
                fs::write(dir.join("README.md"), "hand-authored notes\n").unwrap();

                let destroy_plan = plan_migration(
                    tmp.path(),
                    "AddTitleToPosts",
                    &["title:String".into()],
                    "99999999999999",
                )
                .unwrap();
                let err = destroy_plan
                    .revert(Flags {
                        dry_run: false,
                        force: false,
                    })
                    .unwrap_err();
                assert!(matches!(err, GenerateError::Diverged(_)));
                assert!(
                    dir.join("README.md").exists(),
                    "hand-authored file must survive without --force"
                );

                let destroy_plan = plan_migration(
                    tmp.path(),
                    "AddTitleToPosts",
                    &["title:String".into()],
                    "99999999999999",
                )
                .unwrap();
                destroy_plan
                    .revert(Flags {
                        dry_run: false,
                        force: true,
                    })
                    .unwrap();
                assert!(!dir.exists(), "--force must still remove the directory");
            },
        );
    }

    #[test]
    fn add_columns_migration_emits_alter() {
        let tmp = project();
        let plan = plan_migration(
            tmp.path(),
            "AddTitleToPosts",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_add_title_to_posts/up.sql"),
        )
        .unwrap();
        let down = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_add_title_to_posts/down.sql"),
        )
        .unwrap();
        assert!(up.contains("ALTER TABLE posts ADD COLUMN title TEXT NOT NULL"));
        assert!(down.contains("ALTER TABLE posts DROP COLUMN title"));
    }

    #[test]
    fn remove_columns_migration_emits_drop() {
        let tmp = project();
        let plan = plan_migration(
            tmp.path(),
            "RemoveBodyFromPosts",
            &["body:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_remove_body_from_posts/up.sql"),
        )
        .unwrap();
        assert!(up.contains("ALTER TABLE posts DROP COLUMN body"));
    }

    #[test]
    fn remove_columns_migration_with_references_field_restores_fk_on_rollback() {
        // `RemovePostFromComments post:references` — down.sql must restore
        // the FK constraint and index, not just a bare column (issue #1026).
        let tmp = project();
        let plan = plan_migration(
            tmp.path(),
            "RemovePostFromComments",
            &["post:references".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let down = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_remove_post_from_comments/down.sql"),
        )
        .unwrap();
        assert!(
            down.contains(
                "ALTER TABLE comments ADD COLUMN post_id BIGINT NOT NULL REFERENCES posts(id);"
            ),
            "down.sql: {down}"
        );
        assert!(
            down.contains("CREATE INDEX idx_comments_post_id ON comments (post_id);"),
            "down.sql: {down}"
        );
    }

    #[test]
    fn remove_columns_with_references_field_errors_on_uuid_target() {
        // The restored FK constraint in remove_columns_down_sql needs the
        // same UUID-PK guard as AddColumns — otherwise a target with a UUID
        // primary key still produces a down.sql that fails on rollback.
        let tmp = project();
        let models_dir = tmp.path().join("src/models");
        fs::create_dir_all(&models_dir).unwrap();
        fs::write(
            models_dir.join("post.rs"),
            "#[autumn_web::model]\npub struct Post {\n    #[id]\n    pub id: uuid::Uuid,\n}\n",
        )
        .unwrap();

        let err = plan_migration(
            tmp.path(),
            "RemovePostFromComments",
            &["post:references".into()],
            "20260427000000",
        )
        .unwrap_err();
        assert!(err.to_string().contains("UUID"));
    }

    #[test]
    fn remove_columns_with_references_field_warns_when_target_model_missing() {
        let tmp = project();
        let plan = plan_migration(
            tmp.path(),
            "RemovePostFromComments",
            &["post:references".into()],
            "20260427000000",
        )
        .unwrap();
        assert_eq!(plan.warnings.len(), 1, "warnings: {:?}", plan.warnings);
        assert!(plan.warnings[0].contains("posts"));
    }

    #[test]
    fn add_pattern_with_no_fields_is_empty() {
        let tmp = project();
        let plan = plan_migration(tmp.path(), "AddTitleToPosts", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_add_title_to_posts/up.sql"),
        )
        .unwrap();
        assert!(up.is_empty());
    }

    #[test]
    fn snake_case_name_is_accepted() {
        let tmp = project();
        let plan = plan_migration(
            tmp.path(),
            "add_title_to_posts",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_add_title_to_posts/up.sql"),
        )
        .unwrap();
        assert!(up.contains("ALTER TABLE posts ADD COLUMN title TEXT NOT NULL"));
    }

    #[test]
    fn add_search_migration_emits_fts_columns_and_indices() {
        let tmp = project();
        let models_dir = tmp.path().join("src/models");
        fs::create_dir_all(&models_dir).unwrap();
        let model_src = r#"
#[autumn_web::model(table = "posts")]
#[searchable(language = "english")]
pub struct Post {
    #[id]
    pub id: i64,
    #[searchable(weight = "A")]
    pub title: String,
    #[searchable(weight = "B")]
    pub body: String,
}
"#;
        fs::write(models_dir.join("post.rs"), model_src).unwrap();

        let plan = plan_migration(tmp.path(), "AddSearchToPosts", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();

        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_add_search_to_posts/up.sql"),
        )
        .unwrap();
        let down = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_add_search_to_posts/down.sql"),
        )
        .unwrap();

        assert!(up.contains("ALTER TABLE posts ADD COLUMN search_vector tsvector GENERATED ALWAYS AS (setweight(to_tsvector('english'::regconfig, coalesce(\"title\"::text, '')), 'A') || setweight(to_tsvector('english'::regconfig, coalesce(\"body\"::text, '')), 'B')) STORED;"));
        assert!(
            up.contains("CREATE INDEX idx_posts_search_vector ON posts USING gin(search_vector);")
        );
        assert!(down.contains("DROP INDEX IF EXISTS idx_posts_search_vector;"));
        assert!(down.contains("ALTER TABLE posts DROP COLUMN IF EXISTS search_vector;"));
    }

    // ── SQLite backend awareness (issue #1614) ──────────────────────────────

    /// Null the DB-URL environment variables so backend detection reads the
    /// temp project's `autumn.toml` deterministically.
    fn with_no_db_env<R>(f: impl FnOnce() -> R) -> R {
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                ("AUTUMN_DATABASE__URL", None::<&str>),
                ("DATABASE_URL", None::<&str>),
            ],
            f,
        )
    }

    fn sqlite_project() -> TempDir {
        let tmp = project();
        fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"sqlite://app.db\"\n",
        )
        .unwrap();
        tmp
    }

    /// `AddSearchTo…` on a `SQLite` app now emits an FTS5 external-content virtual
    /// table + maintenance triggers (issue #1910) instead of being rejected, and
    /// no Postgres-only `tsvector`/GIN DDL leaks into the `SQLite` migration.
    #[test]
    fn add_search_migration_on_sqlite_emits_fts5() {
        with_no_db_env(|| {
            let tmp = sqlite_project();
            // The AddSearch shape reads the model's #[searchable] config from a
            // model file to know which columns to index.
            fs::create_dir_all(tmp.path().join("src/models")).unwrap();
            fs::write(
                tmp.path().join("src/models/post.rs"),
                "#[autumn_web::model(table = \"posts\")]\n\
                 #[searchable(language = \"english\")]\n\
                 pub struct Post {\n\
                 \x20   #[id]\n\
                 \x20   pub id: i64,\n\
                 \x20   #[searchable(weight = \"A\")]\n\
                 \x20   pub title: String,\n\
                 \x20   #[searchable(weight = \"B\")]\n\
                 \x20   pub body: String,\n\
                 }\n",
            )
            .unwrap();

            let plan =
                plan_migration(tmp.path(), "AddSearchToPosts", &[], "20260427000000").unwrap();
            plan.execute(Flags::default()).unwrap();

            let dir = tmp
                .path()
                .join("migrations/20260427000000_add_search_to_posts");
            let up = fs::read_to_string(dir.join("up.sql")).unwrap();
            let down = fs::read_to_string(dir.join("down.sql")).unwrap();

            assert!(
                up.contains(
                    "CREATE VIRTUAL TABLE \"posts__fts\" USING fts5(\"title\", \"body\", \
                     content='posts', content_rowid='id', tokenize='unicode61');"
                ),
                "up.sql must create the FTS5 vtable: {up}"
            );
            assert!(
                up.contains("INSERT INTO \"posts__fts\"(\"posts__fts\") VALUES('rebuild');"),
                "up.sql must backfill via 'rebuild': {up}"
            );
            for trig in ["posts__fts_ai", "posts__fts_ad", "posts__fts_au"] {
                assert!(up.contains(trig), "up.sql must create trigger {trig}: {up}");
                assert!(
                    down.contains(&format!("DROP TRIGGER IF EXISTS \"{trig}\";")),
                    "down.sql must drop trigger {trig}: {down}"
                );
            }
            assert!(
                down.contains("DROP TABLE IF EXISTS \"posts__fts\";"),
                "down.sql must drop the FTS table: {down}"
            );
            for leak in ["tsvector", "to_tsvector", "USING gin", "search_vector"] {
                assert!(!up.contains(leak), "SQLite up.sql leaked `{leak}`: {up}");
            }
        });
    }

    /// `Add…To…` on a `SQLite` app emits `SQLite`-valid column types
    /// (`i64` -> `INTEGER`, not Postgres `BIGINT`). Uses a *nullable* column
    /// because `SQLite` rejects `ADD COLUMN … NOT NULL` without a default (see
    /// `add_columns_migration_on_sqlite_rejects_not_null_without_default`).
    #[test]
    fn add_columns_migration_on_sqlite_emits_sqlite_types() {
        with_no_db_env(|| {
            let tmp = sqlite_project();
            let plan = plan_migration(
                tmp.path(),
                "AddViewsToPosts",
                &["views:Option<i64>".into()],
                "20260427000000",
            )
            .unwrap();
            plan.execute(Flags::default()).unwrap();
            let up = fs::read_to_string(
                tmp.path()
                    .join("migrations/20260427000000_add_views_to_posts/up.sql"),
            )
            .unwrap();
            assert!(
                up.contains("ALTER TABLE posts ADD COLUMN views INTEGER NULL"),
                "up.sql: {up}"
            );
            assert!(!up.contains("BIGINT"), "SQLite up.sql leaked BIGINT: {up}");
        });
    }

    /// `Add…To…` on a `SQLite` app with a `NOT NULL` column and no default is
    /// rejected at generate time (issue #1614 AC #4): `SQLite` rejects
    /// `ALTER TABLE … ADD COLUMN … NOT NULL` without a `DEFAULT` once the table
    /// has rows, and this command has no way to attach a column default, so the
    /// generated migration would fail to apply. Mirrors the `--search`
    /// reject-at-generate contract.
    #[test]
    fn add_columns_migration_on_sqlite_rejects_not_null_without_default() {
        with_no_db_env(|| {
            let tmp = sqlite_project();
            let err = plan_migration(
                tmp.path(),
                "AddViewsToPosts",
                &["views:i64".into()],
                "20260427000000",
            )
            .unwrap_err();
            let msg = err.to_string();
            assert!(
                matches!(err, GenerateError::Config(_)),
                "expected Config error, got: {err:?}"
            );
            assert!(
                msg.contains("NOT NULL") && msg.contains("views") && msg.contains("posts"),
                "message must name the column/table and the constraint: {msg}"
            );
            assert!(
                msg.contains("nullable") || msg.contains("default"),
                "message must be actionable (nullable / default): {msg}"
            );
        });
    }

    /// A *nullable* `NOT NULL`-free column is added without a default on
    /// `SQLite`, while the reject above guards the `NOT NULL` case — together
    /// they cover both branches of the `SQLite` `ADD COLUMN` gate.
    #[test]
    fn add_columns_migration_on_sqlite_allows_nullable_without_default() {
        with_no_db_env(|| {
            let tmp = sqlite_project();
            let plan = plan_migration(
                tmp.path(),
                "AddNoteToPosts",
                &["note:Option<String>".into()],
                "20260427000000",
            )
            .unwrap();
            plan.execute(Flags::default()).unwrap();
            let up = fs::read_to_string(
                tmp.path()
                    .join("migrations/20260427000000_add_note_to_posts/up.sql"),
            )
            .unwrap();
            assert!(
                up.contains("ALTER TABLE posts ADD COLUMN note TEXT NULL"),
                "up.sql: {up}"
            );
        });
    }

    /// A `SQLite` `Add…To…` migration that adds a nullable `references` field
    /// creates an index in `up.sql`, and its `down.sql` must `DROP INDEX` before
    /// `DROP COLUMN` — `SQLite` refuses to drop a column still used by an index
    /// (issue #1614).
    #[test]
    fn add_columns_migration_on_sqlite_drops_index_before_column_on_rollback() {
        with_no_db_env(|| {
            let tmp = sqlite_project();
            let plan = plan_migration(
                tmp.path(),
                "AddAuthorToPosts",
                &["author:references?".into()],
                "20260427000000",
            )
            .unwrap();
            plan.execute(Flags::default()).unwrap();
            let dir = tmp
                .path()
                .join("migrations/20260427000000_add_author_to_posts");
            let up = fs::read_to_string(dir.join("up.sql")).unwrap();
            assert!(
                up.contains("CREATE INDEX idx_posts_author_id ON posts (author_id);"),
                "up.sql: {up}"
            );
            let down = fs::read_to_string(dir.join("down.sql")).unwrap();
            let drop_idx = down
                .find("DROP INDEX idx_posts_author_id;")
                .expect("drop index");
            let drop_col = down
                .find("ALTER TABLE posts DROP COLUMN author_id;")
                .expect("drop column");
            assert!(
                drop_idx < drop_col,
                "down.sql must DROP INDEX before DROP COLUMN: {down}"
            );
        });
    }

    /// Issue #1906: a `Remove…From…` on `SQLite` must drop a PRE-EXISTING index
    /// that names the removed column, not just the conventional
    /// `idx_<table>_<col>` the generator itself would have created. `SQLite`
    /// refuses `DROP COLUMN` while any index still references the column, so a
    /// composite index from an earlier migration would otherwise break the
    /// migration at apply time.
    #[test]
    fn remove_columns_migration_on_sqlite_drops_a_pre_existing_composite_index() {
        with_no_db_env(|| {
            let tmp = sqlite_project();
            let earlier = tmp.path().join("migrations/20260101000000_create_posts");
            fs::create_dir_all(&earlier).unwrap();
            fs::write(
                earlier.join("up.sql"),
                "CREATE TABLE posts (id INTEGER PRIMARY KEY AUTOINCREMENT, \
                 author_id INTEGER, title TEXT);\n\
                 CREATE INDEX idx_posts_author_title ON posts (author_id, title);\n",
            )
            .unwrap();

            let plan = plan_migration(
                tmp.path(),
                "RemoveTitleFromPosts",
                &["title:Option<String>".into()],
                "20260427000000",
            )
            .unwrap();
            plan.execute(Flags::default()).unwrap();
            let dir = tmp
                .path()
                .join("migrations/20260427000000_remove_title_from_posts");

            let up = fs::read_to_string(dir.join("up.sql")).unwrap();
            let drop_idx = up
                .find("DROP INDEX IF EXISTS idx_posts_author_title;")
                .unwrap_or_else(|| panic!("composite index not dropped: {up}"));
            let drop_col = up
                .find("ALTER TABLE posts DROP COLUMN title;")
                .unwrap_or_else(|| panic!("column not dropped: {up}"));
            assert!(drop_idx < drop_col, "index drop must come first: {up}");

            // The rollback restores it, after the column is back.
            let down = fs::read_to_string(dir.join("down.sql")).unwrap();
            let add_col = down
                .find("ALTER TABLE posts ADD COLUMN title")
                .unwrap_or_else(|| panic!("column not re-added: {down}"));
            let recreate = down
                .find("CREATE INDEX idx_posts_author_title ON posts (author_id, title);")
                .unwrap_or_else(|| panic!("index not re-created: {down}"));
            assert!(add_col < recreate, "column must precede its index: {down}");
        });
    }

    /// Issue #2579: a column behind an inline `UNIQUE` cannot be dropped on
    /// `SQLite`. The generator says so now, not at apply time.
    #[test]
    fn remove_columns_migration_on_sqlite_rejects_an_inline_unique_column() {
        with_no_db_env(|| {
            let tmp = sqlite_project();
            let earlier = tmp.path().join("migrations/20260101000000_create_posts");
            fs::create_dir_all(&earlier).unwrap();
            fs::write(
                earlier.join("up.sql"),
                "CREATE TABLE posts (id INTEGER PRIMARY KEY, slug TEXT UNIQUE);\n",
            )
            .unwrap();

            let err = plan_migration(
                tmp.path(),
                "RemoveSlugFromPosts",
                &["slug:Option<String>".into()],
                "20260427000000",
            )
            .unwrap_err()
            .to_string();
            assert!(err.contains("posts.slug"), "got: {err}");
        });
    }

    /// Issue #2579: an earlier migration that does not replay stops the
    /// generator with the file name, instead of a guess.
    #[test]
    fn remove_columns_migration_on_sqlite_names_a_migration_that_does_not_replay() {
        with_no_db_env(|| {
            let tmp = sqlite_project();
            let earlier = tmp.path().join("migrations/20260101000000_broken");
            fs::create_dir_all(&earlier).unwrap();
            fs::write(earlier.join("up.sql"), "CREATE TABEL posts (id INTEGER);\n").unwrap();

            let err = plan_migration(
                tmp.path(),
                "RemoveTitleFromPosts",
                &["title:Option<String>".into()],
                "20260427000000",
            )
            .unwrap_err()
            .to_string();
            assert!(err.contains("20260101000000_broken"), "got: {err}");
        });
    }

    /// The same project shape on Postgres emits no explicit `DROP INDEX` — it
    /// cascades the drop with the column, so the output is unchanged by #1906.
    #[test]
    fn remove_columns_migration_on_postgres_ignores_pre_existing_indexes() {
        with_no_db_env(|| {
            let tmp = project();
            let earlier = tmp.path().join("migrations/20260101000000_create_posts");
            fs::create_dir_all(&earlier).unwrap();
            fs::write(
                earlier.join("up.sql"),
                "CREATE INDEX idx_posts_author_title ON posts (author_id, title);\n",
            )
            .unwrap();

            let plan = plan_migration(
                tmp.path(),
                "RemoveTitleFromPosts",
                &["title:Option<String>".into()],
                "20260427000000",
            )
            .unwrap();
            plan.execute(Flags::default()).unwrap();
            let dir = tmp
                .path()
                .join("migrations/20260427000000_remove_title_from_posts");
            let up = fs::read_to_string(dir.join("up.sql")).unwrap();
            let down = fs::read_to_string(dir.join("down.sql")).unwrap();
            assert!(!up.contains("DROP INDEX"), "Postgres up.sql: {up}");
            assert!(!down.contains("idx_posts_author_title"), "down.sql: {down}");
        });
    }

    /// Regression guard: the same `Add…To…` on a Postgres app emits no explicit
    /// `DROP INDEX` in `down.sql` — Postgres cascades the index drop with the
    /// column, so the rollback stays byte-for-byte the historical output.
    #[test]
    fn add_columns_migration_on_postgres_has_no_explicit_drop_index_on_rollback() {
        with_no_db_env(|| {
            let tmp = project();
            let plan = plan_migration(
                tmp.path(),
                "AddAuthorToPosts",
                &["author:references?".into()],
                "20260427000000",
            )
            .unwrap();
            plan.execute(Flags::default()).unwrap();
            let down = fs::read_to_string(
                tmp.path()
                    .join("migrations/20260427000000_add_author_to_posts/down.sql"),
            )
            .unwrap();
            assert!(!down.contains("DROP INDEX"), "Postgres down.sql: {down}");
            assert!(
                down.contains("ALTER TABLE posts DROP COLUMN author_id;"),
                "down.sql: {down}"
            );
        });
    }

    /// A `SQLite` `Add…To…` / `Remove…From…` migration now accepts every field
    /// kind: #1924 gave `Uuid`, `Decimal` and `Enum` working `SQLite`
    /// conversions, so the generate-time rejection no longer fires. All three
    /// store `TEXT`.
    ///
    /// Nullable columns here, deliberately: `SQLite`'s own `ALTER TABLE ADD
    /// COLUMN` rule still refuses a `NOT NULL` column with no default, which is
    /// a separate gate (#1918) this test must not trip over.
    #[test]
    fn column_migrations_on_sqlite_accept_uuid_decimal_and_enum_after_1924() {
        with_no_db_env(|| {
            for token in [
                "token:Option<Uuid>",
                "price:Option<decimal{10,2}>",
                "status:Option<enum{draft,published}>",
            ] {
                for name in ["AddTokenToPosts", "RemoveTokenFromPosts"] {
                    let tmp = sqlite_project();
                    let plan = plan_migration(tmp.path(), name, &[token.into()], "20260427000000")
                        .unwrap_or_else(|e| {
                            panic!("{name} with `{token}` must plan on SQLite (#1924): {e}")
                        });
                    let up = sql_action(&plan, "up.sql");
                    let down = sql_action(&plan, "down.sql");
                    for sql in [&up, &down] {
                        for leak in ["UUID", "NUMERIC"] {
                            assert!(
                                !sql.contains(leak),
                                "{name}/{token}: SQLite SQL leaked `{leak}`: {sql}"
                            );
                        }
                    }
                }
            }
        });
    }

    /// Regression guard: with no `autumn.toml`, the backend defaults to Postgres
    /// and `Add…To…` emits the historical Postgres column type.
    #[test]
    fn add_columns_migration_defaults_to_postgres_types() {
        with_no_db_env(|| {
            let tmp = project();
            let plan = plan_migration(
                tmp.path(),
                "AddViewsToPosts",
                &["views:i64".into()],
                "20260427000000",
            )
            .unwrap();
            plan.execute(Flags::default()).unwrap();
            let up = fs::read_to_string(
                tmp.path()
                    .join("migrations/20260427000000_add_views_to_posts/up.sql"),
            )
            .unwrap();
            assert!(
                up.contains("ALTER TABLE posts ADD COLUMN views BIGINT NOT NULL"),
                "up.sql: {up}"
            );
        });
    }

    /// `Remove…From…` on a `SQLite` app is rejected at generate time when the
    /// rollback would re-add a `NOT NULL` column with no default (issue #1614
    /// AC #4). The `down.sql` of a "remove columns" migration regenerates
    /// `ALTER TABLE … ADD COLUMN …` to restore the dropped column, and `SQLite`
    /// rejects that DDL for a `NOT NULL` column without a `DEFAULT` — the same
    /// limit the forward path guards
    /// (`add_columns_migration_on_sqlite_rejects_not_null_without_default`), so
    /// the reverse path must be consistent.
    #[test]
    fn remove_columns_migration_on_sqlite_rejects_not_null_re_add_on_rollback() {
        with_no_db_env(|| {
            let tmp = sqlite_project();
            let err = plan_migration(
                tmp.path(),
                "RemoveViewsFromPosts",
                &["views:i64".into()],
                "20260427000000",
            )
            .unwrap_err();
            let msg = err.to_string();
            assert!(
                matches!(err, GenerateError::Config(_)),
                "expected Config error, got: {err:?}"
            );
            assert!(
                msg.contains("NOT NULL") && msg.contains("views") && msg.contains("posts"),
                "message must name the column/table and the constraint: {msg}"
            );
            assert!(
                msg.contains("nullable") || msg.contains("default"),
                "message must be actionable (nullable / default): {msg}"
            );
        });
    }

    /// A *nullable* re-added column is restored without a default on `SQLite`,
    /// while the reject above guards the `NOT NULL` case — together they cover
    /// both branches of the `SQLite` rollback `ADD COLUMN` gate.
    #[test]
    fn remove_columns_migration_on_sqlite_allows_nullable_re_add_on_rollback() {
        with_no_db_env(|| {
            let tmp = sqlite_project();
            let plan = plan_migration(
                tmp.path(),
                "RemoveNoteFromPosts",
                &["note:Option<String>".into()],
                "20260427000000",
            )
            .unwrap();
            plan.execute(Flags::default()).unwrap();
            let down = fs::read_to_string(
                tmp.path()
                    .join("migrations/20260427000000_remove_note_from_posts/down.sql"),
            )
            .unwrap();
            assert!(
                down.contains("ALTER TABLE posts ADD COLUMN note TEXT NULL"),
                "down.sql: {down}"
            );
        });
    }

    /// Regression guard: with no `autumn.toml`, the backend defaults to Postgres
    /// and `Remove…From…`'s rollback re-adds the `NOT NULL` column with the
    /// historical Postgres column type — byte-for-byte unchanged by the
    /// `SQLite` reject above.
    #[test]
    fn remove_columns_migration_defaults_to_postgres_types_on_rollback() {
        with_no_db_env(|| {
            let tmp = project();
            let plan = plan_migration(
                tmp.path(),
                "RemoveViewsFromPosts",
                &["views:i64".into()],
                "20260427000000",
            )
            .unwrap();
            plan.execute(Flags::default()).unwrap();
            let down = fs::read_to_string(
                tmp.path()
                    .join("migrations/20260427000000_remove_views_from_posts/down.sql"),
            )
            .unwrap();
            assert!(
                down.contains("ALTER TABLE posts ADD COLUMN views BIGINT NOT NULL"),
                "down.sql: {down}"
            );
        });
    }

    // ── `plan_migration_destroy_fallback` (issue #1048 PR review) ───────────

    /// A project holding a `#[searchable]` `Post` model and the
    /// `AddSearchToPosts` migration generated from it, returned with the
    /// migration's directory. Shared by the three `destroy` fallback tests.
    fn searchable_post_with_migration() -> (TempDir, PathBuf) {
        let tmp = project();
        let models_dir = tmp.path().join("src/models");
        fs::create_dir_all(&models_dir).unwrap();
        fs::write(
            models_dir.join("post.rs"),
            r#"
#[autumn_web::model(table = "posts")]
#[searchable(language = "english")]
pub struct Post {
    #[id]
    pub id: i64,
    #[searchable(weight = "A")]
    pub title: String,
}
"#,
        )
        .unwrap();

        let plan = plan_migration(tmp.path(), "AddSearchToPosts", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let dir = tmp
            .path()
            .join("migrations/20260427000000_add_search_to_posts");
        assert!(dir.exists());
        (tmp, dir)
    }

    #[test]
    fn destroy_add_search_migration_after_model_already_destroyed_still_removes_it() {
        // A common cleanup order — destroying the model before destroying
        // an `AddSearchTo<Table>` migration that depended on its
        // `#[searchable]` config — must not strand the migration directory
        // just because `plan_migration_with_options` can no longer read it.
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                ("AUTUMN_DATABASE__URL", None::<&str>),
                ("DATABASE_URL", None::<&str>),
            ],
            || {
                let (tmp, dir) = searchable_post_with_migration();
                // Simulate `autumn destroy model Post` having already run.
                fs::remove_file(tmp.path().join("src/models/post.rs")).unwrap();
                assert!(
                    plan_migration(tmp.path(), "AddSearchToPosts", &[], "99999999999999").is_err()
                );

                let fallback_plan = plan_migration_destroy_fallback(
                    tmp.path(),
                    "AddSearchToPosts",
                    "99999999999999",
                )
                .unwrap();
                // The fallback plan cannot reproduce the SQL — the search
                // config is gone — but the digest `generate` recorded still
                // proves the files are its own untouched output, so no
                // --force is needed (issue #1835).
                fallback_plan.revert(Flags::default()).unwrap();
                assert!(!dir.exists());
            },
        );
    }

    #[test]
    fn destroy_add_search_migration_still_refuses_hand_edited_sql() {
        // The #1048 guard under the #1835 code path: the recorded digest makes
        // the fallback plan usable, and an edit still has to break it.
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                ("AUTUMN_DATABASE__URL", None::<&str>),
                ("DATABASE_URL", None::<&str>),
            ],
            || {
                let (tmp, dir) = searchable_post_with_migration();
                fs::remove_file(tmp.path().join("src/models/post.rs")).unwrap();
                fs::write(dir.join("up.sql"), "-- my own SQL\n").unwrap();

                let err = plan_migration_destroy_fallback(
                    tmp.path(),
                    "AddSearchToPosts",
                    "99999999999999",
                )
                .unwrap()
                .revert(Flags::default())
                .unwrap_err();

                assert!(matches!(err, GenerateError::Diverged(_)));
                assert!(dir.exists());
            },
        );
    }

    #[test]
    fn destroy_add_search_migration_without_provenance_still_needs_force() {
        // The pre-#1835 path, still taken by a project generated before the
        // manifest existed: nothing was recorded and the search config is
        // gone, so the SQL is unverifiable and the directory is left alone.
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                ("AUTUMN_DATABASE__URL", None::<&str>),
                ("DATABASE_URL", None::<&str>),
            ],
            || {
                let (tmp, dir) = searchable_post_with_migration();
                fs::remove_file(tmp.path().join("src/models/post.rs")).unwrap();
                fs::remove_file(tmp.path().join(crate::generate::provenance::MANIFEST_PATH))
                    .unwrap();

                let err = plan_migration_destroy_fallback(
                    tmp.path(),
                    "AddSearchToPosts",
                    "99999999999999",
                )
                .unwrap()
                .revert(Flags::default())
                .unwrap_err();
                assert!(matches!(err, GenerateError::Diverged(_)));
                assert!(dir.exists());

                plan_migration_destroy_fallback(tmp.path(), "AddSearchToPosts", "99999999999999")
                    .unwrap()
                    .revert(Flags {
                        dry_run: false,
                        force: true,
                    })
                    .unwrap();
                assert!(!dir.exists());
            },
        );
    }

    #[test]
    fn plan_migration_destroy_fallback_fails_outside_project() {
        let tmp = TempDir::new().unwrap();
        let err = plan_migration_destroy_fallback(tmp.path(), "AddSearchToPosts", "20260427000000")
            .unwrap_err();
        assert!(matches!(err, GenerateError::NotInProject));
    }

    // ── references field: parity with `generate model` (issue #1026) ───────

    #[test]
    fn add_columns_with_references_field_emits_fk_and_index() {
        let tmp = project();
        let plan = plan_migration(
            tmp.path(),
            "AddPostToComments",
            &["post:references".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_add_post_to_comments/up.sql"),
        )
        .unwrap();
        assert!(up.contains("post_id BIGINT NOT NULL REFERENCES posts(id)"));
        assert!(up.contains("CREATE INDEX idx_comments_post_id ON comments (post_id);"));
    }

    #[test]
    fn add_columns_with_references_field_warns_when_target_model_missing() {
        let tmp = project();
        let plan = plan_migration(
            tmp.path(),
            "AddPostToComments",
            &["post:references".into()],
            "20260427000000",
        )
        .unwrap();
        assert_eq!(plan.warnings.len(), 1, "warnings: {:?}", plan.warnings);
        assert!(plan.warnings[0].contains("posts"));
    }

    #[test]
    fn add_columns_with_references_field_errors_on_uuid_target() {
        let tmp = project();
        let models_dir = tmp.path().join("src/models");
        fs::create_dir_all(&models_dir).unwrap();
        fs::write(
            models_dir.join("post.rs"),
            "#[autumn_web::model]\npub struct Post {\n    #[id]\n    pub id: uuid::Uuid,\n}\n",
        )
        .unwrap();

        let err = plan_migration(
            tmp.path(),
            "AddPostToComments",
            &["post:references".into()],
            "20260427000000",
        )
        .unwrap_err();
        assert!(err.to_string().contains("UUID"));
    }

    #[test]
    fn add_columns_self_reference_to_table_being_altered_has_no_warning() {
        // `AddCategoryToCategories category:references` targets the very
        // table it's altering — a filesystem lookup for a "Category" model
        // is irrelevant here (the table obviously already exists, that's
        // the point of ALTER TABLE), so no "model not found" warning should
        // fire for the self-reference.
        let tmp = project();
        let plan = plan_migration(
            tmp.path(),
            "AddCategoryToCategories",
            &["category:references".into()],
            "20260427000000",
        )
        .unwrap();
        assert!(plan.warnings.is_empty(), "warnings: {:?}", plan.warnings);
    }

    #[test]
    fn add_columns_self_reference_errors_when_existing_model_has_uuid_pk() {
        // Unlike `generate model`, `generate migration Add…To…` alters an
        // EXISTING table — if that table's own model file is on disk and
        // declares a UUID primary key, the self-reference must still be
        // caught (it's not "unknown PK type, can't check", it's "known PK
        // type, from the file the caller didn't think to look at").
        let tmp = project();
        let models_dir = tmp.path().join("src/models");
        fs::create_dir_all(&models_dir).unwrap();
        fs::write(
            models_dir.join("category.rs"),
            "#[autumn_web::model]\npub struct Category {\n    #[id]\n    pub id: uuid::Uuid,\n}\n",
        )
        .unwrap();

        let err = plan_migration(
            tmp.path(),
            "AddCategoryToCategories",
            &["category:references".into()],
            "20260427000000",
        )
        .unwrap_err();
        assert!(err.to_string().contains("UUID"));
        assert!(err.to_string().contains("self-referential"));
    }

    // ── optimistic locking (issue #1318) ────────────────────────────────────

    /// The contents of the planned `up.sql`/`down.sql` action.
    fn sql_action(plan: &Plan, file: &str) -> String {
        plan.actions
            .iter()
            .find(|a| a.path().file_name().is_some_and(|n| n == file))
            .map_or_else(
                || panic!("no {file} action"),
                |a| match a {
                    Action::Create { contents, .. } | Action::Modify { contents, .. } => {
                        contents.clone()
                    }
                    _ => String::new(),
                },
            )
    }

    #[test]
    fn adding_a_lock_version_column_carries_the_default_that_makes_it_usable() {
        // The retrofit path — "add optimistic locking to a resource I already
        // shipped" — is how this column normally arrives. `#[lock_version]`
        // keeps it out of `New{Model}`, so a bare NOT NULL add would leave
        // every later insert failing; the DEFAULT also backfills existing rows.
        let tmp = project();
        let plan = plan_migration(
            tmp.path(),
            "AddLockVersionToPosts",
            &["lock_version:i32".into()],
            "20260427000000",
        )
        .unwrap();
        let up = sql_action(&plan, "up.sql");
        assert!(
            up.contains("ADD COLUMN lock_version INTEGER NOT NULL DEFAULT 0;"),
            "up.sql:\n{up}"
        );
    }

    #[test]
    fn adding_a_lock_version_column_of_the_wrong_type_is_rejected() {
        // Same DSL token, same feedback as `generate model`/`generate scaffold`
        // — otherwise the diagnosis depends only on which subcommand you typed.
        let tmp = project();
        let err = plan_migration(
            tmp.path(),
            "AddLockVersionToPosts",
            &["lock_version:String".into()],
            "20260427000000",
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("lock_version") && msg.contains("i32"),
            "got: {msg}"
        );
    }

    #[test]
    fn removing_a_legacy_lock_version_column_is_never_type_checked() {
        // Dropping a pre-existing ordinary `lock_version` is exactly the escape
        // hatch the other error messages point at, and the rollback re-adds the
        // column with the type the caller supplied. Applying the optimistic-lock
        // type restriction to a REMOVE migration would block it.
        let tmp = project();
        let plan = plan_migration(
            tmp.path(),
            "RemoveLockVersionFromPosts",
            &["lock_version:String".into()],
            "20260427000000",
        )
        .expect("a removal migration must not be type-checked as a lock version");
        let down = sql_action(&plan, "down.sql");
        assert!(
            down.contains("ADD COLUMN lock_version TEXT"),
            "the rollback must restore the caller's original type:\n{down}"
        );
    }

    // ── `{encrypted}` is not a `generate migration` token (issue #1340) ─────

    /// R8: `generate migration` emits SQL only — it never touches a model
    /// file — so accepting `{encrypted}` here would add a plaintext column
    /// while the developer believes they declared encryption. That is exactly
    /// the silent failure issue #1340 exists to close, so refuse and name the
    /// two commands that really do wire the attribute.
    #[test]
    fn add_columns_migration_rejects_the_encrypted_modifier() {
        let tmp = project();
        let err = plan_migration(
            tmp.path(),
            "AddApiTokenToAccounts",
            &["api_token:String{encrypted}".into()],
            "20260427000000",
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("encrypted"), "must name the modifier: {msg}");
        assert!(
            msg.contains("generate model") || msg.contains("generate scaffold"),
            "must point at the commands that emit the attribute: {msg}"
        );
        assert!(
            msg.contains("EncryptApiTokenOnAccounts") || msg.contains("Encrypt"),
            "must point at the existing encrypt-columns migration shape: {msg}"
        );
    }

    /// The pre-existing `Encrypt<Column>On<Table>` shape is unaffected — it
    /// takes no field tokens and stays the supported way to convert an
    /// existing plaintext column.
    #[test]
    fn encrypt_columns_migration_shape_still_works() {
        let tmp = project();
        let plan = plan_migration(
            tmp.path(),
            "EncryptApiTokenOnAccounts",
            &[],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_encrypt_api_token_on_accounts/up.sql"),
        )
        .unwrap();
        assert!(up.contains("api_token"), "up.sql: {up}");
    }
}