rullst-orm-macros 12.1.1

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
#[cfg(test)]
mod tests {
    use super::*;
    use proc_macro2::Span;

    #[test]
    fn test_split_top_level() {
        // Test basic splitting
        let parts = split_top_level("a, b, c");
        assert_eq!(parts, vec!["a", " b", " c"]);

        // Test parentheses protection
        let parts = split_top_level("a(1, 2), b, c(3, 4)");
        assert_eq!(parts, vec!["a(1, 2)", " b", " c(3, 4)"]);

        // Test unmatched parentheses (depth check behavior)
        let parts = split_top_level("a), b");
        assert_eq!(parts, vec!["a)", " b"]);
    }

    #[test]
    fn test_strip_outer_call() {
        // Test valid call
        assert_eq!(
            strip_outer_call("soft_delete(field = \"a\")", "soft_delete"),
            Some("field = \"a\"".to_string())
        );

        // Test with whitespace
        assert_eq!(
            strip_outer_call("  soft_delete  (  field = \"a\"  )  ", "soft_delete"),
            Some("field = \"a\"".to_string())
        );

        // Test not a call
        assert_eq!(strip_outer_call("soft_delete", "soft_delete"), None);
        assert_eq!(strip_outer_call("soft_delete(a", "soft_delete"), None);
        assert_eq!(strip_outer_call("soft_delete a)", "soft_delete"), None);
    }

    #[test]
    fn test_validate_relation_attribute() {
        // Test valid relations
        assert!(validate_relation_attribute("has_many", "User", Span::call_site()).is_ok());
        assert!(validate_relation_attribute("has_one", "Profile", Span::call_site()).is_ok());
        assert!(validate_relation_attribute("belongs_to", "Team", Span::call_site()).is_ok());
        assert!(validate_relation_attribute("belongs_to_many", "Role", Span::call_site()).is_ok());
        assert!(validate_relation_attribute("morph_many", "Comment", Span::call_site()).is_ok());
        assert!(validate_relation_attribute("morph_one", "Image", Span::call_site()).is_ok());
        assert!(validate_relation_attribute("morph_to", "Post", Span::call_site()).is_ok());

        // Test empty model
        assert!(validate_relation_attribute("has_many", "", Span::call_site()).is_err());
        assert!(validate_relation_attribute("belongs_to", "", Span::call_site()).is_err());

        // Test empty modifier values
        assert!(validate_relation_attribute("foreign_key", "", Span::call_site()).is_err());
        assert!(validate_relation_attribute("related_key", "", Span::call_site()).is_err());
        assert!(validate_relation_attribute("pivot_table", "", Span::call_site()).is_err());
        assert!(validate_relation_attribute("local_key", "", Span::call_site()).is_err());
        assert!(validate_relation_attribute("name", "", Span::call_site()).is_err());
    }

    #[test]
    fn test_parse_model_attributes() {
        // To kill mutants on match arms ("morph_many", "belongs_to", etc.) 
        // we could test `parse` directly by passing a Mock `DeriveInput`
        use syn::parse_quote;

        let input: DeriveInput = parse_quote! {
            #[orm(table_name = "test_table", global_scope = "active_only", tenant_column = "tenant_id", policy = "TestPolicy")]
            #[orm(auditable, searchable)]
            #[orm(before_save = "before_s", after_save = "after_s")]
            #[orm(before_delete = "before_d", after_delete = "after_d")]
            #[orm(after_fetch = "after_f")]
            #[orm(soft_delete(column = "del_at", value = "1", delval = "0"))]
            struct TestModel {
                id: i32,
                tenant_id: String,
                del_at: i64,
                #[orm(has_many = "M1")] m1: Vec<M1>,
                #[orm(has_one = "M2")] m2: M2,
                #[orm(belongs_to = "M3")] m3: M3,
                #[orm(belongs_to_many = "M4", pivot_table = "piv_m4")] m4: Vec<M4>,
                #[orm(morph_many = "M5", name = "m5_able", local_key = "custom_id")] m5: Vec<M5>,
                #[orm(morph_one = "M6", name = "m6_able", foreign_key = "f_id", related_key = "r_id")] m6: M6,
                m7_able_id: i32,
                m7_able_type: String,
                #[orm(morph_to = "M7", morph_name = "m7_able")] m7: Option<M7>,
                #[orm(skip)] skipped: i32,
                #[orm(hidden)] hidden: String,
                #[orm(masked)] token: String,
            }
        };

        let parsed = parse(&input).unwrap();
        
        assert_eq!(parsed.table_name, "test_table");
        assert_eq!(parsed.global_scope, "active_only");
        assert_eq!(parsed.tenant_column, "tenant_id");
        assert_eq!(parsed.policy, "TestPolicy");
        assert!(parsed.auditable);
        assert!(parsed.searchable);
        assert_eq!(parsed.before_save, "before_s");
        assert_eq!(parsed.after_save, "after_s");
        assert_eq!(parsed.before_delete, "before_d");
        assert_eq!(parsed.after_delete, "after_d");
        assert_eq!(parsed.after_fetch, "after_f");

        let sd = parsed.soft_delete.unwrap();
        assert_eq!(sd.column, "del_at");
        assert_eq!(sd.value, "1");
        assert_eq!(sd.delval, "0");

        let r = &parsed.relations;
        assert_eq!(r.len(), 7);
        assert_eq!(r[0].rel_type, "has_many");
        assert_eq!(r[1].rel_type, "has_one");
        assert_eq!(r[2].rel_type, "belongs_to");
        assert_eq!(r[3].rel_type, "belongs_to_many");
        assert_eq!(r[3].pivot_table, "piv_m4");
        assert_eq!(r[4].rel_type, "morph_many");
        assert_eq!(r[4].morph_name, "m5_able");
        assert_eq!(r[4].local_key, "custom_id");
        assert_eq!(r[5].rel_type, "morph_one");
        assert_eq!(r[5].morph_name, "m6_able");
        assert_eq!(r[5].foreign_key, "f_id");
        assert_eq!(r[5].related_key, "r_id");
        assert_eq!(r[6].rel_type, "morph_to");
        assert_eq!(r[6].morph_name, "m7_able");

        assert!(parsed.skipped_fields.iter().any(|i| i == "skipped"));
        assert!(parsed.hidden_fields.iter().any(|i| i == "hidden"));
    }

    #[test]
    fn morph_to_requires_persisted_id_and_string_discriminator() {
        use syn::parse_quote;

        let invalid_id: DeriveInput = parse_quote! {
            struct Comment {
                id: i32,
                commentable_id: Vec<i32>,
                commentable_type: String,
                #[orm(morph_to = "Post", morph_name = "commentable")]
                post: Option<Post>,
            }
        };
        let error = match parse(&invalid_id) {
            Ok(_) => panic!("an unsupported polymorphic id type must fail"),
            Err(error) => error,
        };
        assert!(error.to_string().contains("id fields support"));

        let missing_discriminator: DeriveInput = parse_quote! {
            struct Comment {
                id: i32,
                commentable_id: i32,
                #[orm(morph_to = "Post", morph_name = "commentable")]
                post: Option<Post>,
            }
        };
        let error = match parse(&missing_discriminator) {
            Ok(_) => panic!("missing discriminator must fail"),
            Err(error) => error,
        };
        assert!(error.to_string().contains("commentable_type"));

        let invalid_discriminator: DeriveInput = parse_quote! {
            struct Comment {
                id: i32,
                commentable_id: i32,
                commentable_type: i32,
                #[orm(morph_to = "Post", morph_name = "commentable")]
                post: Option<Post>,
            }
        };
        let error = match parse(&invalid_discriminator) {
            Ok(_) => panic!("numeric discriminator must fail"),
            Err(error) => error,
        };
        assert!(error.to_string().contains("must use String"));
    }

    #[test]
    fn parses_supported_orm_backends_and_defaults_to_sqlx() {
        use syn::parse_quote;

        let default_backend: DeriveInput = parse_quote! {
            struct DefaultModel { id: i64 }
        };
        assert_eq!(
            parse(&default_backend)
                .expect("default backend should parse")
                .backend,
            "sqlx"
        );

        let turso_backend: DeriveInput = parse_quote! {
            #[orm(table = "users", backend = "turso")]
            struct TursoModel { id: i64, name: String }
        };
        assert_eq!(
            parse(&turso_backend)
                .expect("Turso backend should parse")
                .backend,
            "turso"
        );
    }

    #[test]
    fn rejects_unknown_orm_backend() {
        use syn::parse_quote;

        let input: DeriveInput = parse_quote! {
            #[orm(backend = "mongodb")]
            struct UnsupportedModel { id: i64 }
        };
        let error = parse(&input)
            .err()
            .expect("unknown backend must be rejected");
        assert!(error.to_string().contains("`sqlx` or `turso`"));
    }

    #[test]
    fn rejects_unsupported_model_shapes_without_rendering_the_full_ast() {
        // This compact form preserves the expression shape found by the v12
        // release fuzz campaign. Formatting the complete union in
        // `syn::Error::new_spanned` makes syn recursively print its attribute
        // expression; anchoring the error to the identifier stays bounded.
        let pathological_union = "#[Li=555527577500346.07.10/..0/..1./005L.07.100/..1./07.10/..0/..1./005L.03.77500346.07.10/..0/..1./005L10.07.10/..0/..1./005L.07.100/..1./07.10/..0/..1./005L.07.100/..1./005LL7.500346.07.10/..0/..1./005L107.100/..1./07.10/..0/..1./005L.07.100/..1./0/..1./00=5555555SSSSSSSSSSS]#[K]union n<l,>{}";
        let input: DeriveInput = syn::parse_str(pathological_union)
            .expect("the release-campaign union must remain a valid derive input");
        let error = match parse(&input) {
            Ok(_) => panic!("unions must not be accepted as ORM models"),
            Err(error) => error,
        };
        assert_eq!(error.to_string(), "Orm macro can only be used on structs");

        let pathological_struct = pathological_union.replacen("union n", "struct n", 1);
        let input: DeriveInput = syn::parse_str(&pathological_struct)
            .expect("the release-campaign struct must remain a valid derive input");
        let error = match parse(&input) {
            Ok(_) => panic!("models without a persisted id must not be accepted"),
            Err(error) => error,
        };
        assert_eq!(
            error.to_string(),
            "Orm models require a persisted named `id` field"
        );

        let tuple: DeriveInput = syn::parse_str("struct Tuple(i64);")
            .expect("the tuple-struct regression input must parse");
        let error = match parse(&tuple) {
            Ok(_) => panic!("tuple structs must not be accepted as ORM models"),
            Err(error) => error,
        };
        assert_eq!(
            error.to_string(),
            "Orm macro only supports structs with named fields"
        );
    }

    #[test]
    fn rejects_missing_id_without_rendering_a_pathological_field() {
        // The v12 release fuzz campaign found a valid derive input whose field
        // type took more than ten seconds to render through `Field::span()`.
        // The same checked-in corpus seed must reach the bounded model-name
        // diagnostic without converting the complete field back into tokens.
        let source = include_str!(
            "../../rullst-orm/fuzz/corpus/fuzz_parser/pathological_field_span"
        );
        let input: DeriveInput = syn::parse_str(source)
            .expect("the release-campaign field input must remain a valid derive input");
        let error = match parse(&input) {
            Ok(_) => panic!("models without a persisted id must not be accepted"),
            Err(error) => error,
        };
        assert_eq!(
            error.to_string(),
            "Orm models require a persisted named `id` field"
        );
    }

    #[test]
    fn tenant_column_must_reference_a_supported_persisted_field() {
        use syn::parse_quote;

        let missing: DeriveInput = parse_quote! {
            #[orm(table = "records", tenant_column = "tenant_id")]
            struct Record { id: i32, name: String }
        };
        let error = parse(&missing)
            .err()
            .expect("missing tenant field must fail");
        assert!(error.to_string().contains("must name a persisted field"));

        let unsupported: DeriveInput = parse_quote! {
            #[orm(table = "records", tenant_column = "tenant_id")]
            struct Record { id: i32, tenant_id: i64 }
        };
        let error = parse(&unsupported)
            .err()
            .expect("unsupported tenant type must fail");
        assert!(error.to_string().contains("String, i32, f64, or bool"));
    }

    #[test]
    fn test_parse_sensitive_fields_audit() {
        use syn::parse_quote;

        // Test that password triggers error if auditable and not masked
        let input: DeriveInput = parse_quote! {
            #[orm(table = "t", auditable)]
            struct Model { id: i32, password: String }
        };
        assert!(parse(&input).is_err());

        // Test that token triggers error if auditable and not masked
        let input2: DeriveInput = parse_quote! {
            #[orm(table = "t", auditable)]
            struct Model { id: i32, token_field: String }
        };
        assert!(parse(&input2).is_err());

        // Test that secret triggers error if auditable and not masked
        let input3: DeriveInput = parse_quote! {
            #[orm(table = "t", auditable)]
            struct Model { id: i32, my_secret: String }
        };
        assert!(parse(&input3).is_err());

        // Test that api_key triggers error if auditable and not masked
        let input4: DeriveInput = parse_quote! {
            #[orm(table = "t", auditable)]
            struct Model { id: i32, api_key: String }
        };
        assert!(parse(&input4).is_err());

        // Test that if masked, it passes
        let input5: DeriveInput = parse_quote! {
            #[orm(table = "t", auditable)]
            struct Model { id: i32, #[orm(masked)] password: String }
        };
        assert!(parse(&input5).is_ok());

        // Test that if skipped, it passes
        let input6: DeriveInput = parse_quote! {
            #[orm(table = "t", auditable)]
            struct Model { id: i32, #[orm(skip)] password: String }
        };
        assert!(parse(&input6).is_ok());

        // Test that if relation, it passes
        let input7: DeriveInput = parse_quote! {
            #[orm(table = "t", auditable)]
            struct Model { id: i32, #[orm(has_one="P")] password: String }
        };
        assert!(parse(&input7).is_ok());
    }

    #[test]
    fn parses_supported_encrypted_fields() {
        use syn::parse_quote;

        let input: DeriveInput = parse_quote! {
            #[orm(table = "vault_records")]
            struct VaultRecord {
                id: i32,
                #[orm(encrypted)]
                secret: String,
                #[orm(encrypted)]
                recovery_code: Option<String>,
            }
        };
        let parsed = parse(&input).expect("encrypted String fields should parse");

        assert_eq!(parsed.encrypted_fields.len(), 2);
        assert_eq!(parsed.encrypted_fields[0].name, "secret");
        assert_eq!(parsed.encrypted_fields[0].kind, EncryptedFieldKind::String);
        assert_eq!(parsed.encrypted_fields[1].name, "recovery_code");
        assert_eq!(
            parsed.encrypted_fields[1].kind,
            EncryptedFieldKind::OptionalString
        );
    }

    #[test]
    fn rejects_invalid_encrypted_field_declarations() {
        use syn::parse_quote;

        let wrong_type: DeriveInput = parse_quote! {
            struct VaultRecord {
                id: i32,
                #[orm(encrypted)]
                secret: i64,
            }
        };
        assert!(parse(&wrong_type)
            .err()
            .expect("non-string encryption must fail")
            .to_string()
            .contains("supports only String and Option<String>"));

        let skipped: DeriveInput = parse_quote! {
            struct VaultRecord {
                id: i32,
                #[orm(encrypted, skip)]
                secret: String,
            }
        };
        assert!(parse(&skipped)
            .err()
            .expect("encrypted skipped fields must fail")
            .to_string()
            .contains("cannot be combined"));
    }
}