doido-generators 0.0.17

Doido code generators plus the unified CLI (server, console, db, worker, generate, new, credentials).
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
//! Parsing of `name:type[:modifier...]` field specs passed to the model and
//! scaffold generators (Rails-style), e.g.
//!
//! ```text
//! doido generate model Post title:string body:text published:boolean \
//!     author:references views:integer:index slug:string:unique
//! ```
//!
//! Each parsed [`Field`] knows how to render both a migration column line
//! (`t.string("title").not_null();`) and a SeaORM model field
//! (`pub title: String,`).

use crate::generators::to_snake;
use doido_core::anyhow::{anyhow, bail};
use doido_core::Result;

/// A column type supported by both the migration builder and the SeaORM model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColumnType {
    String,
    Text,
    Integer,
    BigInteger,
    Float,
    Double,
    Decimal,
    Boolean,
    Timestamp,
    Date,
    Json,
    Uuid,
    Binary,
    References,
}

impl ColumnType {
    /// Parse a type token; accepts common aliases.
    fn parse(token: &str) -> Result<Self> {
        Ok(match token.to_lowercase().as_str() {
            "string" => Self::String,
            "text" => Self::Text,
            "integer" | "int" => Self::Integer,
            "bigint" | "biginteger" | "big_integer" | "long" => Self::BigInteger,
            "float" => Self::Float,
            "double" => Self::Double,
            "decimal" | "numeric" => Self::Decimal,
            "boolean" | "bool" => Self::Boolean,
            "timestamp" | "datetime" => Self::Timestamp,
            "date" => Self::Date,
            "json" | "jsonb" => Self::Json,
            "uuid" => Self::Uuid,
            "binary" | "blob" | "bytes" => Self::Binary,
            "references" | "reference" | "belongs_to" => Self::References,
            other => bail!("unknown column type `{other}`"),
        })
    }

    /// The [`TableBuilder`](doido_model::migration) method that adds this column.
    fn builder_method(self) -> &'static str {
        match self {
            Self::String => "string",
            Self::Text => "text",
            Self::Integer => "integer",
            Self::BigInteger => "big_integer",
            Self::Float => "float",
            Self::Double => "double",
            Self::Decimal => "decimal",
            Self::Boolean => "boolean",
            Self::Timestamp => "timestamp",
            Self::Date => "date",
            Self::Json => "json",
            Self::Uuid => "uuid",
            Self::Binary => "binary",
            Self::References => "references",
        }
    }

    /// The `ColumnDef` type method used inside `alter_table`'s `add_column`
    /// closure (`c.string()`, `c.integer()`, …). Mirrors [`Self::builder_method`]
    /// except `References`, which has no `ColumnDef` helper — there it is a plain
    /// big-integer `<name>_id` column (kept NOT NULL by the field itself).
    fn column_def_method(self) -> &'static str {
        match self {
            Self::References => "big_integer",
            _ => self.builder_method(),
        }
    }

    /// The Rust type used for this column in the SeaORM model struct.
    fn rust_type(self) -> &'static str {
        match self {
            Self::String | Self::Text => "String",
            Self::Integer => "i32",
            Self::BigInteger | Self::References => "i64",
            Self::Float => "f32",
            Self::Double => "f64",
            Self::Decimal => "Decimal",
            Self::Boolean => "bool",
            Self::Timestamp => "DateTime",
            Self::Date => "Date",
            Self::Json => "Json",
            Self::Uuid => "Uuid",
            Self::Binary => "Vec<u8>",
        }
    }
}

/// A single parsed column definition.
#[derive(Debug, Clone)]
pub struct Field {
    /// Name as written by the user (snake-cased), e.g. `author` for a reference.
    raw_name: String,
    ty: ColumnType,
    not_null: bool,
    unique: bool,
    index: bool,
}

impl Field {
    /// Parse one `name:type[:modifier...]` spec. Type defaults to `string`.
    pub fn parse(spec: &str) -> Result<Self> {
        let mut parts = spec.split(':');
        let name = parts
            .next()
            .filter(|s| !s.is_empty())
            .ok_or_else(|| anyhow!("empty field spec"))?;

        let ty = match parts.next() {
            Some(t) if !t.is_empty() => ColumnType::parse(t)?,
            _ => ColumnType::String,
        };

        let mut field = Field {
            raw_name: to_snake(name),
            ty,
            not_null: false,
            unique: false,
            index: false,
        };

        for modifier in parts {
            match modifier.to_lowercase().as_str() {
                "" => {}
                "not_null" | "notnull" | "required" => field.not_null = true,
                "unique" | "uniq" => field.unique = true,
                "index" => field.index = true,
                other => bail!("unknown modifier `{other}` in field `{spec}`"),
            }
        }

        Ok(field)
    }

    /// Parse every spec in `specs`, short-circuiting on the first error.
    pub fn parse_all(specs: &[&str]) -> Result<Vec<Field>> {
        specs.iter().map(|s| Field::parse(s)).collect()
    }

    /// The database column name. References get an `_id` suffix.
    pub fn column_name(&self) -> String {
        match self.ty {
            ColumnType::References => format!("{}_id", self.raw_name),
            _ => self.raw_name.clone(),
        }
    }

    /// Whether the column (and therefore the model field) is NOT NULL.
    /// References are always non-null (the builder enforces it).
    pub fn is_required(&self) -> bool {
        self.not_null || self.ty == ColumnType::References
    }

    /// Whether this field requested its own index.
    pub fn wants_index(&self) -> bool {
        self.index
    }

    /// The Rust type as written in a scaffold params struct / model field,
    /// wrapped in `Option<…>` when the column is nullable.
    fn rust_type(&self) -> String {
        let ty = self.ty.rust_type();
        if self.is_required() {
            ty.to_string()
        } else {
            format!("Option<{ty}>")
        }
    }

    /// Render a field for the scaffold's form-params struct, e.g.
    /// `pub title: String,` — mirrors the column's nullability.
    pub fn params_struct_field(&self) -> String {
        format!("pub {}: {},", self.column_name(), self.rust_type())
    }

    /// Render an `ActiveModel` struct-literal entry from a parsed `form`, e.g.
    /// `title: Set(form.title),` (used by `create`).
    pub fn active_model_set(&self) -> String {
        let col = self.column_name();
        format!("{col}: Set(form.{col}),")
    }

    /// Render an `ActiveModel` field assignment from a parsed `form`, e.g.
    /// `record.title = Set(form.title);` (used by `update`).
    pub fn active_model_assign(&self) -> String {
        let col = self.column_name();
        format!("record.{col} = Set(form.{col});")
    }

    /// The HTML `<input type="…">` (or `textarea`/`checkbox`) for this column,
    /// used by the scaffold form view.
    pub fn html_input_type(&self) -> &'static str {
        match self.ty {
            ColumnType::Text => "textarea",
            ColumnType::Boolean => "checkbox",
            ColumnType::Integer
            | ColumnType::BigInteger
            | ColumnType::Float
            | ColumnType::Double
            | ColumnType::Decimal
            | ColumnType::References => "number",
            ColumnType::Date => "date",
            ColumnType::Timestamp => "datetime-local",
            _ => "text",
        }
    }

    /// Render the migration builder line, e.g. `t.string("title").not_null();`.
    /// `references` passes the bare name (it appends `_id` itself).
    pub fn migration_line(&self) -> String {
        let arg = &self.raw_name;
        let mut line = format!("t.{}(\"{arg}\")", self.ty.builder_method());
        // `references` is already NOT NULL; only add it for other types.
        if self.not_null && self.ty != ColumnType::References {
            line.push_str(".not_null()");
        }
        if self.unique {
            line.push_str(".unique_key()");
        }
        line.push(';');
        line
    }

    /// Render an `alter_table` add-column line, e.g.
    /// `t.add_column("email", |c| { c.string().not_null(); });`. References
    /// become a NOT NULL `<name>_id` big integer.
    pub fn alter_add_line(&self) -> String {
        let col = self.column_name();
        let mut body = format!("c.{}()", self.ty.column_def_method());
        if self.is_required() {
            body.push_str(".not_null()");
        }
        if self.unique {
            body.push_str(".unique_key()");
        }
        format!("t.add_column(\"{col}\", |c| {{ {body}; }});")
    }

    /// Render an `alter_table` drop-column line, e.g. `t.drop_column("email");`.
    pub fn alter_drop_line(&self) -> String {
        format!("t.drop_column(\"{}\");", self.column_name())
    }

    /// Render the SeaORM model struct field, e.g. `pub title: String,` or
    /// `pub age: Option<i32>,` for a nullable column.
    pub fn model_field(&self) -> String {
        format!("pub {}: {},", self.column_name(), self.rust_type())
    }

    /// A sample form value for this column, used to build request bodies in the
    /// generated scaffold controller test. `None` for types that cannot be
    /// represented as a urlencoded scalar (binary), which are omitted.
    pub fn sample_form_value(&self) -> Option<&'static str> {
        Some(match self.ty {
            ColumnType::String | ColumnType::Text => "Test",
            ColumnType::Integer | ColumnType::BigInteger | ColumnType::References => "1",
            ColumnType::Float | ColumnType::Double | ColumnType::Decimal => "1",
            ColumnType::Boolean => "true",
            ColumnType::Timestamp => "2020-01-01T00:00:00",
            ColumnType::Date => "2020-01-01",
            ColumnType::Json => "null",
            ColumnType::Uuid => "00000000-0000-0000-0000-000000000000",
            ColumnType::Binary => return None,
        })
    }

    /// `col=value` pair for a urlencoded request body, or `None` to omit.
    pub fn sample_form_pair(&self) -> Option<String> {
        self.sample_form_value()
            .map(|v| format!("{}={}", self.column_name(), v))
    }
}

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

    #[test]
    fn defaults_to_string_when_type_omitted() {
        let f = Field::parse("title").unwrap();
        assert_eq!(f.column_name(), "title");
        assert_eq!(f.migration_line(), "t.string(\"title\");");
        assert_eq!(f.model_field(), "pub title: Option<String>,");
    }

    #[test]
    fn maps_types_and_nullability() {
        let f = Field::parse("age:integer:not_null").unwrap();
        assert_eq!(f.migration_line(), "t.integer(\"age\").not_null();");
        assert_eq!(f.model_field(), "pub age: i32,");
    }

    #[test]
    fn unique_modifier_renders_unique_key() {
        let f = Field::parse("email:string:unique").unwrap();
        assert_eq!(f.migration_line(), "t.string(\"email\").unique_key();");
    }

    #[test]
    fn references_get_id_suffix_and_are_non_null() {
        let f = Field::parse("author:references").unwrap();
        assert_eq!(f.column_name(), "author_id");
        assert_eq!(f.migration_line(), "t.references(\"author\");");
        assert_eq!(f.model_field(), "pub author_id: i64,");
    }

    #[test]
    fn alter_add_and_drop_lines() {
        let f = Field::parse("email:string:not_null:unique").unwrap();
        assert_eq!(
            f.alter_add_line(),
            "t.add_column(\"email\", |c| { c.string().not_null().unique_key(); });"
        );
        assert_eq!(f.alter_drop_line(), "t.drop_column(\"email\");");

        let plain = Field::parse("note:text").unwrap();
        assert_eq!(
            plain.alter_add_line(),
            "t.add_column(\"note\", |c| { c.text(); });"
        );

        // References become a NOT NULL big-integer `<name>_id`.
        let r = Field::parse("author:references").unwrap();
        assert_eq!(
            r.alter_add_line(),
            "t.add_column(\"author_id\", |c| { c.big_integer().not_null(); });"
        );
        assert_eq!(r.alter_drop_line(), "t.drop_column(\"author_id\");");
    }

    #[test]
    fn index_modifier_is_tracked() {
        let f = Field::parse("slug:string:index").unwrap();
        assert!(f.wants_index());
    }

    #[test]
    fn params_struct_field_and_active_model_set() {
        let f = Field::parse("title:string:not_null").unwrap();
        assert_eq!(f.params_struct_field(), "pub title: String,");
        assert_eq!(f.active_model_set(), "title: Set(form.title),");

        let r = Field::parse("author:references").unwrap();
        assert_eq!(r.params_struct_field(), "pub author_id: i64,");
        assert_eq!(r.active_model_set(), "author_id: Set(form.author_id),");
    }

    #[test]
    fn html_input_types_map_by_column_type() {
        assert_eq!(Field::parse("name").unwrap().html_input_type(), "text");
        assert_eq!(
            Field::parse("bio:text").unwrap().html_input_type(),
            "textarea"
        );
        assert_eq!(
            Field::parse("age:integer").unwrap().html_input_type(),
            "number"
        );
        assert_eq!(
            Field::parse("ok:boolean").unwrap().html_input_type(),
            "checkbox"
        );
        assert_eq!(Field::parse("born:date").unwrap().html_input_type(), "date");
    }

    #[test]
    fn rejects_unknown_type_and_modifier() {
        assert!(Field::parse("x:notatype").is_err());
        assert!(Field::parse("x:string:notamod").is_err());
    }

    #[test]
    fn aliases_resolve() {
        assert_eq!(
            Field::parse("count:int").unwrap().model_field(),
            "pub count: Option<i32>,"
        );
        assert_eq!(
            Field::parse("active:bool:not_null").unwrap().model_field(),
            "pub active: bool,"
        );
        assert_eq!(
            Field::parse("meta:jsonb").unwrap().model_field(),
            "pub meta: Option<Json>,"
        );
    }
}