rullst-orm-macros 13.0.0-alpha.2

Procedural macros and derive attributes for the rullst-orm Active Record pattern.
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
#[path = "parser/attributes.rs"]
mod attributes;
#[path = "parser/field_types.rs"]
mod field_types;

use attributes::{FieldAttributes, ModelAttributes};
#[cfg(test)]
use attributes::{split_top_level, strip_outer_call, validate_relation_attribute};
use field_types::encrypted_field_kind;
pub(crate) use field_types::is_secret_string_type;
use syn::{Data, DeriveInput, Fields};

pub struct ParsedModel {
    pub name: syn::Ident,
    pub backend: String,
    pub table_name: String,
    pub global_scope: String,
    pub tenant_column: String,
    pub auditable: bool,
    pub searchable: bool,
    pub policy: String,
    pub before_save: String,
    pub after_save: String,
    pub before_delete: String,
    pub after_delete: String,
    pub after_fetch: String,
    /// Soft delete configuration. `column` defaults to `deleted_at`,
    /// `value` is the literal SQL expression for the "not deleted" sentinel
    /// (e.g. `0`, `false`, `null`, `'N'`), `delval` is the literal SQL
    /// expression for the "deleted" sentinel (e.g. `1`, `true`, `now()`,
    /// `UNIX_TIMESTAMP()`). All values are emitted as raw SQL fragments
    /// (never user input) so the user is responsible for keeping them
    /// safe and portable across MySQL / PostgreSQL / SQLite.
    pub soft_delete: Option<SoftDeleteConfig>,

    pub normal_fields: Vec<syn::Ident>,
    pub normal_fields_types: Vec<syn::Type>,
    pub hidden_fields: Vec<syn::Ident>,
    /// String fields transparently encrypted by generated persistence methods.
    pub encrypted_fields: Vec<ParsedEncryptedField>,
    /// Persisted fields tagged `#[orm(masked)]`. Their values are redacted from
    /// generated audit, event and search projections.
    pub masked_fields: Vec<syn::Ident>,
    /// Persisted `SecretString` / `Option<SecretString>` fields, redacted like
    /// masked fields and compared through `PartialEq` for audit changes.
    pub secret_fields: Vec<syn::Ident>,
    /// Persisted `#[sqlx(json)]` fields and whether they are `json(nullable)`.
    pub json_fields: Vec<(syn::Ident, bool)>,
    /// Persisted `#[orm(db_default)]` fields: generated INSERT and full-row
    /// UPDATE statements leave them to the database.
    pub db_default_fields: Vec<syn::Ident>,
    /// Fields tagged with `#[orm(skip)]` or `#[sqlx(skip)]`. They are
    /// still part of the struct but excluded from generated INSERT /
    /// UPDATE statements, the `*Column` enum and JSON serialisation.
    /// Tracked for introspection; not currently consumed by the
    /// codegen because the parser already moves them out of
    /// `normal_fields` before the generators run.
    #[allow(dead_code)]
    pub skipped_fields: Vec<syn::Ident>,
    pub relations: Vec<ParsedRelation>,
    pub has_soft_deletes: bool,
    pub rag_context_fields: Vec<syn::Ident>,
    pub embedding_for: Option<(syn::Ident, String)>,
}

impl ParsedModel {
    /// Whether generated audit, event and search projections must withhold
    /// this field's value (`#[orm(encrypted)]` or `#[orm(masked)]`).
    pub fn is_redacted(&self, field: &syn::Ident) -> bool {
        self.masked_fields.contains(field)
            || self.secret_fields.contains(field)
            || self
                .encrypted_fields
                .iter()
                .any(|encrypted| encrypted.name == *field)
    }
}

#[derive(Clone, Debug)]
pub struct SoftDeleteConfig {
    pub column: String,
    /// SQL fragment representing the "not deleted" state.
    /// When this is the literal string `null` (case-insensitive) the
    /// generated `SELECT` / `restore` statements compare the column
    /// against `IS NULL`. For all other values the comparison is
    /// `<column> = <value>`.
    pub value: String,
    /// SQL fragment representing the "deleted" state. This is
    /// interpolated verbatim into the generated `UPDATE` statement,
    /// so users can use database functions such as `now()`,
    /// `CURRENT_TIMESTAMP`, `UNIX_TIMESTAMP()` etc.
    pub delval: String,
}

pub struct ParsedRelation {
    pub field_name: syn::Ident,
    pub rel_type: String,
    pub rel_model: String,
    pub foreign_key: String,
    pub local_key: String,
    pub related_key: String,
    pub pivot_table: String,
    pub morph_name: String,
    pub cascade_soft_delete: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EncryptedFieldKind {
    String,
    OptionalString,
}

pub struct ParsedEncryptedField {
    pub name: syn::Ident,
    pub kind: EncryptedFieldKind,
}

pub fn parse(input: &DeriveInput) -> Result<ParsedModel, syn::Error> {
    let name = input.ident.clone();
    let mut model_attributes = ModelAttributes::parse(input)?;

    let fields = match &input.data {
        Data::Struct(data_struct) => match &data_struct.fields {
            Fields::Named(fields_named) => &fields_named.named,
            _ => {
                return Err(syn::Error::new(
                    name.span(),
                    "Orm macro only supports structs with named fields",
                ));
            }
        },
        _ => {
            // Do not render the complete derive tree just to locate this
            // diagnostic. In particular, syn's expression printer can take
            // superlinear time on adversarial attributes attached to an enum
            // or union. The model identifier is the precise, bounded location
            // that the user needs to fix.
            return Err(syn::Error::new(
                name.span(),
                "Orm macro can only be used on structs",
            ));
        }
    };

    let mut normal_fields = vec![];
    let mut normal_fields_types = vec![];
    let mut hidden_fields = vec![];
    let mut encrypted_fields = vec![];
    let mut masked_fields = vec![];
    let mut secret_fields = vec![];
    let mut json_fields = vec![];
    let mut db_default_fields = vec![];
    let mut skipped_fields = vec![];
    let mut relations = vec![];
    let mut rag_context_fields = vec![];
    let mut embedding_for = None;
    // If the user explicitly opted in via `#[orm(soft_delete(...))]` the
    // `has_soft_deletes` flag is derived from that. Otherwise we keep the
    // legacy behaviour of detecting a `deleted_at` field by name so
    // existing models keep working without changes.
    let mut has_soft_deletes = model_attributes.soft_delete.is_some();
    // Track the column name that should be considered the soft delete
    // marker. Used at the end of field iteration to synthesise a
    // default `SoftDeleteConfig` for legacy `deleted_at` models so the
    // downstream generators can always assume `soft_delete` is `Some`
    // when `has_soft_deletes` is true.
    let mut detected_soft_delete_column: Option<String> = None;

    for field in fields {
        let field_name = match field.ident.as_ref() {
            Some(ident) => ident.clone(),
            None => continue, // Skip fields without identifiers
        };
        let field_span = field_name.span();
        let field_name_str = field_name.to_string();
        if field_name_str == "deleted_at" {
            has_soft_deletes = true;
            detected_soft_delete_column = Some(field_name_str.clone());
        }

        let field_attributes = FieldAttributes::parse(field, field_span)?;
        if field_attributes.is_encrypted {
            if field_attributes.is_relation() || field_attributes.is_skipped {
                return Err(syn::Error::new(
                    field_span,
                    "#[orm(encrypted)] cannot be combined with relation or skipped fields",
                ));
            }
            let kind = encrypted_field_kind(&field.ty).ok_or_else(|| {
                syn::Error::new(
                    field_span,
                    "#[orm(encrypted)] supports only String and Option<String> fields",
                )
            })?;
            encrypted_fields.push(ParsedEncryptedField {
                name: field_name.clone(),
                kind,
            });
        }
        if field_attributes.rag_context {
            rag_context_fields.push(field_name.clone());
        }
        if let Some(target) = field_attributes.embedding_for.clone() {
            if embedding_for.is_some() {
                return Err(syn::Error::new(
                    field_span,
                    "only one persisted field may declare #[orm(embedding_for = \"...\")]",
                ));
            }
            embedding_for = Some((field_name.clone(), target));
        }

        if model_attributes.auditable
            && !field_attributes.is_masked
            && !field_attributes.is_skipped
            && !field_attributes.is_relation()
        {
            let lower_name = field_name_str.to_lowercase();
            if lower_name.contains("password")
                || lower_name.contains("token")
                || lower_name.contains("secret")
                || lower_name.contains("api_key")
            {
                return Err(syn::Error::new(
                    field_span,
                    format!(
                        "Sensitive field `{}` must be explicitly marked with `#[orm(masked)]` when `#[orm(auditable)]` is enabled.",
                        field_name_str
                    ),
                ));
            }
        }

        if field_attributes.is_relation() {
            let mut relation = field_attributes.into_relation(field_name);
            if relation.rel_type == "belongs_to_many" {
                if relation.foreign_key.is_empty() {
                    relation.foreign_key = format!("{}_id", name.to_string().to_lowercase());
                }
                if relation.related_key.is_empty() {
                    relation.related_key =
                        format!("{}_id", relation.rel_model.to_ascii_lowercase());
                }
            }
            relations.push(relation);
        } else if field_attributes.is_skipped {
            // Skipped fields are not exposed to the generated SQL or the
            // column enum; record the ident so downstream code (if it ever
            // needs to introspect) can still see them.
            skipped_fields.push(field_name.clone());
            if field_attributes.is_hidden {
                hidden_fields.push(field_name);
            }
        } else {
            attributes::validate_sql_identifier(&field_name_str, "column name", field_span)?;
            normal_fields.push(field_name.clone());
            normal_fields_types.push(field.ty.clone());
            if field_attributes.is_masked {
                masked_fields.push(field_name.clone());
            }
            if is_secret_string_type(&field.ty) {
                secret_fields.push(field_name.clone());
            }
            if let Some(nullable) = field_attributes.sqlx_json {
                json_fields.push((field_name.clone(), nullable));
            }
            if field_attributes.is_db_default {
                if field_name_str == "id" || field_name_str == model_attributes.tenant_column {
                    return Err(syn::Error::new(
                        field_span,
                        "db_default cannot apply to `id` or the tenant column",
                    ));
                }
                db_default_fields.push(field_name.clone());
            }
            if field_attributes.is_hidden {
                hidden_fields.push(field_name);
            }
        }
    }

    if !model_attributes.tenant_column.is_empty() {
        let Some((tenant_field, tenant_type)) = normal_fields
            .iter()
            .zip(normal_fields_types.iter())
            .find(|(field, _)| *field == model_attributes.tenant_column.as_str())
        else {
            return Err(syn::Error::new(
                name.span(),
                format!(
                    "tenant_column `{}` must name a persisted field on the model",
                    model_attributes.tenant_column
                ),
            ));
        };
        let supported = match tenant_type {
            syn::Type::Path(path) if path.qself.is_none() => {
                path.path.segments.last().is_some_and(|segment| {
                    matches!(
                        segment.ident.to_string().as_str(),
                        "String" | "i32" | "f64" | "bool"
                    )
                })
            }
            _ => false,
        };
        if !supported {
            return Err(syn::Error::new(
                tenant_field.span(),
                "tenant_column supports String, i32, f64, or bool so it can be bound without lossy conversion",
            ));
        }
    }

    if !normal_fields.iter().any(|field| field == "id") {
        return Err(syn::Error::new(
            name.span(),
            "Orm models require a persisted named `id` field",
        ));
    }

    if let Some(config) = model_attributes.soft_delete.as_ref()
        && !normal_fields.iter().any(|field| field == &config.column)
    {
        return Err(syn::Error::new(
            name.span(),
            format!(
                "soft_delete column `{}` must name a persisted field on the model",
                config.column
            ),
        ));
    }

    if let Some((_, target)) = embedding_for.as_ref()
        && !normal_fields.iter().any(|field| field == target)
    {
        return Err(syn::Error::new(
            name.span(),
            format!("embedding_for target `{target}` must name a persisted field on the model"),
        ));
    }

    for relation in &relations {
        if matches!(
            relation.rel_type.as_str(),
            "morph_many" | "morph_one" | "morph_to"
        ) && relation.morph_name.is_empty()
        {
            return Err(syn::Error::new(
                relation.field_name.span(),
                format!(
                    "polymorphic relation `{}` requires `morph_name = \"...\"` (the legacy alias `name` is also accepted)",
                    relation.field_name
                ),
            ));
        }

        if relation.rel_type != "morph_to" {
            continue;
        }

        let morph_id_column = if relation.foreign_key.is_empty() {
            format!("{}_id", relation.morph_name)
        } else {
            relation.foreign_key.clone()
        };
        let morph_type_column = format!("{}_type", relation.morph_name);
        let persisted_field = |column: &str| {
            normal_fields
                .iter()
                .zip(normal_fields_types.iter())
                .find(|(field, _)| *field == column)
        };

        let Some((morph_id_field, morph_id_type)) = persisted_field(&morph_id_column) else {
            return Err(syn::Error::new(
                relation.field_name.span(),
                format!(
                    "morph_to relation `{}` requires persisted id field `{}`",
                    relation.field_name, morph_id_column
                ),
            ));
        };
        let id_is_bindable = match morph_id_type {
            syn::Type::Path(path) if path.qself.is_none() => {
                path.path.segments.last().is_some_and(|segment| {
                    matches!(
                        segment.ident.to_string().as_str(),
                        "String" | "i32" | "f64" | "bool"
                    )
                })
            }
            _ => false,
        };
        if !id_is_bindable {
            return Err(syn::Error::new(
                morph_id_field.span(),
                "morph_to id fields support String, i32, f64, or bool so they can be bound without lossy conversion",
            ));
        }

        let Some((morph_type_field, morph_type_type)) = persisted_field(&morph_type_column) else {
            return Err(syn::Error::new(
                relation.field_name.span(),
                format!(
                    "morph_to relation `{}` requires persisted discriminator field `{}`",
                    relation.field_name, morph_type_column
                ),
            ));
        };
        let discriminator_is_string = match morph_type_type {
            syn::Type::Path(path) if path.qself.is_none() => path
                .path
                .segments
                .last()
                .is_some_and(|segment| segment.ident == "String"),
            _ => false,
        };
        if !discriminator_is_string {
            return Err(syn::Error::new(
                morph_type_field.span(),
                "morph_to discriminator fields must use String",
            ));
        }
    }

    // Synthesise a default `SoftDeleteConfig` for legacy models that
    // declared a `deleted_at` field without an explicit
    // `#[orm(soft_delete(...))]`. The defaults match the historical
    // behaviour (column = `deleted_at`, not-deleted = NULL, deleted =
    // `CURRENT_TIMESTAMP`) so all pre-existing models continue to
    // compile and behave identically.
    let soft_delete = model_attributes.soft_delete.take().or_else(|| {
        detected_soft_delete_column.map(|column| SoftDeleteConfig {
            column,
            value: String::new(),
            delval: String::new(),
        })
    });

    Ok(ParsedModel {
        name,
        backend: model_attributes.backend,
        table_name: model_attributes.table_name,
        global_scope: model_attributes.global_scope,
        tenant_column: model_attributes.tenant_column,
        auditable: model_attributes.auditable,
        searchable: model_attributes.searchable,
        policy: model_attributes.policy,
        before_save: model_attributes.before_save,
        after_save: model_attributes.after_save,
        before_delete: model_attributes.before_delete,
        after_delete: model_attributes.after_delete,
        after_fetch: model_attributes.after_fetch,
        soft_delete,
        normal_fields,
        normal_fields_types,
        hidden_fields,
        encrypted_fields,
        masked_fields,
        secret_fields,
        json_fields,
        db_default_fields,
        skipped_fields,
        relations,
        has_soft_deletes,
        rag_context_fields,
        embedding_for,
    })
}

include!("parser_tests.rs");