rustio-admin-cli 0.23.0

Command-line tools for rustio-admin: project scaffolding, migrations, user management.
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
//! Generated-file emission (§5.1, §5.2, §7).
//!
//! Produces the text of every file the Builder writes under
//! `src/_generated/` and `migrations/`. This module never touches
//! the filesystem -- it returns [`GeneratedFile`] values. The
//! lifecycle module ([`crate::builder::commit`]) is the only place
//! that decides whether to write them.
//!
//! Every emitted file carries the doctrine header from §5.2:
//!
//! ```text
//! // @generated by rustio <semver> from .rustio/draft.toml
//! // SPDX-SchemaHash: sha256:<hex>
//! // SPDX-EmitterVersion: rio-canon-1
//! // To change, edit draft.toml and run `rustio-admin commit`. Manual
//! // edits will be overwritten.
//! ```
//!
//! All emitted text passes through
//! [`crate::builder::canonical::canonicalize`] so the on-disk bytes
//! satisfy the §4.4 fixings (LF, NFC, trailing-LF, no trailing
//! whitespace).

use std::path::PathBuf;

use crate::builder::canonical::canonicalize;
use crate::builder::draft::{Draft, Field, Model};
use crate::builder::hash::{admin_hash, initial_migration_hash, mod_hash, model_hash};
use crate::builder::lockfile::EMITTER_VERSION;

/// One generated artefact: target path (relative to project root)
/// plus its canonical content.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct GeneratedFile {
    pub path: PathBuf,
    pub content: String,
    /// SchemaHash for the projection of `draft.toml` that produced
    /// this content. Stored separately so the lifecycle can verify
    /// drift without re-parsing the header.
    pub schema_hash: String,
}

/// Compute every generated artefact for `draft`. Returns the full
/// set the project should carry: `_generated/` files plus the
/// initial migration (when applicable).
///
/// The caller decides whether each is a create or an overwrite.
pub(crate) fn generate_all(draft: &Draft) -> Vec<GeneratedFile> {
    let mut out = Vec::new();

    out.push(emit_mod_rs(draft));
    out.push(emit_admin_rs(draft));
    out.push(emit_models_mod_rs(draft));

    for model in &draft.models {
        out.push(emit_model_rs(draft, model));
    }

    out.push(emit_initial_migration(draft));

    out
}

fn doctrine_header(file_kind: HeaderStyle, schema_hash: &str) -> String {
    let version = env!("CARGO_PKG_VERSION");
    let (prefix, _close) = file_kind.markers();
    format!(
        "{prefix} @generated by rustio {version} from .rustio/draft.toml\n\
         {prefix} SPDX-SchemaHash: {schema_hash}\n\
         {prefix} SPDX-EmitterVersion: {EMITTER_VERSION}\n\
         {prefix} To change, edit draft.toml and run `rustio-admin commit`. Manual\n\
         {prefix} edits will be overwritten.\n"
    )
}

#[derive(Debug, Clone, Copy)]
enum HeaderStyle {
    Rust,
    Sql,
}

impl HeaderStyle {
    fn markers(self) -> (&'static str, &'static str) {
        match self {
            HeaderStyle::Rust => ("//", ""),
            HeaderStyle::Sql => ("--", ""),
        }
    }
}

fn emit_mod_rs(draft: &Draft) -> GeneratedFile {
    let hash = mod_hash(draft);
    let mut body = String::new();
    body.push_str(&doctrine_header(HeaderStyle::Rust, &hash));
    body.push('\n');
    body.push_str("pub mod admin;\n");
    body.push_str("pub mod models;\n");
    GeneratedFile {
        path: PathBuf::from("src/_generated/mod.rs"),
        content: canonicalize(&body),
        schema_hash: hash,
    }
}

fn emit_admin_rs(draft: &Draft) -> GeneratedFile {
    let hash = admin_hash(draft);
    let mut body = String::new();
    body.push_str(&doctrine_header(HeaderStyle::Rust, &hash));
    body.push('\n');
    body.push_str("use rustio_admin::Admin;\n");
    if !draft.models.is_empty() {
        body.push('\n');
        for m in &draft.models {
            body.push_str(&format!(
                "use super::models::{}::{};\n",
                snake(&m.name),
                m.name
            ));
        }
    }
    body.push('\n');
    body.push_str("/// Generator-owned admin builder. `main.rs` calls this to\n");
    body.push_str("/// obtain an `Admin` with every model from `draft.toml`\n");
    body.push_str("/// registered. The developer chains further configuration\n");
    body.push_str("/// (`.app_name(...)`, `.public_url(...)`, etc.) after this.\n");
    body.push_str("pub fn build_admin() -> Admin {\n");
    if draft.models.is_empty() {
        body.push_str("    Admin::new()\n");
    } else {
        body.push_str("    Admin::new()\n");
        for m in &draft.models {
            body.push_str(&format!("        .model::<{}>()\n", m.name));
        }
    }
    body.push_str("}\n");
    GeneratedFile {
        path: PathBuf::from("src/_generated/admin.rs"),
        content: canonicalize(&body),
        schema_hash: hash,
    }
}

fn emit_models_mod_rs(draft: &Draft) -> GeneratedFile {
    // Reuses the same projection as `mod_hash` -- every model's
    // name, nothing more -- so changes to a model's *internals*
    // do not change this file's hash.
    let hash = mod_hash(draft);
    let mut body = String::new();
    body.push_str(&doctrine_header(HeaderStyle::Rust, &hash));
    if !draft.models.is_empty() {
        body.push('\n');
        for m in &draft.models {
            body.push_str(&format!("pub mod {};\n", snake(&m.name)));
        }
    }
    GeneratedFile {
        path: PathBuf::from("src/_generated/models/mod.rs"),
        content: canonicalize(&body),
        schema_hash: hash,
    }
}

fn emit_model_rs(draft: &Draft, model: &Model) -> GeneratedFile {
    let hash = model_hash(draft, &model.name).expect("model is present in draft");
    let mut body = String::new();
    body.push_str(&doctrine_header(HeaderStyle::Rust, &hash));
    body.push('\n');
    body.push_str("use chrono::{DateTime, Utc};\n");
    body.push_str("use rustio_admin::{Model, ModelAdmin, Result, Row, RustioAdmin, Value};\n");
    body.push('\n');
    body.push_str("#[derive(Debug, Clone, RustioAdmin)]\n");
    body.push_str(&format!("pub struct {} {{\n", model.name));
    body.push_str("    pub id: i64,\n");
    for f in &model.fields {
        body.push_str(&format!("    pub {}: {},\n", f.name, rust_type(f)));
    }
    body.push_str("    pub created_at: DateTime<Utc>,\n");
    body.push_str("}\n\n");

    // Column lists (in declaration order: id, fields..., created_at).
    let cols: Vec<String> = std::iter::once("id".to_string())
        .chain(model.fields.iter().map(|f| f.name.clone()))
        .chain(std::iter::once("created_at".to_string()))
        .collect();
    let insert_cols: Vec<String> = model
        .fields
        .iter()
        .map(|f| f.name.clone())
        .chain(std::iter::once("created_at".to_string()))
        .collect();
    let cols_lit = cols
        .iter()
        .map(|c| format!("\"{c}\""))
        .collect::<Vec<_>>()
        .join(", ");
    let insert_cols_lit = insert_cols
        .iter()
        .map(|c| format!("\"{c}\""))
        .collect::<Vec<_>>()
        .join(", ");

    body.push_str(&format!("impl Model for {} {{\n", model.name));
    body.push_str(&format!(
        "    const TABLE: &'static str = \"{}\";\n",
        model.table
    ));
    body.push_str(&format!(
        "    const COLUMNS: &'static [&'static str] = &[{cols_lit}];\n"
    ));
    body.push_str(&format!(
        "    const INSERT_COLUMNS: &'static [&'static str] = &[{insert_cols_lit}];\n\n"
    ));
    body.push_str("    fn id(&self) -> i64 {\n");
    body.push_str("        self.id\n");
    body.push_str("    }\n\n");

    body.push_str("    fn from_row(row: Row<'_>) -> Result<Self> {\n");
    body.push_str("        Ok(Self {\n");
    body.push_str("            id: row.get_i64(\"id\")?,\n");
    for f in &model.fields {
        body.push_str(&format!(
            "            {}: row.{}(\"{}\")?,\n",
            f.name,
            row_accessor(f),
            f.name
        ));
    }
    body.push_str("            created_at: row.get_datetime(\"created_at\")?,\n");
    body.push_str("        })\n");
    body.push_str("    }\n\n");

    body.push_str("    fn insert_values(&self) -> Vec<Value> {\n");
    body.push_str("        vec![\n");
    for f in &model.fields {
        body.push_str(&format!(
            "            Value::from({}),\n",
            insert_expr(&f.name, f)
        ));
    }
    body.push_str("            Value::from(self.created_at),\n");
    body.push_str("        ]\n");
    body.push_str("    }\n");
    body.push_str("}\n\n");

    body.push_str(&format!("impl ModelAdmin for {} {{}}\n", model.name));

    GeneratedFile {
        path: PathBuf::from(format!("src/_generated/models/{}.rs", snake(&model.name))),
        content: canonicalize(&body),
        schema_hash: hash,
    }
}

fn emit_initial_migration(draft: &Draft) -> GeneratedFile {
    let hash = initial_migration_hash(draft);
    let mut body = String::new();
    body.push_str(&doctrine_header(HeaderStyle::Sql, &hash));
    body.push('\n');
    body.push_str("-- Rollback hint (free-form, not parsed -- DESIGN_BUILDER.md §7.5):\n");
    body.push_str("--   To roll back, DROP TABLE every table below in reverse order.\n");
    body.push_str("--   Verify FK constraints first if any have been added by hand.\n");
    body.push('\n');
    for m in &draft.models {
        body.push_str(&format!("CREATE TABLE {} (\n", m.table));
        // Compute column-name width per table. The floor of 10
        // preserves the layout for short-field tables (matches the
        // hand-rolled width before this bug fix) and the dynamic
        // upper bound prevents long names like
        // `engine_displacement_cc` from collapsing against the
        // type column.
        let name_w = m
            .fields
            .iter()
            .map(|f| f.name.len())
            .max()
            .unwrap_or(0)
            .max(10);
        body.push_str(&format!(
            "    {:<width$}  BIGSERIAL    PRIMARY KEY,\n",
            "id",
            width = name_w
        ));
        for f in &m.fields {
            let unique = if f.unique { " UNIQUE" } else { "" };
            body.push_str(&format!(
                "    {:<width$}  {:<11} NOT NULL{},\n",
                f.name,
                sql_type(f),
                unique,
                width = name_w
            ));
        }
        body.push_str(&format!(
            "    {:<width$}  TIMESTAMPTZ  NOT NULL DEFAULT NOW()\n",
            "created_at",
            width = name_w
        ));
        body.push_str(");\n\n");
    }
    GeneratedFile {
        path: PathBuf::from("migrations/0001_initial.sql"),
        content: canonicalize(&body),
        schema_hash: hash,
    }
}

fn rust_type(field: &Field) -> &'static str {
    match field.r#type.as_str() {
        "text" => "String",
        "integer" => "i64",
        "boolean" => "bool",
        "timestamp" => "DateTime<Utc>",
        _ => unreachable!("FIELD_TYPES is closed; unknown type would have been refused upstream"),
    }
}

fn row_accessor(field: &Field) -> &'static str {
    match field.r#type.as_str() {
        "text" => "get_string",
        "integer" => "get_i64",
        "boolean" => "get_bool",
        "timestamp" => "get_datetime",
        _ => unreachable!(),
    }
}

fn insert_expr(field_name: &str, field: &Field) -> String {
    match field.r#type.as_str() {
        "text" => format!("self.{field_name}.clone()"),
        "integer" | "boolean" | "timestamp" => format!("self.{field_name}"),
        _ => unreachable!(),
    }
}

fn sql_type(field: &Field) -> &'static str {
    match field.r#type.as_str() {
        "text" => "TEXT",
        "integer" => "BIGINT",
        "boolean" => "BOOLEAN",
        "timestamp" => "TIMESTAMPTZ",
        _ => unreachable!(),
    }
}

/// CamelCase → snake_case (single-word fallback). Mirrors the
/// proc-macro's helper so generator and macro stay in lockstep.
fn snake(name: &str) -> String {
    let mut out = String::new();
    for (i, c) in name.chars().enumerate() {
        if c.is_ascii_uppercase() && i > 0 {
            out.push('_');
        }
        out.push(c.to_ascii_lowercase());
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::builder::draft::{Field, Project};

    fn sample() -> Draft {
        Draft {
            schema_version: 1,
            project: Project {
                name: "demo".into(),
                rust_version: "1.88".into(),
                builder_pinned: env!("CARGO_PKG_VERSION").into(),
                created_at: "2026-05-15T10:30:00Z".into(),
            },
            models: vec![Model {
                name: "Patient".into(),
                table: "patients".into(),
                fields: vec![Field {
                    name: "full_name".into(),
                    r#type: "text".into(),
                    required: true,
                    unique: false,
                }],
            }],
        }
    }

    #[test]
    fn every_emitted_file_carries_doctrine_header() {
        for file in generate_all(&sample()) {
            assert!(
                file.content.contains("@generated by rustio"),
                "missing @generated marker in {:?}:\n{}",
                file.path,
                file.content
            );
            assert!(
                file.content.contains("SPDX-SchemaHash:"),
                "missing SchemaHash marker in {:?}",
                file.path,
            );
            assert!(
                file.content.contains("SPDX-EmitterVersion:"),
                "missing EmitterVersion marker in {:?}",
                file.path,
            );
            assert!(
                file.content.contains(&file.schema_hash),
                "header hash does not match file.schema_hash in {:?}",
                file.path,
            );
        }
    }

    #[test]
    fn output_is_canonical_text() {
        for file in generate_all(&sample()) {
            assert!(!file.content.contains('\r'), "CR in {:?}", file.path);
            assert!(
                file.content.ends_with('\n'),
                "no trailing LF in {:?}",
                file.path
            );
            assert!(
                !file.content.ends_with("\n\n"),
                "trailing blank lines in {:?}",
                file.path
            );
        }
    }

    #[test]
    fn generation_is_deterministic() {
        let a = generate_all(&sample());
        let b = generate_all(&sample());
        assert_eq!(a.len(), b.len());
        for (x, y) in a.iter().zip(b.iter()) {
            assert_eq!(x.path, y.path);
            assert_eq!(x.content, y.content, "non-stable output in {:?}", x.path);
            assert_eq!(x.schema_hash, y.schema_hash);
        }
    }

    #[test]
    fn model_file_includes_field_columns() {
        let files = generate_all(&sample());
        let model_file = files
            .iter()
            .find(|f| f.path.ends_with("models/patient.rs"))
            .expect("patient.rs in generated set");
        assert!(model_file.content.contains("pub struct Patient"));
        assert!(model_file.content.contains("pub full_name: String"));
        assert!(model_file
            .content
            .contains("TABLE: &'static str = \"patients\""));
        assert!(model_file.content.contains("get_string(\"full_name\")"));
        assert!(model_file.content.contains("impl ModelAdmin for Patient"));
    }

    #[test]
    fn admin_file_registers_each_model() {
        let mut d = sample();
        d.models.push(Model {
            name: "Doctor".into(),
            table: "doctors".into(),
            fields: vec![],
        });
        let files = generate_all(&d);
        let admin = files.iter().find(|f| f.path.ends_with("admin.rs")).unwrap();
        assert!(admin.content.contains(".model::<Patient>()"));
        assert!(admin.content.contains(".model::<Doctor>()"));
        assert!(admin.content.contains("pub fn build_admin() -> Admin"));
    }

    #[test]
    fn initial_migration_creates_each_table() {
        let mut d = sample();
        d.models.push(Model {
            name: "Doctor".into(),
            table: "doctors".into(),
            fields: vec![],
        });
        let files = generate_all(&d);
        let mig = files
            .iter()
            .find(|f| f.path.ends_with("0001_initial.sql"))
            .unwrap();
        assert!(mig.content.starts_with("-- @generated"));
        assert!(mig.content.contains("CREATE TABLE patients"));
        // Layout-agnostic checks: the `full_name` line must have
        // a positive gap between the identifier and the type token
        // (the v0.14.0 bug regressed when the gap collapsed to 0).
        let line = mig
            .content
            .lines()
            .find(|l| l.trim_start().starts_with("full_name "))
            .expect("full_name line emitted");
        assert!(line.contains("TEXT"), "{line}");
        assert!(line.contains("NOT NULL"), "{line}");
        assert!(
            !line.contains("full_nameTEXT"),
            "identifier collapsed against type: {line}"
        );
        assert!(mig.content.contains("CREATE TABLE doctors"));
        assert!(
            mig.content.contains("Rollback hint"),
            "rollback hint required by §7.5"
        );
    }

    #[test]
    fn snake_helper_matches_macro_convention() {
        assert_eq!(snake("Patient"), "patient");
        assert_eq!(snake("BlogPost"), "blog_post");
        assert_eq!(snake("user"), "user");
    }

    /// Long field names must not collapse against the type
    /// column. Regression for the v0.14.0 bug where the codegen
    /// used hardcoded `{:<12}` and produced malformed SQL like
    /// `engine_displacement_ccBIGINT` (no space).
    #[test]
    fn long_field_names_keep_separator_from_type_column() {
        let d = Draft {
            schema_version: 1,
            project: Project {
                name: "demo".into(),
                rust_version: "1.88".into(),
                builder_pinned: env!("CARGO_PKG_VERSION").into(),
                created_at: "2026-05-15T10:30:00Z".into(),
            },
            models: vec![Model {
                name: "Vehicle".into(),
                table: "vehicles".into(),
                fields: vec![
                    Field {
                        name: "vin".into(),
                        r#type: "text".into(),
                        required: true,
                        unique: true,
                    },
                    Field {
                        name: "engine_displacement_cc".into(),
                        r#type: "integer".into(),
                        required: true,
                        unique: false,
                    },
                ],
            }],
        };
        let files = generate_all(&d);
        let mig = files
            .iter()
            .find(|f| f.path.ends_with("0001_initial.sql"))
            .unwrap();
        // Both identifiers must have at least one space before the
        // type token. The short name gets padded; the long name
        // gets only the 2 literal spaces, but it MUST get those.
        assert!(
            mig.content.contains("vin                     TEXT"),
            "short vin should align to long-name width:\n{}",
            mig.content
        );
        assert!(
            mig.content.contains("engine_displacement_cc  BIGINT"),
            "long field name must keep ≥2 spaces before its type:\n{}",
            mig.content
        );
        // Forbid the regressed concatenation explicitly.
        assert!(
            !mig.content.contains("engine_displacement_ccBIGINT"),
            "long field name collapsed into its type -- v0.14.0 codegen bug regressed:\n{}",
            mig.content
        );
    }

    #[test]
    fn unique_modifier_emits_sql_constraint() {
        let mut d = sample();
        d.models[0].fields[0].unique = true;
        let files = generate_all(&d);
        let mig = files
            .iter()
            .find(|f| f.path.ends_with("0001_initial.sql"))
            .unwrap();
        assert!(
            mig.content.contains("UNIQUE"),
            "missing UNIQUE constraint:\n{}",
            mig.content,
        );
    }
}