larust-macros 0.15.0

A Laravel-shaped web framework for Rust.
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
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
use crate::belongs_to_many;
use crate::has_many_through;
use crate::observe;
use crate::relations;
use crate::soft_delete;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{Data, DeriveInput, Fields};

pub fn expand(input: DeriveInput) -> syn::Result<TokenStream> {
    let struct_name = &input.ident;
    let table = table_attr(&input)?;
    let route_key = route_key_attr(&input)?;

    let Data::Struct(data) = &input.data else {
        return Err(syn::Error::new_spanned(
            &input,
            "#[derive(Model)] only supports structs",
        ));
    };
    let Fields::Named(fields) = &data.fields else {
        return Err(syn::Error::new_spanned(
            &data.fields,
            "#[derive(Model)] requires named fields",
        ));
    };

    // `#[timestamps]` - Laravel's `$table->timestamps()` +  Eloquent's
    // default auto-touch behavior, ported as a single opt-in struct
    // attribute rather than name-sniffing every struct for a
    // `created_at`/`updated_at` field unconditionally - this codebase
    // requires an explicit `#[primary_key]` even though `id` would be an
    // equally obvious convention, so silently inferring timestamp columns
    // by name alone would be the one place this macro broke its own
    // "explicit, not sniffed" precedent. See `xr convert`'s own
    // `migrations.rs`, which already emits exactly `created_at INTEGER`/
    // `updated_at INTEGER` for a ported `$table->timestamps()` - this is
    // the other half that was missing.
    let has_timestamps = has_timestamps_attr(&input);
    // `#[soft_deletes]` - see `soft_delete.rs`'s own module doc comment.
    let has_soft_deletes = soft_delete::has_soft_deletes_attr(&input);
    // `#[observe(...)]` - see `observe.rs`'s own module doc comment.
    let observers = observe::parse_observe_attr(&input)?;

    let mut primary_key: Option<(&syn::Ident, &syn::Type)> = None;
    let mut created_at_field: Option<&syn::Ident> = None;
    let mut updated_at_field: Option<&syn::Ident> = None;
    let mut deleted_at_field: Option<&syn::Ident> = None;
    let mut insertable: Vec<(&syn::Ident, &syn::Type)> = Vec::new();
    let mut all_fields: Vec<&syn::Ident> = Vec::new();
    let mut all_fields_with_types: Vec<(&syn::Ident, &syn::Type)> = Vec::new();

    for field in &fields.named {
        let ident = field.ident.as_ref().expect("named field has an ident");
        all_fields.push(ident);
        all_fields_with_types.push((ident, &field.ty));

        let field_name = field_name_str(ident);
        if field.attrs.iter().any(|a| a.path().is_ident("primary_key")) {
            if primary_key.is_some() {
                return Err(syn::Error::new_spanned(
                    field,
                    "#[derive(Model)] only supports a single #[primary_key] field",
                ));
            }
            primary_key = Some((ident, &field.ty));
        } else if has_timestamps && field_name == "created_at" {
            if !is_i64_type(&field.ty) {
                return Err(syn::Error::new_spanned(
                    &field.ty,
                    "`created_at` must be `i64` (Unix seconds) under #[timestamps]",
                ));
            }
            created_at_field = Some(ident);
        } else if has_timestamps && field_name == "updated_at" {
            if !is_i64_type(&field.ty) {
                return Err(syn::Error::new_spanned(
                    &field.ty,
                    "`updated_at` must be `i64` (Unix seconds) under #[timestamps]",
                ));
            }
            updated_at_field = Some(ident);
        } else if has_soft_deletes && field_name == "deleted_at" {
            if !is_option_i64_type(&field.ty) {
                return Err(syn::Error::new_spanned(
                    &field.ty,
                    "`deleted_at` must be `Option<i64>` (Unix seconds) under #[soft_deletes]",
                ));
            }
            deleted_at_field = Some(ident);
        } else {
            insertable.push((ident, &field.ty));
        }
    }

    let Some((pk_ident, pk_ty)) = primary_key else {
        return Err(syn::Error::new_spanned(
            &input,
            "#[derive(Model)] requires exactly one field marked #[primary_key]",
        ));
    };
    if !is_i64_type(pk_ty) {
        return Err(syn::Error::new_spanned(
            pk_ty,
            "#[primary_key] field must be `i64` (other key types land in a later milestone)",
        ));
    }
    if has_timestamps && (created_at_field.is_none() || updated_at_field.is_none()) {
        return Err(syn::Error::new_spanned(
            &input,
            "#[timestamps] requires both a `created_at: i64` field and an `updated_at: i64` field",
        ));
    }
    if has_soft_deletes && deleted_at_field.is_none() {
        return Err(syn::Error::new_spanned(
            &input,
            "#[soft_deletes] requires a `deleted_at: Option<i64>` field",
        ));
    }
    // Both automatically populated by `create()`/`update()` below - never
    // caller-supplied, so neither is a real column name here, just the
    // SQL text these two get spliced into.
    let created_at_name = created_at_field.map(field_name_str);
    let updated_at_name = updated_at_field.map(field_name_str);
    // Never caller-supplied either - managed only through `delete()`/
    // `restore()` (see `soft_delete.rs`), never part of `insertable` or
    // the generated `New*` struct.
    let deleted_at_name = deleted_at_field.map(field_name_str);

    let field_consts = all_fields.iter().map(|ident| {
        let name = field_name_str(ident);
        let const_ident = format_ident!("{}", name.to_uppercase());
        quote! { pub const #const_ident: &'static str = #name; }
    });
    let pk_name = field_name_str(pk_ident);
    let pk_const_ident = format_ident!("{}", pk_name.to_uppercase());

    let new_struct_ident = format_ident!("New{struct_name}");
    let new_fields = insertable
        .iter()
        .map(|(ident, ty)| quote! { pub #ident: #ty });

    // Every identifier below is quoted (`"..."`) because it's always a
    // developer-controlled name (the `#[table("...")]` literal or a struct
    // field name) rather than data - quoting protects against it colliding
    // with a SQL reserved keyword (a field named `order` or a table named
    // `group` are both real possibilities), not against injection.
    let insertable_names: Vec<String> = insertable.iter().map(|(i, _)| field_name_str(i)).collect();
    let insert_binds = insertable
        .iter()
        .map(|(ident, _)| quote! { .bind(data.#ident) });
    // `created_at`/`updated_at` (under `#[timestamps]`) are appended after
    // every caller-supplied column, never part of `insertable` itself -
    // both always bound to the same `__larust_now` value, computed once
    // per `create()`/`update()` call by `now_decl` below, not read from
    // `data`. `created_at` is insert-only (never appears in `update_sql`);
    // `updated_at` is re-stamped on every write, matching Eloquent's own
    // auto-touch behavior exactly.
    let insert_column_names: Vec<String> = insertable_names
        .iter()
        .cloned()
        .chain(created_at_name.clone())
        .chain(updated_at_name.clone())
        .collect();
    let update_column_names: Vec<String> = insertable_names
        .iter()
        .cloned()
        .chain(updated_at_name.clone())
        .collect();
    let timestamp_insert_binds = if has_timestamps {
        quote! { .bind(__larust_now).bind(__larust_now) }
    } else {
        quote! {}
    };
    let timestamp_update_bind = if has_timestamps {
        quote! { .bind(__larust_now) }
    } else {
        quote! {}
    };
    // Matches `larust_queue`'s own private `now_unix_secs()` exactly (same
    // Unix-seconds convention every other framework-owned timestamp column
    // already uses) - duplicated rather than shared, since pulling in a
    // dependency on `larust-queue` from generated model code for one
    // three-line computation would be a strange, one-off coupling.
    let now_decl = if has_timestamps {
        quote! {
            let __larust_now: i64 = ::std::time::SystemTime::now()
                .duration_since(::std::time::UNIX_EPOCH)
                .expect("system clock is before the Unix epoch")
                .as_secs() as i64;
        }
    } else {
        quote! {}
    };
    // Two backend-specific forms for the "insert every column at its
    // default" (no `insertable` fields) case only - SQLite's `DEFAULT
    // VALUES` clause has no MySQL equivalent; MySQL's own way to say the
    // same thing is an explicitly empty column/value list. Neither form
    // uses `RETURNING` (MySQL supports it for none of the standard
    // engines) - `create()`'s generated body below instead reads the new
    // row's id off the `INSERT`'s own `AnyQueryResult::last_insert_id()`
    // (populated by both the SQLite and MySQL drivers under `Any`) and
    // fetches the full row back with a follow-up `SELECT ... WHERE pk =
    // ?`, portable across both backends with no branching needed there.
    let (insert_sql_sqlite, insert_sql_mysql) = if insert_column_names.is_empty() {
        (
            format!("INSERT INTO \"{table}\" DEFAULT VALUES"),
            format!("INSERT INTO \"{table}\" () VALUES ()"),
        )
    } else {
        let insert_columns = insert_column_names
            .iter()
            .map(|n| format!("\"{n}\""))
            .collect::<Vec<_>>()
            .join(", ");
        let insert_placeholders = insert_column_names
            .iter()
            .map(|_| "?")
            .collect::<Vec<_>>()
            .join(", ");
        let sql =
            format!("INSERT INTO \"{table}\" ({insert_columns}) VALUES ({insert_placeholders})");
        (sql.clone(), sql)
    };
    // Postgres has neither `last_insert_rowid()` nor `LAST_INSERT_ID()` -
    // its own idiomatic way to get a just-inserted row back is `INSERT ...
    // RETURNING *` directly, one statement instead of the acquire-insert-
    // select-id-select-row dance the other two backends need (see
    // `create()`'s generated body below). `DEFAULT VALUES` (unlike MySQL)
    // is standard SQL Postgres supports natively, same as SQLite.
    let insert_sql_postgres = if insert_column_names.is_empty() {
        format!("INSERT INTO \"{table}\" DEFAULT VALUES RETURNING *")
    } else {
        let insert_columns = insert_column_names
            .iter()
            .map(|n| format!("\"{n}\""))
            .collect::<Vec<_>>()
            .join(", ");
        let insert_placeholders = (1..=insert_column_names.len())
            .map(|n| format!("${n}"))
            .collect::<Vec<_>>()
            .join(", ");
        format!(
            "INSERT INTO \"{table}\" ({insert_columns}) VALUES ({insert_placeholders}) RETURNING *"
        )
    };

    let select_by_pk_sql = format!("SELECT * FROM \"{table}\" WHERE \"{pk_name}\" = ?");
    let select_by_pk_sql_postgres = format!("SELECT * FROM \"{table}\" WHERE \"{pk_name}\" = $1");

    let delete_sql = format!("DELETE FROM \"{table}\" WHERE \"{pk_name}\" = ?");
    let delete_sql_postgres = format!("DELETE FROM \"{table}\" WHERE \"{pk_name}\" = $1");

    // `UPDATE ... SET ... WHERE` needs no backend branch - unlike `create()`'s
    // insert text, this SQL shape is identical on SQLite and MySQL, and
    // there's no `last_insert_id()`-style complication since the caller
    // already has the pk. A model with zero non-pk fields (nothing to ever
    // update) is a real but degenerate case - matching `create()`'s own
    // "no insertable fields" special case, this becomes a harmless
    // self-assignment of the primary key rather than invalid `SET` syntax
    // with an empty clause list.
    let update_sql = if update_column_names.is_empty() {
        format!("UPDATE \"{table}\" SET \"{pk_name}\" = \"{pk_name}\" WHERE \"{pk_name}\" = ?")
    } else {
        let set_clauses = update_column_names
            .iter()
            .map(|n| format!("\"{n}\" = ?"))
            .collect::<Vec<_>>()
            .join(", ");
        format!("UPDATE \"{table}\" SET {set_clauses} WHERE \"{pk_name}\" = ?")
    };
    let update_sql_postgres = if update_column_names.is_empty() {
        format!("UPDATE \"{table}\" SET \"{pk_name}\" = \"{pk_name}\" WHERE \"{pk_name}\" = $1")
    } else {
        let set_clauses = update_column_names
            .iter()
            .enumerate()
            .map(|(i, n)| format!("\"{n}\" = ${}", i + 1))
            .collect::<Vec<_>>()
            .join(", ");
        let where_placeholder = update_column_names.len() + 1;
        format!("UPDATE \"{table}\" SET {set_clauses} WHERE \"{pk_name}\" = ${where_placeholder}")
    };
    // Three independent maps over `insertable` (not shared with each other
    // or with `insert_binds` above) - each is a one-shot `Map` iterator,
    // and `quote!`'s `#(#var)*` repetition consumes whatever iterator it's
    // given; reusing the same one across multiple `#(...)*` interpolations
    // in one `quote!` invocation silently only renders it correctly the
    // first time.
    let update_binds = insertable
        .iter()
        .map(|(ident, _)| quote! { .bind(data.#ident) });
    let insert_binds_postgres = insertable
        .iter()
        .map(|(ident, _)| quote! { .bind(data.#ident) });
    let new_struct_doc =
        format!("Insertable fields for `{struct_name}` (everything except the primary key).");

    // Route model binding: `pub async fn show(post: Post)` on a route
    // declared `/posts/{post}` - the path parameter name is the
    // snake_case'd struct name (Laravel's own convention), and the lookup
    // column is the primary key by default or whatever `#[route_key("...")]`
    // names, validated against the struct's actual fields.
    let route_param_name = to_snake_case(&struct_name.to_string());
    let lookup = match &route_key {
        Some(column) => {
            if !all_fields.iter().any(|f| field_name_str(f) == *column) {
                return Err(syn::Error::new_spanned(
                    &input,
                    format!("#[route_key(\"{column}\")] does not match any field on this struct"),
                ));
            }
            let const_ident = format_ident!("{}", column.to_uppercase());
            quote! { Self::query().where_eq(Self::#const_ident, raw.clone()).first().await? }
        }
        None => quote! {
            {
                let parsed: i64 = match raw.parse() {
                    Ok(v) => v,
                    Err(_) => return ::std::result::Result::Err(::larust_support::AppError::NotFound),
                };
                Self::find(parsed).await?
            }
        },
    };

    let relations = relations::expand(&input, &all_fields_with_types, pk_ident)?;
    let belongs_to_many_relations = belongs_to_many::expand(&input, pk_ident)?;
    let has_many_through_relations =
        has_many_through::expand(&input, &all_fields_with_types, pk_ident)?;

    // `#[observe(...)]` hook fragments - spliced into `create`/`update`/
    // `delete` below. An absent hook renders as an identity/no-op
    // fragment, so every model's generated body has exactly the same
    // shape regardless of whether `#[observe(...)]` is present at all.
    let creating_expr = match &observers.creating {
        Some(hook) => quote! { #hook(data).await? },
        None => quote! { data },
    };
    let created_stmt = match &observers.created {
        Some(hook) => quote! { #hook(&__larust_created).await?; },
        None => quote! {},
    };
    let updating_expr = match &observers.updating {
        Some(hook) => quote! { #hook(#pk_ident, data).await? },
        None => quote! { data },
    };
    let updated_stmt = match &observers.updated {
        Some(hook) => quote! { #hook(&__larust_updated).await?; },
        None => quote! {},
    };
    // `deleting`/`deleted` need the row fetched first - there's no
    // already-loaded instance the way Eloquent's `$model->delete()` has.
    // Only paid for when something would actually use it. Returns early
    // with `Ok(())` (not `NotFound`) when the row is already gone,
    // preserving `delete()`'s own existing "not an error if it didn't
    // exist" contract - no hook fires for a row that was never there to
    // observe, and the real `DELETE`/soft-delete `UPDATE` below would be
    // a no-op anyway.
    let delete_snapshot_decl = if observers.needs_delete_snapshot() {
        let fetch = if has_soft_deletes {
            quote! { Self::find_with_trashed(#pk_ident).await? }
        } else {
            quote! { Self::find(#pk_ident).await? }
        };
        quote! {
            let __larust_snapshot = match #fetch {
                ::std::option::Option::Some(v) => v,
                ::std::option::Option::None => return ::std::result::Result::Ok(()),
            };
        }
    } else {
        quote! {}
    };
    let deleting_stmt = match &observers.deleting {
        Some(hook) => quote! { #hook(&__larust_snapshot).await?; },
        None => quote! {},
    };
    let deleted_stmt = match &observers.deleted {
        Some(hook) => quote! { #hook(&__larust_snapshot).await?; },
        None => quote! {},
    };

    // `query()`'s extra call, `delete()`'s branching body, and `Model`'s
    // `SOFT_DELETE_COLUMN` override - the three spots that modify code
    // already being generated below, rather than something separable
    // into `soft_delete.rs`'s own standalone `impl` block (see that
    // module's doc comment for why).
    let (soft_delete_query_call, delete_method, soft_delete_column_const) = if has_soft_deletes {
        let deleted_at_name = deleted_at_name.as_deref().expect("validated above");
        let query_call = quote! { .__with_soft_delete_column(#deleted_at_name) };

        let soft_delete_sql = format!(
            "UPDATE \"{table}\" SET \"{deleted_at_name}\" = ? WHERE \"{pk_name}\" = ? AND \"{deleted_at_name}\" IS NULL"
        );
        let soft_delete_sql_postgres = format!(
            "UPDATE \"{table}\" SET \"{deleted_at_name}\" = $1 WHERE \"{pk_name}\" = $2 AND \"{deleted_at_name}\" IS NULL"
        );
        let delete_method = quote! {
            // Soft-deletes (sets `deleted_at` instead of removing the
            // row) - `force_delete` (see `soft_delete.rs`) is the real
            // delete for a model that opted into `#[soft_deletes]`. The
            // trailing `AND "deleted_at" IS NULL` keeps this idempotent:
            // deleting an already-trashed row doesn't re-stamp its
            // `deleted_at` with a newer timestamp.
            pub async fn delete(
                #pk_ident: #pk_ty,
            ) -> ::std::result::Result<(), ::larust_support::AppError> {
                #delete_snapshot_decl
                #deleting_stmt
                let __larust_now: i64 = ::std::time::SystemTime::now()
                    .duration_since(::std::time::UNIX_EPOCH)
                    .expect("system clock is before the Unix epoch")
                    .as_secs() as i64;
                let __larust_sql = match ::larust_support::orm::backend() {
                    ::larust_support::orm::Backend::Sqlite
                    | ::larust_support::orm::Backend::MySql => #soft_delete_sql,
                    ::larust_support::orm::Backend::Postgres => #soft_delete_sql_postgres,
                };
                ::larust_support::orm::sqlx::query(__larust_sql)
                    .bind(__larust_now)
                    .bind(#pk_ident)
                    .execute(::larust_support::orm::pool()?)
                    .await
                    .map_err(|e| ::larust_support::AppError::Internal(::std::boxed::Box::new(e)))?;
                #deleted_stmt
                ::std::result::Result::Ok(())
            }
        };

        let column_const = quote! {
            const SOFT_DELETE_COLUMN: ::std::option::Option<&'static str> =
                ::std::option::Option::Some(#deleted_at_name);
        };

        (query_call, delete_method, column_const)
    } else {
        let delete_method = quote! {
            pub async fn delete(
                #pk_ident: #pk_ty,
            ) -> ::std::result::Result<(), ::larust_support::AppError> {
                #delete_snapshot_decl
                #deleting_stmt
                let __larust_delete_sql = match ::larust_support::orm::backend() {
                    ::larust_support::orm::Backend::Sqlite
                    | ::larust_support::orm::Backend::MySql => #delete_sql,
                    ::larust_support::orm::Backend::Postgres => #delete_sql_postgres,
                };
                ::larust_support::orm::sqlx::query(__larust_delete_sql)
                    .bind(#pk_ident)
                    .execute(::larust_support::orm::pool()?)
                    .await
                    .map_err(|e| ::larust_support::AppError::Internal(::std::boxed::Box::new(e)))?;
                #deleted_stmt
                ::std::result::Result::Ok(())
            }
        };
        (quote! {}, delete_method, quote! {})
    };

    // The soft-delete-only methods (`force_delete`/`restore`/
    // `find_with_trashed`/`.trashed()`) plus `impl SoftDeletes` - fully
    // additive, so this is empty output when `#[soft_deletes]` is absent.
    let soft_delete_extra = if has_soft_deletes {
        soft_delete::expand(
            struct_name,
            &table,
            pk_ident,
            pk_ty,
            &pk_name,
            deleted_at_field.expect("validated above"),
            deleted_at_name.as_deref().expect("validated above"),
        )
    } else {
        quote! {}
    };

    // `Repository<Self>`'s `create`/`update` take a full `Self` rather than
    // `#new_struct_ident` (the generic trait has no way to know a "New"
    // struct without the pk exists) - these just pick the insertable fields
    // back out of the given value and forward to the static methods above,
    // discarding whatever pk the caller's `Self` happened to carry (a brand
    // new row's real pk is only known after `create()`'s own INSERT runs).
    let repository_create_fields = insertable
        .iter()
        .map(|(ident, _)| quote! { #ident: value.#ident });
    let repository_update_fields = insertable
        .iter()
        .map(|(ident, _)| quote! { #ident: value.#ident });

    Ok(quote! {
        #[doc = #new_struct_doc]
        pub struct #new_struct_ident {
            #(#new_fields,)*
        }

        #relations
        #belongs_to_many_relations
        #has_many_through_relations
        #soft_delete_extra

        impl #struct_name {
            #(#field_consts)*
            pub const TABLE: &'static str = #table;

            pub fn query() -> ::larust_support::orm::QueryBuilder<Self> {
                ::larust_support::orm::QueryBuilder::new(Self::TABLE) #soft_delete_query_call
            }

            pub async fn all() -> ::std::result::Result<::std::vec::Vec<Self>, ::larust_support::AppError> {
                Self::query().get().await
            }

            pub async fn find(
                #pk_ident: #pk_ty,
            ) -> ::std::result::Result<::std::option::Option<Self>, ::larust_support::AppError> {
                Self::query().where_eq(Self::#pk_const_ident, #pk_ident).first().await
            }

            pub async fn create(
                data: #new_struct_ident,
            ) -> ::std::result::Result<Self, ::larust_support::AppError> {
                let data = #creating_expr;
                #now_decl
                // Postgres has neither `last_insert_rowid()` nor
                // `LAST_INSERT_ID()` - its own idiomatic way to get a
                // just-inserted row back is `INSERT ... RETURNING *`
                // directly, one statement instead of the acquire-insert-
                // select-id-select-row dance the other two backends need
                // below, and with no connection-affinity concern to manage
                // (a single statement, run directly on the pool).
                if ::larust_support::orm::backend() == ::larust_support::orm::Backend::Postgres {
                    let __larust_created = ::larust_support::orm::sqlx::query_as::<_, Self>(#insert_sql_postgres)
                        #(#insert_binds_postgres)*
                        #timestamp_insert_binds
                        .fetch_one(::larust_support::orm::pool()?)
                        .await
                        .map_err(|e| ::larust_support::AppError::Internal(::std::boxed::Box::new(e)))?;
                    #created_stmt
                    return ::std::result::Result::Ok(__larust_created);
                }

                let __larust_insert_sql = match ::larust_support::orm::backend() {
                    ::larust_support::orm::Backend::Sqlite => #insert_sql_sqlite,
                    ::larust_support::orm::Backend::MySql => #insert_sql_mysql,
                    ::larust_support::orm::Backend::Postgres => ::std::unreachable!(),
                };
                // `AnyQueryResult::last_insert_id()` looks like the obvious
                // way to get the new row's id, but `sqlx-sqlite`'s own
                // `Any`-driver adapter hardcodes it to `None` unconditionally
                // (confirmed by reading its source - MySQL's adapter *does*
                // populate it, so this asymmetry is SQLite-specific) - so a
                // portable `SELECT last_insert_rowid()`/`SELECT
                // LAST_INSERT_ID()` follow-up query is used instead, which
                // works through `Any` on both backends. That value is
                // connection-local session state, not something a query
                // result carries - so the `INSERT` and this follow-up
                // `SELECT` must run on the *same* acquired connection, not
                // just "the pool" (two separate `pool`-level calls aren't
                // guaranteed to land on the same physical connection).
                let mut __larust_conn = ::larust_support::orm::pool()?
                    .acquire()
                    .await
                    .map_err(|e| ::larust_support::AppError::Internal(::std::boxed::Box::new(e)))?;
                ::larust_support::orm::sqlx::query(__larust_insert_sql)
                    #(#insert_binds)*
                    #timestamp_insert_binds
                    .execute(&mut *__larust_conn)
                    .await
                    .map_err(|e| ::larust_support::AppError::Internal(::std::boxed::Box::new(e)))?;
                let __larust_last_id_sql = match ::larust_support::orm::backend() {
                    ::larust_support::orm::Backend::Sqlite => "SELECT last_insert_rowid()",
                    ::larust_support::orm::Backend::MySql => "SELECT LAST_INSERT_ID()",
                    ::larust_support::orm::Backend::Postgres => ::std::unreachable!(),
                };
                let (__larust_id,): (i64,) =
                    ::larust_support::orm::sqlx::query_as(__larust_last_id_sql)
                        .fetch_one(&mut *__larust_conn)
                        .await
                        .map_err(|e| ::larust_support::AppError::Internal(::std::boxed::Box::new(e)))?;
                let __larust_created = ::larust_support::orm::sqlx::query_as::<_, Self>(#select_by_pk_sql)
                    .bind(__larust_id)
                    .fetch_one(&mut *__larust_conn)
                    .await
                    .map_err(|e| ::larust_support::AppError::Internal(::std::boxed::Box::new(e)))?;
                #created_stmt
                ::std::result::Result::Ok(__larust_created)
            }

            pub async fn update(
                #pk_ident: #pk_ty,
                data: #new_struct_ident,
            ) -> ::std::result::Result<Self, ::larust_support::AppError> {
                let data = #updating_expr;
                #now_decl
                let __larust_update_sql = match ::larust_support::orm::backend() {
                    ::larust_support::orm::Backend::Sqlite
                    | ::larust_support::orm::Backend::MySql => #update_sql,
                    ::larust_support::orm::Backend::Postgres => #update_sql_postgres,
                };
                let __larust_select_by_pk_sql = match ::larust_support::orm::backend() {
                    ::larust_support::orm::Backend::Sqlite
                    | ::larust_support::orm::Backend::MySql => #select_by_pk_sql,
                    ::larust_support::orm::Backend::Postgres => #select_by_pk_sql_postgres,
                };
                ::larust_support::orm::sqlx::query(__larust_update_sql)
                    #(#update_binds)*
                    #timestamp_update_bind
                    .bind(#pk_ident)
                    .execute(::larust_support::orm::pool()?)
                    .await
                    .map_err(|e| ::larust_support::AppError::Internal(::std::boxed::Box::new(e)))?;
                let __larust_updated = ::larust_support::orm::sqlx::query_as::<_, Self>(__larust_select_by_pk_sql)
                    .bind(#pk_ident)
                    .fetch_one(::larust_support::orm::pool()?)
                    .await
                    .map_err(|e| ::larust_support::AppError::Internal(::std::boxed::Box::new(e)))?;
                #updated_stmt
                ::std::result::Result::Ok(__larust_updated)
            }

            #delete_method
        }

        #[::larust_support::axum::async_trait]
        impl<S: ::std::marker::Send + ::std::marker::Sync>
            ::larust_support::axum::extract::FromRequestParts<S> for #struct_name
        {
            type Rejection = ::larust_support::AppError;

            async fn from_request_parts(
                parts: &mut ::larust_support::axum::http::request::Parts,
                state: &S,
            ) -> ::std::result::Result<Self, Self::Rejection> {
                let ::larust_support::axum::extract::Path(params) = <
                    ::larust_support::axum::extract::Path<
                        ::std::collections::HashMap<::std::string::String, ::std::string::String>
                    > as ::larust_support::axum::extract::FromRequestParts<S>
                >::from_request_parts(parts, state)
                    .await
                    .map_err(|_| ::larust_support::AppError::NotFound)?;

                let raw = params
                    .get(#route_param_name)
                    .ok_or(::larust_support::AppError::NotFound)?;

                let found: ::std::option::Option<Self> = #lookup;
                found.ok_or(::larust_support::AppError::NotFound)
            }
        }

        // Lets generic code (model factories, and more in later
        // milestones) call `T::create(...)` without knowing the concrete
        // struct - see `larust_orm::model`'s own doc comment. `Self::create`
        // below resolves to the inherent `create` generated above, not this
        // same trait method - inherent methods always take priority over
        // trait methods of the same name, so this doesn't recurse.
        impl ::larust_support::orm::Model for #struct_name {
            type New = #new_struct_ident;
            const TABLE: &'static str = #table;
            #soft_delete_column_const

            async fn create(
                data: Self::New,
            ) -> ::std::result::Result<Self, ::larust_support::AppError> {
                Self::create(data).await
            }
        }

        // Makes `Self` conform to `larust_support::repository::Repository`
        // for free - `larust_orm::AnyRepository<T>` is a stateless marker
        // type this impl targets; the actual SQL-family logic is just the
        // static methods generated above. This is what lets SQL-family code
        // written generically against `Repository<T>` be handed a
        // `#struct_name`-backed repository interchangeably with a
        // hand-written non-SQL one - existing `Self::query()`/`Self::find()`
        // call sites are completely unaffected and never need to go through
        // this.
        impl ::larust_support::repository::Repository<#struct_name>
            for ::larust_support::orm::AnyRepository<#struct_name>
        {
            type Filter = ::larust_support::orm::QueryBuilder<#struct_name>;
            type Id = #pk_ty;

            async fn find(
                &self,
                id: Self::Id,
            ) -> ::std::result::Result<::std::option::Option<#struct_name>, ::larust_support::AppError>
            {
                #struct_name::find(id).await
            }

            async fn query(
                &self,
                filter: Self::Filter,
            ) -> ::std::result::Result<::std::vec::Vec<#struct_name>, ::larust_support::AppError> {
                filter.get().await
            }

            async fn create(
                &self,
                value: #struct_name,
            ) -> ::std::result::Result<#struct_name, ::larust_support::AppError> {
                #struct_name::create(#new_struct_ident {
                    #(#repository_create_fields,)*
                })
                .await
            }

            async fn update(
                &self,
                id: Self::Id,
                value: #struct_name,
            ) -> ::std::result::Result<#struct_name, ::larust_support::AppError> {
                #struct_name::update(
                    id,
                    #new_struct_ident {
                        #(#repository_update_fields,)*
                    },
                )
                .await
            }

            async fn delete(
                &self,
                id: Self::Id,
            ) -> ::std::result::Result<(), ::larust_support::AppError> {
                #struct_name::delete(id).await
            }
        }
    })
}

fn table_attr(input: &DeriveInput) -> syn::Result<String> {
    for attr in &input.attrs {
        if attr.path().is_ident("table") {
            let lit: syn::LitStr = attr.parse_args()?;
            return Ok(lit.value());
        }
    }
    Err(syn::Error::new_spanned(
        input,
        "#[derive(Model)] requires a #[table(\"...\")] attribute",
    ))
}

pub(crate) fn is_i64_type(ty: &syn::Type) -> bool {
    matches!(ty, syn::Type::Path(p) if p.path.segments.last().is_some_and(|s| s.ident == "i64"))
}

/// `true` for exactly `Option<i64>` - what `#[soft_deletes]`'s
/// `deleted_at` field must be typed as (nullable: absent until trashed).
pub(crate) fn is_option_i64_type(ty: &syn::Type) -> bool {
    let syn::Type::Path(path) = ty else {
        return false;
    };
    let Some(segment) = path.path.segments.last() else {
        return false;
    };
    if segment.ident != "Option" {
        return false;
    }
    let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
        return false;
    };
    args.args.len() == 1
        && matches!(
            &args.args[0],
            syn::GenericArgument::Type(inner) if is_i64_type(inner)
        )
}

/// `#[timestamps]` - opts a struct into automatic `created_at`/
/// `updated_at` population (Laravel's `$table->timestamps()` + Eloquent's
/// default auto-touch behavior). Bare, no arguments - unlike `#[table("...")]`/
/// `#[route_key("...")]`, there's no name to parametrize, since the two
/// column names it looks for are fixed by convention.
fn has_timestamps_attr(input: &DeriveInput) -> bool {
    input.attrs.iter().any(|a| a.path().is_ident("timestamps"))
}

/// `#[route_key("slug")]` - which field route model binding looks records
/// up by, instead of the primary key. Optional.
fn route_key_attr(input: &DeriveInput) -> syn::Result<Option<String>> {
    for attr in &input.attrs {
        if attr.path().is_ident("route_key") {
            let lit: syn::LitStr = attr.parse_args()?;
            return Ok(Some(lit.value()));
        }
    }
    Ok(None)
}

/// `Post` -> `"post"`, `BlogPost` -> `"blog_post"` - the default route
/// parameter name route model binding looks for (Laravel's own convention:
/// the path segment name matches the lowercased model name). Also used by
/// `relations.rs` to derive a relationship method's default name from its
/// related type.
pub(crate) fn to_snake_case(name: &str) -> String {
    let mut result = String::with_capacity(name.len() + 4);
    for (i, c) in name.chars().enumerate() {
        if c.is_uppercase() {
            if i != 0 {
                result.push('_');
            }
            result.extend(c.to_lowercase());
        } else {
            result.push(c);
        }
    }
    result
}

/// Strips a raw-identifier prefix (`r#type` -> `type`) - this is used both
/// as the SQL column name and as the basis for a generated `CONST_NAME`,
/// neither of which should carry Rust's own keyword-escaping syntax.
/// Without this, a field named `r#type` panics `format_ident!` (rather
/// than a clean `syn::Error`) and the wrong string (`"r#type"`) would end
/// up as both the constant's value and the actual SQL column name.
pub(crate) fn field_name_str(ident: &syn::Ident) -> String {
    ident.to_string().trim_start_matches("r#").to_string()
}

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

    #[test]
    fn single_word_lowercases() {
        assert_eq!(to_snake_case("Post"), "post");
    }

    #[test]
    fn multi_word_inserts_underscores() {
        assert_eq!(to_snake_case("BlogPost"), "blog_post");
        assert_eq!(to_snake_case("UserProfileSetting"), "user_profile_setting");
    }
}