gize-core 0.9.6

Core domain model, conventions and manifest for the Gize framework.
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
//! Model and field definitions parsed from the CLI (`name:String email:String ...`).

use crate::validation::{validate_column, validate_identifier, validate_model_name};
use anyhow::{Context, Result, bail, ensure};
use serde::{Deserialize, Serialize};

/// The set of scalar field types Gize understands in the MVP.
///
/// Kept deliberately small and explicit (ADR-003 / ADR-011): each variant maps to a Rust
/// type and a SQL column type. Unknown types are rejected early with a helpful error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FieldType {
    String,
    Bool,
    I32,
    I64,
    F64,
    Uuid,
    DateTime,
}

impl FieldType {
    /// Parse a field type from its CLI spelling (case-insensitive).
    pub fn parse(raw: &str) -> Result<Self> {
        let ty = match raw.to_ascii_lowercase().as_str() {
            "string" | "str" => Self::String,
            "bool" | "boolean" => Self::Bool,
            "i32" | "int" => Self::I32,
            "i64" | "bigint" | "long" => Self::I64,
            "f64" | "float" | "double" => Self::F64,
            "uuid" => Self::Uuid,
            "datetime" | "timestamp" => Self::DateTime,
            other => bail!(
                "unknown field type `{other}` (supported: String, Bool, i32, i64, f64, Uuid, DateTime)"
            ),
        };
        Ok(ty)
    }

    /// The idiomatic Rust type used in generated structs.
    pub fn rust_type(self) -> &'static str {
        match self {
            Self::String => "String",
            Self::Bool => "bool",
            Self::I32 => "i32",
            Self::I64 => "i64",
            Self::F64 => "f64",
            Self::Uuid => "uuid::Uuid",
            Self::DateTime => "chrono::DateTime<chrono::Utc>",
        }
    }

    /// Whether the mapped Rust type is `Copy`. Used by generators to decide between
    /// `.bind(x)` (Copy) and `.bind(x.clone())` (owned), keeping generated code
    /// clippy-clean (`clone_on_copy`).
    pub fn is_copy(self) -> bool {
        // `String` is the only non-Copy type in the MVP set; `uuid::Uuid` and
        // `chrono::DateTime<Utc>` are both Copy.
        !matches!(self, Self::String)
    }

    /// The canonical CLI/manifest spelling of this type (the inverse of [`Self::parse`]).
    /// Used to serialize a field back into a `name:Type` token for `gize.toml` so the
    /// manifest is normalized regardless of the spelling the user typed (ADR-009 revision).
    pub fn as_token(self) -> &'static str {
        match self {
            Self::String => "String",
            Self::Bool => "bool",
            Self::I32 => "i32",
            Self::I64 => "i64",
            Self::F64 => "f64",
            Self::Uuid => "Uuid",
            Self::DateTime => "DateTime",
        }
    }

    /// The PostgreSQL column type used in generated migrations (ADR-011).
    pub fn sql_type(self) -> &'static str {
        match self {
            Self::String => "TEXT",
            Self::Bool => "BOOLEAN",
            Self::I32 => "INTEGER",
            Self::I64 => "BIGINT",
            Self::F64 => "DOUBLE PRECISION",
            Self::Uuid => "UUID",
            Self::DateTime => "TIMESTAMPTZ",
        }
    }
}

/// A single field of a model: `name:Type`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Field {
    pub name: String,
    pub ty: FieldType,
}

impl Field {
    /// Serialize this field back into its canonical `name:Type` token (inverse of
    /// [`Self::parse`] for the type part), for recording in `gize.toml`.
    pub fn to_token(&self) -> String {
        format!("{}:{}", self.name, self.ty.as_token())
    }

    /// Parse one `name:Type` token.
    pub fn parse(token: &str) -> Result<Self> {
        let (name, ty) = token
            .split_once(':')
            .with_context(|| format!("field `{token}` must be in the form name:Type"))?;
        validate_column(name)?;
        Ok(Self {
            name: name.to_string(),
            ty: FieldType::parse(ty)?,
        })
    }
}

/// A `belongs_to` relationship declared on a model (ADR-014): a foreign key from this model
/// to `target`'s primary key. `field` is the local name (`author`), which yields the FK
/// column `author_id`. Serialized under `[[module.belongs_to]]` in `gize.toml`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Relation {
    /// The local relationship name, e.g. `author`.
    pub field: String,
    /// The referenced module/table, e.g. `users`.
    pub target: String,
}

impl Relation {
    /// The foreign-key column this relationship produces: `author` -> `author_id`.
    pub fn fk_column(&self) -> String {
        format!("{}_id", self.field)
    }

    /// The `name:belongs_to:target` token spelling, for reconstructing a model from the
    /// manifest and for round-tripping.
    pub fn to_token(&self) -> String {
        format!("{}:belongs_to:{}", self.field, self.target)
    }
}

/// A model: a name plus its fields and relationships, as produced by
/// `gize make crud Name f:T author:belongs_to:users ...`.
///
/// Each relationship is also expanded into a synthetic `<name>_id: Uuid` [`Field`] appended
/// to `fields`, so every field-driven template (model, dto, repository, …) picks up the
/// foreign-key column for free; only the migration consults `relations` directly, to emit the
/// `FOREIGN KEY` constraint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelSpec {
    pub name: String,
    pub fields: Vec<Field>,
    pub relations: Vec<Relation>,
}

impl ModelSpec {
    /// Build a model spec from a name and raw tokens. A token of the form
    /// `name:belongs_to:target` is parsed as a relationship; anything else is a scalar
    /// `name:Type` field.
    pub fn parse(name: impl Into<String>, tokens: &[String]) -> Result<Self> {
        let name = name.into();
        validate_model_name(&name)?;
        let mut fields = Vec::new();
        let mut relations = Vec::new();
        for token in tokens {
            let parts: Vec<&str> = token.splitn(3, ':').collect();
            if parts.len() == 3 && parts[1] == "belongs_to" {
                let (field, target) = (parts[0], parts[2]);
                if field.is_empty() || target.is_empty() {
                    bail!("relationship `{token}` must be in the form name:belongs_to:target");
                }
                relations.push(Relation {
                    field: field.to_string(),
                    target: target.to_string(),
                });
            } else {
                fields.push(Field::parse(token)?);
            }
        }
        // Expand each relationship into its foreign-key column so the code templates render it.
        for r in &relations {
            fields.push(Field {
                name: r.fk_column(),
                ty: FieldType::Uuid,
            });
        }
        let model = Self {
            name,
            fields,
            relations,
        };
        model.validate()?;
        Ok(model)
    }

    /// Validate an expanded model, including specs assembled programmatically.
    pub fn validate_for_dialect(&self, dialect: crate::Dialect) -> Result<()> {
        self.validate()?;
        let check = crate::validation::validate_sql_identifier_for_dialect;
        check(
            &crate::naming::table_name(&self.name),
            "generated table",
            dialect,
        )?;
        for field in &self.fields {
            check(&field.name, "field", dialect)?;
        }
        for relation in &self.relations {
            check(&relation.target, "relationship target", dialect)?;
        }
        Ok(())
    }

    pub fn validate(&self) -> Result<()> {
        use std::collections::BTreeSet;
        validate_model_name(&self.name)?;
        let mut names = BTreeSet::new();
        for field in &self.fields {
            validate_column(&field.name)?;
            ensure!(
                names.insert(field.name.as_str()),
                "duplicate field `{}` in model `{}` (including generated relationship columns)",
                field.name,
                self.name
            );
        }
        let mut relations = BTreeSet::new();
        for relation in &self.relations {
            validate_identifier(&relation.field, "relationship")?;
            validate_identifier(&relation.target, "relationship target")?;
            ensure!(
                relations.insert(relation.field.as_str()),
                "duplicate relationship `{}` in model `{}`",
                relation.field,
                self.name
            );
            ensure!(
                !names.contains(relation.field.as_str()),
                "relationship `{}` collides with a field in model `{}`",
                relation.field,
                self.name
            );
            let fk = relation.fk_column();
            ensure!(
                self.fields
                    .iter()
                    .any(|f| f.name == fk && f.ty == FieldType::Uuid),
                "relationship `{}` requires generated UUID field `{fk}`",
                relation.field
            );
        }
        Ok(())
    }

    /// Serialize the scalar fields back into canonical `name:Type` tokens, for recording the
    /// model's shape in `gize.toml` (ADR-009 revision). Synthetic foreign-key columns are
    /// omitted — relationships are recorded separately under `[[module.belongs_to]]`.
    pub fn to_field_tokens(&self) -> Vec<String> {
        let fk: std::collections::BTreeSet<String> =
            self.relations.iter().map(Relation::fk_column).collect();
        self.fields
            .iter()
            .filter(|f| !fk.contains(&f.name))
            .map(Field::to_token)
            .collect()
    }
}

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

    #[test]
    fn parses_a_field() {
        let f = Field::parse("email:String").unwrap();
        assert_eq!(f.name, "email");
        assert_eq!(f.ty, FieldType::String);
        assert_eq!(f.ty.rust_type(), "String");
        assert_eq!(f.ty.sql_type(), "TEXT");
    }

    #[test]
    fn rejects_unknown_type() {
        assert!(Field::parse("x:Blob").is_err());
    }

    #[test]
    fn rejects_malformed_token() {
        assert!(Field::parse("notype").is_err());
    }

    #[test]
    fn parses_a_model() {
        let m = ModelSpec::parse(
            "User",
            &["name:String".to_string(), "active:bool".to_string()],
        )
        .unwrap();
        assert_eq!(m.name, "User");
        assert_eq!(m.fields.len(), 2);
        assert_eq!(m.fields[1].ty, FieldType::Bool);
        assert!(m.relations.is_empty());
    }

    #[test]
    fn parses_a_belongs_to_relationship() {
        let m = ModelSpec::parse(
            "Post",
            &[
                "title:String".to_string(),
                "author:belongs_to:users".to_string(),
            ],
        )
        .unwrap();
        // The relationship is recorded...
        assert_eq!(m.relations.len(), 1);
        assert_eq!(m.relations[0].field, "author");
        assert_eq!(m.relations[0].target, "users");
        assert_eq!(m.relations[0].fk_column(), "author_id");
        // ...and expanded into a synthetic UUID foreign-key field for codegen.
        let fk = m.fields.iter().find(|f| f.name == "author_id").unwrap();
        assert_eq!(fk.ty, FieldType::Uuid);
        // ...but the FK column is not re-emitted as a scalar field token.
        assert_eq!(m.to_field_tokens(), vec!["title:String".to_string()]);
    }

    #[test]
    fn rejects_malformed_relationship() {
        assert!(ModelSpec::parse("Post", &["author:belongs_to:".to_string()]).is_err());
        assert!(ModelSpec::parse("Post", &[":belongs_to:users".to_string()]).is_err());
    }
    #[test]
    fn rejects_invalid_and_reserved_field_names() {
        for name in [
            "",
            "_",
            "9name",
            "first-name",
            "first name",
            "Name",
            "café",
            "r#type",
            "../field",
            "type",
            "async",
            "gen",
            "id",
            "created_at",
            "updated_at",
        ] {
            let error = Field::parse(&format!("{name}:String"))
                .unwrap_err()
                .to_string();
            assert!(error.contains(name), "{error}");
        }
        assert!(Field::parse(&format!("{}:String", "a".repeat(64))).is_err());
        for name in ["name", "first_name", "address2", "_internal"] {
            Field::parse(&format!("{name}:String")).unwrap();
        }
    }

    #[test]
    fn rejects_duplicates_and_relationship_collisions() {
        for fields in [
            vec!["name:String", "name:i32"],
            vec!["author_id:Uuid", "author:belongs_to:users"],
            vec!["author:belongs_to:users", "author_id:Uuid"],
            vec!["author:belongs_to:users", "author:belongs_to:posts"],
            vec!["author:String", "author:belongs_to:users"],
            vec!["type:belongs_to:users"],
            vec!["author:belongs_to:../users"],
            vec!["author:belongs_to:users:extra"],
        ] {
            let tokens: Vec<_> = fields.iter().map(|f| f.to_string()).collect();
            assert!(
                ModelSpec::parse("Post", &tokens).is_err(),
                "accepted {fields:?}"
            );
        }
    }

    #[test]
    fn validates_models_and_preserves_valid_relation_roundtrip() {
        for name in [
            "",
            "post",
            "Self",
            "String",
            "Vec",
            "../Post",
            "Post-Item",
            "Post Item",
            "Post_Item",
        ] {
            assert!(ModelSpec::parse(name, &[]).is_err(), "accepted {name}");
        }
        let model = ModelSpec::parse(
            "BlogPost",
            &["title:String".into(), "user:belongs_to:users".into()],
        )
        .unwrap();
        model.validate().unwrap();
        let mut tokens = model.to_field_tokens();
        tokens.extend(model.relations.iter().map(Relation::to_token));
        assert_eq!(ModelSpec::parse("BlogPost", &tokens).unwrap(), model);
    }
}