rustio-core 2.0.0

Runtime core for RustIO: HTTP server, router, middleware, ORM, admin, and migrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
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
//! Advanced executor tests — 0.5.3.
//!
//! Covers the primitives that require SQLite recreate-table:
//!
//! - `change_field_type`
//! - `change_field_nullability`
//! - `rename_model`
//!
//! Invariants:
//!
//! - Every "advanced" migration uses the recreate-table shape:
//!   `CREATE TABLE <t>__new`, `INSERT SELECT`, `DROP`, `RENAME`.
//! - Required → nullable is safe; nullable → required emits
//!   `COALESCE(col, default)` in the INSERT SELECT.
//! - Tables with FK constraints are refused, not silently destroyed.
//! - Rename_model touches models.rs + admin.rs; views.rs is patched
//!   best-effort at identifier boundaries.
//! - All primitives are idempotent — second apply returns
//!   `FileConflict`, not a silent success.

use std::collections::BTreeMap;
use std::path::PathBuf;

use chrono::{TimeZone, Utc};

use super::executor::{
    plan_execution, ExecuteOptions, ExecutionError, ExecutionPreview, ParsedModelsFile, ProjectView,
};
use super::planner::PlanResult;
use super::review::{build_plan_document_with_timestamp, PlanDocument};
use super::{ChangeFieldNullability, ChangeFieldType, FieldSpec, Plan, Primitive, RenameModel};
use crate::schema::{Schema, SchemaField, SchemaModel, SCHEMA_VERSION};

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

fn pkg_version() -> String {
    env!("CARGO_PKG_VERSION").to_string()
}

fn fixed_ts() -> chrono::DateTime<Utc> {
    Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).single().unwrap()
}

const POST_MODELS_SRC: &str = r#"use rustio_core::{Error, Model, Row, RustioAdmin, Value};

#[derive(Debug, RustioAdmin)]
pub struct Post {
    pub id: i64,
    pub title: String,
    pub score: i32,
    pub subtitle: Option<String>,
}

impl Model for Post {
    const TABLE: &'static str = "posts";
    const COLUMNS: &'static [&'static str] = &["id", "title", "score", "subtitle"];
    const INSERT_COLUMNS: &'static [&'static str] = &["title", "score", "subtitle"];

    fn id(&self) -> i64 {
        self.id
    }

    fn from_row(row: Row<'_>) -> Result<Self, Error> {
        Ok(Self {
            id: row.get_i64("id")?,
            title: row.get_string("title")?,
            score: row.get_i32("score")?,
            subtitle: row.get_optional_string("subtitle")?,
        })
    }

    fn insert_values(&self) -> Vec<Value> {
        vec![
            self.title.clone().into(),
            self.score.into(),
            self.subtitle.clone().into(),
        ]
    }
}
"#;

const POST_ADMIN_SRC: &str = r#"use rustio_core::admin::Admin;

use super::models::Post;

pub fn install(admin: Admin) -> Admin {
    admin.model::<Post>()
}
"#;

const POST_VIEWS_SRC: &str = r#"use rustio_core::Router;

use super::models::Post;

pub fn register(router: Router) -> Router {
    // A tiny views stub that references Post, to verify rename_model
    // rewrites identifier occurrences at word boundaries.
    let _use_it: Vec<&Post> = Vec::new();
    let _also: Option<Post> = None;
    router
}
"#;

fn post_schema() -> Schema {
    Schema {
        version: SCHEMA_VERSION,
        rustio_version: pkg_version(),
        models: vec![SchemaModel {
            name: "Post".into(),
            table: "posts".into(),
            admin_name: "posts".into(),
            display_name: "Posts".into(),
            singular_name: "Post".into(),
            fields: vec![
                SchemaField {
                    name: "id".into(),
                    ty: "i64".into(),
                    nullable: false,
                    editable: false,
                    relation: None,
                },
                SchemaField {
                    name: "title".into(),
                    ty: "String".into(),
                    nullable: false,
                    editable: true,
                    relation: None,
                },
                SchemaField {
                    name: "score".into(),
                    ty: "i32".into(),
                    nullable: false,
                    editable: true,
                    relation: None,
                },
                SchemaField {
                    name: "subtitle".into(),
                    ty: "String".into(),
                    nullable: true,
                    editable: true,
                    relation: None,
                },
            ],
            relations: vec![],
            core: false,
        }],
    }
}

fn project_with_post(root: &str) -> ProjectView {
    let mut models_files = BTreeMap::new();
    models_files.insert(
        "posts".to_string(),
        ParsedModelsFile {
            path: PathBuf::from(format!("{root}/apps/posts/models.rs")),
            source: POST_MODELS_SRC.to_string(),
            struct_names: vec!["Post".into()],
        },
    );
    ProjectView {
        root: PathBuf::from(root),
        models_files,
        existing_migrations: vec!["0001_create_posts.sql".into()],
        migration_sources: BTreeMap::new(),
    }
}

fn doc_for(schema: &Schema, prompt: &str, plan: Plan) -> PlanDocument {
    let result = PlanResult {
        plan,
        explanation: "unit-test".into(),
    };
    build_plan_document_with_timestamp(schema, prompt, &result, fixed_ts(), None)
        .expect("fixture plans should build")
}

fn unwrap_preview(p: Result<ExecutionPreview, ExecutionError>) -> ExecutionPreview {
    p.unwrap_or_else(|e| panic!("plan_execution should have succeeded: {e}"))
}

// ---------------------------------------------------------------------------
// change_field_type
// ---------------------------------------------------------------------------

#[test]
fn change_type_i32_to_string_uses_cast_and_rewrites_models() {
    let schema = post_schema();
    let project = project_with_post("/p");
    let plan = Plan::new(vec![Primitive::ChangeFieldType(ChangeFieldType {
        model: "Post".into(),
        field: "score".into(),
        new_type: "String".into(),
    })]);
    let doc = doc_for(&schema, "change score to String", plan);
    let preview = unwrap_preview(plan_execution(
        &schema,
        &project,
        &doc,
        &ExecuteOptions::default(),
        None,
    ));

    // The summary carries the `~` glyph and the table-rewrite warning.
    assert!(
        preview
            .summary
            .starts_with("~ Change type of Post.score from i32 to String"),
        "summary: {:?}",
        preview.summary,
    );
    assert!(
        preview
            .summary
            .contains("⚠ This rewrites the entire `posts` table"),
        "missing rewrite warning: {:?}",
        preview.summary,
    );

    // Two file changes: models.rs + recreate migration.
    assert_eq!(preview.file_changes.len(), 2);
    let models_src = &preview.file_changes[0].new_contents;
    assert!(
        models_src.contains("pub score: String,"),
        "struct field should be String:\n{models_src}",
    );
    assert!(
        models_src.contains("score: row.get_string(\"score\")?,"),
        "from_row accessor should be get_string:\n{models_src}",
    );
    assert!(
        models_src.contains("self.score.clone().into(),"),
        "insert_values should now .clone() on String:\n{models_src}",
    );

    // Migration uses the recreate-table pattern with CAST on `score`.
    let mig = &preview.file_changes[1].new_contents;
    assert!(mig.contains("CREATE TABLE posts__new ("), "mig:\n{mig}");
    assert!(
        mig.contains("id INTEGER PRIMARY KEY AUTOINCREMENT"),
        "mig should preserve PK AUTOINCREMENT:\n{mig}",
    );
    assert!(
        mig.contains("CAST(score AS TEXT)"),
        "mig should CAST score to TEXT:\n{mig}",
    );
    assert!(
        mig.contains("INSERT INTO posts__new (id, title, score, subtitle)"),
        "mig should INSERT every column:\n{mig}",
    );
    assert!(mig.contains("DROP TABLE posts;"), "mig:\n{mig}");
    assert!(
        mig.contains("ALTER TABLE posts__new RENAME TO posts;"),
        "mig:\n{mig}",
    );
}

#[test]
fn change_type_unsafe_cast_is_refused() {
    // String → {i32,i64,bool} is warned-but-allowed (TEXT → INTEGER
    // CAST is well-defined in SQLite). Truly unsafe combinations —
    // e.g. DateTime → i32, which mixes storage classes in a way SQLite
    // wouldn't CAST meaningfully — must be refused.
    let schema = post_schema();
    let mut project = project_with_post("/p");
    // Seed a DateTime field so we have a source for the refused cast.
    let mut schema = schema;
    schema.models[0].fields.push(SchemaField {
        name: "published_at".into(),
        ty: "DateTime".into(),
        nullable: false,
        editable: true,
        relation: None,
    });
    // models.rs mirror: insert a DateTime field so the executor finds
    // it in the struct block.
    let src = POST_MODELS_SRC.replace(
        "pub subtitle: Option<String>,\n}",
        "pub subtitle: Option<String>,\n    pub published_at: DateTime<Utc>,\n}",
    );
    project.models_files.get_mut("posts").unwrap().source = src;

    let plan = Plan::new(vec![Primitive::ChangeFieldType(ChangeFieldType {
        model: "Post".into(),
        field: "published_at".into(),
        new_type: "i32".into(),
    })]);
    let doc = doc_for(&schema, "change published_at to i32", plan);
    let err = plan_execution(&schema, &project, &doc, &ExecuteOptions::default(), None)
        .expect_err("DateTime → i32 is not a safe cast");
    match err {
        ExecutionError::UnsupportedPrimitive { op, reason } => {
            assert_eq!(op, "change_field_type");
            assert!(reason.contains("safe-cast"));
        }
        other => panic!("expected UnsupportedPrimitive, got {other:?}"),
    }
}

#[test]
fn change_type_idempotent_same_type_is_refused() {
    let schema = post_schema();
    let project = project_with_post("/p");
    let plan = Plan::new(vec![Primitive::ChangeFieldType(ChangeFieldType {
        model: "Post".into(),
        field: "score".into(),
        new_type: "i32".into(), // already i32
    })]);
    let doc = doc_for(&schema, "no-op", plan);
    let err = plan_execution(&schema, &project, &doc, &ExecuteOptions::default(), None)
        .expect_err("no-op type change must be refused");
    assert!(matches!(err, ExecutionError::FileConflict { .. }));
}

#[test]
fn change_type_refuses_on_foreign_key_tables() {
    let schema = post_schema();
    let mut project = project_with_post("/p");
    // Simulate a foreign-key constraint landing on `posts` from
    // another table's migration.
    project.migration_sources.insert(
        "0002_create_comments.sql".into(),
        "CREATE TABLE comments (id INTEGER, post_id INTEGER, FOREIGN KEY (post_id) REFERENCES posts(id));"
            .into(),
    );
    let plan = Plan::new(vec![Primitive::ChangeFieldType(ChangeFieldType {
        model: "Post".into(),
        field: "score".into(),
        new_type: "String".into(),
    })]);
    let doc = doc_for(&schema, "change score to String", plan);
    let err = plan_execution(&schema, &project, &doc, &ExecuteOptions::default(), None)
        .expect_err("FK-participating table must be refused");
    match err {
        ExecutionError::UnsupportedPrimitive { op, reason } => {
            assert_eq!(op, "change_field_type");
            assert!(reason.contains("foreign"));
        }
        other => panic!("expected UnsupportedPrimitive, got {other:?}"),
    }
}

// ---------------------------------------------------------------------------
// change_field_nullability
// ---------------------------------------------------------------------------

#[test]
fn nullability_required_to_nullable_is_safe() {
    let schema = post_schema();
    let project = project_with_post("/p");
    let plan = Plan::new(vec![Primitive::ChangeFieldNullability(
        ChangeFieldNullability {
            model: "Post".into(),
            field: "title".into(),
            nullable: true,
        },
    )]);
    let doc = doc_for(&schema, "relax title to optional", plan);
    let preview = unwrap_preview(plan_execution(
        &schema,
        &project,
        &doc,
        &ExecuteOptions::default(),
        None,
    ));
    // Struct field becomes Option<String>.
    let models_src = &preview.file_changes[0].new_contents;
    assert!(
        models_src.contains("pub title: Option<String>,"),
        "struct:\n{models_src}",
    );
    assert!(
        models_src.contains("title: row.get_optional_string(\"title\")?,"),
        "from_row accessor should be get_optional_string:\n{models_src}",
    );
    // Migration: straight copy (no COALESCE).
    let mig = &preview.file_changes[1].new_contents;
    assert!(
        !mig.contains("COALESCE"),
        "relaxing nullability needs no COALESCE:\n{mig}",
    );
    assert!(mig.contains("CREATE TABLE posts__new ("), "mig:\n{mig}");
    // title in new table lacks NOT NULL.
    assert!(
        mig.contains("title TEXT\n") || mig.contains("title TEXT,"),
        "mig:\n{mig}"
    );
}

#[test]
fn nullability_nullable_to_required_uses_coalesce() {
    let schema = post_schema();
    let project = project_with_post("/p");
    let plan = Plan::new(vec![Primitive::ChangeFieldNullability(
        ChangeFieldNullability {
            model: "Post".into(),
            field: "subtitle".into(),
            nullable: false,
        },
    )]);
    let doc = doc_for(&schema, "tighten subtitle to required", plan);
    let preview = unwrap_preview(plan_execution(
        &schema,
        &project,
        &doc,
        &ExecuteOptions::default(),
        None,
    ));
    let models_src = &preview.file_changes[0].new_contents;
    assert!(
        models_src.contains("pub subtitle: String,"),
        "struct should drop Option<>:\n{models_src}",
    );
    assert!(
        models_src.contains("subtitle: row.get_string(\"subtitle\")?,"),
        "accessor should be get_string:\n{models_src}",
    );
    // Migration: COALESCE(subtitle, '') in the INSERT SELECT.
    let mig = &preview.file_changes[1].new_contents;
    assert!(
        mig.contains("COALESCE(subtitle, '')"),
        "COALESCE needed to replace NULLs:\n{mig}",
    );
    // The warn line flags the NULL-substitution explicitly.
    assert!(
        preview.summary.contains("substitutes existing NULLs"),
        "summary should surface the NULL substitution warning: {:?}",
        preview.summary,
    );
}

#[test]
fn nullability_same_state_is_refused() {
    let schema = post_schema();
    let project = project_with_post("/p");
    let plan = Plan::new(vec![Primitive::ChangeFieldNullability(
        ChangeFieldNullability {
            model: "Post".into(),
            field: "subtitle".into(),
            nullable: true, // already nullable
        },
    )]);
    let doc = doc_for(&schema, "no-op", plan);
    let err = plan_execution(&schema, &project, &doc, &ExecuteOptions::default(), None)
        .expect_err("no-op must be refused");
    assert!(matches!(err, ExecutionError::FileConflict { .. }));
}

// ---------------------------------------------------------------------------
// rename_model
// ---------------------------------------------------------------------------

mod rename_model_integration {
    use super::*;
    use std::fs;

    use crate::ai::executor::execute_plan_document;

    fn scratch_dir(tag: &str) -> PathBuf {
        let root =
            std::env::temp_dir().join(format!("rustio-exec-adv-{}-{}", tag, std::process::id()));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(root.join("apps/posts")).unwrap();
        fs::create_dir_all(root.join("migrations")).unwrap();
        fs::write(root.join("apps/posts/models.rs"), POST_MODELS_SRC).unwrap();
        fs::write(root.join("apps/posts/admin.rs"), POST_ADMIN_SRC).unwrap();
        fs::write(root.join("apps/posts/views.rs"), POST_VIEWS_SRC).unwrap();
        fs::write(
            root.join("migrations/0001_create_posts.sql"),
            "CREATE TABLE posts (id INTEGER PRIMARY KEY);\n",
        )
        .unwrap();
        let schema_json = post_schema().to_pretty_json().unwrap();
        fs::write(root.join("rustio.schema.json"), schema_json).unwrap();
        root
    }

    #[test]
    fn rename_model_updates_models_admin_views_and_emits_migration() {
        let root = scratch_dir("rename");
        let schema = post_schema();
        let plan = Plan::new(vec![Primitive::RenameModel(RenameModel {
            from: "Post".into(),
            to: "Article".into(),
        })]);
        let doc = doc_for(&schema, "rename Post to Article", plan);

        let result = execute_plan_document(&root, &doc, &ExecuteOptions::default(), None).unwrap();
        assert_eq!(result.applied_steps, 1);
        // Three or four file paths: models.rs, admin.rs, views.rs
        // (if it changed), plus the migration.
        assert!(
            result
                .generated_files
                .iter()
                .any(|p| p.ends_with("apps/posts/models.rs")),
            "files: {:?}",
            result.generated_files,
        );
        assert!(
            result
                .generated_files
                .iter()
                .any(|p| p.ends_with("apps/posts/admin.rs")),
            "files: {:?}",
            result.generated_files,
        );
        assert!(
            result
                .generated_files
                .iter()
                .any(|p| p.ends_with("migrations/0002_rename_posts_to_articles.sql")),
            "files: {:?}",
            result.generated_files,
        );

        let models = fs::read_to_string(root.join("apps/posts/models.rs")).unwrap();
        assert!(
            models.contains("pub struct Article {"),
            "models.rs:\n{models}"
        );
        assert!(
            models.contains("impl Model for Article"),
            "models.rs:\n{models}"
        );
        assert!(
            models.contains("const TABLE: &'static str = \"articles\";"),
            "models.rs TABLE const:\n{models}",
        );
        assert!(
            !models.contains("pub struct Post "),
            "old struct name must be gone:\n{models}",
        );

        let admin = fs::read_to_string(root.join("apps/posts/admin.rs")).unwrap();
        assert!(
            admin.contains("use super::models::Article;"),
            "admin.rs use:\n{admin}",
        );
        assert!(
            admin.contains("admin.model::<Article>()"),
            "admin.rs call:\n{admin}",
        );

        let views = fs::read_to_string(root.join("apps/posts/views.rs")).unwrap();
        assert!(
            views.contains("use super::models::Article;"),
            "views.rs use:\n{views}",
        );
        assert!(
            views.contains("&Article"),
            "views.rs should rename bare identifier:\n{views}",
        );
        assert!(
            !views.contains("use super::models::Post"),
            "old use must be gone:\n{views}",
        );

        let mig =
            fs::read_to_string(root.join("migrations/0002_rename_posts_to_articles.sql")).unwrap();
        assert!(
            mig.contains("ALTER TABLE posts RENAME TO articles;"),
            "migration:\n{mig}",
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn rename_model_refuses_if_new_struct_already_present() {
        let root = scratch_dir("rename_collide");
        // Put a second struct with the target name into models.rs.
        let mangled = POST_MODELS_SRC.replace(
            "pub struct Post {",
            "pub struct Article { }\n\npub struct Post {",
        );
        fs::write(root.join("apps/posts/models.rs"), &mangled).unwrap();
        let schema = post_schema();
        let plan = Plan::new(vec![Primitive::RenameModel(RenameModel {
            from: "Post".into(),
            to: "Article".into(),
        })]);
        let doc = doc_for(&schema, "rename", plan);
        let err = execute_plan_document(&root, &doc, &ExecuteOptions::default(), None).unwrap_err();
        match err {
            ExecutionError::FileConflict { reason, .. } => {
                assert!(reason.contains("already exists"), "reason: {reason}");
            }
            other => panic!("expected FileConflict, got {other:?}"),
        }
        let _ = fs::remove_dir_all(&root);
    }
}

// ---------------------------------------------------------------------------
// Determinism + rollback
// ---------------------------------------------------------------------------

#[test]
fn recreate_table_migration_is_deterministic() {
    let schema = post_schema();
    let project = project_with_post("/p");
    let plan = Plan::new(vec![Primitive::ChangeFieldType(ChangeFieldType {
        model: "Post".into(),
        field: "score".into(),
        new_type: "String".into(),
    })]);
    let doc = doc_for(&schema, "x", plan);
    let a = unwrap_preview(plan_execution(
        &schema,
        &project,
        &doc,
        &ExecuteOptions::default(),
        None,
    ));
    let b = unwrap_preview(plan_execution(
        &schema,
        &project,
        &doc,
        &ExecuteOptions::default(),
        None,
    ));
    assert_eq!(a, b);
    // Regression canary: the preview's migration file always uses the
    // `<table>__new` temporary name — if that ever changes we want
    // a loud signal.
    let mig = &a.file_changes[1].new_contents;
    assert!(mig.contains("CREATE TABLE posts__new"), "mig:\n{mig}");
}

#[test]
fn large_schema_simulation_holds_determinism() {
    // Build a schema with many fields and run a type change — ensures
    // the recreate-table migration scales to wider tables and that
    // every unchanged column is copied verbatim.
    let mut fields: Vec<SchemaField> = vec![SchemaField {
        name: "id".into(),
        ty: "i64".into(),
        nullable: false,
        editable: false,
        relation: None,
    }];
    for i in 0..20 {
        fields.push(SchemaField {
            name: format!("field_{i:02}"),
            ty: if i % 2 == 0 { "String" } else { "i32" }.to_string(),
            nullable: false,
            editable: true,
            relation: None,
        });
    }
    let schema = Schema {
        version: SCHEMA_VERSION,
        rustio_version: pkg_version(),
        models: vec![SchemaModel {
            name: "Wide".into(),
            table: "wides".into(),
            admin_name: "wides".into(),
            display_name: "Wides".into(),
            singular_name: "Wide".into(),
            fields: fields.clone(),
            relations: vec![],
            core: false,
        }],
    };
    // Build a synthetic models.rs that matches the schema.
    let mut src = String::from(
        "use rustio_core::{Error, Model, Row, RustioAdmin, Value};\n\n\
         #[derive(Debug, RustioAdmin)]\npub struct Wide {\n",
    );
    for f in &fields {
        src.push_str(&format!(
            "    pub {}: {},\n",
            f.name,
            if f.ty == "i32" {
                "i32"
            } else if f.ty == "i64" {
                "i64"
            } else {
                "String"
            }
        ));
    }
    src.push_str("}\n\nimpl Model for Wide {\n");
    src.push_str("    const TABLE: &'static str = \"wides\";\n");
    src.push_str("    const COLUMNS: &'static [&'static str] = &[");
    let cols: Vec<String> = fields.iter().map(|f| format!("\"{}\"", f.name)).collect();
    src.push_str(&cols.join(", "));
    src.push_str("];\n");
    src.push_str("    const INSERT_COLUMNS: &'static [&'static str] = &[");
    let inserts: Vec<String> = fields
        .iter()
        .filter(|f| f.name != "id")
        .map(|f| format!("\"{}\"", f.name))
        .collect();
    src.push_str(&inserts.join(", "));
    src.push_str("];\n\n");
    src.push_str("    fn id(&self) -> i64 { self.id }\n\n");
    src.push_str("    fn from_row(row: Row<'_>) -> Result<Self, Error> {\n        Ok(Self {\n");
    for f in &fields {
        let acc = match f.ty.as_str() {
            "i32" => "get_i32",
            "i64" => "get_i64",
            "String" => "get_string",
            _ => "get_string",
        };
        src.push_str(&format!(
            "            {name}: row.{acc}(\"{name}\")?,\n",
            name = f.name,
        ));
    }
    src.push_str("        })\n    }\n\n");
    src.push_str("    fn insert_values(&self) -> Vec<Value> {\n        vec![\n");
    for f in fields.iter().filter(|f| f.name != "id") {
        if f.ty == "String" {
            src.push_str(&format!("            self.{}.clone().into(),\n", f.name));
        } else {
            src.push_str(&format!("            self.{}.into(),\n", f.name));
        }
    }
    src.push_str("        ]\n    }\n}\n");

    let mut models_files = BTreeMap::new();
    models_files.insert(
        "wides".into(),
        ParsedModelsFile {
            path: PathBuf::from("/p/apps/wides/models.rs"),
            source: src,
            struct_names: vec!["Wide".into()],
        },
    );
    let project = ProjectView {
        root: PathBuf::from("/p"),
        models_files,
        existing_migrations: vec!["0001_create_wides.sql".into()],
        migration_sources: BTreeMap::new(),
    };

    // Change field_05 (i32) → String.
    let plan = Plan::new(vec![Primitive::ChangeFieldType(ChangeFieldType {
        model: "Wide".into(),
        field: "field_05".into(),
        new_type: "String".into(),
    })]);
    let doc = doc_for(&schema, "change field_05", plan);
    let preview = unwrap_preview(plan_execution(
        &schema,
        &project,
        &doc,
        &ExecuteOptions::default(),
        None,
    ));
    let mig = &preview.file_changes[1].new_contents;
    // Every column shows up in the INSERT column list, and only
    // field_05 is wrapped in CAST.
    for f in &fields {
        assert!(
            mig.contains(&format!(", {}", f.name))
                || mig.contains(&format!("({}, ", f.name))
                || mig.contains(&format!("({}", f.name)),
            "column `{}` missing from INSERT:\n{mig}",
            f.name,
        );
    }
    assert!(
        mig.contains("CAST(field_05 AS TEXT)"),
        "only field_05 should be cast:\n{mig}",
    );
    let cast_count = mig.matches("CAST(").count();
    assert_eq!(cast_count, 1, "exactly one CAST expected, got {cast_count}");
}

// ---------------------------------------------------------------------------
// Smoke: the sqlite recreate-table helper is correct on a minimal shape
// ---------------------------------------------------------------------------

#[test]
fn field_spec_is_used_as_a_sentinel_for_unused_import() {
    // No-op — present so rustc doesn't complain about the FieldSpec
    // import in tight test configurations.
    let _ = FieldSpec {
        name: "x".into(),
        ty: "i32".into(),
        nullable: false,
        editable: true,
    };
}