Skip to main content

rustango_macros/
lib.rs

1//! Proc-macros for rustango.
2//!
3//! v0.1 ships `#[derive(Model)]`, which emits:
4//! * a `Model` impl carrying a static `ModelSchema`,
5//! * an `inventory::submit!` so the model is discoverable from the registry,
6//! * an inherent `objects()` returning a `QuerySet<Self>`,
7//! * a `sqlx::FromRow` impl so query results decode into the struct.
8
9use proc_macro::TokenStream;
10use proc_macro2::TokenStream as TokenStream2;
11use quote::quote;
12use syn::{
13    parse_macro_input, spanned::Spanned, Data, DeriveInput, Fields, GenericArgument, LitStr,
14    PathArguments, Type, TypePath,
15};
16
17/// Derive a `Model` impl. See crate docs for the supported attributes.
18#[proc_macro_derive(Model, attributes(rustango))]
19pub fn derive_model(input: TokenStream) -> TokenStream {
20    let input = parse_macro_input!(input as DeriveInput);
21    expand(&input)
22        .unwrap_or_else(syn::Error::into_compile_error)
23        .into()
24}
25
26/// Derive a `router(prefix, pool) -> axum::Router` associated method on a
27/// marker struct, wiring the full CRUD ViewSet in one annotation.
28///
29/// ```ignore
30/// #[derive(ViewSet)]
31/// #[viewset(
32///     model        = Post,
33///     fields       = "id, title, body, author_id",
34///     filter_fields = "author_id",
35///     search_fields = "title, body",
36///     ordering     = "-published_at",
37///     page_size    = 20,
38/// )]
39/// pub struct PostViewSet;
40///
41/// // Mount into your app:
42/// let app = Router::new()
43///     .merge(PostViewSet::router("/api/posts", pool.clone()));
44/// ```
45///
46/// Attributes:
47/// * `model = TypeName` — *required*. The `#[derive(Model)]` struct whose
48///   `SCHEMA` constant drives the endpoints.
49/// * `fields = "a, b, c"` — scalar fields included in list/retrieve JSON
50///   and accepted on create/update (default: all scalar fields).
51/// * `filter_fields = "a, b"` — fields filterable via `?a=v` query params.
52/// * `search_fields = "a, b"` — fields searched by `?search=...`.
53/// * `ordering = "a, -b"` — default list ordering; prefix `-` for DESC.
54/// * `page_size = N` — default page size (default: 20, max: 1000).
55/// * `read_only` — flag; wires only `list` + `retrieve` (no mutations).
56/// * `permissions(list = "...", retrieve = "...", create = "...",
57///   update = "...", destroy = "...")` — codenames required per action.
58#[proc_macro_derive(ViewSet, attributes(viewset))]
59pub fn derive_viewset(input: TokenStream) -> TokenStream {
60    let input = parse_macro_input!(input as DeriveInput);
61    expand_viewset(&input)
62        .unwrap_or_else(syn::Error::into_compile_error)
63        .into()
64}
65
66/// Derive `rustango::forms::FormStruct` (slice 8.4B). Generates a
67/// `parse(&HashMap<String, String>) -> Result<Self, FormError>` impl
68/// that walks every named field and:
69///
70/// * Parses the string value into the field's Rust type (`String`,
71///   `i32`, `i64`, `f32`, `f64`, `bool`, plus `Option<T>` for the
72///   nullable case).
73/// * Applies any `#[form(min = ..)]` / `#[form(max = ..)]` /
74///   `#[form(min_length = ..)]` / `#[form(max_length = ..)]`
75///   validators in declaration order, returning `FormError::Parse`
76///   on the first failure.
77///
78/// Example:
79///
80/// ```ignore
81/// #[derive(Form)]
82/// pub struct CreateItemForm {
83///     #[form(min_length = 1, max_length = 64)]
84///     pub name: String,
85///     #[form(min = 0, max = 150)]
86///     pub age: i32,
87///     pub active: bool,
88///     pub email: Option<String>,
89/// }
90///
91/// let parsed = CreateItemForm::parse(&form_map)?;
92/// ```
93#[proc_macro_derive(Form, attributes(form))]
94pub fn derive_form(input: TokenStream) -> TokenStream {
95    let input = parse_macro_input!(input as DeriveInput);
96    expand_form(&input)
97        .unwrap_or_else(syn::Error::into_compile_error)
98        .into()
99}
100
101/// Derive [`rustango::serializer::ModelSerializer`] for a struct.
102///
103/// # Container attribute (required)
104/// `#[serializer(model = TypeName)]` — the [`Model`] type this serializer maps from.
105///
106/// # Field attributes
107/// - `#[serializer(read_only)]` — mapped from model; included in JSON output; excluded from `writable_fields()`
108/// - `#[serializer(write_only)]` — `Default::default()` in `from_model`; excluded from JSON output; included in `writable_fields()`
109/// - `#[serializer(source = "field_name")]` — reads from `model.field_name` instead of `model.<field_ident>`
110/// - `#[serializer(skip)]` — `Default::default()` in `from_model`; included in JSON output; excluded from `writable_fields()` (user sets manually)
111///
112/// The macro also emits a custom `impl serde::Serialize` — do **not** also `#[derive(Serialize)]`.
113#[proc_macro_derive(Serializer, attributes(serializer))]
114pub fn derive_serializer(input: TokenStream) -> TokenStream {
115    let input = parse_macro_input!(input as DeriveInput);
116    expand_serializer(&input)
117        .unwrap_or_else(syn::Error::into_compile_error)
118        .into()
119}
120
121/// Bake every `*.json` migration file in a directory into the binary
122/// at compile time. Returns a `&'static [(&'static str, &'static str)]`
123/// of `(name, json_content)` pairs, lex-sorted by file stem.
124///
125/// Pair with `rustango::migrate::migrate_embedded` at runtime — same
126/// behaviour as `migrate(pool, dir)` but with no filesystem access.
127/// The path is interpreted relative to the user's `CARGO_MANIFEST_DIR`
128/// (i.e. the crate that invokes the macro). Default is
129/// `"./migrations"` if no argument is supplied.
130///
131/// ```ignore
132/// const EMBEDDED: &[(&str, &str)] = rustango::embed_migrations!();
133/// // or:
134/// const EMBEDDED: &[(&str, &str)] = rustango::embed_migrations!("./migrations");
135///
136/// rustango::migrate::migrate_embedded(&pool, EMBEDDED).await?;
137/// ```
138///
139/// **Compile-time guarantees** (rustango v0.4+, slice 5): every JSON
140/// file's `name` field must equal its file stem, every `prev`
141/// reference must point to another migration in the same directory,
142/// and the JSON must parse. A broken chain — orphan `prev`, missing
143/// predecessor, malformed file — fails at macro-expansion time with
144/// a clear `compile_error!`. *No other Django-shape Rust framework
145/// validates migration chains at compile time*: Cot's migrations are
146/// imperative Rust code (no static chain), Loco's are SeaORM
147/// up/down (same), Rwf's are raw SQL (no chain at all).
148///
149/// Each migration is included via `include_str!` so cargo's rebuild
150/// detection picks up file *content* changes. **Caveat:** cargo
151/// doesn't watch directory listings, so adding or removing a
152/// migration file inside the dir won't auto-trigger a rebuild — run
153/// `cargo clean` (or just bump any other source file) when you add
154/// new migrations during embedded development.
155#[proc_macro]
156pub fn embed_migrations(input: TokenStream) -> TokenStream {
157    expand_embed_migrations(input.into())
158        .unwrap_or_else(syn::Error::into_compile_error)
159        .into()
160}
161
162/// `#[rustango::main]` — the Django-shape runserver entrypoint. Wraps
163/// `#[tokio::main]` and a default `tracing_subscriber` initialisation
164/// (env-filter, falling back to `info,sqlx=warn`) so user `main`
165/// functions are zero-boilerplate:
166///
167/// ```ignore
168/// #[rustango::main]
169/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
170///     rustango::server::Builder::from_env().await?
171///         .migrate("migrations").await?
172///         .api(my_app::urls::api())
173///         .seed_with(my_app::seed::run).await?
174///         .serve("0.0.0.0:8080").await
175/// }
176/// ```
177///
178/// Optional `flavor = "current_thread"` passes through to
179/// `#[tokio::main]`; default is the multi-threaded runtime.
180///
181/// Pulls `tracing-subscriber` into the rustango crate behind the
182/// `runtime` sub-feature (implied by `tenancy`), so apps that opt
183/// out get plain `#[tokio::main]` ergonomics without the dependency.
184#[proc_macro_attribute]
185pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
186    expand_main(args.into(), item.into())
187        .unwrap_or_else(syn::Error::into_compile_error)
188        .into()
189}
190
191fn expand_main(args: TokenStream2, item: TokenStream2) -> syn::Result<TokenStream2> {
192    let mut input: syn::ItemFn = syn::parse2(item)?;
193    if input.sig.asyncness.is_none() {
194        return Err(syn::Error::new(
195            input.sig.ident.span(),
196            "`#[rustango::main]` must wrap an `async fn`",
197        ));
198    }
199
200    // Parse optional `flavor = "..."` etc. from the attribute args
201    // and pass them straight through to `#[tokio::main(...)]`.
202    let tokio_attr = if args.is_empty() {
203        quote! { #[::tokio::main] }
204    } else {
205        quote! { #[::tokio::main(#args)] }
206    };
207
208    // Re-block the body so the tracing init runs before user code.
209    let body = input.block.clone();
210    input.block = syn::parse2(quote! {{
211        {
212            use ::rustango::__private_runtime::tracing_subscriber::{self, EnvFilter};
213            // `try_init` so duplicate installers (e.g. tests already
214            // holding a subscriber) don't panic.
215            let _ = tracing_subscriber::fmt()
216                .with_env_filter(
217                    EnvFilter::try_from_default_env()
218                        .unwrap_or_else(|_| EnvFilter::new("info,sqlx=warn")),
219                )
220                .try_init();
221        }
222        #body
223    }})?;
224
225    Ok(quote! {
226        #tokio_attr
227        #input
228    })
229}
230
231fn expand_embed_migrations(input: TokenStream2) -> syn::Result<TokenStream2> {
232    // Default to "./migrations" if invoked without args.
233    let path_str = if input.is_empty() {
234        "./migrations".to_string()
235    } else {
236        let lit: LitStr = syn::parse2(input)?;
237        lit.value()
238    };
239
240    let manifest = std::env::var("CARGO_MANIFEST_DIR").map_err(|_| {
241        syn::Error::new(
242            proc_macro2::Span::call_site(),
243            "embed_migrations! must be invoked during a Cargo build (CARGO_MANIFEST_DIR not set)",
244        )
245    })?;
246    let abs = std::path::Path::new(&manifest).join(&path_str);
247
248    let mut entries: Vec<(String, std::path::PathBuf)> = Vec::new();
249    if abs.is_dir() {
250        let read = std::fs::read_dir(&abs).map_err(|e| {
251            syn::Error::new(
252                proc_macro2::Span::call_site(),
253                format!("embed_migrations!: cannot read {}: {e}", abs.display()),
254            )
255        })?;
256        for entry in read.flatten() {
257            let path = entry.path();
258            if !path.is_file() {
259                continue;
260            }
261            if path.extension().and_then(|s| s.to_str()) != Some("json") {
262                continue;
263            }
264            let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
265                continue;
266            };
267            entries.push((stem.to_owned(), path));
268        }
269    }
270    entries.sort_by(|a, b| a.0.cmp(&b.0));
271
272    // Compile-time chain validation: read each migration's JSON,
273    // pull `name` and `prev` (file-stem-keyed for the chain check),
274    // and verify every `prev` points to another migration in the
275    // slice. Mismatches between the file stem and the embedded
276    // `name` field — and broken `prev` chains — fail at MACRO
277    // EXPANSION time so a misshapen migration set never compiles.
278    //
279    // This is the v0.4 Slice 5 distinguisher: rustango's JSON
280    // migrations + a Rust proc-macro that reads them is the unique
281    // combo nothing else in the Django-shape Rust camp can match
282    // (Cot's are imperative Rust code, Loco's are SeaORM up/down,
283    // Rwf's are raw SQL — none have a static chain to validate).
284    let mut chain_names: Vec<String> = Vec::with_capacity(entries.len());
285    let mut prev_refs: Vec<(String, Option<String>)> = Vec::with_capacity(entries.len());
286    for (stem, path) in &entries {
287        let raw = std::fs::read_to_string(path).map_err(|e| {
288            syn::Error::new(
289                proc_macro2::Span::call_site(),
290                format!(
291                    "embed_migrations!: cannot read {} for chain validation: {e}",
292                    path.display()
293                ),
294            )
295        })?;
296        let json: serde_json::Value = serde_json::from_str(&raw).map_err(|e| {
297            syn::Error::new(
298                proc_macro2::Span::call_site(),
299                format!(
300                    "embed_migrations!: {} is not valid JSON: {e}",
301                    path.display()
302                ),
303            )
304        })?;
305        let name = json
306            .get("name")
307            .and_then(|v| v.as_str())
308            .ok_or_else(|| {
309                syn::Error::new(
310                    proc_macro2::Span::call_site(),
311                    format!(
312                        "embed_migrations!: {} is missing the `name` field",
313                        path.display()
314                    ),
315                )
316            })?
317            .to_owned();
318        if name != *stem {
319            return Err(syn::Error::new(
320                proc_macro2::Span::call_site(),
321                format!(
322                    "embed_migrations!: file stem `{stem}` does not match the migration's \
323                     `name` field `{name}` — rename the file or fix the JSON",
324                ),
325            ));
326        }
327        let prev = json.get("prev").and_then(|v| v.as_str()).map(str::to_owned);
328        chain_names.push(name.clone());
329        prev_refs.push((name, prev));
330    }
331
332    let name_set: std::collections::HashSet<&str> =
333        chain_names.iter().map(String::as_str).collect();
334    for (name, prev) in &prev_refs {
335        if let Some(p) = prev {
336            if !name_set.contains(p.as_str()) {
337                return Err(syn::Error::new(
338                    proc_macro2::Span::call_site(),
339                    format!(
340                        "embed_migrations!: broken migration chain — `{name}` declares \
341                         prev=`{p}` but no migration with that name exists in {}",
342                        abs.display()
343                    ),
344                ));
345            }
346        }
347    }
348
349    let pairs: Vec<TokenStream2> = entries
350        .iter()
351        .map(|(name, path)| {
352            let path_lit = path.display().to_string();
353            quote! { (#name, ::core::include_str!(#path_lit)) }
354        })
355        .collect();
356
357    Ok(quote! {
358        {
359            const __RUSTANGO_EMBEDDED: &[(&'static str, &'static str)] = &[#(#pairs),*];
360            __RUSTANGO_EMBEDDED
361        }
362    })
363}
364
365fn expand(input: &DeriveInput) -> syn::Result<TokenStream2> {
366    let struct_name = &input.ident;
367
368    let Data::Struct(data) = &input.data else {
369        return Err(syn::Error::new_spanned(
370            struct_name,
371            "Model can only be derived on structs",
372        ));
373    };
374    let Fields::Named(named) = &data.fields else {
375        return Err(syn::Error::new_spanned(
376            struct_name,
377            "Model requires a struct with named fields",
378        ));
379    };
380
381    let container = parse_container_attrs(input)?;
382    let table = container
383        .table
384        .unwrap_or_else(|| to_snake_case(&struct_name.to_string()));
385    let model_name = struct_name.to_string();
386
387    let collected = collect_fields(named, &table)?;
388
389    // Validate that #[rustango(display = "…")] names a real field.
390    if let Some((ref display, span)) = container.display {
391        if !collected.field_names.iter().any(|n| n == display) {
392            return Err(syn::Error::new(
393                span,
394                format!("`display = \"{display}\"` does not match any field on this struct"),
395            ));
396        }
397    }
398    let display = container.display.map(|(name, _)| name);
399    let app_label = container.app.clone();
400
401    // Validate admin field-name lists against declared field names.
402    if let Some(admin) = &container.admin {
403        for (label, list) in [
404            ("list_display", &admin.list_display),
405            ("search_fields", &admin.search_fields),
406            ("readonly_fields", &admin.readonly_fields),
407            ("list_filter", &admin.list_filter),
408        ] {
409            if let Some((names, span)) = list {
410                for name in names {
411                    if !collected.field_names.iter().any(|n| n == name) {
412                        return Err(syn::Error::new(
413                            *span,
414                            format!(
415                                "`{label} = \"{name}\"`: \"{name}\" is not a declared field on this struct"
416                            ),
417                        ));
418                    }
419                }
420            }
421        }
422        if let Some((pairs, span)) = &admin.ordering {
423            for (name, _) in pairs {
424                if !collected.field_names.iter().any(|n| n == name) {
425                    return Err(syn::Error::new(
426                        *span,
427                        format!(
428                            "`ordering = \"{name}\"`: \"{name}\" is not a declared field on this struct"
429                        ),
430                    ));
431                }
432            }
433        }
434        if let Some((groups, span)) = &admin.fieldsets {
435            for (_, fields) in groups {
436                for name in fields {
437                    if !collected.field_names.iter().any(|n| n == name) {
438                        return Err(syn::Error::new(
439                            *span,
440                            format!(
441                                "`fieldsets`: \"{name}\" is not a declared field on this struct"
442                            ),
443                        ));
444                    }
445                }
446            }
447        }
448    }
449    if let Some(audit) = &container.audit {
450        if let Some((names, span)) = &audit.track {
451            for name in names {
452                if !collected.field_names.iter().any(|n| n == name) {
453                    return Err(syn::Error::new(
454                        *span,
455                        format!(
456                            "`audit(track = \"{name}\")`: \"{name}\" is not a declared field on this struct"
457                        ),
458                    ));
459                }
460            }
461        }
462    }
463
464    // Build the audit_track list for ModelSchema: None when no audit attr,
465    // Some(empty) when audit present without track, Some(names) when explicit.
466    let audit_track_names: Option<Vec<String>> = container.audit.as_ref().map(|audit| {
467        audit
468            .track
469            .as_ref()
470            .map(|(names, _)| names.clone())
471            .unwrap_or_default()
472    });
473
474    // Merge field-level indexes into the container's index list.
475    let mut all_indexes: Vec<IndexAttr> = container.indexes;
476    for field in &named.named {
477        let ident = field.ident.as_ref().expect("named");
478        let col = to_snake_case(&ident.to_string()); // column name fallback
479                                                     // Re-parse field attrs to check for index flag
480        if let Ok(fa) = parse_field_attrs(field) {
481            if fa.index {
482                let col_name = fa.column.clone().unwrap_or_else(|| col.clone());
483                let auto_name = if fa.index_unique {
484                    format!("{table}_{col_name}_uq_idx")
485                } else {
486                    format!("{table}_{col_name}_idx")
487                };
488                all_indexes.push(IndexAttr {
489                    name: fa.index_name.or(Some(auto_name)),
490                    columns: vec![col_name],
491                    unique: fa.index_unique,
492                });
493            }
494        }
495    }
496
497    let model_impl = model_impl_tokens(
498        struct_name,
499        &model_name,
500        &table,
501        display.as_deref(),
502        app_label.as_deref(),
503        container.admin.as_ref(),
504        &collected.field_schemas,
505        collected.soft_delete_column.as_deref(),
506        container.permissions,
507        audit_track_names.as_deref(),
508        &container.m2m,
509        &all_indexes,
510        &container.checks,
511        &container.composite_fks,
512        &container.generic_fks,
513        container.scope.as_deref(),
514    );
515    let module_ident = column_module_ident(struct_name);
516    let column_consts = column_const_tokens(&module_ident, &collected.column_entries);
517    let audited_fields: Option<Vec<&ColumnEntry>> = container.audit.as_ref().map(|audit| {
518        let track_set: Option<std::collections::HashSet<&str>> = audit
519            .track
520            .as_ref()
521            .map(|(names, _)| names.iter().map(String::as_str).collect());
522        collected
523            .column_entries
524            .iter()
525            .filter(|c| {
526                track_set
527                    .as_ref()
528                    .map_or(true, |s| s.contains(c.name.as_str()))
529            })
530            .collect()
531    });
532    let inherent_impl = inherent_impl_tokens(
533        struct_name,
534        &collected,
535        collected.primary_key.as_ref(),
536        &column_consts,
537        audited_fields.as_deref(),
538        &all_indexes,
539    );
540    let column_module = column_module_tokens(&module_ident, struct_name, &collected.column_entries);
541    let from_row_impl = from_row_impl_tokens(struct_name, &collected.from_row_inits);
542    let reverse_helpers = reverse_helper_tokens(struct_name, &collected.fk_relations);
543    let m2m_accessors = m2m_accessor_tokens(struct_name, &container.m2m);
544
545    Ok(quote! {
546        #model_impl
547        #inherent_impl
548        #from_row_impl
549        #column_module
550        #reverse_helpers
551        #m2m_accessors
552
553        ::rustango::core::inventory::submit! {
554            ::rustango::core::ModelEntry {
555                schema: <#struct_name as ::rustango::core::Model>::SCHEMA,
556                // `module_path!()` evaluates at the registration site,
557                // so a Model declared in `crate::blog::models` records
558                // `"<crate>::blog::models"` and `resolved_app_label()`
559                // can infer "blog" without an explicit attribute.
560                module_path: ::core::module_path!(),
561            }
562        }
563    })
564}
565
566/// Emit `impl LoadRelated for #StructName` — slice 9.0d. Pattern-
567/// matches `field_name` against the model's FK fields and, for a
568/// match, decodes the FK target via the parent's macro-generated
569/// `__rustango_from_aliased_row`, reads the parent's PK, and stores
570/// `ForeignKey::Loaded` on `self`.
571///
572/// Always emitted (with empty arms for FK-less models, which
573/// return `Ok(false)` for any field name) so the `T: LoadRelated`
574/// trait bound on `fetch_on` is universally satisfied — users
575/// never have to think about implementing it.
576fn load_related_impl_tokens(struct_name: &syn::Ident, fk_relations: &[FkRelation]) -> TokenStream2 {
577    let arms = fk_relations.iter().map(|rel| {
578        let parent_ty = &rel.parent_type;
579        let fk_col = rel.fk_column.as_str();
580        // FK field's Rust ident matches its SQL column name in v0.8
581        // (no `column = "..."` rename ships on FK fields).
582        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
583        let (variant_ident, default_expr) = rel.pk_kind.sqlvalue_match_arm();
584        let assign = if rel.nullable {
585            quote! {
586                self.#field_ident = ::core::option::Option::Some(
587                    ::rustango::sql::ForeignKey::loaded(_pk, _parent),
588                );
589            }
590        } else {
591            quote! {
592                self.#field_ident = ::rustango::sql::ForeignKey::loaded(_pk, _parent);
593            }
594        };
595        quote! {
596            #fk_col => {
597                let _parent: #parent_ty = <#parent_ty>::__rustango_from_aliased_row(row, alias)?;
598                // Loud-in-debug, default-in-release: a divergence
599                // between the FK field's declared `K` (drives the
600                // expected `SqlValue::<Variant>`) and the parent's
601                // `__rustango_pk_value` output is a macro-internal
602                // invariant break — surfacing the panic in dev
603                // catches it before users hit silent PK=0 corruption.
604                let _pk = match <#parent_ty>::__rustango_pk_value(&_parent) {
605                    ::rustango::core::SqlValue::#variant_ident(v) => v,
606                    _other => {
607                        ::core::debug_assert!(
608                            false,
609                            "rustango macro bug: load_related on FK `{}` expected \
610                             SqlValue::{} from parent's __rustango_pk_value but got \
611                             {:?} — file a bug at https://github.com/ujeenet/rustango",
612                            #fk_col,
613                            ::core::stringify!(#variant_ident),
614                            _other,
615                        );
616                        #default_expr
617                    }
618                };
619                #assign
620                ::core::result::Result::Ok(true)
621            }
622        }
623    });
624    quote! {
625        impl ::rustango::sql::LoadRelated for #struct_name {
626            #[allow(unused_variables)]
627            fn __rustango_load_related(
628                &mut self,
629                row: &::rustango::sql::sqlx::postgres::PgRow,
630                field_name: &str,
631                alias: &str,
632            ) -> ::core::result::Result<bool, ::rustango::sql::sqlx::Error> {
633                match field_name {
634                    #( #arms )*
635                    _ => ::core::result::Result::Ok(false),
636                }
637            }
638        }
639    }
640}
641
642/// MySQL counterpart of [`load_related_impl_tokens`] — v0.23.0-batch8.
643/// Emits a call to the cfg-gated `__impl_my_load_related!` macro_rules,
644/// which expands to a `LoadRelatedMy` impl when rustango is built with
645/// the `mysql` feature, and to nothing otherwise. The decoded parent
646/// is read via `__rustango_from_aliased_my_row` (the MySQL aliased
647/// decoder, also batch8) so the dual emission is symmetric across
648/// backends.
649fn load_related_impl_my_tokens(
650    struct_name: &syn::Ident,
651    fk_relations: &[FkRelation],
652) -> TokenStream2 {
653    let arms = fk_relations.iter().map(|rel| {
654        let parent_ty = &rel.parent_type;
655        let fk_col = rel.fk_column.as_str();
656        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
657        let (variant_ident, default_expr) = rel.pk_kind.sqlvalue_match_arm();
658        let assign = if rel.nullable {
659            quote! {
660                __self.#field_ident = ::core::option::Option::Some(
661                    ::rustango::sql::ForeignKey::loaded(_pk, _parent),
662                );
663            }
664        } else {
665            quote! {
666                __self.#field_ident = ::rustango::sql::ForeignKey::loaded(_pk, _parent);
667            }
668        };
669        // `self` IS hygiene-tracked through macro_rules — emitted from
670        // a different context than the `&mut self` parameter inside
671        // the macro_rules-expanded fn. Pass it through as `__self`
672        // and let the macro_rules rebind it to the receiver.
673        quote! {
674            #fk_col => {
675                let _parent: #parent_ty =
676                    <#parent_ty>::__rustango_from_aliased_my_row(row, alias)?;
677                // See note in `load_related_impl_tokens` (PG twin) —
678                // the same loud-in-debug invariant guard.
679                let _pk = match <#parent_ty>::__rustango_pk_value(&_parent) {
680                    ::rustango::core::SqlValue::#variant_ident(v) => v,
681                    _other => {
682                        ::core::debug_assert!(
683                            false,
684                            "rustango macro bug: load_related on FK `{}` expected \
685                             SqlValue::{} from parent's __rustango_pk_value but got \
686                             {:?} — file a bug at https://github.com/ujeenet/rustango",
687                            #fk_col,
688                            ::core::stringify!(#variant_ident),
689                            _other,
690                        );
691                        #default_expr
692                    }
693                };
694                #assign
695                ::core::result::Result::Ok(true)
696            }
697        }
698    });
699    quote! {
700        ::rustango::__impl_my_load_related!(#struct_name, |__self, row, field_name, alias| {
701            #( #arms )*
702        });
703    }
704}
705
706/// Same shape as [`load_related_impl_my_tokens`] but for SQLite.
707/// Emits a call to `__impl_sqlite_load_related!` which expands to a
708/// `LoadRelatedSqlite` impl when the `sqlite` feature is on.
709fn load_related_impl_sqlite_tokens(
710    struct_name: &syn::Ident,
711    fk_relations: &[FkRelation],
712) -> TokenStream2 {
713    let arms = fk_relations.iter().map(|rel| {
714        let parent_ty = &rel.parent_type;
715        let fk_col = rel.fk_column.as_str();
716        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
717        let (variant_ident, default_expr) = rel.pk_kind.sqlvalue_match_arm();
718        let assign = if rel.nullable {
719            quote! {
720                __self.#field_ident = ::core::option::Option::Some(
721                    ::rustango::sql::ForeignKey::loaded(_pk, _parent),
722                );
723            }
724        } else {
725            quote! {
726                __self.#field_ident = ::rustango::sql::ForeignKey::loaded(_pk, _parent);
727            }
728        };
729        quote! {
730            #fk_col => {
731                let _parent: #parent_ty =
732                    <#parent_ty>::__rustango_from_aliased_sqlite_row(row, alias)?;
733                let _pk = match <#parent_ty>::__rustango_pk_value(&_parent) {
734                    ::rustango::core::SqlValue::#variant_ident(v) => v,
735                    _other => {
736                        ::core::debug_assert!(
737                            false,
738                            "rustango macro bug: load_related on FK `{}` expected \
739                             SqlValue::{} from parent's __rustango_pk_value but got \
740                             {:?} — file a bug at https://github.com/ujeenet/rustango",
741                            #fk_col,
742                            ::core::stringify!(#variant_ident),
743                            _other,
744                        );
745                        #default_expr
746                    }
747                };
748                #assign
749                ::core::result::Result::Ok(true)
750            }
751        }
752    });
753    quote! {
754        ::rustango::__impl_sqlite_load_related!(#struct_name, |__self, row, field_name, alias| {
755            #( #arms )*
756        });
757    }
758}
759
760/// Emit `impl FkPkAccess for #StructName` — slice 9.0e. Pattern-
761/// matches `field_name` against the model's FK fields and returns
762/// the FK's stored PK as `i64`. Used by `fetch_with_prefetch` to
763/// group children by parent PK.
764///
765/// Always emitted (with `_ => None` for FK-less models) so the
766/// trait bound on `fetch_with_prefetch` is universally satisfied.
767fn fk_pk_access_impl_tokens(struct_name: &syn::Ident, fk_relations: &[FkRelation]) -> TokenStream2 {
768    let arms = fk_relations.iter().map(|rel| {
769        let fk_col = rel.fk_column.as_str();
770        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
771        if rel.pk_kind == DetectedKind::I64 {
772            // i64 FK — return the stored PK so prefetch_related can
773            // group children by it. Nullable variant unwraps via
774            // `as_ref().map(...)`: an unset (NULL) FK column yields
775            // `None` and that child sits out of the grouping (correct
776            // semantics — it has no parent to attach to).
777            if rel.nullable {
778                quote! {
779                    #fk_col => self.#field_ident
780                        .as_ref()
781                        .map(|fk| ::rustango::sql::ForeignKey::pk(fk)),
782                }
783            } else {
784                quote! {
785                    #fk_col => ::core::option::Option::Some(self.#field_ident.pk()),
786                }
787            }
788        } else {
789            // Non-i64 FK PKs (e.g. `ForeignKey<T, String>`,
790            // `ForeignKey<T, Uuid>`) opt out of `prefetch_related`'s
791            // i64-keyed grouping path — the trait signature is
792            // `Option<i64>` and a non-i64 PK can't lower into it.
793            // The FK still works for everything else (CRUD, lazy
794            // load via `.get()`, select_related JOINs); only the
795            // bulk prefetch grouper needs the integer key.
796            quote! {
797                #fk_col => ::core::option::Option::None,
798            }
799        }
800    });
801    // PK-type-agnostic version: every FK arm emits an
802    // `Option<SqlValue>` so `fetch_with_prefetch` can group by any
803    // PK type (i64, i32, String, Uuid). Models with non-i64 FK PKs
804    // opt OUT of the legacy i64 method (it returns None) but opt IN
805    // here.
806    let value_arms = fk_relations.iter().map(|rel| {
807        let fk_col = rel.fk_column.as_str();
808        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
809        if rel.nullable {
810            quote! {
811                #fk_col => self.#field_ident
812                    .as_ref()
813                    .map(|fk| ::core::convert::Into::<::rustango::core::SqlValue>::into(
814                        ::rustango::sql::ForeignKey::pk(fk)
815                    )),
816            }
817        } else {
818            quote! {
819                #fk_col => ::core::option::Option::Some(
820                    ::core::convert::Into::<::rustango::core::SqlValue>::into(
821                        self.#field_ident.pk()
822                    )
823                ),
824            }
825        }
826    });
827    quote! {
828        impl ::rustango::sql::FkPkAccess for #struct_name {
829            #[allow(unused_variables)]
830            fn __rustango_fk_pk(&self, field_name: &str) -> ::core::option::Option<i64> {
831                match field_name {
832                    #( #arms )*
833                    _ => ::core::option::Option::None,
834                }
835            }
836            #[allow(unused_variables)]
837            fn __rustango_fk_pk_value(
838                &self,
839                field_name: &str,
840            ) -> ::core::option::Option<::rustango::core::SqlValue> {
841                match field_name {
842                    #( #value_arms )*
843                    _ => ::core::option::Option::None,
844                }
845            }
846        }
847    }
848}
849
850/// For every `ForeignKey<Parent>` field on `Child`, emit
851/// `impl Parent { pub async fn <child_table>_set(&self, executor) -> Vec<Child> }`.
852/// Reads the parent's PK via the macro-generated `__rustango_pk_value`
853/// and runs a single `SELECT … FROM <child_table> WHERE <fk_column> = $1`
854/// — the canonical reverse-FK fetch. One round trip, no N+1.
855fn reverse_helper_tokens(child_ident: &syn::Ident, fk_relations: &[FkRelation]) -> TokenStream2 {
856    if fk_relations.is_empty() {
857        return TokenStream2::new();
858    }
859    // Snake-case the child struct name to derive the method suffix —
860    // `Post` → `post_set`, `BlogComment` → `blog_comment_set`. Avoids
861    // English-plural edge cases (Django's `<child>_set` convention).
862    let suffix = format!("{}_set", to_snake_case(&child_ident.to_string()));
863    let method_ident = syn::Ident::new(&suffix, child_ident.span());
864    let impls = fk_relations.iter().map(|rel| {
865        let parent_ty = &rel.parent_type;
866        let fk_col = rel.fk_column.as_str();
867        let doc = format!(
868            "Fetch every `{child_ident}` whose `{fk_col}` foreign key points at this row. \
869             Single SQL query — `SELECT … FROM <{child_ident} table> WHERE {fk_col} = $1` — \
870             generated from the FK declaration on `{child_ident}::{fk_col}`. Composes with \
871             further `{child_ident}::objects()` filters via direct queryset use."
872        );
873        quote! {
874            impl #parent_ty {
875                #[doc = #doc]
876                ///
877                /// # Errors
878                /// Returns [`::rustango::sql::ExecError`] for SQL-writing
879                /// or driver failures.
880                pub async fn #method_ident<'_c, _E>(
881                    &self,
882                    _executor: _E,
883                ) -> ::core::result::Result<
884                    ::std::vec::Vec<#child_ident>,
885                    ::rustango::sql::ExecError,
886                >
887                where
888                    _E: ::rustango::sql::sqlx::Executor<
889                        '_c,
890                        Database = ::rustango::sql::sqlx::Postgres,
891                    >,
892                {
893                    let _pk: ::rustango::core::SqlValue = self.__rustango_pk_value();
894                    ::rustango::query::QuerySet::<#child_ident>::new()
895                        .filter(#fk_col, ::rustango::core::Op::Eq, _pk)
896                        .fetch_on(_executor)
897                        .await
898                }
899            }
900        }
901    });
902    quote! { #( #impls )* }
903}
904
905/// Emit `<name>_m2m(&self) -> M2MManager` inherent methods for every M2M
906/// relation declared on the model.
907fn m2m_accessor_tokens(struct_name: &syn::Ident, m2m_relations: &[M2MAttr]) -> TokenStream2 {
908    if m2m_relations.is_empty() {
909        return TokenStream2::new();
910    }
911    let methods = m2m_relations.iter().map(|rel| {
912        let method_name = format!("{}_m2m", rel.name);
913        let method_ident = syn::Ident::new(&method_name, struct_name.span());
914        let through = rel.through.as_str();
915        let src_col = rel.src.as_str();
916        let dst_col = rel.dst.as_str();
917        quote! {
918            pub fn #method_ident(&self) -> ::rustango::sql::M2MManager {
919                ::rustango::sql::M2MManager {
920                    src_pk: self.__rustango_pk_value(),
921                    through: #through,
922                    src_col: #src_col,
923                    dst_col: #dst_col,
924                }
925            }
926        }
927    });
928    quote! {
929        impl #struct_name {
930            #( #methods )*
931        }
932    }
933}
934
935struct ColumnEntry {
936    /// The struct field ident, used both for the inherent const name on
937    /// the model and for the inner column type's name.
938    ident: syn::Ident,
939    /// The struct's field type, used as `Column::Value`.
940    value_ty: Type,
941    /// Rust-side field name (e.g. `"id"`).
942    name: String,
943    /// SQL-side column name (e.g. `"user_id"`).
944    column: String,
945    /// `::rustango::core::FieldType::I64` etc.
946    field_type_tokens: TokenStream2,
947}
948
949struct CollectedFields {
950    field_schemas: Vec<TokenStream2>,
951    from_row_inits: Vec<TokenStream2>,
952    /// Aliased counterparts of `from_row_inits` — read columns via
953    /// `format!("{prefix}__{col}")` aliases so a Model can be
954    /// decoded from a JOINed row's projected target columns.
955    from_aliased_row_inits: Vec<TokenStream2>,
956    /// Static column-name list — used by the simple insert path
957    /// (no `Auto<T>` fields). Aligned with `insert_values`.
958    insert_columns: Vec<TokenStream2>,
959    /// Static `Into<SqlValue>` expressions, one per field. Aligned
960    /// with `insert_columns`. Used by the simple insert path only.
961    insert_values: Vec<TokenStream2>,
962    /// Per-field push expressions for the dynamic (Auto-aware)
963    /// insert path. Each statement either unconditionally pushes
964    /// `(column, value)` or, for an `Auto<T>` field, conditionally
965    /// pushes only when `Auto::Set(_)`. Built only when `has_auto`.
966    insert_pushes: Vec<TokenStream2>,
967    /// SQL columns for `RETURNING` — one per `Auto<T>` field. Empty
968    /// when `has_auto == false`.
969    returning_cols: Vec<TokenStream2>,
970    /// `self.<field> = Row::try_get(&row, "<col>")?;` for each Auto
971    /// field. Run after `insert_returning` to populate the model.
972    auto_assigns: Vec<TokenStream2>,
973    /// `(ident, column_literal)` pairs for every Auto field. Used by
974    /// the bulk_insert codegen to rebuild assigns against `_row_mut`
975    /// instead of `self`.
976    auto_field_idents: Vec<(syn::Ident, String)>,
977    /// Inner `T` of the first `Auto<T>` field, for the MySQL
978    /// `LAST_INSERT_ID()` assignment in `AssignAutoPkPool`.
979    first_auto_value_ty: Option<Type>,
980    /// Bulk-insert per-row pushes for **non-Auto fields only**. Used
981    /// by the all-Auto-Unset bulk path (Auto cols dropped from
982    /// `columns`).
983    bulk_pushes_no_auto: Vec<TokenStream2>,
984    /// Bulk-insert per-row pushes for **all fields including Auto**.
985    /// Used by the all-Auto-Set bulk path (Auto col included with the
986    /// caller-supplied value).
987    bulk_pushes_all: Vec<TokenStream2>,
988    /// Column-name literals for non-Auto fields only (paired with
989    /// `bulk_pushes_no_auto`).
990    bulk_columns_no_auto: Vec<TokenStream2>,
991    /// Column-name literals for every field including Auto (paired
992    /// with `bulk_pushes_all`).
993    bulk_columns_all: Vec<TokenStream2>,
994    /// `let _i_unset_<n> = matches!(rows[0].<auto_field>, Auto::Unset);`
995    /// + the loop that asserts every row matches. One pair per Auto
996    /// field. Empty when `has_auto == false`.
997    bulk_auto_uniformity: Vec<TokenStream2>,
998    /// Identifier of the first Auto field, used as the witness for
999    /// "all rows agree on Set vs Unset". Set only when `has_auto`.
1000    first_auto_ident: Option<syn::Ident>,
1001    /// `true` if any field on the struct is `Auto<T>`.
1002    has_auto: bool,
1003    /// `true` when the primary-key field's Rust type is `Auto<T>`.
1004    /// Gates `save()` codegen — only Auto PKs let us infer
1005    /// insert-vs-update from the in-memory value.
1006    pk_is_auto: bool,
1007    /// `Assignment` constructors for every non-PK column. Drives the
1008    /// UPDATE branch of `save()`.
1009    update_assignments: Vec<TokenStream2>,
1010    /// Column name literals (`"col"`) for every non-PK, non-auto_now_add column.
1011    /// Drives the `ON CONFLICT ... DO UPDATE SET` clause in `upsert_on`.
1012    upsert_update_columns: Vec<TokenStream2>,
1013    primary_key: Option<(syn::Ident, String)>,
1014    column_entries: Vec<ColumnEntry>,
1015    /// Rust-side field names, in declaration order. Used to validate
1016    /// container attributes like `display = "…"`.
1017    field_names: Vec<String>,
1018    /// FK fields on this child model. Drives the reverse-relation
1019    /// helper emit — for each FK, the macro adds an inherent
1020    /// `<parent>::<child_table>_set(&self, executor) -> Vec<Self>`
1021    /// method on the parent type.
1022    fk_relations: Vec<FkRelation>,
1023    /// SQL column name of the `#[rustango(soft_delete)]` field, if
1024    /// the model has one. Drives emission of the `soft_delete_on` /
1025    /// `restore_on` inherent methods. At most one such column per
1026    /// model is allowed; collect_fields rejects duplicates.
1027    soft_delete_column: Option<String>,
1028}
1029
1030#[derive(Clone)]
1031struct FkRelation {
1032    /// Inner type of `ForeignKey<T, K>` — the parent model. The reverse
1033    /// helper is emitted as `impl <ParentType> { … }`.
1034    parent_type: Type,
1035    /// SQL column name on the child table for this FK (e.g. `"author"`).
1036    /// Used in the generated `WHERE <fk_column> = $1` clause.
1037    fk_column: String,
1038    /// `K`'s underlying scalar kind — drives the `match SqlValue { … }`
1039    /// arm emitted by [`load_related_impl_tokens`]. `I64` for the
1040    /// default `ForeignKey<T>` (no explicit K); other kinds when the
1041    /// user wrote `ForeignKey<T, String>`, `ForeignKey<T, Uuid>`, etc.
1042    pk_kind: DetectedKind,
1043    /// `true` when the field is `Option<ForeignKey<T, K>>` (nullable
1044    /// FK column). Drives the `Some(...)` wrapping in load_related
1045    /// assignment and `.as_ref().map(...)` in the FK PK accessor so
1046    /// the codegen matches the field's declared shape.
1047    nullable: bool,
1048}
1049
1050fn collect_fields(named: &syn::FieldsNamed, table: &str) -> syn::Result<CollectedFields> {
1051    let cap = named.named.len();
1052    let mut out = CollectedFields {
1053        field_schemas: Vec::with_capacity(cap),
1054        from_row_inits: Vec::with_capacity(cap),
1055        from_aliased_row_inits: Vec::with_capacity(cap),
1056        insert_columns: Vec::with_capacity(cap),
1057        insert_values: Vec::with_capacity(cap),
1058        insert_pushes: Vec::with_capacity(cap),
1059        returning_cols: Vec::new(),
1060        auto_assigns: Vec::new(),
1061        auto_field_idents: Vec::new(),
1062        first_auto_value_ty: None,
1063        bulk_pushes_no_auto: Vec::with_capacity(cap),
1064        bulk_pushes_all: Vec::with_capacity(cap),
1065        bulk_columns_no_auto: Vec::with_capacity(cap),
1066        bulk_columns_all: Vec::with_capacity(cap),
1067        bulk_auto_uniformity: Vec::new(),
1068        first_auto_ident: None,
1069        has_auto: false,
1070        pk_is_auto: false,
1071        update_assignments: Vec::with_capacity(cap),
1072        upsert_update_columns: Vec::with_capacity(cap),
1073        primary_key: None,
1074        column_entries: Vec::with_capacity(cap),
1075        field_names: Vec::with_capacity(cap),
1076        fk_relations: Vec::new(),
1077        soft_delete_column: None,
1078    };
1079
1080    for field in &named.named {
1081        let info = process_field(field, table)?;
1082        out.field_names.push(info.ident.to_string());
1083        out.field_schemas.push(info.schema);
1084        out.from_row_inits.push(info.from_row_init);
1085        out.from_aliased_row_inits.push(info.from_aliased_row_init);
1086        if let Some(parent_ty) = info.fk_inner.clone() {
1087            out.fk_relations.push(FkRelation {
1088                parent_type: parent_ty,
1089                fk_column: info.column.clone(),
1090                pk_kind: info.fk_pk_kind,
1091                nullable: info.nullable,
1092            });
1093        }
1094        if info.soft_delete {
1095            if out.soft_delete_column.is_some() {
1096                return Err(syn::Error::new_spanned(
1097                    field,
1098                    "only one field may be marked `#[rustango(soft_delete)]`",
1099                ));
1100            }
1101            out.soft_delete_column = Some(info.column.clone());
1102        }
1103        let column = info.column.as_str();
1104        let ident = info.ident;
1105        // Generated columns (`#[rustango(generated_as = "EXPR")]`)
1106        // skip every write path — Postgres recomputes the value
1107        // from EXPR. Push only the column-entry record (so typed
1108        // column constants still exist for filtering / projection)
1109        // and the schema literal (already pushed above) and move
1110        // on. No insert_columns/values, no insert_pushes, no
1111        // bulk_*, no update_assignments, no upsert_update_columns,
1112        // no returning_cols.
1113        if info.generated_as.is_some() {
1114            out.column_entries.push(ColumnEntry {
1115                ident: ident.clone(),
1116                value_ty: info.value_ty.clone(),
1117                name: ident.to_string(),
1118                column: info.column.clone(),
1119                field_type_tokens: info.field_type_tokens,
1120            });
1121            continue;
1122        }
1123        out.insert_columns.push(quote!(#column));
1124        out.insert_values.push(quote! {
1125            ::core::convert::Into::<::rustango::core::SqlValue>::into(
1126                ::core::clone::Clone::clone(&self.#ident)
1127            )
1128        });
1129        if info.auto {
1130            out.has_auto = true;
1131            if out.first_auto_ident.is_none() {
1132                out.first_auto_ident = Some(ident.clone());
1133                out.first_auto_value_ty = auto_inner_type(info.value_ty).cloned();
1134            }
1135            out.returning_cols.push(quote!(#column));
1136            out.auto_field_idents
1137                .push((ident.clone(), info.column.clone()));
1138            out.auto_assigns.push(quote! {
1139                self.#ident = ::rustango::sql::try_get_returning(_returning_row, #column)?;
1140            });
1141            out.insert_pushes.push(quote! {
1142                if let ::rustango::sql::Auto::Set(_v) = &self.#ident {
1143                    _columns.push(#column);
1144                    _values.push(::core::convert::Into::<::rustango::core::SqlValue>::into(
1145                        ::core::clone::Clone::clone(_v)
1146                    ));
1147                }
1148            });
1149            // Bulk: Auto fields appear only in the all-Set path,
1150            // never in the Unset path (we drop them from `columns`).
1151            out.bulk_columns_all.push(quote!(#column));
1152            out.bulk_pushes_all.push(quote! {
1153                _row_vals.push(::core::convert::Into::<::rustango::core::SqlValue>::into(
1154                    ::core::clone::Clone::clone(&_row.#ident)
1155                ));
1156            });
1157            // Uniformity check: every row's Auto state must match the
1158            // first row's. Mixed Set/Unset within one bulk_insert is
1159            // rejected here so the column list stays consistent.
1160            let ident_clone = ident.clone();
1161            out.bulk_auto_uniformity.push(quote! {
1162                for _r in rows.iter().skip(1) {
1163                    if matches!(_r.#ident_clone, ::rustango::sql::Auto::Unset) != _first_unset {
1164                        return ::core::result::Result::Err(
1165                            ::rustango::sql::ExecError::Sql(
1166                                ::rustango::sql::SqlError::BulkAutoMixed
1167                            )
1168                        );
1169                    }
1170                }
1171            });
1172        } else {
1173            out.insert_pushes.push(quote! {
1174                _columns.push(#column);
1175                _values.push(::core::convert::Into::<::rustango::core::SqlValue>::into(
1176                    ::core::clone::Clone::clone(&self.#ident)
1177                ));
1178            });
1179            // Bulk: non-Auto fields appear in BOTH paths.
1180            out.bulk_columns_no_auto.push(quote!(#column));
1181            out.bulk_columns_all.push(quote!(#column));
1182            let push_expr = quote! {
1183                _row_vals.push(::core::convert::Into::<::rustango::core::SqlValue>::into(
1184                    ::core::clone::Clone::clone(&_row.#ident)
1185                ));
1186            };
1187            out.bulk_pushes_no_auto.push(push_expr.clone());
1188            out.bulk_pushes_all.push(push_expr);
1189        }
1190        if info.primary_key {
1191            if out.primary_key.is_some() {
1192                return Err(syn::Error::new_spanned(
1193                    field,
1194                    "only one field may be marked `#[rustango(primary_key)]`",
1195                ));
1196            }
1197            out.primary_key = Some((ident.clone(), info.column.clone()));
1198            if info.auto {
1199                out.pk_is_auto = true;
1200            }
1201        } else if info.auto_now_add {
1202            // Immutable post-insert: skip from UPDATE entirely.
1203        } else if info.auto_now {
1204            // `auto_now` columns: bind `chrono::Utc::now()` on every
1205            // UPDATE so the column is always overridden with the
1206            // wall-clock at write time, regardless of what value the
1207            // user left in the struct field.
1208            out.update_assignments.push(quote! {
1209                ::rustango::core::Assignment {
1210                    column: #column,
1211                    value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
1212                        ::chrono::Utc::now()
1213                    ),
1214                }
1215            });
1216            out.upsert_update_columns.push(quote!(#column));
1217        } else {
1218            out.update_assignments.push(quote! {
1219                ::rustango::core::Assignment {
1220                    column: #column,
1221                    value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
1222                        ::core::clone::Clone::clone(&self.#ident)
1223                    ),
1224                }
1225            });
1226            out.upsert_update_columns.push(quote!(#column));
1227        }
1228        out.column_entries.push(ColumnEntry {
1229            ident: ident.clone(),
1230            value_ty: info.value_ty.clone(),
1231            name: ident.to_string(),
1232            column: info.column.clone(),
1233            field_type_tokens: info.field_type_tokens,
1234        });
1235    }
1236    Ok(out)
1237}
1238
1239fn model_impl_tokens(
1240    struct_name: &syn::Ident,
1241    model_name: &str,
1242    table: &str,
1243    display: Option<&str>,
1244    app_label: Option<&str>,
1245    admin: Option<&AdminAttrs>,
1246    field_schemas: &[TokenStream2],
1247    soft_delete_column: Option<&str>,
1248    permissions: bool,
1249    audit_track: Option<&[String]>,
1250    m2m_relations: &[M2MAttr],
1251    indexes: &[IndexAttr],
1252    checks: &[CheckAttr],
1253    composite_fks: &[CompositeFkAttr],
1254    generic_fks: &[GenericFkAttr],
1255    scope: Option<&str>,
1256) -> TokenStream2 {
1257    let display_tokens = if let Some(name) = display {
1258        quote!(::core::option::Option::Some(#name))
1259    } else {
1260        quote!(::core::option::Option::None)
1261    };
1262    let app_label_tokens = if let Some(name) = app_label {
1263        quote!(::core::option::Option::Some(#name))
1264    } else {
1265        quote!(::core::option::Option::None)
1266    };
1267    let soft_delete_tokens = if let Some(col) = soft_delete_column {
1268        quote!(::core::option::Option::Some(#col))
1269    } else {
1270        quote!(::core::option::Option::None)
1271    };
1272    let audit_track_tokens = match audit_track {
1273        None => quote!(::core::option::Option::None),
1274        Some(names) => {
1275            let lits = names.iter().map(|n| n.as_str());
1276            quote!(::core::option::Option::Some(&[ #(#lits),* ]))
1277        }
1278    };
1279    let admin_tokens = admin_config_tokens(admin);
1280    // Default `tenant` so single-tenant projects (no `scope` attr
1281    // anywhere) keep the v0.24.x behavior. Container-attr parser
1282    // already validated the value is "registry" or "tenant".
1283    let scope_tokens = match scope.map(|s| s.to_ascii_lowercase()).as_deref() {
1284        Some("registry") => quote!(::rustango::core::ModelScope::Registry),
1285        _ => quote!(::rustango::core::ModelScope::Tenant),
1286    };
1287    let indexes_tokens = indexes.iter().map(|idx| {
1288        let name = idx.name.as_deref().unwrap_or("unnamed_index");
1289        let cols: Vec<&str> = idx.columns.iter().map(String::as_str).collect();
1290        let unique = idx.unique;
1291        quote! {
1292            ::rustango::core::IndexSchema {
1293                name: #name,
1294                columns: &[ #(#cols),* ],
1295                unique: #unique,
1296            }
1297        }
1298    });
1299    let checks_tokens = checks.iter().map(|c| {
1300        let name = c.name.as_str();
1301        let expr = c.expr.as_str();
1302        quote! {
1303            ::rustango::core::CheckConstraint {
1304                name: #name,
1305                expr: #expr,
1306            }
1307        }
1308    });
1309    let composite_fk_tokens = composite_fks.iter().map(|rel| {
1310        let name = rel.name.as_str();
1311        let to = rel.to.as_str();
1312        let from_cols: Vec<&str> = rel.from.iter().map(String::as_str).collect();
1313        let on_cols: Vec<&str> = rel.on.iter().map(String::as_str).collect();
1314        quote! {
1315            ::rustango::core::CompositeFkRelation {
1316                name: #name,
1317                to: #to,
1318                from: &[ #(#from_cols),* ],
1319                on: &[ #(#on_cols),* ],
1320            }
1321        }
1322    });
1323    let generic_fk_tokens = generic_fks.iter().map(|rel| {
1324        let name = rel.name.as_str();
1325        let ct_col = rel.ct_column.as_str();
1326        let pk_col = rel.pk_column.as_str();
1327        quote! {
1328            ::rustango::core::GenericRelation {
1329                name: #name,
1330                ct_column: #ct_col,
1331                pk_column: #pk_col,
1332            }
1333        }
1334    });
1335    let m2m_tokens = m2m_relations.iter().map(|rel| {
1336        let name = rel.name.as_str();
1337        let to = rel.to.as_str();
1338        let through = rel.through.as_str();
1339        let src = rel.src.as_str();
1340        let dst = rel.dst.as_str();
1341        quote! {
1342            ::rustango::core::M2MRelation {
1343                name: #name,
1344                to: #to,
1345                through: #through,
1346                src_col: #src,
1347                dst_col: #dst,
1348            }
1349        }
1350    });
1351    quote! {
1352        impl ::rustango::core::Model for #struct_name {
1353            const SCHEMA: &'static ::rustango::core::ModelSchema = &::rustango::core::ModelSchema {
1354                name: #model_name,
1355                table: #table,
1356                fields: &[ #(#field_schemas),* ],
1357                display: #display_tokens,
1358                app_label: #app_label_tokens,
1359                admin: #admin_tokens,
1360                soft_delete_column: #soft_delete_tokens,
1361                permissions: #permissions,
1362                audit_track: #audit_track_tokens,
1363                m2m: &[ #(#m2m_tokens),* ],
1364                indexes: &[ #(#indexes_tokens),* ],
1365                check_constraints: &[ #(#checks_tokens),* ],
1366                composite_relations: &[ #(#composite_fk_tokens),* ],
1367                generic_relations: &[ #(#generic_fk_tokens),* ],
1368                scope: #scope_tokens,
1369            };
1370        }
1371    }
1372}
1373
1374/// Emit the `admin: Option<&'static AdminConfig>` field for the model
1375/// schema. `None` when the user wrote no `#[rustango(admin(...))]`;
1376/// otherwise a static reference to a populated `AdminConfig`.
1377fn admin_config_tokens(admin: Option<&AdminAttrs>) -> TokenStream2 {
1378    let Some(admin) = admin else {
1379        return quote!(::core::option::Option::None);
1380    };
1381
1382    let list_display = admin
1383        .list_display
1384        .as_ref()
1385        .map(|(v, _)| v.as_slice())
1386        .unwrap_or(&[]);
1387    let list_display_lits = list_display.iter().map(|s| s.as_str());
1388
1389    let search_fields = admin
1390        .search_fields
1391        .as_ref()
1392        .map(|(v, _)| v.as_slice())
1393        .unwrap_or(&[]);
1394    let search_fields_lits = search_fields.iter().map(|s| s.as_str());
1395
1396    let readonly_fields = admin
1397        .readonly_fields
1398        .as_ref()
1399        .map(|(v, _)| v.as_slice())
1400        .unwrap_or(&[]);
1401    let readonly_fields_lits = readonly_fields.iter().map(|s| s.as_str());
1402
1403    let list_filter = admin
1404        .list_filter
1405        .as_ref()
1406        .map(|(v, _)| v.as_slice())
1407        .unwrap_or(&[]);
1408    let list_filter_lits = list_filter.iter().map(|s| s.as_str());
1409
1410    let actions = admin
1411        .actions
1412        .as_ref()
1413        .map(|(v, _)| v.as_slice())
1414        .unwrap_or(&[]);
1415    let actions_lits = actions.iter().map(|s| s.as_str());
1416
1417    let fieldsets = admin
1418        .fieldsets
1419        .as_ref()
1420        .map(|(v, _)| v.as_slice())
1421        .unwrap_or(&[]);
1422    let fieldset_tokens = fieldsets.iter().map(|(title, fields)| {
1423        let title = title.as_str();
1424        let field_lits = fields.iter().map(|s| s.as_str());
1425        quote!(::rustango::core::Fieldset {
1426            title: #title,
1427            fields: &[ #( #field_lits ),* ],
1428        })
1429    });
1430
1431    let list_per_page = admin.list_per_page.unwrap_or(0);
1432
1433    let ordering_pairs = admin
1434        .ordering
1435        .as_ref()
1436        .map(|(v, _)| v.as_slice())
1437        .unwrap_or(&[]);
1438    let ordering_tokens = ordering_pairs.iter().map(|(name, desc)| {
1439        let name = name.as_str();
1440        let desc = *desc;
1441        quote!((#name, #desc))
1442    });
1443
1444    quote! {
1445        ::core::option::Option::Some(&::rustango::core::AdminConfig {
1446            list_display: &[ #( #list_display_lits ),* ],
1447            search_fields: &[ #( #search_fields_lits ),* ],
1448            list_per_page: #list_per_page,
1449            ordering: &[ #( #ordering_tokens ),* ],
1450            readonly_fields: &[ #( #readonly_fields_lits ),* ],
1451            list_filter: &[ #( #list_filter_lits ),* ],
1452            actions: &[ #( #actions_lits ),* ],
1453            fieldsets: &[ #( #fieldset_tokens ),* ],
1454        })
1455    }
1456}
1457
1458fn inherent_impl_tokens(
1459    struct_name: &syn::Ident,
1460    fields: &CollectedFields,
1461    primary_key: Option<&(syn::Ident, String)>,
1462    column_consts: &TokenStream2,
1463    audited_fields: Option<&[&ColumnEntry]>,
1464    indexes: &[IndexAttr],
1465) -> TokenStream2 {
1466    // Audit-emit fragments threaded into write paths. Non-empty only
1467    // when the model carries `#[rustango(audit(...))]`. They reborrow
1468    // `_executor` (a `&mut PgConnection` for audited models — the
1469    // macro switches the signature below) so the data write and the
1470    // audit INSERT both run on the same caller-supplied connection.
1471    let executor_passes_to_data_write = if audited_fields.is_some() {
1472        quote!(&mut *_executor)
1473    } else {
1474        quote!(_executor)
1475    };
1476    let executor_param = if audited_fields.is_some() {
1477        quote!(_executor: &mut ::rustango::sql::sqlx::PgConnection)
1478    } else {
1479        quote!(_executor: _E)
1480    };
1481    let executor_generics = if audited_fields.is_some() {
1482        quote!()
1483    } else {
1484        quote!(<'_c, _E>)
1485    };
1486    let executor_where = if audited_fields.is_some() {
1487        quote!()
1488    } else {
1489        quote! {
1490            where
1491                _E: ::rustango::sql::sqlx::Executor<'_c, Database = ::rustango::sql::sqlx::Postgres>,
1492        }
1493    };
1494    // For audited models the `_on` methods take `&mut PgConnection`, so
1495    // the &PgPool convenience wrappers (`save`, `insert`, `delete`)
1496    // must acquire a connection first. Non-audited models keep the
1497    // direct delegation since `&PgPool` IS an Executor.
1498    let pool_to_save_on = if audited_fields.is_some() {
1499        quote! {
1500            let mut _conn = pool.acquire().await?;
1501            self.save_on(&mut *_conn).await
1502        }
1503    } else {
1504        quote!(self.save_on(pool).await)
1505    };
1506    let pool_to_insert_on = if audited_fields.is_some() {
1507        quote! {
1508            let mut _conn = pool.acquire().await?;
1509            self.insert_on(&mut *_conn).await
1510        }
1511    } else {
1512        quote!(self.insert_on(pool).await)
1513    };
1514    let pool_to_delete_on = if audited_fields.is_some() {
1515        quote! {
1516            let mut _conn = pool.acquire().await?;
1517            self.delete_on(&mut *_conn).await
1518        }
1519    } else {
1520        quote!(self.delete_on(pool).await)
1521    };
1522    let pool_to_bulk_insert_on = if audited_fields.is_some() {
1523        quote! {
1524            let mut _conn = pool.acquire().await?;
1525            Self::bulk_insert_on(rows, &mut *_conn).await
1526        }
1527    } else {
1528        quote!(Self::bulk_insert_on(rows, pool).await)
1529    };
1530    // Pre-existing bug surfaced by batch 22's first audited Auto<T>
1531    // PK test model: `upsert(&PgPool)` body called `self.upsert_on(pool)`
1532    // directly, but `upsert_on` for audited models takes
1533    // `&mut PgConnection` (the audit emit needs a real connection).
1534    // Add the missing acquire shim to keep audited Auto-PK upsert
1535    // compiling.
1536    let pool_to_upsert_on = if audited_fields.is_some() {
1537        quote! {
1538            let mut _conn = pool.acquire().await?;
1539            self.upsert_on(&mut *_conn).await
1540        }
1541    } else {
1542        quote!(self.upsert_on(pool).await)
1543    };
1544
1545    // `insert_pool(&Pool)` — v0.23.0-batch9. Non-audited models only
1546    // (audit-on-connection over &Pool needs a bi-dialect transaction
1547    // helper, deferred). Two body shapes:
1548    // - has_auto: build InsertQuery skipping Auto::Unset columns,
1549    //   request Auto cols in `returning`, dispatch via
1550    //   `insert_returning_pool`, then on the returned `PgRow` /
1551    //   `MySqlAutoId(id)` enum — pull each Auto field from the PG
1552    //   row OR drop the single i64 into the first Auto field on MySQL
1553    //   (multi-Auto models on MySQL error at runtime since
1554    //   `LAST_INSERT_ID()` only reports one)
1555    // - non-Auto: build InsertQuery with explicit columns/values and
1556    //   call `insert_pool` (no returning needed)
1557    // pool_insert_method body for the audited Auto-PK case is moved
1558    // to after audit_pair_tokens / audit_pk_to_string (they live
1559    // ~150 lines below). This block keeps the non-audited and
1560    // non-Auto branches in place — the audited Auto-PK arm is
1561    // computed below and merged via the dispatch helper variable.
1562    let pool_insert_method = if audited_fields.is_some() && !fields.has_auto {
1563        // Audited models with explicit (non-Auto) PKs go through
1564        // the non-Auto insert path below — the audit emit is one
1565        // round-trip after the INSERT inside the same tx via
1566        // audit::save_one_with_audit_pool? No, INSERT semantics
1567        // differ. For non-Auto PK + audited, route through a
1568        // dedicated insert + audit emit on the same tx, but defer
1569        // the macro emission to the audit-bundle-aware block below
1570        // — this `quote!()` placeholder gets overwritten there.
1571        quote!()
1572    } else if audited_fields.is_some() && fields.has_auto {
1573        // Audited Auto-PK insert_pool — assembled after the audit
1574        // bundles. Placeholder; real emission below.
1575        quote!()
1576    } else if fields.has_auto {
1577        let pushes = &fields.insert_pushes;
1578        let returning_cols = &fields.returning_cols;
1579        quote! {
1580            /// Insert this row against either backend, populating any
1581            /// `Auto<T>` PK from the auto-assigned value.
1582            ///
1583            /// # Errors
1584            /// As [`Self::insert`].
1585            pub async fn insert_pool(
1586                &mut self,
1587                pool: &::rustango::sql::Pool,
1588            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
1589                let mut _columns: ::std::vec::Vec<&'static str> =
1590                    ::std::vec::Vec::new();
1591                let mut _values: ::std::vec::Vec<::rustango::core::SqlValue> =
1592                    ::std::vec::Vec::new();
1593                #( #pushes )*
1594                let _query = ::rustango::core::InsertQuery {
1595                    model: <Self as ::rustango::core::Model>::SCHEMA,
1596                    columns: _columns,
1597                    values: _values,
1598                    returning: ::std::vec![ #( #returning_cols ),* ],
1599                    on_conflict: ::core::option::Option::None,
1600                };
1601                let _result = ::rustango::sql::insert_returning_pool(
1602                    pool, &_query,
1603                ).await?;
1604                ::rustango::sql::apply_auto_pk_pool(_result, self)
1605            }
1606        }
1607    } else {
1608        let insert_columns = &fields.insert_columns;
1609        let insert_values = &fields.insert_values;
1610        quote! {
1611            /// Insert this row into its table against either backend.
1612            /// Equivalent to [`Self::insert`] but takes
1613            /// [`::rustango::sql::Pool`].
1614            ///
1615            /// # Errors
1616            /// As [`Self::insert`].
1617            pub async fn insert_pool(
1618                &self,
1619                pool: &::rustango::sql::Pool,
1620            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
1621                let _query = ::rustango::core::InsertQuery {
1622                    model: <Self as ::rustango::core::Model>::SCHEMA,
1623                    columns: ::std::vec![ #( #insert_columns ),* ],
1624                    values: ::std::vec![ #( #insert_values ),* ],
1625                    returning: ::std::vec::Vec::new(),
1626                    on_conflict: ::core::option::Option::None,
1627                };
1628                ::rustango::sql::insert_pool(pool, &_query).await
1629            }
1630        }
1631    };
1632
1633    // pool_save_method moved to after audit_pair_tokens /
1634    // audit_pk_to_string (they live ~70 lines below) — needed for
1635    // the audited branch which builds an UpdateQuery + PendingEntry
1636    // and dispatches via audit::save_one_with_audit_pool.
1637
1638    // pool_delete_method moved to after audit_pair_tokens / audit_pk_to_string
1639    // are computed (they live ~80 lines below).
1640
1641    // Build the (column, JSON value) pair list used by every
1642    // snapshot-style audit emission. Reused across delete_on,
1643    // soft_delete_on, restore_on, and (later) bulk paths. Empty
1644    // when the model isn't audited.
1645    let audit_pair_tokens: Vec<TokenStream2> = audited_fields
1646        .map(|tracked| {
1647            tracked
1648                .iter()
1649                .map(|c| {
1650                    let column_lit = c.column.as_str();
1651                    let ident = &c.ident;
1652                    quote! {
1653                        (
1654                            #column_lit,
1655                            ::serde_json::to_value(&self.#ident)
1656                                .unwrap_or(::serde_json::Value::Null),
1657                        )
1658                    }
1659                })
1660                .collect()
1661        })
1662        .unwrap_or_default();
1663    let audit_pk_to_string = if let Some((pk_ident, _)) = primary_key {
1664        if fields.pk_is_auto {
1665            quote!(self.#pk_ident.get().map(|v| ::std::format!("{}", v)).unwrap_or_default())
1666        } else {
1667            quote!(::std::format!("{}", &self.#pk_ident))
1668        }
1669    } else {
1670        quote!(::std::string::String::new())
1671    };
1672    let make_op_emit = |op_path: TokenStream2| -> TokenStream2 {
1673        if audited_fields.is_some() {
1674            let pairs = audit_pair_tokens.iter();
1675            let pk_str = audit_pk_to_string.clone();
1676            quote! {
1677                let _audit_entry = ::rustango::audit::PendingEntry {
1678                    entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
1679                    entity_pk: #pk_str,
1680                    operation: #op_path,
1681                    source: ::rustango::audit::current_source(),
1682                    changes: ::rustango::audit::snapshot_changes(&[
1683                        #( #pairs ),*
1684                    ]),
1685                };
1686                ::rustango::audit::emit_one(&mut *_executor, &_audit_entry).await?;
1687            }
1688        } else {
1689            quote!()
1690        }
1691    };
1692    let audit_insert_emit = make_op_emit(quote!(::rustango::audit::AuditOp::Create));
1693    let audit_delete_emit = make_op_emit(quote!(::rustango::audit::AuditOp::Delete));
1694    let audit_softdelete_emit = make_op_emit(quote!(::rustango::audit::AuditOp::SoftDelete));
1695    let audit_restore_emit = make_op_emit(quote!(::rustango::audit::AuditOp::Restore));
1696
1697    // `save_pool(&Pool)` — emitted for every model with a PK.
1698    // Audited Auto-PK models are deferred (the Auto::Unset →
1699    // insert_pool path needs the audited-insert flow from a future
1700    // batch). Three body shapes:
1701    // - non-audited, plain PK: build UpdateQuery + dispatch through
1702    //   sql::update_pool
1703    // - non-audited, Auto-PK: same, but Auto::Unset routes to
1704    //   self.insert_pool which already handles RETURNING / LAST_INSERT_ID
1705    // - audited, plain PK: build UpdateQuery + PendingEntry, dispatch
1706    //   through audit::save_one_with_audit_pool (per-backend tx wraps
1707    //   UPDATE + audit emit atomically). Snapshot-style audit (post-
1708    //   write field values) — diff-style audit (with pre-UPDATE
1709    //   SELECT for `before` values) needs per-tracked-column codegen
1710    //   that doesn't fit the runtime-helper pattern; legacy &PgPool
1711    //   `save` keeps the diff for now.
1712    let pool_save_method = if let Some((pk_ident, pk_col)) = primary_key {
1713        let pk_column_lit = pk_col.as_str();
1714        let assignments = &fields.update_assignments;
1715        if audited_fields.is_some() {
1716            if fields.pk_is_auto {
1717                // Auto-PK + audited: defer. The Auto::Unset insert
1718                // path needs a transactional INSERT + LAST_INSERT_ID
1719                // + audit emit flow — that's a follow-up batch.
1720                quote!()
1721            } else {
1722                let pairs = audit_pair_tokens.iter();
1723                let pk_str = audit_pk_to_string.clone();
1724                quote! {
1725                    /// Save (UPDATE) this row against either backend
1726                    /// with audit emission inside the same transaction.
1727                    /// Bi-dialect counterpart of [`Self::save`] for
1728                    /// audited models with non-`Auto<T>` PKs.
1729                    ///
1730                    /// Captures **post-write** field state (snapshot
1731                    /// audit). The legacy &PgPool [`Self::save`]
1732                    /// captures BEFORE+AFTER for true diff audit;
1733                    /// porting that to the &Pool path needs runtime
1734                    /// per-tracked-column decoding and is deferred.
1735                    ///
1736                    /// # Errors
1737                    /// As [`Self::save`].
1738                    pub async fn save_pool(
1739                        &mut self,
1740                        pool: &::rustango::sql::Pool,
1741                    ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
1742                        let _query = ::rustango::core::UpdateQuery {
1743                            model: <Self as ::rustango::core::Model>::SCHEMA,
1744                            set: ::std::vec![ #( #assignments ),* ],
1745                            where_clause: ::rustango::core::WhereExpr::Predicate(
1746                                ::rustango::core::Filter {
1747                                    column: #pk_column_lit,
1748                                    op: ::rustango::core::Op::Eq,
1749                                    value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
1750                                        ::core::clone::Clone::clone(&self.#pk_ident)
1751                                    ),
1752                                }
1753                            ),
1754                        };
1755                        let _audit_entry = ::rustango::audit::PendingEntry {
1756                            entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
1757                            entity_pk: #pk_str,
1758                            operation: ::rustango::audit::AuditOp::Update,
1759                            source: ::rustango::audit::current_source(),
1760                            changes: ::rustango::audit::snapshot_changes(&[
1761                                #( #pairs ),*
1762                            ]),
1763                        };
1764                        let _ = ::rustango::audit::save_one_with_audit_pool(
1765                            pool, &_query, &_audit_entry,
1766                        ).await?;
1767                        ::core::result::Result::Ok(())
1768                    }
1769                }
1770            }
1771        } else {
1772            let dispatch_unset = if fields.pk_is_auto {
1773                quote! {
1774                    if matches!(self.#pk_ident, ::rustango::sql::Auto::Unset) {
1775                        return self.insert_pool(pool).await;
1776                    }
1777                }
1778            } else {
1779                quote!()
1780            };
1781            quote! {
1782                /// Save this row to its table against either backend.
1783                /// `INSERT` when the `Auto<T>` PK is `Unset`, else
1784                /// `UPDATE` keyed on the PK.
1785                ///
1786                /// # Errors
1787                /// As [`Self::save`].
1788                pub async fn save_pool(
1789                    &mut self,
1790                    pool: &::rustango::sql::Pool,
1791                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
1792                    #dispatch_unset
1793                    let _query = ::rustango::core::UpdateQuery {
1794                        model: <Self as ::rustango::core::Model>::SCHEMA,
1795                        set: ::std::vec![ #( #assignments ),* ],
1796                        where_clause: ::rustango::core::WhereExpr::Predicate(
1797                            ::rustango::core::Filter {
1798                                column: #pk_column_lit,
1799                                op: ::rustango::core::Op::Eq,
1800                                value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
1801                                    ::core::clone::Clone::clone(&self.#pk_ident)
1802                                ),
1803                            }
1804                        ),
1805                    };
1806                    let _ = ::rustango::sql::update_pool(pool, &_query).await?;
1807                    ::core::result::Result::Ok(())
1808                }
1809            }
1810        }
1811    } else {
1812        quote!()
1813    };
1814
1815    // Audited `insert_pool` (overrides the placeholder set higher up
1816    // in the function). v0.23.0-batch22 — both Auto-PK and non-Auto-PK
1817    // audited models get insert_pool routing through
1818    // audit::insert_one_with_audit_pool (per-backend tx wraps INSERT
1819    // + auto-PK readback + audit emit). Snapshot-style audit (the
1820    // PendingEntry's `changes` carries post-write field values).
1821    let pool_insert_method = if audited_fields.is_some() {
1822        if let Some(_) = primary_key {
1823            let pushes = if fields.has_auto {
1824                fields.insert_pushes.clone()
1825            } else {
1826                // For non-Auto-PK models, the macro normally builds
1827                // {columns, values} from fields.insert_columns +
1828                // fields.insert_values rather than insert_pushes.
1829                // Map those into the pushes shape.
1830                fields
1831                    .insert_columns
1832                    .iter()
1833                    .zip(&fields.insert_values)
1834                    .map(|(col, val)| {
1835                        quote! {
1836                            _columns.push(#col);
1837                            _values.push(#val);
1838                        }
1839                    })
1840                    .collect()
1841            };
1842            let returning_cols: Vec<proc_macro2::TokenStream> = if fields.has_auto {
1843                fields.returning_cols.clone()
1844            } else {
1845                // Non-Auto-PK: still need RETURNING something for the
1846                // audit helper's contract (it errors on empty
1847                // returning). Return the PK column so the audit row
1848                // can carry the assigned PK back. Some non-Auto PKs
1849                // are server-side-default (e.g. UUIDv4 default), so
1850                // RETURNING is genuinely useful.
1851                primary_key
1852                    .map(|(_, col)| {
1853                        let lit = col.as_str();
1854                        vec![quote!(#lit)]
1855                    })
1856                    .unwrap_or_default()
1857            };
1858            let pairs = audit_pair_tokens.iter();
1859            let pk_str = audit_pk_to_string.clone();
1860            quote! {
1861                /// Insert this row against either backend with audit
1862                /// emission inside the same transaction. Bi-dialect
1863                /// counterpart of [`Self::insert`] for audited models.
1864                ///
1865                /// Snapshot-style audit (post-write field values).
1866                ///
1867                /// # Errors
1868                /// As [`Self::insert`].
1869                pub async fn insert_pool(
1870                    &mut self,
1871                    pool: &::rustango::sql::Pool,
1872                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
1873                    let mut _columns: ::std::vec::Vec<&'static str> =
1874                        ::std::vec::Vec::new();
1875                    let mut _values: ::std::vec::Vec<::rustango::core::SqlValue> =
1876                        ::std::vec::Vec::new();
1877                    #( #pushes )*
1878                    let _query = ::rustango::core::InsertQuery {
1879                        model: <Self as ::rustango::core::Model>::SCHEMA,
1880                        columns: _columns,
1881                        values: _values,
1882                        returning: ::std::vec![ #( #returning_cols ),* ],
1883                        on_conflict: ::core::option::Option::None,
1884                    };
1885                    let _audit_entry = ::rustango::audit::PendingEntry {
1886                        entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
1887                        entity_pk: #pk_str,
1888                        operation: ::rustango::audit::AuditOp::Create,
1889                        source: ::rustango::audit::current_source(),
1890                        changes: ::rustango::audit::snapshot_changes(&[
1891                            #( #pairs ),*
1892                        ]),
1893                    };
1894                    let _result = ::rustango::audit::insert_one_with_audit_pool(
1895                        pool, &_query, &_audit_entry,
1896                    ).await?;
1897                    ::rustango::sql::apply_auto_pk_pool(_result, self)
1898                }
1899            }
1900        } else {
1901            quote!()
1902        }
1903    } else {
1904        // Keep the non-audited pool_insert_method we built earlier.
1905        pool_insert_method
1906    };
1907
1908    // Update audited save_pool: now that insert_pool is wired for
1909    // audited Auto-PK models, save_pool can dispatch Auto::Unset →
1910    // insert_pool. Non-audited save_pool already does this.
1911    // v0.23.0-batch25 — diff-style audit on the audited save_pool path.
1912    // Replaces the snapshot-only emission with a per-backend transaction
1913    // body that:
1914    //  1. SELECTs the tracked columns by PK (typed Row::try_get per
1915    //     column), capturing BEFORE values
1916    //  2. compiles the UPDATE via pool.dialect() and runs it on the tx
1917    //  3. builds AFTER pairs from &self
1918    //  4. diffs BEFORE/AFTER, emits one PendingEntry with
1919    //     AuditOp::Update + diff_changes(...) on the same tx connection
1920    //  5. commits
1921    //
1922    // Per-backend arms inline the SQL string + placeholder shape, then
1923    // share the `audit_before_pair_tokens` decoder block (Row::try_get
1924    // is polymorphic over Row type — the same tokens work against
1925    // PgRow and MySqlRow as long as the field's Rust type implements
1926    // both Decode<Postgres> and Decode<MySql>, which Auto<T> +
1927    // primitives + chrono/uuid/serde_json::Value all do).
1928    let pool_save_method = if let Some(tracked) = audited_fields {
1929        if let Some((pk_ident, pk_col)) = primary_key {
1930            let pk_column_lit = pk_col.as_str();
1931            // Two iterators — quote!'s `#(#var)*` consumes the
1932            // iterator, and we need to splice the same after-pairs
1933            // sequence into both per-backend arms.
1934            let after_pairs_pg = audit_pair_tokens.iter().collect::<Vec<_>>();
1935            let pk_str = audit_pk_to_string.clone();
1936            // Per-tracked-column BEFORE-pair token list. Each entry
1937            // is `(col_lit, try_get_returning<value_ty>(row, col_lit) → Json)`.
1938            // The Row alias resolves to PgRow / MySqlRow per call site,
1939            // so the same template generates both the PG and MySQL bodies.
1940            let mk_before_pairs =
1941                |getter: proc_macro2::TokenStream| -> Vec<proc_macro2::TokenStream> {
1942                    tracked
1943                        .iter()
1944                        .map(|c| {
1945                            let column_lit = c.column.as_str();
1946                            let value_ty = &c.value_ty;
1947                            quote! {
1948                                (
1949                                    #column_lit,
1950                                    match #getter::<#value_ty>(
1951                                        _audit_before_row, #column_lit,
1952                                    ) {
1953                                        ::core::result::Result::Ok(v) => {
1954                                            ::serde_json::to_value(&v)
1955                                                .unwrap_or(::serde_json::Value::Null)
1956                                        }
1957                                        ::core::result::Result::Err(_) => ::serde_json::Value::Null,
1958                                    },
1959                                )
1960                            }
1961                        })
1962                        .collect()
1963                };
1964            let before_pairs_pg: Vec<proc_macro2::TokenStream> =
1965                mk_before_pairs(quote!(::rustango::sql::try_get_returning));
1966            let before_pairs_my: Vec<proc_macro2::TokenStream> =
1967                mk_before_pairs(quote!(::rustango::sql::try_get_returning_my));
1968            let before_pairs_sqlite: Vec<proc_macro2::TokenStream> =
1969                mk_before_pairs(quote!(::rustango::sql::try_get_returning_sqlite));
1970            let pg_select_cols: String = tracked
1971                .iter()
1972                .map(|c| format!("\"{}\"", c.column.replace('"', "\"\"")))
1973                .collect::<Vec<_>>()
1974                .join(", ");
1975            let my_select_cols: String = tracked
1976                .iter()
1977                .map(|c| format!("`{}`", c.column.replace('`', "``")))
1978                .collect::<Vec<_>>()
1979                .join(", ");
1980            // SQLite uses double-quote identifier quoting (same as
1981            // Postgres in default config), so the column-list shape
1982            // matches PG.
1983            let sqlite_select_cols: String = pg_select_cols.clone();
1984            let pk_value_for_bind = if fields.pk_is_auto {
1985                quote!(self.#pk_ident.get().copied().unwrap_or_default())
1986            } else {
1987                quote!(::core::clone::Clone::clone(&self.#pk_ident))
1988            };
1989            let assignments = &fields.update_assignments;
1990            let unset_dispatch = if fields.has_auto {
1991                quote! {
1992                    if matches!(self.#pk_ident, ::rustango::sql::Auto::Unset) {
1993                        return self.insert_pool(pool).await;
1994                    }
1995                }
1996            } else {
1997                quote!()
1998            };
1999            quote! {
2000                /// Save this row against either backend with audit
2001                /// emission (diff-style: BEFORE+AFTER) inside the
2002                /// same transaction. Auto::Unset PK routes to
2003                /// insert_pool. Bi-dialect counterpart of
2004                /// [`Self::save`] for audited models.
2005                ///
2006                /// The audit row's `changes` JSON contains one
2007                /// `{ "field": { "before": …, "after": … } }` entry
2008                /// per tracked column whose value actually changed
2009                /// — same shape as the existing &PgPool save() emits.
2010                ///
2011                /// # Errors
2012                /// As [`Self::save`].
2013                pub async fn save_pool(
2014                    &mut self,
2015                    pool: &::rustango::sql::Pool,
2016                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
2017                    #unset_dispatch
2018                    let _query = ::rustango::core::UpdateQuery {
2019                        model: <Self as ::rustango::core::Model>::SCHEMA,
2020                        set: ::std::vec![ #( #assignments ),* ],
2021                        where_clause: ::rustango::core::WhereExpr::Predicate(
2022                            ::rustango::core::Filter {
2023                                column: #pk_column_lit,
2024                                op: ::rustango::core::Op::Eq,
2025                                value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
2026                                    ::core::clone::Clone::clone(&self.#pk_ident)
2027                                ),
2028                            }
2029                        ),
2030                    };
2031                    let _after_pairs: ::std::vec::Vec<(&'static str, ::serde_json::Value)> =
2032                        ::std::vec![ #( #after_pairs_pg ),* ];
2033                    ::rustango::audit::save_one_with_diff_pool(
2034                        pool,
2035                        &_query,
2036                        #pk_column_lit,
2037                        ::core::convert::Into::<::rustango::core::SqlValue>::into(
2038                            #pk_value_for_bind,
2039                        ),
2040                        <Self as ::rustango::core::Model>::SCHEMA.table,
2041                        #pk_str,
2042                        _after_pairs,
2043                        #pg_select_cols,
2044                        #my_select_cols,
2045                        #sqlite_select_cols,
2046                        |_audit_before_row| ::std::vec![ #( #before_pairs_pg ),* ],
2047                        |_audit_before_row| ::std::vec![ #( #before_pairs_my ),* ],
2048                        |_audit_before_row| ::std::vec![ #( #before_pairs_sqlite ),* ],
2049                    ).await
2050                }
2051            }
2052        } else {
2053            quote!()
2054        }
2055    } else {
2056        pool_save_method
2057    };
2058
2059    // `delete_pool(&Pool)` — emitted for every model with a PK. Two
2060    // body shapes:
2061    // - non-audited: simple dispatch through `sql::delete_pool`
2062    // - audited: routes through `audit::delete_one_with_audit_pool`,
2063    //   which opens a per-backend transaction wrapping DELETE +
2064    //   audit emit so the data write and audit row commit atomically.
2065    let pool_delete_method = {
2066        let pk_column_lit = primary_key.map(|(_, col)| col.as_str()).unwrap_or("id");
2067        let pk_ident_for_pool = primary_key.map(|(ident, _)| ident);
2068        if let Some(pk_ident) = pk_ident_for_pool {
2069            if audited_fields.is_some() {
2070                let pairs = audit_pair_tokens.iter();
2071                let pk_str = audit_pk_to_string.clone();
2072                quote! {
2073                    /// Delete this row against either backend with audit
2074                    /// emission inside the same transaction. Bi-dialect
2075                    /// counterpart of [`Self::delete`] for audited models.
2076                    ///
2077                    /// # Errors
2078                    /// As [`Self::delete`].
2079                    pub async fn delete_pool(
2080                        &self,
2081                        pool: &::rustango::sql::Pool,
2082                    ) -> ::core::result::Result<u64, ::rustango::sql::ExecError> {
2083                        let _query = ::rustango::core::DeleteQuery {
2084                            model: <Self as ::rustango::core::Model>::SCHEMA,
2085                            where_clause: ::rustango::core::WhereExpr::Predicate(
2086                                ::rustango::core::Filter {
2087                                    column: #pk_column_lit,
2088                                    op: ::rustango::core::Op::Eq,
2089                                    value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
2090                                        ::core::clone::Clone::clone(&self.#pk_ident)
2091                                    ),
2092                                }
2093                            ),
2094                        };
2095                        let _audit_entry = ::rustango::audit::PendingEntry {
2096                            entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
2097                            entity_pk: #pk_str,
2098                            operation: ::rustango::audit::AuditOp::Delete,
2099                            source: ::rustango::audit::current_source(),
2100                            changes: ::rustango::audit::snapshot_changes(&[
2101                                #( #pairs ),*
2102                            ]),
2103                        };
2104                        ::rustango::audit::delete_one_with_audit_pool(
2105                            pool, &_query, &_audit_entry,
2106                        ).await
2107                    }
2108                }
2109            } else {
2110                quote! {
2111                    /// Delete the row identified by this instance's primary key
2112                    /// against either backend. Equivalent to [`Self::delete`] but
2113                    /// takes [`::rustango::sql::Pool`] and dispatches per backend.
2114                    ///
2115                    /// # Errors
2116                    /// As [`Self::delete`].
2117                    pub async fn delete_pool(
2118                        &self,
2119                        pool: &::rustango::sql::Pool,
2120                    ) -> ::core::result::Result<u64, ::rustango::sql::ExecError> {
2121                        let _query = ::rustango::core::DeleteQuery {
2122                            model: <Self as ::rustango::core::Model>::SCHEMA,
2123                            where_clause: ::rustango::core::WhereExpr::Predicate(
2124                                ::rustango::core::Filter {
2125                                    column: #pk_column_lit,
2126                                    op: ::rustango::core::Op::Eq,
2127                                    value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
2128                                        ::core::clone::Clone::clone(&self.#pk_ident)
2129                                    ),
2130                                }
2131                            ),
2132                        };
2133                        ::rustango::sql::delete_pool(pool, &_query).await
2134                    }
2135                }
2136            }
2137        } else {
2138            quote!()
2139        }
2140    };
2141
2142    // Update emission captures both BEFORE and AFTER state — runs an
2143    // extra SELECT against `_executor` BEFORE the UPDATE, captures
2144    // each tracked field's prior value, then after the UPDATE diffs
2145    // against the in-memory `&self`. `diff_changes` drops unchanged
2146    // columns so the JSON only contains the actual delta.
2147    //
2148    // Two-fragment shape: `audit_update_pre` runs before the UPDATE
2149    // and binds `_audit_before_pairs`; `audit_update_post` runs
2150    // after the UPDATE and emits the PendingEntry.
2151    let (audit_update_pre, audit_update_post): (TokenStream2, TokenStream2) = if let Some(tracked) =
2152        audited_fields
2153    {
2154        if tracked.is_empty() {
2155            (quote!(), quote!())
2156        } else {
2157            let select_cols: String = tracked
2158                .iter()
2159                .map(|c| format!("\"{}\"", c.column.replace('"', "\"\"")))
2160                .collect::<Vec<_>>()
2161                .join(", ");
2162            let pk_column_for_select = primary_key.map(|(_, col)| col.clone()).unwrap_or_default();
2163            let select_cols_lit = select_cols;
2164            let pk_column_lit_for_select = pk_column_for_select;
2165            let pk_value_for_bind = if let Some((pk_ident, _)) = primary_key {
2166                if fields.pk_is_auto {
2167                    quote!(self.#pk_ident.get().copied().unwrap_or_default())
2168                } else {
2169                    quote!(::core::clone::Clone::clone(&self.#pk_ident))
2170                }
2171            } else {
2172                quote!(0_i64)
2173            };
2174            let before_pairs = tracked.iter().map(|c| {
2175                let column_lit = c.column.as_str();
2176                let value_ty = &c.value_ty;
2177                quote! {
2178                    (
2179                        #column_lit,
2180                        match ::rustango::sql::sqlx::Row::try_get::<#value_ty, _>(
2181                            &_audit_before_row, #column_lit,
2182                        ) {
2183                            ::core::result::Result::Ok(v) => {
2184                                ::serde_json::to_value(&v)
2185                                    .unwrap_or(::serde_json::Value::Null)
2186                            }
2187                            ::core::result::Result::Err(_) => ::serde_json::Value::Null,
2188                        },
2189                    )
2190                }
2191            });
2192            let after_pairs = tracked.iter().map(|c| {
2193                let column_lit = c.column.as_str();
2194                let ident = &c.ident;
2195                quote! {
2196                    (
2197                        #column_lit,
2198                        ::serde_json::to_value(&self.#ident)
2199                            .unwrap_or(::serde_json::Value::Null),
2200                    )
2201                }
2202            });
2203            let pk_str = audit_pk_to_string.clone();
2204            let pre = quote! {
2205                let _audit_select_sql = ::std::format!(
2206                    r#"SELECT {} FROM "{}" WHERE "{}" = $1"#,
2207                    #select_cols_lit,
2208                    <Self as ::rustango::core::Model>::SCHEMA.table,
2209                    #pk_column_lit_for_select,
2210                );
2211                let _audit_before_pairs:
2212                    ::std::option::Option<::std::vec::Vec<(&'static str, ::serde_json::Value)>> =
2213                    match ::rustango::sql::sqlx::query(&_audit_select_sql)
2214                        .bind(#pk_value_for_bind)
2215                        .fetch_optional(&mut *_executor)
2216                        .await
2217                    {
2218                        ::core::result::Result::Ok(::core::option::Option::Some(_audit_before_row)) => {
2219                            ::core::option::Option::Some(::std::vec![ #( #before_pairs ),* ])
2220                        }
2221                        _ => ::core::option::Option::None,
2222                    };
2223            };
2224            let post = quote! {
2225                if let ::core::option::Option::Some(_audit_before) = _audit_before_pairs {
2226                    let _audit_after:
2227                        ::std::vec::Vec<(&'static str, ::serde_json::Value)> =
2228                        ::std::vec![ #( #after_pairs ),* ];
2229                    let _audit_entry = ::rustango::audit::PendingEntry {
2230                        entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
2231                        entity_pk: #pk_str,
2232                        operation: ::rustango::audit::AuditOp::Update,
2233                        source: ::rustango::audit::current_source(),
2234                        changes: ::rustango::audit::diff_changes(
2235                            &_audit_before,
2236                            &_audit_after,
2237                        ),
2238                    };
2239                    ::rustango::audit::emit_one(&mut *_executor, &_audit_entry).await?;
2240                }
2241            };
2242            (pre, post)
2243        }
2244    } else {
2245        (quote!(), quote!())
2246    };
2247
2248    // Bulk-insert audit: capture every row's tracked fields after the
2249    // RETURNING populates each PK, then push one batched INSERT INTO
2250    // audit_log via `emit_many`. One round-trip regardless of N rows.
2251    let audit_bulk_insert_emit: TokenStream2 = if audited_fields.is_some() {
2252        let row_pk_str = if let Some((pk_ident, _)) = primary_key {
2253            if fields.pk_is_auto {
2254                quote!(_row.#pk_ident.get().map(|v| ::std::format!("{}", v)).unwrap_or_default())
2255            } else {
2256                quote!(::std::format!("{}", &_row.#pk_ident))
2257            }
2258        } else {
2259            quote!(::std::string::String::new())
2260        };
2261        let row_pairs = audited_fields.unwrap_or(&[]).iter().map(|c| {
2262            let column_lit = c.column.as_str();
2263            let ident = &c.ident;
2264            quote! {
2265                (
2266                    #column_lit,
2267                    ::serde_json::to_value(&_row.#ident)
2268                        .unwrap_or(::serde_json::Value::Null),
2269                )
2270            }
2271        });
2272        quote! {
2273            let _audit_source = ::rustango::audit::current_source();
2274            let mut _audit_entries:
2275                ::std::vec::Vec<::rustango::audit::PendingEntry> =
2276                    ::std::vec::Vec::with_capacity(rows.len());
2277            for _row in rows.iter() {
2278                _audit_entries.push(::rustango::audit::PendingEntry {
2279                    entity_table: <Self as ::rustango::core::Model>::SCHEMA.table,
2280                    entity_pk: #row_pk_str,
2281                    operation: ::rustango::audit::AuditOp::Create,
2282                    source: _audit_source.clone(),
2283                    changes: ::rustango::audit::snapshot_changes(&[
2284                        #( #row_pairs ),*
2285                    ]),
2286                });
2287            }
2288            ::rustango::audit::emit_many(&mut *_executor, &_audit_entries).await?;
2289        }
2290    } else {
2291        quote!()
2292    };
2293
2294    let save_method = if fields.pk_is_auto {
2295        let (pk_ident, pk_column) = primary_key.expect("pk_is_auto implies primary_key is Some");
2296        let pk_column_lit = pk_column.as_str();
2297        let assignments = &fields.update_assignments;
2298        let upsert_cols = &fields.upsert_update_columns;
2299        let upsert_pushes = &fields.insert_pushes;
2300        let upsert_returning = &fields.returning_cols;
2301        let upsert_auto_assigns = &fields.auto_assigns;
2302        // Conflict target: prefer the first declared `unique_together`
2303        // when it exists. Plain `Auto<T>` PKs are server-assigned via
2304        // `BIGSERIAL` and never collide on insert, so a PK-only target
2305        // would silently turn `upsert()` into "always-insert" for
2306        // surrogate-PK models with composite UNIQUE constraints — see
2307        // `RolePermission` / `UserRole` / `UserPermission` in the
2308        // tenancy permission engine. When no `unique_together` is
2309        // declared we keep the PK target (the original behaviour).
2310        let upsert_target_columns: Vec<String> = indexes
2311            .iter()
2312            .find(|i| i.unique && !i.columns.is_empty())
2313            .map(|i| i.columns.clone())
2314            .unwrap_or_else(|| vec![pk_column.clone()]);
2315        let upsert_target_lits = upsert_target_columns
2316            .iter()
2317            .map(String::as_str)
2318            .collect::<Vec<_>>();
2319        let conflict_clause = if fields.upsert_update_columns.is_empty() {
2320            quote!(::rustango::core::ConflictClause::DoNothing)
2321        } else {
2322            quote!(::rustango::core::ConflictClause::DoUpdate {
2323                target: ::std::vec![ #( #upsert_target_lits ),* ],
2324                update_columns: ::std::vec![ #( #upsert_cols ),* ],
2325            })
2326        };
2327        Some(quote! {
2328            /// Insert this row if its `Auto<T>` primary key is
2329            /// `Unset`, otherwise update the existing row matching the
2330            /// PK. Mirrors Django's `save()` — caller doesn't need to
2331            /// pick `insert` vs the bulk-update path manually.
2332            ///
2333            /// On the insert branch, populates the PK from `RETURNING`
2334            /// (same behavior as `insert`). On the update branch,
2335            /// writes every non-PK column back; if no row matches the
2336            /// PK, returns `Ok(())` silently.
2337            ///
2338            /// Only generated when the primary key is declared as
2339            /// `Auto<T>`. Models with a manually-managed PK must use
2340            /// `insert` or the QuerySet update builder.
2341            ///
2342            /// # Errors
2343            /// Returns [`::rustango::sql::ExecError`] for SQL-writing
2344            /// or driver failures.
2345            pub async fn save(
2346                &mut self,
2347                pool: &::rustango::sql::sqlx::PgPool,
2348            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
2349                #pool_to_save_on
2350            }
2351
2352            /// Like [`Self::save`] but accepts any sqlx executor —
2353            /// `&PgPool`, `&mut PgConnection`, or a transaction. The
2354            /// escape hatch for tenant-scoped writes: schema-mode
2355            /// tenants share the registry pool but rely on a per-
2356            /// checkout `SET search_path`, so passing `&PgPool` would
2357            /// silently hit the wrong schema. Acquire a connection
2358            /// via `TenantPools::acquire(&org)` and pass `&mut *conn`.
2359            ///
2360            /// # Errors
2361            /// As [`Self::save`].
2362            pub async fn save_on #executor_generics (
2363                &mut self,
2364                #executor_param,
2365            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
2366            #executor_where
2367            {
2368                if matches!(self.#pk_ident, ::rustango::sql::Auto::Unset) {
2369                    return self.insert_on(#executor_passes_to_data_write).await;
2370                }
2371                #audit_update_pre
2372                let _query = ::rustango::core::UpdateQuery {
2373                    model: <Self as ::rustango::core::Model>::SCHEMA,
2374                    set: ::std::vec![ #( #assignments ),* ],
2375                    where_clause: ::rustango::core::WhereExpr::Predicate(
2376                        ::rustango::core::Filter {
2377                            column: #pk_column_lit,
2378                            op: ::rustango::core::Op::Eq,
2379                            value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
2380                                ::core::clone::Clone::clone(&self.#pk_ident)
2381                            ),
2382                        }
2383                    ),
2384                };
2385                let _ = ::rustango::sql::update_on(
2386                    #executor_passes_to_data_write,
2387                    &_query,
2388                ).await?;
2389                #audit_update_post
2390                ::core::result::Result::Ok(())
2391            }
2392
2393            /// Per-call override for the audit source. Runs
2394            /// [`Self::save_on`] inside an [`::rustango::audit::with_source`]
2395            /// scope so the resulting audit entry records `source`
2396            /// instead of the task-local default. Useful for seed
2397            /// scripts and one-off CLI tools that don't sit inside an
2398            /// admin handler. The override applies only to this call;
2399            /// no global state changes.
2400            ///
2401            /// # Errors
2402            /// As [`Self::save_on`].
2403            pub async fn save_on_with #executor_generics (
2404                &mut self,
2405                #executor_param,
2406                source: ::rustango::audit::AuditSource,
2407            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
2408            #executor_where
2409            {
2410                ::rustango::audit::with_source(source, self.save_on(_executor)).await
2411            }
2412
2413            /// Insert this row or update it in-place if the primary key already
2414            /// exists — single round-trip via `INSERT … ON CONFLICT (pk) DO UPDATE`.
2415            ///
2416            /// With `Auto::Unset` PK the server assigns a new key and no conflict
2417            /// can occur (equivalent to `insert`). With `Auto::Set` PK the row is
2418            /// inserted if absent or all non-PK columns are overwritten if present.
2419            ///
2420            /// # Errors
2421            /// As [`Self::insert_on`].
2422            pub async fn upsert(
2423                &mut self,
2424                pool: &::rustango::sql::sqlx::PgPool,
2425            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
2426                #pool_to_upsert_on
2427            }
2428
2429            /// Like [`Self::upsert`] but accepts any sqlx executor.
2430            /// See [`Self::save_on`] for tenancy-scoped rationale.
2431            ///
2432            /// # Errors
2433            /// As [`Self::upsert`].
2434            pub async fn upsert_on #executor_generics (
2435                &mut self,
2436                #executor_param,
2437            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
2438            #executor_where
2439            {
2440                let mut _columns: ::std::vec::Vec<&'static str> =
2441                    ::std::vec::Vec::new();
2442                let mut _values: ::std::vec::Vec<::rustango::core::SqlValue> =
2443                    ::std::vec::Vec::new();
2444                #( #upsert_pushes )*
2445                let query = ::rustango::core::InsertQuery {
2446                    model: <Self as ::rustango::core::Model>::SCHEMA,
2447                    columns: _columns,
2448                    values: _values,
2449                    returning: ::std::vec![ #( #upsert_returning ),* ],
2450                    on_conflict: ::core::option::Option::Some(#conflict_clause),
2451                };
2452                let _returning_row_v = ::rustango::sql::insert_returning_on(
2453                    #executor_passes_to_data_write,
2454                    &query,
2455                ).await?;
2456                let _returning_row = &_returning_row_v;
2457                #( #upsert_auto_assigns )*
2458                ::core::result::Result::Ok(())
2459            }
2460        })
2461    } else {
2462        None
2463    };
2464
2465    let pk_methods = primary_key.map(|(pk_ident, pk_column)| {
2466        let pk_column_lit = pk_column.as_str();
2467        // Optional `soft_delete_on` / `restore_on` companions when the
2468        // model has a `#[rustango(soft_delete)]` column. They land
2469        // alongside the regular `delete_on` so callers have both
2470        // options — a hard delete (audit-tracked as a real DELETE) and
2471        // a logical delete (audit-tracked as an UPDATE setting the
2472        // deleted_at column to NOW()).
2473        let soft_delete_methods = if let Some(col) = fields.soft_delete_column.as_deref() {
2474            let col_lit = col;
2475            quote! {
2476                /// Soft-delete this row by setting its
2477                /// `#[rustango(soft_delete)]` column to `NOW()`.
2478                /// Mirrors Django's `SoftDeleteModel.delete()` shape:
2479                /// the row stays in the table; query helpers can
2480                /// filter it out by checking the column for `IS NOT
2481                /// NULL`.
2482                ///
2483                /// # Errors
2484                /// As [`Self::delete`].
2485                pub async fn soft_delete_on #executor_generics (
2486                    &self,
2487                    #executor_param,
2488                ) -> ::core::result::Result<u64, ::rustango::sql::ExecError>
2489                #executor_where
2490                {
2491                    let _query = ::rustango::core::UpdateQuery {
2492                        model: <Self as ::rustango::core::Model>::SCHEMA,
2493                        set: ::std::vec![
2494                            ::rustango::core::Assignment {
2495                                column: #col_lit,
2496                                value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
2497                                    ::chrono::Utc::now()
2498                                ),
2499                            },
2500                        ],
2501                        where_clause: ::rustango::core::WhereExpr::Predicate(
2502                            ::rustango::core::Filter {
2503                                column: #pk_column_lit,
2504                                op: ::rustango::core::Op::Eq,
2505                                value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
2506                                    ::core::clone::Clone::clone(&self.#pk_ident)
2507                                ),
2508                            }
2509                        ),
2510                    };
2511                    let _affected = ::rustango::sql::update_on(
2512                        #executor_passes_to_data_write,
2513                        &_query,
2514                    ).await?;
2515                    #audit_softdelete_emit
2516                    ::core::result::Result::Ok(_affected)
2517                }
2518
2519                /// Inverse of [`Self::soft_delete_on`] — clears the
2520                /// soft-delete column back to NULL so the row is
2521                /// considered live again.
2522                ///
2523                /// # Errors
2524                /// As [`Self::delete`].
2525                pub async fn restore_on #executor_generics (
2526                    &self,
2527                    #executor_param,
2528                ) -> ::core::result::Result<u64, ::rustango::sql::ExecError>
2529                #executor_where
2530                {
2531                    let _query = ::rustango::core::UpdateQuery {
2532                        model: <Self as ::rustango::core::Model>::SCHEMA,
2533                        set: ::std::vec![
2534                            ::rustango::core::Assignment {
2535                                column: #col_lit,
2536                                value: ::rustango::core::SqlValue::Null,
2537                            },
2538                        ],
2539                        where_clause: ::rustango::core::WhereExpr::Predicate(
2540                            ::rustango::core::Filter {
2541                                column: #pk_column_lit,
2542                                op: ::rustango::core::Op::Eq,
2543                                value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
2544                                    ::core::clone::Clone::clone(&self.#pk_ident)
2545                                ),
2546                            }
2547                        ),
2548                    };
2549                    let _affected = ::rustango::sql::update_on(
2550                        #executor_passes_to_data_write,
2551                        &_query,
2552                    ).await?;
2553                    #audit_restore_emit
2554                    ::core::result::Result::Ok(_affected)
2555                }
2556            }
2557        } else {
2558            quote!()
2559        };
2560        quote! {
2561            /// Delete the row identified by this instance's primary key.
2562            ///
2563            /// Returns the number of rows affected (0 or 1).
2564            ///
2565            /// # Errors
2566            /// Returns [`::rustango::sql::ExecError`] for SQL-writing or
2567            /// driver failures.
2568            pub async fn delete(
2569                &self,
2570                pool: &::rustango::sql::sqlx::PgPool,
2571            ) -> ::core::result::Result<u64, ::rustango::sql::ExecError> {
2572                #pool_to_delete_on
2573            }
2574
2575            /// Like [`Self::delete`] but accepts any sqlx executor —
2576            /// for tenant-scoped deletes against an explicitly-acquired
2577            /// connection. See [`Self::save_on`] for the rationale.
2578            ///
2579            /// # Errors
2580            /// As [`Self::delete`].
2581            pub async fn delete_on #executor_generics (
2582                &self,
2583                #executor_param,
2584            ) -> ::core::result::Result<u64, ::rustango::sql::ExecError>
2585            #executor_where
2586            {
2587                let query = ::rustango::core::DeleteQuery {
2588                    model: <Self as ::rustango::core::Model>::SCHEMA,
2589                    where_clause: ::rustango::core::WhereExpr::Predicate(
2590                        ::rustango::core::Filter {
2591                            column: #pk_column_lit,
2592                            op: ::rustango::core::Op::Eq,
2593                            value: ::core::convert::Into::<::rustango::core::SqlValue>::into(
2594                                ::core::clone::Clone::clone(&self.#pk_ident)
2595                            ),
2596                        }
2597                    ),
2598                };
2599                let _affected = ::rustango::sql::delete_on(
2600                    #executor_passes_to_data_write,
2601                    &query,
2602                ).await?;
2603                #audit_delete_emit
2604                ::core::result::Result::Ok(_affected)
2605            }
2606
2607            /// Per-call audit-source override for [`Self::delete_on`].
2608            /// See [`Self::save_on_with`] for shape rationale.
2609            ///
2610            /// # Errors
2611            /// As [`Self::delete_on`].
2612            pub async fn delete_on_with #executor_generics (
2613                &self,
2614                #executor_param,
2615                source: ::rustango::audit::AuditSource,
2616            ) -> ::core::result::Result<u64, ::rustango::sql::ExecError>
2617            #executor_where
2618            {
2619                ::rustango::audit::with_source(source, self.delete_on(_executor)).await
2620            }
2621            #pool_delete_method
2622            #pool_insert_method
2623            #pool_save_method
2624            #soft_delete_methods
2625        }
2626    });
2627
2628    let insert_method = if fields.has_auto {
2629        let pushes = &fields.insert_pushes;
2630        let returning_cols = &fields.returning_cols;
2631        let auto_assigns = &fields.auto_assigns;
2632        quote! {
2633            /// Insert this row into its table. Skips columns whose
2634            /// `Auto<T>` value is `Unset` so Postgres' SERIAL/BIGSERIAL
2635            /// sequence fills them in, then reads each `Auto` column
2636            /// back via `RETURNING` and stores it on `self`.
2637            ///
2638            /// # Errors
2639            /// Returns [`::rustango::sql::ExecError`] for SQL-writing or
2640            /// driver failures.
2641            pub async fn insert(
2642                &mut self,
2643                pool: &::rustango::sql::sqlx::PgPool,
2644            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
2645                #pool_to_insert_on
2646            }
2647
2648            /// Like [`Self::insert`] but accepts any sqlx executor.
2649            /// See [`Self::save_on`] for tenancy-scoped rationale.
2650            ///
2651            /// # Errors
2652            /// As [`Self::insert`].
2653            pub async fn insert_on #executor_generics (
2654                &mut self,
2655                #executor_param,
2656            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
2657            #executor_where
2658            {
2659                let mut _columns: ::std::vec::Vec<&'static str> =
2660                    ::std::vec::Vec::new();
2661                let mut _values: ::std::vec::Vec<::rustango::core::SqlValue> =
2662                    ::std::vec::Vec::new();
2663                #( #pushes )*
2664                let query = ::rustango::core::InsertQuery {
2665                    model: <Self as ::rustango::core::Model>::SCHEMA,
2666                    columns: _columns,
2667                    values: _values,
2668                    returning: ::std::vec![ #( #returning_cols ),* ],
2669                    on_conflict: ::core::option::Option::None,
2670                };
2671                let _returning_row_v = ::rustango::sql::insert_returning_on(
2672                    #executor_passes_to_data_write,
2673                    &query,
2674                ).await?;
2675                let _returning_row = &_returning_row_v;
2676                #( #auto_assigns )*
2677                #audit_insert_emit
2678                ::core::result::Result::Ok(())
2679            }
2680
2681            /// Per-call audit-source override for [`Self::insert_on`].
2682            /// See [`Self::save_on_with`] for shape rationale.
2683            ///
2684            /// # Errors
2685            /// As [`Self::insert_on`].
2686            pub async fn insert_on_with #executor_generics (
2687                &mut self,
2688                #executor_param,
2689                source: ::rustango::audit::AuditSource,
2690            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
2691            #executor_where
2692            {
2693                ::rustango::audit::with_source(source, self.insert_on(_executor)).await
2694            }
2695        }
2696    } else {
2697        let insert_columns = &fields.insert_columns;
2698        let insert_values = &fields.insert_values;
2699        quote! {
2700            /// Insert this row into its table.
2701            ///
2702            /// # Errors
2703            /// Returns [`::rustango::sql::ExecError`] for SQL-writing or
2704            /// driver failures.
2705            pub async fn insert(
2706                &self,
2707                pool: &::rustango::sql::sqlx::PgPool,
2708            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
2709                self.insert_on(pool).await
2710            }
2711
2712            /// Like [`Self::insert`] but accepts any sqlx executor.
2713            /// See [`Self::save_on`] for tenancy-scoped rationale.
2714            ///
2715            /// # Errors
2716            /// As [`Self::insert`].
2717            pub async fn insert_on<'_c, _E>(
2718                &self,
2719                _executor: _E,
2720            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
2721            where
2722                _E: ::rustango::sql::sqlx::Executor<'_c, Database = ::rustango::sql::sqlx::Postgres>,
2723            {
2724                let query = ::rustango::core::InsertQuery {
2725                    model: <Self as ::rustango::core::Model>::SCHEMA,
2726                    columns: ::std::vec![ #( #insert_columns ),* ],
2727                    values: ::std::vec![ #( #insert_values ),* ],
2728                    returning: ::std::vec::Vec::new(),
2729                    on_conflict: ::core::option::Option::None,
2730                };
2731                ::rustango::sql::insert_on(_executor, &query).await
2732            }
2733        }
2734    };
2735
2736    let bulk_insert_method = if fields.has_auto {
2737        let cols_no_auto = &fields.bulk_columns_no_auto;
2738        let cols_all = &fields.bulk_columns_all;
2739        let pushes_no_auto = &fields.bulk_pushes_no_auto;
2740        let pushes_all = &fields.bulk_pushes_all;
2741        let returning_cols = &fields.returning_cols;
2742        let auto_assigns_for_row = bulk_auto_assigns_for_row(fields);
2743        let uniformity = &fields.bulk_auto_uniformity;
2744        let first_auto_ident = fields
2745            .first_auto_ident
2746            .as_ref()
2747            .expect("has_auto implies first_auto_ident is Some");
2748        quote! {
2749            /// Bulk-insert `rows` in a single round-trip. Every row's
2750            /// `Auto<T>` PK fields must uniformly be `Auto::Unset`
2751            /// (sequence fills them in) or uniformly `Auto::Set(_)`
2752            /// (caller-supplied values). Mixed Set/Unset is rejected
2753            /// — call `insert` per row for that case.
2754            ///
2755            /// Empty slice is a no-op. Each row's `Auto` fields are
2756            /// populated from the `RETURNING` clause in input order
2757            /// before this returns.
2758            ///
2759            /// # Errors
2760            /// Returns [`::rustango::sql::ExecError`] for validation,
2761            /// SQL-writing, mixed-Auto rejection, or driver failures.
2762            pub async fn bulk_insert(
2763                rows: &mut [Self],
2764                pool: &::rustango::sql::sqlx::PgPool,
2765            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
2766                #pool_to_bulk_insert_on
2767            }
2768
2769            /// Like [`Self::bulk_insert`] but accepts any sqlx executor.
2770            /// See [`Self::save_on`] for tenancy-scoped rationale.
2771            ///
2772            /// # Errors
2773            /// As [`Self::bulk_insert`].
2774            pub async fn bulk_insert_on #executor_generics (
2775                rows: &mut [Self],
2776                #executor_param,
2777            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
2778            #executor_where
2779            {
2780                if rows.is_empty() {
2781                    return ::core::result::Result::Ok(());
2782                }
2783                let _first_unset = matches!(
2784                    rows[0].#first_auto_ident,
2785                    ::rustango::sql::Auto::Unset
2786                );
2787                #( #uniformity )*
2788
2789                let mut _all_rows: ::std::vec::Vec<
2790                    ::std::vec::Vec<::rustango::core::SqlValue>,
2791                > = ::std::vec::Vec::with_capacity(rows.len());
2792                let _columns: ::std::vec::Vec<&'static str> = if _first_unset {
2793                    for _row in rows.iter() {
2794                        let mut _row_vals: ::std::vec::Vec<::rustango::core::SqlValue> =
2795                            ::std::vec::Vec::new();
2796                        #( #pushes_no_auto )*
2797                        _all_rows.push(_row_vals);
2798                    }
2799                    ::std::vec![ #( #cols_no_auto ),* ]
2800                } else {
2801                    for _row in rows.iter() {
2802                        let mut _row_vals: ::std::vec::Vec<::rustango::core::SqlValue> =
2803                            ::std::vec::Vec::new();
2804                        #( #pushes_all )*
2805                        _all_rows.push(_row_vals);
2806                    }
2807                    ::std::vec![ #( #cols_all ),* ]
2808                };
2809
2810                let _query = ::rustango::core::BulkInsertQuery {
2811                    model: <Self as ::rustango::core::Model>::SCHEMA,
2812                    columns: _columns,
2813                    rows: _all_rows,
2814                    returning: ::std::vec![ #( #returning_cols ),* ],
2815                    on_conflict: ::core::option::Option::None,
2816                };
2817                let _returned = ::rustango::sql::bulk_insert_on(
2818                    #executor_passes_to_data_write,
2819                    &_query,
2820                ).await?;
2821                if _returned.len() != rows.len() {
2822                    return ::core::result::Result::Err(
2823                        ::rustango::sql::ExecError::Sql(
2824                            ::rustango::sql::SqlError::BulkInsertReturningMismatch {
2825                                expected: rows.len(),
2826                                actual: _returned.len(),
2827                            }
2828                        )
2829                    );
2830                }
2831                for (_returning_row, _row_mut) in _returned.iter().zip(rows.iter_mut()) {
2832                    #auto_assigns_for_row
2833                }
2834                #audit_bulk_insert_emit
2835                ::core::result::Result::Ok(())
2836            }
2837        }
2838    } else {
2839        let cols_all = &fields.bulk_columns_all;
2840        let pushes_all = &fields.bulk_pushes_all;
2841        quote! {
2842            /// Bulk-insert `rows` in a single round-trip. Every row's
2843            /// fields are written verbatim — there are no `Auto<T>`
2844            /// fields on this model.
2845            ///
2846            /// Empty slice is a no-op.
2847            ///
2848            /// # Errors
2849            /// Returns [`::rustango::sql::ExecError`] for validation,
2850            /// SQL-writing, or driver failures.
2851            pub async fn bulk_insert(
2852                rows: &[Self],
2853                pool: &::rustango::sql::sqlx::PgPool,
2854            ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
2855                Self::bulk_insert_on(rows, pool).await
2856            }
2857
2858            /// Like [`Self::bulk_insert`] but accepts any sqlx executor.
2859            /// See [`Self::save_on`] for tenancy-scoped rationale.
2860            ///
2861            /// # Errors
2862            /// As [`Self::bulk_insert`].
2863            pub async fn bulk_insert_on<'_c, _E>(
2864                rows: &[Self],
2865                _executor: _E,
2866            ) -> ::core::result::Result<(), ::rustango::sql::ExecError>
2867            where
2868                _E: ::rustango::sql::sqlx::Executor<'_c, Database = ::rustango::sql::sqlx::Postgres>,
2869            {
2870                if rows.is_empty() {
2871                    return ::core::result::Result::Ok(());
2872                }
2873                let mut _all_rows: ::std::vec::Vec<
2874                    ::std::vec::Vec<::rustango::core::SqlValue>,
2875                > = ::std::vec::Vec::with_capacity(rows.len());
2876                for _row in rows.iter() {
2877                    let mut _row_vals: ::std::vec::Vec<::rustango::core::SqlValue> =
2878                        ::std::vec::Vec::new();
2879                    #( #pushes_all )*
2880                    _all_rows.push(_row_vals);
2881                }
2882                let _query = ::rustango::core::BulkInsertQuery {
2883                    model: <Self as ::rustango::core::Model>::SCHEMA,
2884                    columns: ::std::vec![ #( #cols_all ),* ],
2885                    rows: _all_rows,
2886                    returning: ::std::vec::Vec::new(),
2887                    on_conflict: ::core::option::Option::None,
2888                };
2889                let _ = ::rustango::sql::bulk_insert_on(_executor, &_query).await?;
2890                ::core::result::Result::Ok(())
2891            }
2892        }
2893    };
2894
2895    let pk_value_helper = primary_key.map(|(pk_ident, _)| {
2896        quote! {
2897            /// Hidden runtime accessor for the primary-key value as a
2898            /// [`SqlValue`]. Used by reverse-relation helpers
2899            /// (`<parent>::<child>_set`) emitted from sibling models'
2900            /// FK fields. Not part of the public API.
2901            #[doc(hidden)]
2902            pub fn __rustango_pk_value(&self) -> ::rustango::core::SqlValue {
2903                ::core::convert::Into::<::rustango::core::SqlValue>::into(
2904                    ::core::clone::Clone::clone(&self.#pk_ident)
2905                )
2906            }
2907        }
2908    });
2909
2910    let has_pk_value_impl = primary_key.map(|(pk_ident, _)| {
2911        quote! {
2912            impl ::rustango::sql::HasPkValue for #struct_name {
2913                fn __rustango_pk_value_impl(&self) -> ::rustango::core::SqlValue {
2914                    ::core::convert::Into::<::rustango::core::SqlValue>::into(
2915                        ::core::clone::Clone::clone(&self.#pk_ident)
2916                    )
2917                }
2918            }
2919        }
2920    });
2921
2922    let fk_pk_access_impl = fk_pk_access_impl_tokens(struct_name, &fields.fk_relations);
2923
2924    // Slice 17.1 — `AssignAutoPkPool` impl lets `apply_auto_pk_pool`
2925    // dispatch to the right per-backend body without the macro emitting
2926    // any `#[cfg(feature = …)]` arm into consumer code. Always emitted
2927    // so audited models with non-Auto PKs (which still go through
2928    // `insert_one_with_audit_pool` → `apply_auto_pk_pool`) link.
2929    let assign_auto_pk_pool_impl = {
2930        let auto_assigns = &fields.auto_assigns;
2931        // SQLite ≥ 3.35 supports the same RETURNING shape as Postgres,
2932        // so the body is structurally identical to `auto_assigns` —
2933        // only the helper name swaps from `try_get_returning` to
2934        // `try_get_returning_sqlite` so the closure typechecks against
2935        // a `SqliteRow` instead of a `PgRow`.
2936        let auto_assigns_sqlite: Vec<TokenStream2> = fields
2937            .auto_field_idents
2938            .iter()
2939            .map(|(ident, column)| {
2940                quote! {
2941                    self.#ident = ::rustango::sql::try_get_returning_sqlite(
2942                        _returning_row, #column
2943                    )?;
2944                }
2945            })
2946            .collect();
2947        let mysql_body = if let Some(first) = fields.first_auto_ident.as_ref() {
2948            // The MySQL `LAST_INSERT_ID()` is always i64. Route through
2949            // `MysqlAutoIdSet` so Auto<i32> narrows safely and
2950            // Auto<Uuid>/etc. fail to link against MySQL (intended —
2951            // those models can't use AUTO_INCREMENT). The trait is only
2952            // touched on the MySQL arm at runtime, so PG-only consumers
2953            // never see the bound failure.
2954            //
2955            // Pre-v0.20: models with multiple `Auto<T>` fields (e.g.
2956            // Auto<i64> PK + auto_now_add timestamp) errored hard at
2957            // runtime with "multi-column RETURNING". MySQL has no
2958            // multi-column RETURNING semantic and a follow-up SELECT
2959            // would need cross-trait plumbing. Pragmatic shape: succeed
2960            // with the FIRST Auto field populated from LAST_INSERT_ID();
2961            // any other Auto fields stay `Auto::Unset`. Callers that
2962            // need the DB-defaulted timestamp / UUID can re-fetch the
2963            // row by PK after `save_pool`. Fixes the cookbook chapter
2964            // 12 dialect divergence.
2965            let value_ty = fields
2966                .first_auto_value_ty
2967                .as_ref()
2968                .expect("first_auto_value_ty set whenever first_auto_ident is");
2969            quote! {
2970                let _converted = <#value_ty as ::rustango::sql::MysqlAutoIdSet>
2971                    ::rustango_from_mysql_auto_id(_id)?;
2972                self.#first = ::rustango::sql::Auto::Set(_converted);
2973                ::core::result::Result::Ok(())
2974            }
2975        } else {
2976            quote! {
2977                let _ = _id;
2978                ::core::result::Result::Ok(())
2979            }
2980        };
2981        quote! {
2982            impl ::rustango::sql::AssignAutoPkPool for #struct_name {
2983                fn __rustango_assign_from_pg_row(
2984                    &mut self,
2985                    _returning_row: &::rustango::sql::PgReturningRow,
2986                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
2987                    #( #auto_assigns )*
2988                    ::core::result::Result::Ok(())
2989                }
2990                fn __rustango_assign_from_mysql_id(
2991                    &mut self,
2992                    _id: i64,
2993                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
2994                    #mysql_body
2995                }
2996                fn __rustango_assign_from_sqlite_row(
2997                    &mut self,
2998                    _returning_row: &::rustango::sql::SqliteReturningRow,
2999                ) -> ::core::result::Result<(), ::rustango::sql::ExecError> {
3000                    #( #auto_assigns_sqlite )*
3001                    ::core::result::Result::Ok(())
3002                }
3003            }
3004        }
3005    };
3006
3007    let from_aliased_row_inits = &fields.from_aliased_row_inits;
3008    let aliased_row_helper = quote! {
3009        /// Decode a row's aliased target columns (produced by
3010        /// `select_related`'s LEFT JOIN) into a fresh instance of
3011        /// this model. Reads each column via
3012        /// `format!("{prefix}__{col}")`, matching the alias the
3013        /// SELECT writer emitted. Slice 9.0d.
3014        #[doc(hidden)]
3015        pub fn __rustango_from_aliased_row(
3016            row: &::rustango::sql::sqlx::postgres::PgRow,
3017            prefix: &str,
3018        ) -> ::core::result::Result<Self, ::rustango::sql::sqlx::Error> {
3019            ::core::result::Result::Ok(Self {
3020                #( #from_aliased_row_inits ),*
3021            })
3022        }
3023    };
3024    // v0.23.0-batch8 — MySQL counterpart, gated through the
3025    // cfg-aware macro_rules so PG-only builds expand to nothing.
3026    let aliased_row_helper_my = quote! {
3027        ::rustango::__impl_my_aliased_row_decoder!(#struct_name, |row, prefix| {
3028            #( #from_aliased_row_inits ),*
3029        });
3030    };
3031
3032    // v0.27 Phase 3 — SQLite counterpart, same hygiene-aware closure
3033    // pattern + cfg gate on the `sqlite` feature.
3034    let aliased_row_helper_sqlite = quote! {
3035        ::rustango::__impl_sqlite_aliased_row_decoder!(#struct_name, |row, prefix| {
3036            #( #from_aliased_row_inits ),*
3037        });
3038    };
3039
3040    let load_related_impl = load_related_impl_tokens(struct_name, &fields.fk_relations);
3041    let load_related_impl_my = load_related_impl_my_tokens(struct_name, &fields.fk_relations);
3042    let load_related_impl_sqlite =
3043        load_related_impl_sqlite_tokens(struct_name, &fields.fk_relations);
3044
3045    quote! {
3046        impl #struct_name {
3047            /// Start a new `QuerySet` over this model.
3048            #[must_use]
3049            pub fn objects() -> ::rustango::query::QuerySet<#struct_name> {
3050                ::rustango::query::QuerySet::new()
3051            }
3052
3053            #insert_method
3054
3055            #bulk_insert_method
3056
3057            #save_method
3058
3059            #pk_methods
3060
3061            #pk_value_helper
3062
3063            #aliased_row_helper
3064
3065            #column_consts
3066        }
3067
3068        #aliased_row_helper_my
3069
3070        #aliased_row_helper_sqlite
3071
3072        #load_related_impl
3073
3074        #load_related_impl_my
3075
3076        #load_related_impl_sqlite
3077
3078        #has_pk_value_impl
3079
3080        #fk_pk_access_impl
3081
3082        #assign_auto_pk_pool_impl
3083    }
3084}
3085
3086/// Per-row Auto-field assigns for `bulk_insert` — equivalent to
3087/// `auto_assigns` but reading from `_returning_row` and writing to
3088/// `_row_mut` instead of `self`.
3089fn bulk_auto_assigns_for_row(fields: &CollectedFields) -> TokenStream2 {
3090    let lines = fields.auto_field_idents.iter().map(|(ident, column)| {
3091        let col_lit = column.as_str();
3092        quote! {
3093            _row_mut.#ident = ::rustango::sql::sqlx::Row::try_get(
3094                _returning_row,
3095                #col_lit,
3096            )?;
3097        }
3098    });
3099    quote! { #( #lines )* }
3100}
3101
3102/// Emit `pub const id: …Id = …Id;` per field, inside the inherent impl.
3103fn column_const_tokens(module_ident: &syn::Ident, entries: &[ColumnEntry]) -> TokenStream2 {
3104    let lines = entries.iter().map(|e| {
3105        let ident = &e.ident;
3106        let col_ty = column_type_ident(ident);
3107        quote! {
3108            #[allow(non_upper_case_globals)]
3109            pub const #ident: #module_ident::#col_ty = #module_ident::#col_ty;
3110        }
3111    });
3112    quote! { #(#lines)* }
3113}
3114
3115/// Emit a hidden per-model module carrying one zero-sized type per field,
3116/// each with a `Column` impl pointing back at the model.
3117fn column_module_tokens(
3118    module_ident: &syn::Ident,
3119    struct_name: &syn::Ident,
3120    entries: &[ColumnEntry],
3121) -> TokenStream2 {
3122    let items = entries.iter().map(|e| {
3123        let col_ty = column_type_ident(&e.ident);
3124        let value_ty = &e.value_ty;
3125        let name = &e.name;
3126        let column = &e.column;
3127        let field_type_tokens = &e.field_type_tokens;
3128        quote! {
3129            #[derive(::core::clone::Clone, ::core::marker::Copy)]
3130            pub struct #col_ty;
3131
3132            impl ::rustango::core::Column for #col_ty {
3133                type Model = super::#struct_name;
3134                type Value = #value_ty;
3135                const NAME: &'static str = #name;
3136                const COLUMN: &'static str = #column;
3137                const FIELD_TYPE: ::rustango::core::FieldType = #field_type_tokens;
3138            }
3139        }
3140    });
3141    quote! {
3142        #[doc(hidden)]
3143        #[allow(non_camel_case_types, non_snake_case)]
3144        pub mod #module_ident {
3145            // Re-import the parent scope so field types referencing
3146            // sibling models (e.g. `ForeignKey<Author>`) resolve
3147            // inside this submodule. Without this we'd hit
3148            // `proc_macro_derive_resolution_fallback` warnings.
3149            #[allow(unused_imports)]
3150            use super::*;
3151            #(#items)*
3152        }
3153    }
3154}
3155
3156fn column_type_ident(field_ident: &syn::Ident) -> syn::Ident {
3157    syn::Ident::new(&format!("{field_ident}_col"), field_ident.span())
3158}
3159
3160fn column_module_ident(struct_name: &syn::Ident) -> syn::Ident {
3161    syn::Ident::new(
3162        &format!("__rustango_cols_{struct_name}"),
3163        struct_name.span(),
3164    )
3165}
3166
3167fn from_row_impl_tokens(struct_name: &syn::Ident, from_row_inits: &[TokenStream2]) -> TokenStream2 {
3168    // The Postgres impl is always emitted — every rustango build pulls in
3169    // sqlx-postgres via the default `postgres` feature. The MySQL impl is
3170    // routed through `::rustango::__impl_my_from_row!`, a cfg-gated
3171    // macro_rules whose body collapses to nothing when rustango is built
3172    // without the `mysql` feature. No user-facing feature shim required.
3173    //
3174    // The macro_rules pattern expects `[ field: expr, … ]` — we need to
3175    // re-shape `from_row_inits` (each token is `field: row.try_get(...)`)
3176    // back into a comma-separated list inside square brackets. Since each
3177    // entry is already in `field: expr` shape, the existing tokens slot in.
3178    quote! {
3179        impl<'r> ::rustango::sql::sqlx::FromRow<'r, ::rustango::sql::sqlx::postgres::PgRow>
3180            for #struct_name
3181        {
3182            fn from_row(
3183                row: &'r ::rustango::sql::sqlx::postgres::PgRow,
3184            ) -> ::core::result::Result<Self, ::rustango::sql::sqlx::Error> {
3185                ::core::result::Result::Ok(Self {
3186                    #( #from_row_inits ),*
3187                })
3188            }
3189        }
3190
3191        ::rustango::__impl_my_from_row!(#struct_name, |row| {
3192            #( #from_row_inits ),*
3193        });
3194
3195        ::rustango::__impl_sqlite_from_row!(#struct_name, |row| {
3196            #( #from_row_inits ),*
3197        });
3198    }
3199}
3200
3201struct ContainerAttrs {
3202    table: Option<String>,
3203    display: Option<(String, proc_macro2::Span)>,
3204    /// Explicit Django-style app label from `#[rustango(app = "blog")]`.
3205    /// Recorded on the emitted `ModelSchema.app_label`. When unset,
3206    /// `ModelEntry::resolved_app_label()` infers from `module_path!()`
3207    /// at runtime — this attribute is the override for cases where
3208    /// the inference is wrong (e.g. a model that conceptually belongs
3209    /// to one app but is physically in another module).
3210    app: Option<String>,
3211    /// Django ModelAdmin-shape per-model knobs from
3212    /// `#[rustango(admin(...))]`. `None` when the user didn't write the
3213    /// attribute — the emitted `ModelSchema.admin` becomes `None` and
3214    /// admin code falls back to `AdminConfig::DEFAULT`.
3215    admin: Option<AdminAttrs>,
3216    /// Per-model audit configuration from `#[rustango(audit(...))]`.
3217    /// `None` when the model isn't audited — write paths emit no
3218    /// audit entries. When present, single-row writes capture
3219    /// before/after for the listed fields and bulk writes batch
3220    /// snapshots into one INSERT into `rustango_audit_log`.
3221    audit: Option<AuditAttrs>,
3222    /// `true` when `#[rustango(permissions)]` is present. Signals that
3223    /// `auto_create_permissions` should seed the four CRUD codenames for
3224    /// this model.
3225    permissions: bool,
3226    /// Many-to-many relations declared via
3227    /// `#[rustango(m2m(name = "tags", to = "app_tags", through = "post_tags",
3228    ///                 src = "post_id", dst = "tag_id"))]`.
3229    m2m: Vec<M2MAttr>,
3230    /// Composite indexes declared via
3231    /// `#[rustango(index("col1, col2"))]` or
3232    /// `#[rustango(index("col1, col2", unique, name = "my_idx"))]`.
3233    /// Single-column indexes from `#[rustango(index)]` on fields are
3234    /// accumulated here during field collection.
3235    indexes: Vec<IndexAttr>,
3236    /// Table-level CHECK constraints declared via
3237    /// `#[rustango(check(name = "…", expr = "…"))]`.
3238    checks: Vec<CheckAttr>,
3239    /// Composite (multi-column) FKs declared via
3240    /// `#[rustango(fk_composite(name = "…", to = "…", on = (…), from = (…)))]`.
3241    /// Sub-slice F.2 of the v0.15.0 ContentType plan.
3242    composite_fks: Vec<CompositeFkAttr>,
3243    /// Generic ("any model") FKs declared via
3244    /// `#[rustango(generic_fk(name = "…", ct_column = "…", pk_column = "…"))]`.
3245    /// Sub-slice F.4 of the v0.15.0 ContentType plan.
3246    generic_fks: Vec<GenericFkAttr>,
3247    /// Where this model lives in a tenancy deployment, declared via
3248    /// `#[rustango(scope = "registry")]` or `#[rustango(scope = "tenant")]`.
3249    /// Defaults to `"tenant"` when unset; `makemigrations` uses this
3250    /// to partition diff output between registry-scoped and
3251    /// tenant-scoped migration files.
3252    scope: Option<String>,
3253}
3254
3255/// Parsed form of one index declaration (field-level or container-level).
3256struct IndexAttr {
3257    /// Index name; auto-derived when `None` at parse time.
3258    name: Option<String>,
3259    /// Column names in the index.
3260    columns: Vec<String>,
3261    /// `true` for `CREATE UNIQUE INDEX`.
3262    unique: bool,
3263}
3264
3265/// Parsed form of one `#[rustango(check(name = "…", expr = "…"))]` declaration.
3266struct CheckAttr {
3267    name: String,
3268    expr: String,
3269}
3270
3271/// Parsed form of one `#[rustango(fk_composite(name = "audit_target",
3272/// to = "rustango_audit_log", on = ("entity_table", "entity_pk"),
3273/// from = ("table_name", "row_pk")))]` declaration. Sub-slice F.2 of
3274/// the v0.15.0 ContentType plan — multi-column foreign keys live on
3275/// the model, not the field.
3276struct CompositeFkAttr {
3277    /// Logical relation name (free-form Rust identifier).
3278    name: String,
3279    /// SQL table name of the target.
3280    to: String,
3281    /// Source-side column names, in declaration order.
3282    from: Vec<String>,
3283    /// Target-side column names, same length / order as `from`.
3284    on: Vec<String>,
3285}
3286
3287/// Parsed form of one `#[rustango(generic_fk(name = "target",
3288/// ct_column = "content_type_id", pk_column = "object_pk"))]`
3289/// declaration. Sub-slice F.4 of the v0.15.0 ContentType plan —
3290/// generic ("any model") FKs live on the model, not the field.
3291struct GenericFkAttr {
3292    /// Logical relation name (free-form Rust identifier).
3293    name: String,
3294    /// Source-side column carrying the `content_type_id` value.
3295    ct_column: String,
3296    /// Source-side column carrying the target row's primary key.
3297    pk_column: String,
3298}
3299
3300/// Parsed form of one `#[rustango(m2m(...))]` declaration.
3301struct M2MAttr {
3302    /// Accessor suffix: `tags` → generates `tags_m2m()`.
3303    name: String,
3304    /// Target table (e.g. `"app_tags"`).
3305    to: String,
3306    /// Junction table (e.g. `"post_tags"`).
3307    through: String,
3308    /// Source FK column in the junction table (e.g. `"post_id"`).
3309    src: String,
3310    /// Destination FK column in the junction table (e.g. `"tag_id"`).
3311    dst: String,
3312}
3313
3314/// Parsed shape of `#[rustango(audit(track = "name, body", source =
3315/// "user"))]`. `track` is a comma-separated list of field names whose
3316/// before/after values land in the JSONB `changes` column. `source`
3317/// is informational only — it pins a default source when the model
3318/// is written outside any `audit::with_source(...)` scope (rare).
3319#[derive(Default)]
3320struct AuditAttrs {
3321    /// Field names to capture in the `changes` JSONB. Validated
3322    /// against declared scalar fields at compile time. Empty means
3323    /// "track every scalar field" — Django's audit-everything default.
3324    track: Option<(Vec<String>, proc_macro2::Span)>,
3325}
3326
3327/// Parsed shape of `#[rustango(admin(list_display = "…", search_fields =
3328/// "…", list_per_page = N, ordering = "…"))]`. Field-name lists are
3329/// comma-separated strings; we validate each ident against the model's
3330/// declared fields at compile time.
3331#[derive(Default)]
3332struct AdminAttrs {
3333    list_display: Option<(Vec<String>, proc_macro2::Span)>,
3334    search_fields: Option<(Vec<String>, proc_macro2::Span)>,
3335    list_per_page: Option<usize>,
3336    ordering: Option<(Vec<(String, bool)>, proc_macro2::Span)>,
3337    readonly_fields: Option<(Vec<String>, proc_macro2::Span)>,
3338    list_filter: Option<(Vec<String>, proc_macro2::Span)>,
3339    /// Bulk action names. No field-validation against model fields —
3340    /// these are action handlers, not column references.
3341    actions: Option<(Vec<String>, proc_macro2::Span)>,
3342    /// Form fieldsets — `Vec<(title, [field_names])>`. Pipe-separated
3343    /// sections, comma-separated fields per section, optional
3344    /// `Title:` prefix. Empty title omits the `<legend>`.
3345    fieldsets: Option<(Vec<(String, Vec<String>)>, proc_macro2::Span)>,
3346}
3347
3348fn parse_container_attrs(input: &DeriveInput) -> syn::Result<ContainerAttrs> {
3349    let mut out = ContainerAttrs {
3350        table: None,
3351        display: None,
3352        app: None,
3353        admin: None,
3354        audit: None,
3355        permissions: false,
3356        m2m: Vec::new(),
3357        indexes: Vec::new(),
3358        checks: Vec::new(),
3359        composite_fks: Vec::new(),
3360        generic_fks: Vec::new(),
3361        scope: None,
3362    };
3363    for attr in &input.attrs {
3364        if !attr.path().is_ident("rustango") {
3365            continue;
3366        }
3367        attr.parse_nested_meta(|meta| {
3368            if meta.path.is_ident("table") {
3369                let s: LitStr = meta.value()?.parse()?;
3370                out.table = Some(s.value());
3371                return Ok(());
3372            }
3373            if meta.path.is_ident("display") {
3374                let s: LitStr = meta.value()?.parse()?;
3375                out.display = Some((s.value(), s.span()));
3376                return Ok(());
3377            }
3378            if meta.path.is_ident("app") {
3379                let s: LitStr = meta.value()?.parse()?;
3380                out.app = Some(s.value());
3381                return Ok(());
3382            }
3383            if meta.path.is_ident("scope") {
3384                let s: LitStr = meta.value()?.parse()?;
3385                let val = s.value();
3386                if !matches!(val.to_ascii_lowercase().as_str(), "registry" | "tenant") {
3387                    return Err(meta.error(format!(
3388                        "`scope` must be \"registry\" or \"tenant\", got {val:?}"
3389                    )));
3390                }
3391                out.scope = Some(val);
3392                return Ok(());
3393            }
3394            if meta.path.is_ident("admin") {
3395                let mut admin = AdminAttrs::default();
3396                meta.parse_nested_meta(|inner| {
3397                    if inner.path.is_ident("list_display") {
3398                        let s: LitStr = inner.value()?.parse()?;
3399                        admin.list_display =
3400                            Some((split_field_list(&s.value()), s.span()));
3401                        return Ok(());
3402                    }
3403                    if inner.path.is_ident("search_fields") {
3404                        let s: LitStr = inner.value()?.parse()?;
3405                        admin.search_fields =
3406                            Some((split_field_list(&s.value()), s.span()));
3407                        return Ok(());
3408                    }
3409                    if inner.path.is_ident("readonly_fields") {
3410                        let s: LitStr = inner.value()?.parse()?;
3411                        admin.readonly_fields =
3412                            Some((split_field_list(&s.value()), s.span()));
3413                        return Ok(());
3414                    }
3415                    if inner.path.is_ident("list_per_page") {
3416                        let lit: syn::LitInt = inner.value()?.parse()?;
3417                        admin.list_per_page = Some(lit.base10_parse::<usize>()?);
3418                        return Ok(());
3419                    }
3420                    if inner.path.is_ident("ordering") {
3421                        let s: LitStr = inner.value()?.parse()?;
3422                        admin.ordering = Some((
3423                            parse_ordering_list(&s.value()),
3424                            s.span(),
3425                        ));
3426                        return Ok(());
3427                    }
3428                    if inner.path.is_ident("list_filter") {
3429                        let s: LitStr = inner.value()?.parse()?;
3430                        admin.list_filter =
3431                            Some((split_field_list(&s.value()), s.span()));
3432                        return Ok(());
3433                    }
3434                    if inner.path.is_ident("actions") {
3435                        let s: LitStr = inner.value()?.parse()?;
3436                        admin.actions =
3437                            Some((split_field_list(&s.value()), s.span()));
3438                        return Ok(());
3439                    }
3440                    if inner.path.is_ident("fieldsets") {
3441                        let s: LitStr = inner.value()?.parse()?;
3442                        admin.fieldsets =
3443                            Some((parse_fieldset_list(&s.value()), s.span()));
3444                        return Ok(());
3445                    }
3446                    Err(inner.error(
3447                        "unknown admin attribute (supported: \
3448                         `list_display`, `search_fields`, `readonly_fields`, \
3449                         `list_filter`, `list_per_page`, `ordering`, `actions`, \
3450                         `fieldsets`)",
3451                    ))
3452                })?;
3453                out.admin = Some(admin);
3454                return Ok(());
3455            }
3456            if meta.path.is_ident("audit") {
3457                let mut audit = AuditAttrs::default();
3458                meta.parse_nested_meta(|inner| {
3459                    if inner.path.is_ident("track") {
3460                        let s: LitStr = inner.value()?.parse()?;
3461                        audit.track =
3462                            Some((split_field_list(&s.value()), s.span()));
3463                        return Ok(());
3464                    }
3465                    Err(inner.error(
3466                        "unknown audit attribute (supported: `track`)",
3467                    ))
3468                })?;
3469                out.audit = Some(audit);
3470                return Ok(());
3471            }
3472            if meta.path.is_ident("permissions") {
3473                out.permissions = true;
3474                return Ok(());
3475            }
3476            if meta.path.is_ident("unique_together") {
3477                // Django-shape composite UNIQUE index. Two syntaxes:
3478                //
3479                //   #[rustango(unique_together = "org_id, user_id")]                       — auto-derived name
3480                //   #[rustango(unique_together(columns = "org_id, user_id", name = "x"))]  — explicit name
3481                //
3482                // Both produce `CREATE UNIQUE INDEX <name> ON <table>
3483                // (col1, col2)`, where <name> defaults to
3484                // `<table>_<col1>_<col2>_uq` when not supplied.
3485                let (columns, name) = parse_together_attr(&meta, "unique_together")?;
3486                out.indexes.push(IndexAttr { name, columns, unique: true });
3487                return Ok(());
3488            }
3489            if meta.path.is_ident("index_together") {
3490                // Django-shape composite (non-unique) index. Two syntaxes
3491                // mirroring `unique_together`.
3492                //
3493                //   #[rustango(index_together = "created_at, status")]
3494                //   #[rustango(index_together(columns = "created_at, status", name = "x"))]
3495                let (columns, name) = parse_together_attr(&meta, "index_together")?;
3496                out.indexes.push(IndexAttr { name, columns, unique: false });
3497                return Ok(());
3498            }
3499            if meta.path.is_ident("index") {
3500                // Container-level composite index — legacy entry that
3501                // was advertised with a trailing `, unique, name = ...`
3502                // flag block which doesn't actually compose under
3503                // `parse_nested_meta`. Prefer `unique_together` /
3504                // `index_together` (above) for new code. The bare
3505                // `index = "..."` form is kept for back-compat: it
3506                // emits a non-unique composite index.
3507                let cols_lit: LitStr = meta.value()?.parse()?;
3508                let columns = split_field_list(&cols_lit.value());
3509                out.indexes.push(IndexAttr { name: None, columns, unique: false });
3510                return Ok(());
3511            }
3512            if meta.path.is_ident("check") {
3513                // #[rustango(check(name = "…", expr = "…"))]
3514                let mut name: Option<String> = None;
3515                let mut expr: Option<String> = None;
3516                meta.parse_nested_meta(|inner| {
3517                    if inner.path.is_ident("name") {
3518                        let s: LitStr = inner.value()?.parse()?;
3519                        name = Some(s.value());
3520                        return Ok(());
3521                    }
3522                    if inner.path.is_ident("expr") {
3523                        let s: LitStr = inner.value()?.parse()?;
3524                        expr = Some(s.value());
3525                        return Ok(());
3526                    }
3527                    Err(inner.error("unknown check attribute (supported: `name`, `expr`)"))
3528                })?;
3529                let name = name.ok_or_else(|| meta.error("check requires `name = \"...\"`"))?;
3530                let expr = expr.ok_or_else(|| meta.error("check requires `expr = \"...\"`"))?;
3531                out.checks.push(CheckAttr { name, expr });
3532                return Ok(());
3533            }
3534            if meta.path.is_ident("generic_fk") {
3535                let mut gfk = GenericFkAttr {
3536                    name: String::new(),
3537                    ct_column: String::new(),
3538                    pk_column: String::new(),
3539                };
3540                meta.parse_nested_meta(|inner| {
3541                    if inner.path.is_ident("name") {
3542                        let s: LitStr = inner.value()?.parse()?;
3543                        gfk.name = s.value();
3544                        return Ok(());
3545                    }
3546                    if inner.path.is_ident("ct_column") {
3547                        let s: LitStr = inner.value()?.parse()?;
3548                        gfk.ct_column = s.value();
3549                        return Ok(());
3550                    }
3551                    if inner.path.is_ident("pk_column") {
3552                        let s: LitStr = inner.value()?.parse()?;
3553                        gfk.pk_column = s.value();
3554                        return Ok(());
3555                    }
3556                    Err(inner.error(
3557                        "unknown generic_fk attribute (supported: `name`, `ct_column`, `pk_column`)",
3558                    ))
3559                })?;
3560                if gfk.name.is_empty() {
3561                    return Err(meta.error("generic_fk requires `name = \"...\"`"));
3562                }
3563                if gfk.ct_column.is_empty() {
3564                    return Err(meta.error("generic_fk requires `ct_column = \"...\"`"));
3565                }
3566                if gfk.pk_column.is_empty() {
3567                    return Err(meta.error("generic_fk requires `pk_column = \"...\"`"));
3568                }
3569                out.generic_fks.push(gfk);
3570                return Ok(());
3571            }
3572            if meta.path.is_ident("fk_composite") {
3573                let mut fk = CompositeFkAttr {
3574                    name: String::new(),
3575                    to: String::new(),
3576                    from: Vec::new(),
3577                    on: Vec::new(),
3578                };
3579                meta.parse_nested_meta(|inner| {
3580                    if inner.path.is_ident("name") {
3581                        let s: LitStr = inner.value()?.parse()?;
3582                        fk.name = s.value();
3583                        return Ok(());
3584                    }
3585                    if inner.path.is_ident("to") {
3586                        let s: LitStr = inner.value()?.parse()?;
3587                        fk.to = s.value();
3588                        return Ok(());
3589                    }
3590                    // `on = ("col1", "col2", ...)` — parse a parenthesised
3591                    // comma-list of string literals.
3592                    if inner.path.is_ident("on") || inner.path.is_ident("from") {
3593                        let value = inner.value()?;
3594                        let content;
3595                        syn::parenthesized!(content in value);
3596                        let lits: syn::punctuated::Punctuated<syn::LitStr, syn::Token![,]> =
3597                            content.parse_terminated(
3598                                |p| p.parse::<syn::LitStr>(),
3599                                syn::Token![,],
3600                            )?;
3601                        let cols: Vec<String> = lits.iter().map(syn::LitStr::value).collect();
3602                        if inner.path.is_ident("on") {
3603                            fk.on = cols;
3604                        } else {
3605                            fk.from = cols;
3606                        }
3607                        return Ok(());
3608                    }
3609                    Err(inner.error(
3610                        "unknown fk_composite attribute (supported: `name`, `to`, `on`, `from`)",
3611                    ))
3612                })?;
3613                if fk.name.is_empty() {
3614                    return Err(meta.error("fk_composite requires `name = \"...\"`"));
3615                }
3616                if fk.to.is_empty() {
3617                    return Err(meta.error("fk_composite requires `to = \"...\"`"));
3618                }
3619                if fk.from.is_empty() || fk.on.is_empty() {
3620                    return Err(meta.error(
3621                        "fk_composite requires non-empty `from = (...)` and `on = (...)` tuples",
3622                    ));
3623                }
3624                if fk.from.len() != fk.on.len() {
3625                    return Err(meta.error(format!(
3626                        "fk_composite `from` ({} cols) and `on` ({} cols) must be the same length",
3627                        fk.from.len(),
3628                        fk.on.len(),
3629                    )));
3630                }
3631                out.composite_fks.push(fk);
3632                return Ok(());
3633            }
3634            if meta.path.is_ident("m2m") {
3635                let mut m2m = M2MAttr {
3636                    name: String::new(),
3637                    to: String::new(),
3638                    through: String::new(),
3639                    src: String::new(),
3640                    dst: String::new(),
3641                };
3642                meta.parse_nested_meta(|inner| {
3643                    if inner.path.is_ident("name") {
3644                        let s: LitStr = inner.value()?.parse()?;
3645                        m2m.name = s.value();
3646                        return Ok(());
3647                    }
3648                    if inner.path.is_ident("to") {
3649                        let s: LitStr = inner.value()?.parse()?;
3650                        m2m.to = s.value();
3651                        return Ok(());
3652                    }
3653                    if inner.path.is_ident("through") {
3654                        let s: LitStr = inner.value()?.parse()?;
3655                        m2m.through = s.value();
3656                        return Ok(());
3657                    }
3658                    if inner.path.is_ident("src") {
3659                        let s: LitStr = inner.value()?.parse()?;
3660                        m2m.src = s.value();
3661                        return Ok(());
3662                    }
3663                    if inner.path.is_ident("dst") {
3664                        let s: LitStr = inner.value()?.parse()?;
3665                        m2m.dst = s.value();
3666                        return Ok(());
3667                    }
3668                    Err(inner.error("unknown m2m attribute (supported: `name`, `to`, `through`, `src`, `dst`)"))
3669                })?;
3670                if m2m.name.is_empty() {
3671                    return Err(meta.error("m2m requires `name = \"...\"`"));
3672                }
3673                if m2m.to.is_empty() {
3674                    return Err(meta.error("m2m requires `to = \"...\"`"));
3675                }
3676                if m2m.through.is_empty() {
3677                    return Err(meta.error("m2m requires `through = \"...\"`"));
3678                }
3679                if m2m.src.is_empty() {
3680                    return Err(meta.error("m2m requires `src = \"...\"`"));
3681                }
3682                if m2m.dst.is_empty() {
3683                    return Err(meta.error("m2m requires `dst = \"...\"`"));
3684                }
3685                out.m2m.push(m2m);
3686                return Ok(());
3687            }
3688            Err(meta.error("unknown rustango container attribute"))
3689        })?;
3690    }
3691    Ok(out)
3692}
3693
3694/// Split a comma-separated field-name list (e.g. `"name, office"`) into
3695/// owned field names, trimming whitespace and skipping empty entries.
3696/// Field-name validation against the model is done by the caller.
3697fn split_field_list(raw: &str) -> Vec<String> {
3698    raw.split(',')
3699        .map(str::trim)
3700        .filter(|s| !s.is_empty())
3701        .map(str::to_owned)
3702        .collect()
3703}
3704
3705/// Shared parser for `unique_together` and `index_together` container
3706/// attrs. Accepts both shapes:
3707///
3708///   * `attr = "col1, col2"`              — auto-derived index name.
3709///   * `attr(columns = "col1, col2", name = "...")` — explicit name.
3710///
3711/// Returns `(columns, name)`.
3712fn parse_together_attr(
3713    meta: &syn::meta::ParseNestedMeta<'_>,
3714    attr: &str,
3715) -> syn::Result<(Vec<String>, Option<String>)> {
3716    // Disambiguate by whether the next token is `=` (key-value) or
3717    // `(` (parenthesized).
3718    if meta.input.peek(syn::Token![=]) {
3719        let cols_lit: LitStr = meta.value()?.parse()?;
3720        let columns = split_field_list(&cols_lit.value());
3721        check_together_columns(meta, attr, &columns)?;
3722        return Ok((columns, None));
3723    }
3724    let mut columns: Option<Vec<String>> = None;
3725    let mut name: Option<String> = None;
3726    meta.parse_nested_meta(|inner| {
3727        if inner.path.is_ident("columns") {
3728            let s: LitStr = inner.value()?.parse()?;
3729            columns = Some(split_field_list(&s.value()));
3730            return Ok(());
3731        }
3732        if inner.path.is_ident("name") {
3733            let s: LitStr = inner.value()?.parse()?;
3734            name = Some(s.value());
3735            return Ok(());
3736        }
3737        Err(inner.error("unknown sub-attribute (supported: `columns`, `name`)"))
3738    })?;
3739    let columns = columns.ok_or_else(|| {
3740        meta.error(format!(
3741            "{attr}(...) requires a `columns = \"col1, col2\"` argument",
3742        ))
3743    })?;
3744    check_together_columns(meta, attr, &columns)?;
3745    Ok((columns, name))
3746}
3747
3748fn check_together_columns(
3749    meta: &syn::meta::ParseNestedMeta<'_>,
3750    attr: &str,
3751    columns: &[String],
3752) -> syn::Result<()> {
3753    if columns.len() < 2 {
3754        let single = if attr == "unique_together" {
3755            "#[rustango(unique)] on the field"
3756        } else {
3757            "#[rustango(index)] on the field"
3758        };
3759        return Err(meta.error(format!(
3760            "{attr} expects two or more columns; for a single-column equivalent use {single}",
3761        )));
3762    }
3763    Ok(())
3764}
3765
3766/// Parse the fieldsets DSL: pipe-separated sections, optional
3767/// `"Title:"` prefix on each, comma-separated field names after.
3768/// Examples:
3769/// * `"name, office"` → one untitled section with two fields
3770/// * `"Identity: name, office | Metadata: created_at"` → two titled
3771///   sections
3772///
3773/// Returns `(title, fields)` pairs. Title is `""` when no prefix.
3774fn parse_fieldset_list(raw: &str) -> Vec<(String, Vec<String>)> {
3775    raw.split('|')
3776        .map(str::trim)
3777        .filter(|s| !s.is_empty())
3778        .map(|section| {
3779            // Split off an optional `Title:` prefix (first colon).
3780            let (title, rest) = match section.split_once(':') {
3781                Some((title, rest)) if !title.contains(',') => (title.trim().to_owned(), rest),
3782                _ => (String::new(), section),
3783            };
3784            let fields = split_field_list(rest);
3785            (title, fields)
3786        })
3787        .collect()
3788}
3789
3790/// Parse Django-shape ordering — `"name"` is ASC, `"-name"` is DESC.
3791/// Returns `(field_name, desc)` pairs in the same order as the input.
3792fn parse_ordering_list(raw: &str) -> Vec<(String, bool)> {
3793    raw.split(',')
3794        .map(str::trim)
3795        .filter(|s| !s.is_empty())
3796        .map(|spec| {
3797            spec.strip_prefix('-')
3798                .map_or((spec.to_owned(), false), |rest| {
3799                    (rest.trim().to_owned(), true)
3800                })
3801        })
3802        .collect()
3803}
3804
3805struct FieldAttrs {
3806    column: Option<String>,
3807    primary_key: bool,
3808    fk: Option<String>,
3809    o2o: Option<String>,
3810    on: Option<String>,
3811    max_length: Option<u32>,
3812    min: Option<i64>,
3813    max: Option<i64>,
3814    default: Option<String>,
3815    /// `#[rustango(auto_uuid)]` — UUID PK generated by Postgres
3816    /// `gen_random_uuid()`. Implies `auto + primary_key + default =
3817    /// "gen_random_uuid()"`. The Rust field type must be
3818    /// `uuid::Uuid` (or `Auto<Uuid>`); the column is excluded from
3819    /// INSERTs so the DB DEFAULT fires.
3820    auto_uuid: bool,
3821    /// `#[rustango(auto_now_add)]` — `created_at`-shape column.
3822    /// Server-set on insert, immutable from app code afterwards.
3823    /// Implies `auto + default = "now()"`. Field type must be
3824    /// `DateTime<Utc>`.
3825    auto_now_add: bool,
3826    /// `#[rustango(auto_now)]` — `updated_at`-shape column. Set on
3827    /// every insert AND every update. Implies `auto + default =
3828    /// "now()"`; the macro additionally rewrites `update_on` /
3829    /// `save_on` to bind `chrono::Utc::now()` instead of the user's
3830    /// field value.
3831    auto_now: bool,
3832    /// `#[rustango(soft_delete)]` — `deleted_at`-shape column. Type
3833    /// must be `Option<DateTime<Utc>>`. Triggers macro emission of
3834    /// `soft_delete_on(executor)` and `restore_on(executor)`
3835    /// methods on the model.
3836    soft_delete: bool,
3837    /// `#[rustango(unique)]` — adds a `UNIQUE` constraint inline on
3838    /// the column in the generated DDL.
3839    unique: bool,
3840    /// `#[rustango(index)]` or `#[rustango(index(name = "…", unique))]` —
3841    /// generates a `CREATE INDEX` for this column. `unique` here means
3842    /// `CREATE UNIQUE INDEX` (distinct from the `unique` constraint above).
3843    index: bool,
3844    index_unique: bool,
3845    index_name: Option<String>,
3846    /// `#[rustango(generated_as = "EXPR")]` — emit `GENERATED ALWAYS
3847    /// AS (EXPR) STORED` in the column DDL. Read-only from app code:
3848    /// the macro skips this column from every INSERT and UPDATE
3849    /// path, so the database always recomputes the value from
3850    /// `EXPR`. Backlog item #35.
3851    generated_as: Option<String>,
3852}
3853
3854fn parse_field_attrs(field: &syn::Field) -> syn::Result<FieldAttrs> {
3855    let mut out = FieldAttrs {
3856        column: None,
3857        primary_key: false,
3858        fk: None,
3859        o2o: None,
3860        on: None,
3861        max_length: None,
3862        min: None,
3863        max: None,
3864        default: None,
3865        auto_uuid: false,
3866        auto_now_add: false,
3867        auto_now: false,
3868        soft_delete: false,
3869        unique: false,
3870        index: false,
3871        index_unique: false,
3872        index_name: None,
3873        generated_as: None,
3874    };
3875    for attr in &field.attrs {
3876        if !attr.path().is_ident("rustango") {
3877            continue;
3878        }
3879        attr.parse_nested_meta(|meta| {
3880            if meta.path.is_ident("column") {
3881                let s: LitStr = meta.value()?.parse()?;
3882                out.column = Some(s.value());
3883                return Ok(());
3884            }
3885            if meta.path.is_ident("primary_key") {
3886                out.primary_key = true;
3887                return Ok(());
3888            }
3889            if meta.path.is_ident("fk") {
3890                let s: LitStr = meta.value()?.parse()?;
3891                out.fk = Some(s.value());
3892                return Ok(());
3893            }
3894            if meta.path.is_ident("o2o") {
3895                let s: LitStr = meta.value()?.parse()?;
3896                out.o2o = Some(s.value());
3897                return Ok(());
3898            }
3899            if meta.path.is_ident("on") {
3900                let s: LitStr = meta.value()?.parse()?;
3901                out.on = Some(s.value());
3902                return Ok(());
3903            }
3904            if meta.path.is_ident("max_length") {
3905                let lit: syn::LitInt = meta.value()?.parse()?;
3906                out.max_length = Some(lit.base10_parse::<u32>()?);
3907                return Ok(());
3908            }
3909            if meta.path.is_ident("min") {
3910                out.min = Some(parse_signed_i64(&meta)?);
3911                return Ok(());
3912            }
3913            if meta.path.is_ident("max") {
3914                out.max = Some(parse_signed_i64(&meta)?);
3915                return Ok(());
3916            }
3917            if meta.path.is_ident("default") {
3918                let s: LitStr = meta.value()?.parse()?;
3919                out.default = Some(s.value());
3920                return Ok(());
3921            }
3922            if meta.path.is_ident("generated_as") {
3923                let s: LitStr = meta.value()?.parse()?;
3924                out.generated_as = Some(s.value());
3925                return Ok(());
3926            }
3927            if meta.path.is_ident("auto_uuid") {
3928                out.auto_uuid = true;
3929                // Implied: PK + auto + DEFAULT gen_random_uuid().
3930                // Each is also explicitly settable; the explicit
3931                // value wins if conflicting.
3932                out.primary_key = true;
3933                if out.default.is_none() {
3934                    out.default = Some("gen_random_uuid()".into());
3935                }
3936                return Ok(());
3937            }
3938            if meta.path.is_ident("auto_now_add") {
3939                out.auto_now_add = true;
3940                if out.default.is_none() {
3941                    out.default = Some("now()".into());
3942                }
3943                return Ok(());
3944            }
3945            if meta.path.is_ident("auto_now") {
3946                out.auto_now = true;
3947                if out.default.is_none() {
3948                    out.default = Some("now()".into());
3949                }
3950                return Ok(());
3951            }
3952            if meta.path.is_ident("soft_delete") {
3953                out.soft_delete = true;
3954                return Ok(());
3955            }
3956            if meta.path.is_ident("unique") {
3957                out.unique = true;
3958                return Ok(());
3959            }
3960            if meta.path.is_ident("index") {
3961                out.index = true;
3962                // Optional sub-attrs: #[rustango(index(unique, name = "…"))]
3963                if meta.input.peek(syn::token::Paren) {
3964                    meta.parse_nested_meta(|inner| {
3965                        if inner.path.is_ident("unique") {
3966                            out.index_unique = true;
3967                            return Ok(());
3968                        }
3969                        if inner.path.is_ident("name") {
3970                            let s: LitStr = inner.value()?.parse()?;
3971                            out.index_name = Some(s.value());
3972                            return Ok(());
3973                        }
3974                        Err(inner
3975                            .error("unknown index sub-attribute (supported: `unique`, `name`)"))
3976                    })?;
3977                }
3978                return Ok(());
3979            }
3980            Err(meta.error("unknown rustango field attribute"))
3981        })?;
3982    }
3983    Ok(out)
3984}
3985
3986/// Parse a signed integer literal, accepting optional leading `-`.
3987fn parse_signed_i64(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<i64> {
3988    let expr: syn::Expr = meta.value()?.parse()?;
3989    match expr {
3990        syn::Expr::Lit(syn::ExprLit {
3991            lit: syn::Lit::Int(lit),
3992            ..
3993        }) => lit.base10_parse::<i64>(),
3994        syn::Expr::Unary(syn::ExprUnary {
3995            op: syn::UnOp::Neg(_),
3996            expr,
3997            ..
3998        }) => {
3999            if let syn::Expr::Lit(syn::ExprLit {
4000                lit: syn::Lit::Int(lit),
4001                ..
4002            }) = *expr
4003            {
4004                let v: i64 = lit.base10_parse()?;
4005                Ok(-v)
4006            } else {
4007                Err(syn::Error::new_spanned(expr, "expected integer literal"))
4008            }
4009        }
4010        other => Err(syn::Error::new_spanned(
4011            other,
4012            "expected integer literal (signed)",
4013        )),
4014    }
4015}
4016
4017struct FieldInfo<'a> {
4018    ident: &'a syn::Ident,
4019    column: String,
4020    primary_key: bool,
4021    /// `true` when the Rust type was `Auto<T>` — the INSERT path will
4022    /// skip this column when `Auto::Unset` and emit it under
4023    /// `RETURNING` so Postgres' sequence DEFAULT fills in the value.
4024    auto: bool,
4025    /// The original field type, e.g. `i64` or `Option<String>`. Emitted as
4026    /// the `Column::Value` associated type for typed-column tokens.
4027    value_ty: &'a Type,
4028    /// `FieldType` variant tokens (`::rustango::core::FieldType::I64`).
4029    field_type_tokens: TokenStream2,
4030    schema: TokenStream2,
4031    from_row_init: TokenStream2,
4032    /// Variant of [`Self::from_row_init`] that reads the column via
4033    /// `format!("{prefix}__{col}")` so a model can be decoded out of
4034    /// the aliased columns of a JOINed row. Drives slice 9.0d's
4035    /// `Self::__rustango_from_aliased_row(row, prefix)` per-Model
4036    /// helper that `select_related` calls when stitching loaded FKs.
4037    from_aliased_row_init: TokenStream2,
4038    /// Inner type from a `ForeignKey<T, K>` field, if any. The reverse-
4039    /// relation helper emit (`Author::<child>_set`) needs to know `T`
4040    /// to point the generated method at the right child model.
4041    fk_inner: Option<Type>,
4042    /// `K`'s scalar kind for a `ForeignKey<T, K>` field. Mirrors
4043    /// `kind` (since ForeignKey detection sets `kind` to K's
4044    /// underlying type) but stored separately for clarity at the
4045    /// `FkRelation` construction site, which only sees the FK's
4046    /// surface fields.
4047    fk_pk_kind: DetectedKind,
4048    /// `true` when the field is `Option<ForeignKey<T, K>>` rather than
4049    /// the bare `ForeignKey<T, K>`. Routes the load_related and
4050    /// fk_pk_access emitters to wrap assignments / accessors in
4051    /// `Some(...)` / `as_ref().map(...)` respectively, so a nullable
4052    /// FK column compiles end-to-end. The DDL writer reads this off
4053    /// the field schema (`nullable` flag); the macro just needs to
4054    /// keep the Rust-side codegen consistent.
4055    nullable: bool,
4056    /// `true` when this column was marked `#[rustango(auto_now)]` —
4057    /// `update_on` / `save_on` bind `chrono::Utc::now()` for this
4058    /// column instead of the user-supplied value, so `updated_at`
4059    /// always reflects the latest write without the caller having
4060    /// to remember to set it.
4061    auto_now: bool,
4062    /// `true` when this column was marked `#[rustango(auto_now_add)]`
4063    /// — the column is server-set on INSERT (DB DEFAULT) and
4064    /// **immutable** afterwards. `update_on` / `save_on` skip the
4065    /// column entirely so a stale `created_at` value in memory never
4066    /// rewrites the persisted timestamp.
4067    auto_now_add: bool,
4068    /// `true` when this column was marked `#[rustango(soft_delete)]`.
4069    /// Triggers emission of `soft_delete_on(executor)` and
4070    /// `restore_on(executor)` on the model's inherent impl. There is
4071    /// at most one such column per model — emission asserts this.
4072    soft_delete: bool,
4073    /// `Some` when this column was marked
4074    /// `#[rustango(generated_as = "EXPR")]`. The macro skips it from
4075    /// every INSERT and UPDATE path; the database recomputes the
4076    /// value from `EXPR`. Backlog item #35.
4077    generated_as: Option<String>,
4078}
4079
4080fn process_field<'a>(field: &'a syn::Field, table: &str) -> syn::Result<FieldInfo<'a>> {
4081    let attrs = parse_field_attrs(field)?;
4082    let ident = field
4083        .ident
4084        .as_ref()
4085        .ok_or_else(|| syn::Error::new(field.span(), "tuple structs are not supported"))?;
4086    let name = ident.to_string();
4087    let column = attrs.column.clone().unwrap_or_else(|| name.clone());
4088    let primary_key = attrs.primary_key;
4089    let DetectedType {
4090        kind,
4091        nullable,
4092        auto: detected_auto,
4093        fk_inner,
4094    } = detect_type(&field.ty)?;
4095    check_bound_compatibility(field, &attrs, kind)?;
4096    let auto = detected_auto;
4097    // Mixin attributes piggyback on the existing `Auto<T>` skip-on-
4098    // INSERT path: the user must wrap the field in `Auto<T>`, which
4099    // marks the column as DB-default-supplied. The mixin attrs then
4100    // layer in the SQL default (`now()` / `gen_random_uuid()`) and,
4101    // for `auto_now`, force the value on UPDATE too.
4102    if attrs.auto_uuid {
4103        if kind != DetectedKind::Uuid {
4104            return Err(syn::Error::new_spanned(
4105                field,
4106                "`#[rustango(auto_uuid)]` requires the field type to be \
4107                 `Auto<uuid::Uuid>`",
4108            ));
4109        }
4110        if !detected_auto {
4111            return Err(syn::Error::new_spanned(
4112                field,
4113                "`#[rustango(auto_uuid)]` requires the field type to be \
4114                 wrapped in `Auto<...>` so the macro skips the column on \
4115                 INSERT and the DB DEFAULT (`gen_random_uuid()`) fires",
4116            ));
4117        }
4118    }
4119    if attrs.auto_now_add || attrs.auto_now {
4120        if kind != DetectedKind::DateTime {
4121            return Err(syn::Error::new_spanned(
4122                field,
4123                "`#[rustango(auto_now_add)]` / `#[rustango(auto_now)]` require \
4124                 the field type to be `Auto<chrono::DateTime<chrono::Utc>>`",
4125            ));
4126        }
4127        if !detected_auto {
4128            return Err(syn::Error::new_spanned(
4129                field,
4130                "`#[rustango(auto_now_add)]` / `#[rustango(auto_now)]` require \
4131                 the field type to be wrapped in `Auto<...>` so the macro skips \
4132                 the column on INSERT and the DB DEFAULT (`now()`) fires",
4133            ));
4134        }
4135    }
4136    if attrs.soft_delete && !(kind == DetectedKind::DateTime && nullable) {
4137        return Err(syn::Error::new_spanned(
4138            field,
4139            "`#[rustango(soft_delete)]` requires the field type to be \
4140             `Option<chrono::DateTime<chrono::Utc>>`",
4141        ));
4142    }
4143    let is_mixin_auto = attrs.auto_uuid || attrs.auto_now_add || attrs.auto_now;
4144    if detected_auto && !primary_key && !is_mixin_auto {
4145        return Err(syn::Error::new_spanned(
4146            field,
4147            "`Auto<T>` is only valid on a `#[rustango(primary_key)]` field, \
4148             or on a field carrying one of `auto_uuid`, `auto_now_add`, or \
4149             `auto_now`",
4150        ));
4151    }
4152    if detected_auto && attrs.default.is_some() && !is_mixin_auto {
4153        return Err(syn::Error::new_spanned(
4154            field,
4155            "`#[rustango(default = \"…\")]` is redundant on an `Auto<T>` field — \
4156             SERIAL / BIGSERIAL already supplies a default sequence.",
4157        ));
4158    }
4159    if fk_inner.is_some() && primary_key {
4160        return Err(syn::Error::new_spanned(
4161            field,
4162            "`ForeignKey<T>` is not allowed on a primary-key field — \
4163             a row's PK is its own identity, not a reference to a parent.",
4164        ));
4165    }
4166    if attrs.generated_as.is_some() {
4167        if primary_key {
4168            return Err(syn::Error::new_spanned(
4169                field,
4170                "`#[rustango(generated_as = \"…\")]` is not allowed on a \
4171                 primary-key field — a PK must be writable so the row \
4172                 has an identity at INSERT time.",
4173            ));
4174        }
4175        if attrs.default.is_some() {
4176            return Err(syn::Error::new_spanned(
4177                field,
4178                "`#[rustango(generated_as = \"…\")]` cannot combine with \
4179                 `default = \"…\"` — Postgres rejects DEFAULT on \
4180                 generated columns. The expression IS the default.",
4181            ));
4182        }
4183        if detected_auto {
4184            return Err(syn::Error::new_spanned(
4185                field,
4186                "`#[rustango(generated_as = \"…\")]` is not allowed on \
4187                 an `Auto<T>` field — generated columns are computed \
4188                 by the DB, not server-assigned via a sequence. Use a \
4189                 plain Rust type (e.g. `f64`).",
4190            ));
4191        }
4192        if fk_inner.is_some() {
4193            return Err(syn::Error::new_spanned(
4194                field,
4195                "`#[rustango(generated_as = \"…\")]` is not allowed on a \
4196                 ForeignKey field.",
4197            ));
4198        }
4199    }
4200    let relation = relation_tokens(field, &attrs, fk_inner, table)?;
4201    let column_lit = column.as_str();
4202    let field_type_tokens = kind.variant_tokens();
4203    let max_length = optional_u32(attrs.max_length);
4204    let min = optional_i64(attrs.min);
4205    let max = optional_i64(attrs.max);
4206    let default = optional_str(attrs.default.as_deref());
4207
4208    let unique = attrs.unique;
4209    let generated_as = optional_str(attrs.generated_as.as_deref());
4210    let schema = quote! {
4211        ::rustango::core::FieldSchema {
4212            name: #name,
4213            column: #column_lit,
4214            ty: #field_type_tokens,
4215            nullable: #nullable,
4216            primary_key: #primary_key,
4217            relation: #relation,
4218            max_length: #max_length,
4219            min: #min,
4220            max: #max,
4221            default: #default,
4222            auto: #auto,
4223            unique: #unique,
4224            generated_as: #generated_as,
4225        }
4226    };
4227
4228    let from_row_init = quote! {
4229        #ident: ::rustango::sql::sqlx::Row::try_get(row, #column_lit)?
4230    };
4231    let from_aliased_row_init = quote! {
4232        #ident: ::rustango::sql::sqlx::Row::try_get(
4233            row,
4234            ::std::format!("{}__{}", prefix, #column_lit).as_str(),
4235        )?
4236    };
4237
4238    Ok(FieldInfo {
4239        ident,
4240        column,
4241        primary_key,
4242        auto,
4243        value_ty: &field.ty,
4244        field_type_tokens,
4245        schema,
4246        from_row_init,
4247        from_aliased_row_init,
4248        fk_inner: fk_inner.cloned(),
4249        fk_pk_kind: kind,
4250        nullable,
4251        auto_now: attrs.auto_now,
4252        auto_now_add: attrs.auto_now_add,
4253        soft_delete: attrs.soft_delete,
4254        generated_as: attrs.generated_as.clone(),
4255    })
4256}
4257
4258fn check_bound_compatibility(
4259    field: &syn::Field,
4260    attrs: &FieldAttrs,
4261    kind: DetectedKind,
4262) -> syn::Result<()> {
4263    if attrs.max_length.is_some() && kind != DetectedKind::String {
4264        return Err(syn::Error::new_spanned(
4265            field,
4266            "`max_length` is only valid on `String` fields (or `Option<String>`)",
4267        ));
4268    }
4269    if (attrs.min.is_some() || attrs.max.is_some()) && !kind.is_integer() {
4270        return Err(syn::Error::new_spanned(
4271            field,
4272            "`min` / `max` are only valid on integer fields (`i32`, `i64`, optionally Option-wrapped)",
4273        ));
4274    }
4275    if let (Some(min), Some(max)) = (attrs.min, attrs.max) {
4276        if min > max {
4277            return Err(syn::Error::new_spanned(
4278                field,
4279                format!("`min` ({min}) is greater than `max` ({max})"),
4280            ));
4281        }
4282    }
4283    Ok(())
4284}
4285
4286fn optional_u32(value: Option<u32>) -> TokenStream2 {
4287    if let Some(v) = value {
4288        quote!(::core::option::Option::Some(#v))
4289    } else {
4290        quote!(::core::option::Option::None)
4291    }
4292}
4293
4294fn optional_i64(value: Option<i64>) -> TokenStream2 {
4295    if let Some(v) = value {
4296        quote!(::core::option::Option::Some(#v))
4297    } else {
4298        quote!(::core::option::Option::None)
4299    }
4300}
4301
4302fn optional_str(value: Option<&str>) -> TokenStream2 {
4303    if let Some(v) = value {
4304        quote!(::core::option::Option::Some(#v))
4305    } else {
4306        quote!(::core::option::Option::None)
4307    }
4308}
4309
4310fn relation_tokens(
4311    field: &syn::Field,
4312    attrs: &FieldAttrs,
4313    fk_inner: Option<&syn::Type>,
4314    table: &str,
4315) -> syn::Result<TokenStream2> {
4316    if let Some(inner) = fk_inner {
4317        if attrs.fk.is_some() || attrs.o2o.is_some() {
4318            return Err(syn::Error::new_spanned(
4319                field,
4320                "`ForeignKey<T>` already declares the FK target via the type parameter — \
4321                 remove the `fk = \"…\"` / `o2o = \"…\"` attribute.",
4322            ));
4323        }
4324        let on = attrs.on.as_deref().unwrap_or("id");
4325        return Ok(quote! {
4326            ::core::option::Option::Some(::rustango::core::Relation::Fk {
4327                to: <#inner as ::rustango::core::Model>::SCHEMA.table,
4328                on: #on,
4329            })
4330        });
4331    }
4332    match (&attrs.fk, &attrs.o2o) {
4333        (Some(_), Some(_)) => Err(syn::Error::new_spanned(
4334            field,
4335            "`fk` and `o2o` are mutually exclusive",
4336        )),
4337        (Some(to), None) => {
4338            let on = attrs.on.as_deref().unwrap_or("id");
4339            // Self-FK sentinel — `#[rustango(fk = "self")]` resolves to
4340            // the model's own table. Threaded as a literal string at
4341            // macro-expansion time to sidestep the const-eval cycle
4342            // that `Self::SCHEMA.table` would create when referenced
4343            // inside Self::SCHEMA's own initializer.
4344            let resolved = if to == "self" { table } else { to };
4345            Ok(quote! {
4346                ::core::option::Option::Some(::rustango::core::Relation::Fk { to: #resolved, on: #on })
4347            })
4348        }
4349        (None, Some(to)) => {
4350            let on = attrs.on.as_deref().unwrap_or("id");
4351            let resolved = if to == "self" { table } else { to };
4352            Ok(quote! {
4353                ::core::option::Option::Some(::rustango::core::Relation::O2O { to: #resolved, on: #on })
4354            })
4355        }
4356        (None, None) => {
4357            if attrs.on.is_some() {
4358                return Err(syn::Error::new_spanned(
4359                    field,
4360                    "`on` requires `fk` or `o2o`",
4361                ));
4362            }
4363            Ok(quote!(::core::option::Option::None))
4364        }
4365    }
4366}
4367
4368/// Mirrors `rustango_core::FieldType`. Local copy so the macro can reason
4369/// about kinds without depending on `rustango-core` (which would require a
4370/// proc-macro/normal split it doesn't have today).
4371#[derive(Clone, Copy, PartialEq, Eq)]
4372enum DetectedKind {
4373    I16,
4374    I32,
4375    I64,
4376    F32,
4377    F64,
4378    Bool,
4379    String,
4380    DateTime,
4381    Date,
4382    Uuid,
4383    Json,
4384}
4385
4386impl DetectedKind {
4387    fn variant_tokens(self) -> TokenStream2 {
4388        match self {
4389            Self::I16 => quote!(::rustango::core::FieldType::I16),
4390            Self::I32 => quote!(::rustango::core::FieldType::I32),
4391            Self::I64 => quote!(::rustango::core::FieldType::I64),
4392            Self::F32 => quote!(::rustango::core::FieldType::F32),
4393            Self::F64 => quote!(::rustango::core::FieldType::F64),
4394            Self::Bool => quote!(::rustango::core::FieldType::Bool),
4395            Self::String => quote!(::rustango::core::FieldType::String),
4396            Self::DateTime => quote!(::rustango::core::FieldType::DateTime),
4397            Self::Date => quote!(::rustango::core::FieldType::Date),
4398            Self::Uuid => quote!(::rustango::core::FieldType::Uuid),
4399            Self::Json => quote!(::rustango::core::FieldType::Json),
4400        }
4401    }
4402
4403    fn is_integer(self) -> bool {
4404        matches!(self, Self::I16 | Self::I32 | Self::I64)
4405    }
4406
4407    /// `(SqlValue::<Variant>, default expr)` for emitting the
4408    /// `match SqlValue { … }` arm in `LoadRelated::__rustango_load_related`
4409    /// for a `ForeignKey<T, K>` FK whose K maps to `self`. The default
4410    /// fires only when the parent's `__rustango_pk_value` returns a
4411    /// different variant than expected, which is a compile-time bug —
4412    /// but we still need a value-typed fallback to keep the match
4413    /// total.
4414    fn sqlvalue_match_arm(self) -> (TokenStream2, TokenStream2) {
4415        match self {
4416            Self::I16 => (quote!(I16), quote!(0i16)),
4417            Self::I32 => (quote!(I32), quote!(0i32)),
4418            Self::I64 => (quote!(I64), quote!(0i64)),
4419            Self::F32 => (quote!(F32), quote!(0f32)),
4420            Self::F64 => (quote!(F64), quote!(0f64)),
4421            Self::Bool => (quote!(Bool), quote!(false)),
4422            Self::String => (quote!(String), quote!(::std::string::String::new())),
4423            Self::DateTime => (
4424                quote!(DateTime),
4425                quote!(<::chrono::DateTime<::chrono::Utc> as ::std::default::Default>::default()),
4426            ),
4427            Self::Date => (
4428                quote!(Date),
4429                quote!(<::chrono::NaiveDate as ::std::default::Default>::default()),
4430            ),
4431            Self::Uuid => (quote!(Uuid), quote!(::uuid::Uuid::nil())),
4432            Self::Json => (quote!(Json), quote!(::serde_json::Value::Null)),
4433        }
4434    }
4435}
4436
4437/// Result of walking a field's Rust type. `kind` is the underlying
4438/// `FieldType`; `nullable` is set by an outer `Option<T>`; `auto` is
4439/// set by an outer `Auto<T>` (server-assigned PK); `fk_inner` is
4440/// `Some(<T>)` when the field was `ForeignKey<T>` (or
4441/// `Option<ForeignKey<T>>`), letting the codegen reach `T::SCHEMA`.
4442#[derive(Clone, Copy)]
4443struct DetectedType<'a> {
4444    kind: DetectedKind,
4445    nullable: bool,
4446    auto: bool,
4447    fk_inner: Option<&'a syn::Type>,
4448}
4449
4450/// Extract the `T` from a `…::Auto<T>` field type. Returns `None` for
4451/// non-`Auto` types — the caller should already have routed Auto-only
4452/// codegen through this helper, so a `None` indicates a macro-internal
4453/// invariant break.
4454fn auto_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
4455    let Type::Path(TypePath { path, qself: None }) = ty else {
4456        return None;
4457    };
4458    let last = path.segments.last()?;
4459    if last.ident != "Auto" {
4460        return None;
4461    }
4462    let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
4463        return None;
4464    };
4465    args.args.iter().find_map(|a| match a {
4466        syn::GenericArgument::Type(t) => Some(t),
4467        _ => None,
4468    })
4469}
4470
4471fn detect_type(ty: &syn::Type) -> syn::Result<DetectedType<'_>> {
4472    let Type::Path(TypePath { path, qself: None }) = ty else {
4473        return Err(syn::Error::new_spanned(ty, "unsupported field type"));
4474    };
4475    let last = path
4476        .segments
4477        .last()
4478        .ok_or_else(|| syn::Error::new_spanned(ty, "empty type path"))?;
4479
4480    if last.ident == "Option" {
4481        let inner = generic_inner(ty, &last.arguments, "Option")?;
4482        let inner_det = detect_type(inner)?;
4483        if inner_det.nullable {
4484            return Err(syn::Error::new_spanned(
4485                ty,
4486                "nested Option is not supported",
4487            ));
4488        }
4489        if inner_det.auto {
4490            return Err(syn::Error::new_spanned(
4491                ty,
4492                "`Option<Auto<T>>` is not supported — Auto fields are server-assigned and cannot be NULL",
4493            ));
4494        }
4495        return Ok(DetectedType {
4496            nullable: true,
4497            ..inner_det
4498        });
4499    }
4500
4501    if last.ident == "Auto" {
4502        let inner = generic_inner(ty, &last.arguments, "Auto")?;
4503        let inner_det = detect_type(inner)?;
4504        if inner_det.auto {
4505            return Err(syn::Error::new_spanned(ty, "nested Auto is not supported"));
4506        }
4507        if inner_det.nullable {
4508            return Err(syn::Error::new_spanned(
4509                ty,
4510                "`Auto<Option<T>>` is not supported — Auto fields are server-assigned and cannot be NULL",
4511            ));
4512        }
4513        if inner_det.fk_inner.is_some() {
4514            return Err(syn::Error::new_spanned(
4515                ty,
4516                "`Auto<ForeignKey<T>>` is not supported — Auto is for server-assigned PKs, ForeignKey is for parent references",
4517            ));
4518        }
4519        if !matches!(
4520            inner_det.kind,
4521            DetectedKind::I32 | DetectedKind::I64 | DetectedKind::Uuid | DetectedKind::DateTime
4522        ) {
4523            return Err(syn::Error::new_spanned(
4524                ty,
4525                "`Auto<T>` only supports integers (`i32` → SERIAL, `i64` → BIGSERIAL), \
4526                 `uuid::Uuid` (DEFAULT gen_random_uuid()), or `chrono::DateTime<chrono::Utc>` \
4527                 (DEFAULT now())",
4528            ));
4529        }
4530        return Ok(DetectedType {
4531            auto: true,
4532            ..inner_det
4533        });
4534    }
4535
4536    if last.ident == "ForeignKey" {
4537        let (inner, key_ty) = generic_pair(ty, &last.arguments, "ForeignKey")?;
4538        // Resolve the FK column's underlying SQL type from `K`. When the
4539        // user wrote `ForeignKey<T>` without a key parameter, the type
4540        // alias defaults to `i64` and we keep the v0.7 BIGINT shape.
4541        // When the user wrote `ForeignKey<T, K>` with an explicit `K`,
4542        // recurse into K so the column DDL emits the right SQL type
4543        // (VARCHAR for String, UUID for Uuid, …) and the load_related
4544        // emitter knows which `SqlValue` variant to match.
4545        let kind = match key_ty {
4546            Some(k) => detect_type(k)?.kind,
4547            None => DetectedKind::I64,
4548        };
4549        return Ok(DetectedType {
4550            kind,
4551            nullable: false,
4552            auto: false,
4553            fk_inner: Some(inner),
4554        });
4555    }
4556
4557    let kind = match last.ident.to_string().as_str() {
4558        "i16" => DetectedKind::I16,
4559        "i32" => DetectedKind::I32,
4560        "i64" => DetectedKind::I64,
4561        "f32" => DetectedKind::F32,
4562        "f64" => DetectedKind::F64,
4563        "bool" => DetectedKind::Bool,
4564        "String" => DetectedKind::String,
4565        "DateTime" => DetectedKind::DateTime,
4566        "NaiveDate" => DetectedKind::Date,
4567        "Uuid" => DetectedKind::Uuid,
4568        "Value" => DetectedKind::Json,
4569        other => {
4570            return Err(syn::Error::new_spanned(
4571                ty,
4572                format!("unsupported field type `{other}`; v0.1 supports i32/i64/f32/f64/bool/String/DateTime/NaiveDate/Uuid/serde_json::Value, optionally wrapped in Option or Auto (Auto only on integers)"),
4573            ));
4574        }
4575    };
4576    Ok(DetectedType {
4577        kind,
4578        nullable: false,
4579        auto: false,
4580        fk_inner: None,
4581    })
4582}
4583
4584fn generic_inner<'a>(
4585    ty: &'a Type,
4586    arguments: &'a PathArguments,
4587    wrapper: &str,
4588) -> syn::Result<&'a Type> {
4589    let PathArguments::AngleBracketed(args) = arguments else {
4590        return Err(syn::Error::new_spanned(
4591            ty,
4592            format!("{wrapper} requires a generic argument"),
4593        ));
4594    };
4595    args.args
4596        .iter()
4597        .find_map(|a| match a {
4598            GenericArgument::Type(t) => Some(t),
4599            _ => None,
4600        })
4601        .ok_or_else(|| {
4602            syn::Error::new_spanned(ty, format!("{wrapper}<T> requires a type argument"))
4603        })
4604}
4605
4606/// Like [`generic_inner`] but pulls *two* type args — the first is
4607/// required, the second is optional. Used by the `ForeignKey<T, K>`
4608/// detection where K defaults to `i64` when omitted.
4609fn generic_pair<'a>(
4610    ty: &'a Type,
4611    arguments: &'a PathArguments,
4612    wrapper: &str,
4613) -> syn::Result<(&'a Type, Option<&'a Type>)> {
4614    let PathArguments::AngleBracketed(args) = arguments else {
4615        return Err(syn::Error::new_spanned(
4616            ty,
4617            format!("{wrapper} requires a generic argument"),
4618        ));
4619    };
4620    let mut types = args.args.iter().filter_map(|a| match a {
4621        GenericArgument::Type(t) => Some(t),
4622        _ => None,
4623    });
4624    let first = types.next().ok_or_else(|| {
4625        syn::Error::new_spanned(ty, format!("{wrapper}<T> requires a type argument"))
4626    })?;
4627    let second = types.next();
4628    Ok((first, second))
4629}
4630
4631fn to_snake_case(s: &str) -> String {
4632    let mut out = String::with_capacity(s.len() + 4);
4633    for (i, ch) in s.chars().enumerate() {
4634        if ch.is_ascii_uppercase() {
4635            if i > 0 {
4636                out.push('_');
4637            }
4638            out.push(ch.to_ascii_lowercase());
4639        } else {
4640            out.push(ch);
4641        }
4642    }
4643    out
4644}
4645
4646// ============================================================
4647//  #[derive(Form)]  —  slice 8.4B
4648// ============================================================
4649
4650/// Per-field `#[form(...)]` attributes recognised by the derive.
4651#[derive(Default)]
4652struct FormFieldAttrs {
4653    min: Option<i64>,
4654    max: Option<i64>,
4655    min_length: Option<u32>,
4656    max_length: Option<u32>,
4657}
4658
4659/// Detected shape of a form field's Rust type.
4660#[derive(Clone, Copy)]
4661enum FormFieldKind {
4662    String,
4663    I16,
4664    I32,
4665    I64,
4666    F32,
4667    F64,
4668    Bool,
4669}
4670
4671impl FormFieldKind {
4672    fn parse_method(self) -> &'static str {
4673        match self {
4674            Self::I16 => "i16",
4675            Self::I32 => "i32",
4676            Self::I64 => "i64",
4677            Self::F32 => "f32",
4678            Self::F64 => "f64",
4679            // String + Bool don't go through `str::parse`; the codegen
4680            // handles them inline.
4681            Self::String | Self::Bool => "",
4682        }
4683    }
4684}
4685
4686fn expand_form(input: &DeriveInput) -> syn::Result<TokenStream2> {
4687    let struct_name = &input.ident;
4688
4689    let Data::Struct(data) = &input.data else {
4690        return Err(syn::Error::new_spanned(
4691            struct_name,
4692            "Form can only be derived on structs",
4693        ));
4694    };
4695    let Fields::Named(named) = &data.fields else {
4696        return Err(syn::Error::new_spanned(
4697            struct_name,
4698            "Form requires a struct with named fields",
4699        ));
4700    };
4701
4702    let mut field_blocks: Vec<TokenStream2> = Vec::with_capacity(named.named.len());
4703    let mut field_idents: Vec<&syn::Ident> = Vec::with_capacity(named.named.len());
4704
4705    for field in &named.named {
4706        let ident = field
4707            .ident
4708            .as_ref()
4709            .ok_or_else(|| syn::Error::new(field.span(), "tuple structs are not supported"))?;
4710        let attrs = parse_form_field_attrs(field)?;
4711        let (kind, nullable) = detect_form_field(&field.ty, field.span())?;
4712
4713        let name_lit = ident.to_string();
4714        let parse_block = render_form_field_parse(ident, &name_lit, kind, nullable, &attrs);
4715        field_blocks.push(parse_block);
4716        field_idents.push(ident);
4717    }
4718
4719    Ok(quote! {
4720        impl ::rustango::forms::Form for #struct_name {
4721            fn parse(
4722                data: &::std::collections::HashMap<::std::string::String, ::std::string::String>,
4723            ) -> ::core::result::Result<Self, ::rustango::forms::FormErrors> {
4724                let mut __errors = ::rustango::forms::FormErrors::default();
4725                #( #field_blocks )*
4726                if !__errors.is_empty() {
4727                    return ::core::result::Result::Err(__errors);
4728                }
4729                ::core::result::Result::Ok(Self {
4730                    #( #field_idents ),*
4731                })
4732            }
4733        }
4734    })
4735}
4736
4737fn parse_form_field_attrs(field: &syn::Field) -> syn::Result<FormFieldAttrs> {
4738    let mut out = FormFieldAttrs::default();
4739    for attr in &field.attrs {
4740        if !attr.path().is_ident("form") {
4741            continue;
4742        }
4743        attr.parse_nested_meta(|meta| {
4744            if meta.path.is_ident("min") {
4745                let lit: syn::LitInt = meta.value()?.parse()?;
4746                out.min = Some(lit.base10_parse::<i64>()?);
4747                return Ok(());
4748            }
4749            if meta.path.is_ident("max") {
4750                let lit: syn::LitInt = meta.value()?.parse()?;
4751                out.max = Some(lit.base10_parse::<i64>()?);
4752                return Ok(());
4753            }
4754            if meta.path.is_ident("min_length") {
4755                let lit: syn::LitInt = meta.value()?.parse()?;
4756                out.min_length = Some(lit.base10_parse::<u32>()?);
4757                return Ok(());
4758            }
4759            if meta.path.is_ident("max_length") {
4760                let lit: syn::LitInt = meta.value()?.parse()?;
4761                out.max_length = Some(lit.base10_parse::<u32>()?);
4762                return Ok(());
4763            }
4764            Err(meta.error(
4765                "unknown form attribute (supported: `min`, `max`, `min_length`, `max_length`)",
4766            ))
4767        })?;
4768    }
4769    Ok(out)
4770}
4771
4772fn detect_form_field(ty: &Type, span: proc_macro2::Span) -> syn::Result<(FormFieldKind, bool)> {
4773    let Type::Path(TypePath { path, qself: None }) = ty else {
4774        return Err(syn::Error::new(
4775            span,
4776            "Form field must be a simple typed path (e.g. `String`, `i32`, `Option<String>`)",
4777        ));
4778    };
4779    let last = path
4780        .segments
4781        .last()
4782        .ok_or_else(|| syn::Error::new(span, "empty type path"))?;
4783
4784    if last.ident == "Option" {
4785        let inner = generic_inner(ty, &last.arguments, "Option")?;
4786        let (kind, nested) = detect_form_field(inner, span)?;
4787        if nested {
4788            return Err(syn::Error::new(
4789                span,
4790                "nested Option in Form fields is not supported",
4791            ));
4792        }
4793        return Ok((kind, true));
4794    }
4795
4796    let kind = match last.ident.to_string().as_str() {
4797        "String" => FormFieldKind::String,
4798        "i16" => FormFieldKind::I16,
4799        "i32" => FormFieldKind::I32,
4800        "i64" => FormFieldKind::I64,
4801        "f32" => FormFieldKind::F32,
4802        "f64" => FormFieldKind::F64,
4803        "bool" => FormFieldKind::Bool,
4804        other => {
4805            return Err(syn::Error::new(
4806                span,
4807                format!(
4808                    "Form field type `{other}` is not supported in v0.8 — use String / \
4809                     i16 / i32 / i64 / f32 / f64 / bool, optionally wrapped in Option<…>"
4810                ),
4811            ));
4812        }
4813    };
4814    Ok((kind, false))
4815}
4816
4817#[allow(clippy::too_many_lines)]
4818fn render_form_field_parse(
4819    ident: &syn::Ident,
4820    name_lit: &str,
4821    kind: FormFieldKind,
4822    nullable: bool,
4823    attrs: &FormFieldAttrs,
4824) -> TokenStream2 {
4825    // Pull the raw &str from the payload. Uses variable name `data` to
4826    // match the new `Form::parse(data: &HashMap<…>)` signature.
4827    let lookup = quote! {
4828        let __raw: ::core::option::Option<&::std::string::String> = data.get(#name_lit);
4829    };
4830
4831    let parsed_value = match kind {
4832        FormFieldKind::Bool => quote! {
4833            let __v: bool = match __raw {
4834                ::core::option::Option::None => false,
4835                ::core::option::Option::Some(__s) => !matches!(
4836                    __s.to_ascii_lowercase().as_str(),
4837                    "" | "false" | "0" | "off" | "no"
4838                ),
4839            };
4840        },
4841        FormFieldKind::String => {
4842            if nullable {
4843                quote! {
4844                    let __v: ::core::option::Option<::std::string::String> = match __raw {
4845                        ::core::option::Option::None => ::core::option::Option::None,
4846                        ::core::option::Option::Some(__s) if __s.is_empty() => {
4847                            ::core::option::Option::None
4848                        }
4849                        ::core::option::Option::Some(__s) => {
4850                            ::core::option::Option::Some(::core::clone::Clone::clone(__s))
4851                        }
4852                    };
4853                }
4854            } else {
4855                quote! {
4856                    let __v: ::std::string::String = match __raw {
4857                        ::core::option::Option::Some(__s) if !__s.is_empty() => {
4858                            ::core::clone::Clone::clone(__s)
4859                        }
4860                        _ => {
4861                            __errors.add(#name_lit, "This field is required.");
4862                            ::std::string::String::new()
4863                        }
4864                    };
4865                }
4866            }
4867        }
4868        FormFieldKind::I16
4869        | FormFieldKind::I32
4870        | FormFieldKind::I64
4871        | FormFieldKind::F32
4872        | FormFieldKind::F64 => {
4873            let parse_ty = syn::Ident::new(kind.parse_method(), proc_macro2::Span::call_site());
4874            let ty_lit = kind.parse_method();
4875            let default_val = match kind {
4876                FormFieldKind::I16 => quote! { 0i16 },
4877                FormFieldKind::I32 => quote! { 0i32 },
4878                FormFieldKind::I64 => quote! { 0i64 },
4879                FormFieldKind::F32 => quote! { 0f32 },
4880                FormFieldKind::F64 => quote! { 0f64 },
4881                _ => quote! { Default::default() },
4882            };
4883            if nullable {
4884                quote! {
4885                    let __v: ::core::option::Option<#parse_ty> = match __raw {
4886                        ::core::option::Option::None => ::core::option::Option::None,
4887                        ::core::option::Option::Some(__s) if __s.is_empty() => {
4888                            ::core::option::Option::None
4889                        }
4890                        ::core::option::Option::Some(__s) => {
4891                            match __s.parse::<#parse_ty>() {
4892                                ::core::result::Result::Ok(__n) => {
4893                                    ::core::option::Option::Some(__n)
4894                                }
4895                                ::core::result::Result::Err(__e) => {
4896                                    __errors.add(
4897                                        #name_lit,
4898                                        ::std::format!("Enter a valid {} value: {}", #ty_lit, __e),
4899                                    );
4900                                    ::core::option::Option::None
4901                                }
4902                            }
4903                        }
4904                    };
4905                }
4906            } else {
4907                quote! {
4908                    let __v: #parse_ty = match __raw {
4909                        ::core::option::Option::Some(__s) if !__s.is_empty() => {
4910                            match __s.parse::<#parse_ty>() {
4911                                ::core::result::Result::Ok(__n) => __n,
4912                                ::core::result::Result::Err(__e) => {
4913                                    __errors.add(
4914                                        #name_lit,
4915                                        ::std::format!("Enter a valid {} value: {}", #ty_lit, __e),
4916                                    );
4917                                    #default_val
4918                                }
4919                            }
4920                        }
4921                        _ => {
4922                            __errors.add(#name_lit, "This field is required.");
4923                            #default_val
4924                        }
4925                    };
4926                }
4927            }
4928        }
4929    };
4930
4931    let validators = render_form_validators(name_lit, kind, nullable, attrs);
4932
4933    quote! {
4934        let #ident = {
4935            #lookup
4936            #parsed_value
4937            #validators
4938            __v
4939        };
4940    }
4941}
4942
4943fn render_form_validators(
4944    name_lit: &str,
4945    kind: FormFieldKind,
4946    nullable: bool,
4947    attrs: &FormFieldAttrs,
4948) -> TokenStream2 {
4949    let mut checks: Vec<TokenStream2> = Vec::new();
4950
4951    let val_ref = if nullable {
4952        quote! { __v.as_ref() }
4953    } else {
4954        quote! { ::core::option::Option::Some(&__v) }
4955    };
4956
4957    let is_string = matches!(kind, FormFieldKind::String);
4958    let is_numeric = matches!(
4959        kind,
4960        FormFieldKind::I16
4961            | FormFieldKind::I32
4962            | FormFieldKind::I64
4963            | FormFieldKind::F32
4964            | FormFieldKind::F64
4965    );
4966
4967    if is_string {
4968        if let Some(min_len) = attrs.min_length {
4969            let min_len_usize = min_len as usize;
4970            checks.push(quote! {
4971                if let ::core::option::Option::Some(__s) = #val_ref {
4972                    if __s.len() < #min_len_usize {
4973                        __errors.add(
4974                            #name_lit,
4975                            ::std::format!("Ensure this value has at least {} characters.", #min_len_usize),
4976                        );
4977                    }
4978                }
4979            });
4980        }
4981        if let Some(max_len) = attrs.max_length {
4982            let max_len_usize = max_len as usize;
4983            checks.push(quote! {
4984                if let ::core::option::Option::Some(__s) = #val_ref {
4985                    if __s.len() > #max_len_usize {
4986                        __errors.add(
4987                            #name_lit,
4988                            ::std::format!("Ensure this value has at most {} characters.", #max_len_usize),
4989                        );
4990                    }
4991                }
4992            });
4993        }
4994    }
4995
4996    if is_numeric {
4997        if let Some(min) = attrs.min {
4998            checks.push(quote! {
4999                if let ::core::option::Option::Some(__n) = #val_ref {
5000                    if (*__n as f64) < (#min as f64) {
5001                        __errors.add(
5002                            #name_lit,
5003                            ::std::format!("Ensure this value is greater than or equal to {}.", #min),
5004                        );
5005                    }
5006                }
5007            });
5008        }
5009        if let Some(max) = attrs.max {
5010            checks.push(quote! {
5011                if let ::core::option::Option::Some(__n) = #val_ref {
5012                    if (*__n as f64) > (#max as f64) {
5013                        __errors.add(
5014                            #name_lit,
5015                            ::std::format!("Ensure this value is less than or equal to {}.", #max),
5016                        );
5017                    }
5018                }
5019            });
5020        }
5021    }
5022
5023    quote! { #( #checks )* }
5024}
5025
5026// ============================================================
5027//  #[derive(ViewSet)]
5028// ============================================================
5029
5030struct ViewSetAttrs {
5031    model: syn::Path,
5032    fields: Option<Vec<String>>,
5033    filter_fields: Vec<String>,
5034    search_fields: Vec<String>,
5035    /// (field_name, desc)
5036    ordering: Vec<(String, bool)>,
5037    page_size: Option<usize>,
5038    read_only: bool,
5039    perms: ViewSetPermsAttrs,
5040}
5041
5042#[derive(Default)]
5043struct ViewSetPermsAttrs {
5044    list: Vec<String>,
5045    retrieve: Vec<String>,
5046    create: Vec<String>,
5047    update: Vec<String>,
5048    destroy: Vec<String>,
5049}
5050
5051fn expand_viewset(input: &DeriveInput) -> syn::Result<TokenStream2> {
5052    let struct_name = &input.ident;
5053
5054    // Must be a unit struct or an empty named struct.
5055    match &input.data {
5056        Data::Struct(s) => match &s.fields {
5057            Fields::Unit | Fields::Named(_) => {}
5058            Fields::Unnamed(_) => {
5059                return Err(syn::Error::new_spanned(
5060                    struct_name,
5061                    "ViewSet can only be derived on a unit struct or an empty named struct",
5062                ));
5063            }
5064        },
5065        _ => {
5066            return Err(syn::Error::new_spanned(
5067                struct_name,
5068                "ViewSet can only be derived on a struct",
5069            ));
5070        }
5071    }
5072
5073    let attrs = parse_viewset_attrs(input)?;
5074    let model_path = &attrs.model;
5075
5076    // `.fields(&[...])` call — None means skip (use all scalar fields).
5077    let fields_call = if let Some(ref fields) = attrs.fields {
5078        let lits = fields.iter().map(|f| f.as_str());
5079        quote!(.fields(&[ #(#lits),* ]))
5080    } else {
5081        quote!()
5082    };
5083
5084    let filter_fields_call = if attrs.filter_fields.is_empty() {
5085        quote!()
5086    } else {
5087        let lits = attrs.filter_fields.iter().map(|f| f.as_str());
5088        quote!(.filter_fields(&[ #(#lits),* ]))
5089    };
5090
5091    let search_fields_call = if attrs.search_fields.is_empty() {
5092        quote!()
5093    } else {
5094        let lits = attrs.search_fields.iter().map(|f| f.as_str());
5095        quote!(.search_fields(&[ #(#lits),* ]))
5096    };
5097
5098    let ordering_call = if attrs.ordering.is_empty() {
5099        quote!()
5100    } else {
5101        let pairs = attrs.ordering.iter().map(|(f, desc)| {
5102            let f = f.as_str();
5103            quote!((#f, #desc))
5104        });
5105        quote!(.ordering(&[ #(#pairs),* ]))
5106    };
5107
5108    let page_size_call = if let Some(n) = attrs.page_size {
5109        quote!(.page_size(#n))
5110    } else {
5111        quote!()
5112    };
5113
5114    let read_only_call = if attrs.read_only {
5115        quote!(.read_only())
5116    } else {
5117        quote!()
5118    };
5119
5120    let perms = &attrs.perms;
5121    let perms_call = if perms.list.is_empty()
5122        && perms.retrieve.is_empty()
5123        && perms.create.is_empty()
5124        && perms.update.is_empty()
5125        && perms.destroy.is_empty()
5126    {
5127        quote!()
5128    } else {
5129        let list_lits = perms.list.iter().map(|s| s.as_str());
5130        let retrieve_lits = perms.retrieve.iter().map(|s| s.as_str());
5131        let create_lits = perms.create.iter().map(|s| s.as_str());
5132        let update_lits = perms.update.iter().map(|s| s.as_str());
5133        let destroy_lits = perms.destroy.iter().map(|s| s.as_str());
5134        quote! {
5135            .permissions(::rustango::viewset::ViewSetPerms {
5136                list:     ::std::vec![ #(#list_lits.to_owned()),* ],
5137                retrieve: ::std::vec![ #(#retrieve_lits.to_owned()),* ],
5138                create:   ::std::vec![ #(#create_lits.to_owned()),* ],
5139                update:   ::std::vec![ #(#update_lits.to_owned()),* ],
5140                destroy:  ::std::vec![ #(#destroy_lits.to_owned()),* ],
5141            })
5142        }
5143    };
5144
5145    Ok(quote! {
5146        impl #struct_name {
5147            /// Build an `axum::Router` with the six standard REST endpoints
5148            /// for this ViewSet, mounted at `prefix`.
5149            pub fn router(prefix: &str, pool: ::rustango::sql::sqlx::PgPool) -> ::axum::Router {
5150                ::rustango::viewset::ViewSet::for_model(
5151                    <#model_path as ::rustango::core::Model>::SCHEMA
5152                )
5153                    #fields_call
5154                    #filter_fields_call
5155                    #search_fields_call
5156                    #ordering_call
5157                    #page_size_call
5158                    #perms_call
5159                    #read_only_call
5160                    .router(prefix, pool)
5161            }
5162        }
5163    })
5164}
5165
5166fn parse_viewset_attrs(input: &DeriveInput) -> syn::Result<ViewSetAttrs> {
5167    let mut model: Option<syn::Path> = None;
5168    let mut fields: Option<Vec<String>> = None;
5169    let mut filter_fields: Vec<String> = Vec::new();
5170    let mut search_fields: Vec<String> = Vec::new();
5171    let mut ordering: Vec<(String, bool)> = Vec::new();
5172    let mut page_size: Option<usize> = None;
5173    let mut read_only = false;
5174    let mut perms = ViewSetPermsAttrs::default();
5175
5176    for attr in &input.attrs {
5177        if !attr.path().is_ident("viewset") {
5178            continue;
5179        }
5180        attr.parse_nested_meta(|meta| {
5181            if meta.path.is_ident("model") {
5182                let path: syn::Path = meta.value()?.parse()?;
5183                model = Some(path);
5184                return Ok(());
5185            }
5186            if meta.path.is_ident("fields") {
5187                let s: LitStr = meta.value()?.parse()?;
5188                fields = Some(split_field_list(&s.value()));
5189                return Ok(());
5190            }
5191            if meta.path.is_ident("filter_fields") {
5192                let s: LitStr = meta.value()?.parse()?;
5193                filter_fields = split_field_list(&s.value());
5194                return Ok(());
5195            }
5196            if meta.path.is_ident("search_fields") {
5197                let s: LitStr = meta.value()?.parse()?;
5198                search_fields = split_field_list(&s.value());
5199                return Ok(());
5200            }
5201            if meta.path.is_ident("ordering") {
5202                let s: LitStr = meta.value()?.parse()?;
5203                ordering = parse_ordering_list(&s.value());
5204                return Ok(());
5205            }
5206            if meta.path.is_ident("page_size") {
5207                let lit: syn::LitInt = meta.value()?.parse()?;
5208                page_size = Some(lit.base10_parse::<usize>()?);
5209                return Ok(());
5210            }
5211            if meta.path.is_ident("read_only") {
5212                read_only = true;
5213                return Ok(());
5214            }
5215            if meta.path.is_ident("permissions") {
5216                meta.parse_nested_meta(|inner| {
5217                    let parse_codenames = |inner: &syn::meta::ParseNestedMeta| -> syn::Result<Vec<String>> {
5218                        let s: LitStr = inner.value()?.parse()?;
5219                        Ok(split_field_list(&s.value()))
5220                    };
5221                    if inner.path.is_ident("list") {
5222                        perms.list = parse_codenames(&inner)?;
5223                    } else if inner.path.is_ident("retrieve") {
5224                        perms.retrieve = parse_codenames(&inner)?;
5225                    } else if inner.path.is_ident("create") {
5226                        perms.create = parse_codenames(&inner)?;
5227                    } else if inner.path.is_ident("update") {
5228                        perms.update = parse_codenames(&inner)?;
5229                    } else if inner.path.is_ident("destroy") {
5230                        perms.destroy = parse_codenames(&inner)?;
5231                    } else {
5232                        return Err(inner.error(
5233                            "unknown permissions key (supported: list, retrieve, create, update, destroy)",
5234                        ));
5235                    }
5236                    Ok(())
5237                })?;
5238                return Ok(());
5239            }
5240            Err(meta.error(
5241                "unknown viewset attribute (supported: model, fields, filter_fields, \
5242                 search_fields, ordering, page_size, read_only, permissions(...))",
5243            ))
5244        })?;
5245    }
5246
5247    let model = model.ok_or_else(|| {
5248        syn::Error::new_spanned(&input.ident, "`#[viewset(model = SomeModel)]` is required")
5249    })?;
5250
5251    Ok(ViewSetAttrs {
5252        model,
5253        fields,
5254        filter_fields,
5255        search_fields,
5256        ordering,
5257        page_size,
5258        read_only,
5259        perms,
5260    })
5261}
5262
5263// ============================================================ #[derive(Serializer)]
5264
5265struct SerializerContainerAttrs {
5266    model: syn::Path,
5267}
5268
5269#[derive(Default)]
5270struct SerializerFieldAttrs {
5271    read_only: bool,
5272    write_only: bool,
5273    source: Option<String>,
5274    skip: bool,
5275    /// `#[serializer(method = "fn_name")]` — DRF SerializerMethodField
5276    /// analog. The macro emits `from_model` initializer that calls
5277    /// `Self::fn_name(&model)` and stores the return value.
5278    method: Option<String>,
5279    /// `#[serializer(validate = "fn_name")]` — per-field validator
5280    /// callable run by `Self::validate(&self)`. Must return
5281    /// `Result<(), String>`. Errors land in `FormErrors` keyed by
5282    /// the field name.
5283    validate: Option<String>,
5284    /// `#[serializer(nested)]` on a field whose type is another
5285    /// `Serializer` — the macro emits `from_model` initializer that
5286    /// reads the parent via `model.<source>.value()` then calls the
5287    /// child serializer's `from_model(parent)`. When the FK is
5288    /// unloaded the field falls back to `Default::default()` (does
5289    /// NOT panic) so a missing prefetch in prod degrades gracefully.
5290    /// Source field on the model defaults to the field name; override
5291    /// with `source = "..."`. Combine with `strict` to keep the v0.18.1
5292    /// panic-on-unloaded behavior for tests.
5293    nested: bool,
5294    /// `#[serializer(nested, strict)]` — opt back into the v0.18.1
5295    /// strict behavior: panic when the FK isn't loaded. Useful in
5296    /// test code where forgetting select_related must trip a hard
5297    /// failure rather than render a blank nested object.
5298    nested_strict: bool,
5299    /// `#[serializer(many = TagSerializer)]` — declare the field as
5300    /// a list of nested serializers. Field type must be `Vec<S>`
5301    /// where `S` is the inner serializer. The macro initializes the
5302    /// field to `Vec::new()` in `from_model` and emits a typed
5303    /// `set_<field>(&mut self, models: &[<S::Model>])` helper that
5304    /// maps each model row through `S::from_model`. Auto-load isn't
5305    /// possible (the M2M / one-to-many accessor is async); callers
5306    /// fetch the children + call the setter post-from_model.
5307    many: Option<syn::Type>,
5308}
5309
5310fn parse_serializer_container_attrs(input: &DeriveInput) -> syn::Result<SerializerContainerAttrs> {
5311    let mut model: Option<syn::Path> = None;
5312    for attr in &input.attrs {
5313        if !attr.path().is_ident("serializer") {
5314            continue;
5315        }
5316        attr.parse_nested_meta(|meta| {
5317            if meta.path.is_ident("model") {
5318                let _eq: syn::Token![=] = meta.input.parse()?;
5319                model = Some(meta.input.parse()?);
5320                return Ok(());
5321            }
5322            Err(meta.error("unknown serializer container attribute (supported: `model`)"))
5323        })?;
5324    }
5325    let model = model.ok_or_else(|| {
5326        syn::Error::new_spanned(
5327            &input.ident,
5328            "`#[serializer(model = SomeModel)]` is required",
5329        )
5330    })?;
5331    Ok(SerializerContainerAttrs { model })
5332}
5333
5334fn parse_serializer_field_attrs(field: &syn::Field) -> syn::Result<SerializerFieldAttrs> {
5335    let mut out = SerializerFieldAttrs::default();
5336    for attr in &field.attrs {
5337        if !attr.path().is_ident("serializer") {
5338            continue;
5339        }
5340        attr.parse_nested_meta(|meta| {
5341            if meta.path.is_ident("read_only") {
5342                out.read_only = true;
5343                return Ok(());
5344            }
5345            if meta.path.is_ident("write_only") {
5346                out.write_only = true;
5347                return Ok(());
5348            }
5349            if meta.path.is_ident("skip") {
5350                out.skip = true;
5351                return Ok(());
5352            }
5353            if meta.path.is_ident("source") {
5354                let s: LitStr = meta.value()?.parse()?;
5355                out.source = Some(s.value());
5356                return Ok(());
5357            }
5358            if meta.path.is_ident("method") {
5359                let s: LitStr = meta.value()?.parse()?;
5360                out.method = Some(s.value());
5361                return Ok(());
5362            }
5363            if meta.path.is_ident("validate") {
5364                let s: LitStr = meta.value()?.parse()?;
5365                out.validate = Some(s.value());
5366                return Ok(());
5367            }
5368            if meta.path.is_ident("many") {
5369                let _eq: syn::Token![=] = meta.input.parse()?;
5370                out.many = Some(meta.input.parse()?);
5371                return Ok(());
5372            }
5373            if meta.path.is_ident("nested") {
5374                out.nested = true;
5375                // Optional strict flag inside parentheses:
5376                //   #[serializer(nested(strict))]
5377                if meta.input.peek(syn::token::Paren) {
5378                    meta.parse_nested_meta(|inner| {
5379                        if inner.path.is_ident("strict") {
5380                            out.nested_strict = true;
5381                            return Ok(());
5382                        }
5383                        Err(inner.error("unknown nested sub-attribute (supported: `strict`)"))
5384                    })?;
5385                }
5386                return Ok(());
5387            }
5388            Err(meta.error(
5389                "unknown serializer field attribute (supported: \
5390                 `read_only`, `write_only`, `source`, `skip`, `method`, `validate`, `nested`)",
5391            ))
5392        })?;
5393    }
5394    // Validate: read_only + write_only is nonsensical
5395    if out.read_only && out.write_only {
5396        return Err(syn::Error::new_spanned(
5397            field,
5398            "a field cannot be both `read_only` and `write_only`",
5399        ));
5400    }
5401    if out.method.is_some() && out.source.is_some() {
5402        return Err(syn::Error::new_spanned(
5403            field,
5404            "`method` and `source` are mutually exclusive — `method` computes \
5405             the value from a method, `source` reads it from a different model field",
5406        ));
5407    }
5408    Ok(out)
5409}
5410
5411fn expand_serializer(input: &DeriveInput) -> syn::Result<TokenStream2> {
5412    let struct_name = &input.ident;
5413    let struct_name_lit = struct_name.to_string();
5414
5415    let Data::Struct(data) = &input.data else {
5416        return Err(syn::Error::new_spanned(
5417            struct_name,
5418            "Serializer can only be derived on structs",
5419        ));
5420    };
5421    let Fields::Named(named) = &data.fields else {
5422        return Err(syn::Error::new_spanned(
5423            struct_name,
5424            "Serializer requires a struct with named fields",
5425        ));
5426    };
5427
5428    let container = parse_serializer_container_attrs(input)?;
5429    let model_path = &container.model;
5430
5431    // Classify each field. `ty` is only consumed by the
5432    // `#[cfg(feature = "openapi")]` block below, but we always
5433    // capture it to keep the field-info build a single pass.
5434    #[allow(dead_code)]
5435    struct FieldInfo {
5436        ident: syn::Ident,
5437        ty: syn::Type,
5438        attrs: SerializerFieldAttrs,
5439    }
5440    let mut fields_info: Vec<FieldInfo> = Vec::new();
5441    for field in &named.named {
5442        let ident = field.ident.clone().expect("named field has ident");
5443        let attrs = parse_serializer_field_attrs(field)?;
5444        fields_info.push(FieldInfo {
5445            ident,
5446            ty: field.ty.clone(),
5447            attrs,
5448        });
5449    }
5450
5451    // Generate from_model body: struct literal with each field assigned.
5452    let from_model_fields = fields_info.iter().map(|fi| {
5453        let ident = &fi.ident;
5454        let ty = &fi.ty;
5455        if let Some(_inner) = &fi.attrs.many {
5456            // Many — collection field. Initialize empty; caller
5457            // populates via the macro-emitted set_<field> helper
5458            // after fetching the M2M children.
5459            quote! { #ident: ::std::vec::Vec::new() }
5460        } else if let Some(method) = &fi.attrs.method {
5461            // SerializerMethodField: call Self::<method>(&model) to
5462            // compute the value. Method signature must be
5463            // `fn <method>(model: &T) -> <field type>`.
5464            let method_ident = syn::Ident::new(method, ident.span());
5465            quote! { #ident: Self::#method_ident(model) }
5466        } else if fi.attrs.nested {
5467            // Nested serializer. Source defaults to the field name on
5468            // this struct; override via `source = "..."`. The source
5469            // field on the model is expected to be a `ForeignKey<T>`
5470            // whose `.value()` returns `Option<&T>` after lazy-load.
5471            //
5472            // Behavior matrix (tweakable per-field):
5473            //   * FK loaded   → nested object materializes via
5474            //                   ChildSerializer::from_model(parent).
5475            //   * FK unloaded → fall back to ChildSerializer::default()
5476            //                   (so prod doesn't crash on a missing
5477            //                   prefetch — just renders a blank nested
5478            //                   object). Add `#[serializer(nested,
5479            //                   strict)]` to keep the v0.18.1
5480            //                   panic-on-unloaded behavior for tests
5481            //                   that want hard guardrails.
5482            let src_name = fi.attrs.source.as_deref().unwrap_or(&fi.ident.to_string()).to_owned();
5483            let src_ident = syn::Ident::new(&src_name, ident.span());
5484            if fi.attrs.nested_strict {
5485                let panic_msg = format!(
5486                    "nested(strict) serializer for `{ident}` requires `model.{src_name}` to be loaded — \
5487                     call .get(&pool).await? or .select_related(\"{src_name}\") on the model first",
5488                );
5489                quote! {
5490                    #ident: <#ty as ::rustango::serializer::ModelSerializer>::from_model(
5491                        model.#src_ident.value().expect(#panic_msg),
5492                    )
5493                }
5494            } else {
5495                quote! {
5496                    #ident: match model.#src_ident.value() {
5497                        ::core::option::Option::Some(__loaded) =>
5498                            <#ty as ::rustango::serializer::ModelSerializer>::from_model(__loaded),
5499                        ::core::option::Option::None =>
5500                            ::core::default::Default::default(),
5501                    }
5502                }
5503            }
5504        } else if fi.attrs.write_only || fi.attrs.skip {
5505            // Not read from model — use default
5506            quote! { #ident: ::core::default::Default::default() }
5507        } else if let Some(src) = &fi.attrs.source {
5508            let src_ident = syn::Ident::new(src, ident.span());
5509            quote! { #ident: ::core::clone::Clone::clone(&model.#src_ident) }
5510        } else {
5511            quote! { #ident: ::core::clone::Clone::clone(&model.#ident) }
5512        }
5513    });
5514
5515    // Per-field validators (DRF-shape `validators=[...]`). Emit a
5516    // `validate(&self)` method that runs each user-defined validator
5517    // and aggregates errors into `FormErrors`.
5518    let validator_calls: Vec<_> = fields_info
5519        .iter()
5520        .filter_map(|fi| {
5521            let ident = &fi.ident;
5522            let name_lit = ident.to_string();
5523            let method = fi.attrs.validate.as_ref()?;
5524            let method_ident = syn::Ident::new(method, ident.span());
5525            Some(quote! {
5526                if let ::core::result::Result::Err(__e) = Self::#method_ident(&self.#ident) {
5527                    __errors.add(#name_lit.to_owned(), __e);
5528                }
5529            })
5530        })
5531        .collect();
5532    let validate_method = if validator_calls.is_empty() {
5533        quote! {}
5534    } else {
5535        quote! {
5536            impl #struct_name {
5537                /// Run every `#[serializer(validate = "...")]` per-field
5538                /// validator. Aggregates errors into `FormErrors` keyed
5539                /// by the field name. Returns `Ok(())` when all pass.
5540                pub fn validate(&self) -> ::core::result::Result<(), ::rustango::forms::FormErrors> {
5541                    let mut __errors = ::rustango::forms::FormErrors::default();
5542                    #( #validator_calls )*
5543                    if __errors.is_empty() {
5544                        ::core::result::Result::Ok(())
5545                    } else {
5546                        ::core::result::Result::Err(__errors)
5547                    }
5548                }
5549            }
5550        }
5551    };
5552
5553    // For every `#[serializer(many = S)]` field, emit a
5554    // `pub fn set_<field>(&mut self, models: &[<S::Model>]) -> &mut Self`
5555    // helper that maps the parents through `S::from_model`.
5556    let many_setters: Vec<_> = fields_info
5557        .iter()
5558        .filter_map(|fi| {
5559            let many_ty = fi.attrs.many.as_ref()?;
5560            let ident = &fi.ident;
5561            let setter = syn::Ident::new(&format!("set_{ident}"), ident.span());
5562            Some(quote! {
5563                /// Populate this `many` field by mapping each parent model
5564                /// through the inner serializer's `from_model`. Call after
5565                /// fetching the M2M / one-to-many children since
5566                /// `from_model` itself can't await an SQL query.
5567                pub fn #setter(
5568                    &mut self,
5569                    models: &[<#many_ty as ::rustango::serializer::ModelSerializer>::Model],
5570                ) -> &mut Self {
5571                    self.#ident = models.iter()
5572                        .map(<#many_ty as ::rustango::serializer::ModelSerializer>::from_model)
5573                        .collect();
5574                    self
5575                }
5576            })
5577        })
5578        .collect();
5579    let many_setters_impl = if many_setters.is_empty() {
5580        quote! {}
5581    } else {
5582        quote! {
5583            impl #struct_name {
5584                #( #many_setters )*
5585            }
5586        }
5587    };
5588
5589    // Generate custom Serialize: skip write_only fields
5590    let output_fields: Vec<_> = fields_info
5591        .iter()
5592        .filter(|fi| !fi.attrs.write_only)
5593        .collect();
5594    let output_field_count = output_fields.len();
5595    let serialize_fields = output_fields.iter().map(|fi| {
5596        let ident = &fi.ident;
5597        let name_lit = ident.to_string();
5598        quote! { __state.serialize_field(#name_lit, &self.#ident)?; }
5599    });
5600
5601    // writable_fields: normal + write_only (not read_only, not skip)
5602    let writable_lits: Vec<_> = fields_info
5603        .iter()
5604        .filter(|fi| !fi.attrs.read_only && !fi.attrs.skip)
5605        .map(|fi| fi.ident.to_string())
5606        .collect();
5607
5608    // OpenAPI: emit `impl OpenApiSchema` when our `openapi` feature is on.
5609    // Only includes fields shown in JSON output (skips write_only). For each
5610    // `Option<T>` field, omit from `required` and add `.nullable()`.
5611    let openapi_impl = {
5612        #[cfg(feature = "openapi")]
5613        {
5614            let property_calls = output_fields.iter().map(|fi| {
5615                let ident = &fi.ident;
5616                let name_lit = ident.to_string();
5617                let ty = &fi.ty;
5618                let nullable_call = if is_option(ty) {
5619                    quote! { .nullable() }
5620                } else {
5621                    quote! {}
5622                };
5623                quote! {
5624                    .property(
5625                        #name_lit,
5626                        <#ty as ::rustango::openapi::OpenApiSchema>::openapi_schema()
5627                            #nullable_call,
5628                    )
5629                }
5630            });
5631            let required_lits: Vec<_> = output_fields
5632                .iter()
5633                .filter(|fi| !is_option(&fi.ty))
5634                .map(|fi| fi.ident.to_string())
5635                .collect();
5636            quote! {
5637                impl ::rustango::openapi::OpenApiSchema for #struct_name {
5638                    fn openapi_schema() -> ::rustango::openapi::Schema {
5639                        ::rustango::openapi::Schema::object()
5640                            #( #property_calls )*
5641                            .required([ #( #required_lits ),* ])
5642                    }
5643                }
5644            }
5645        }
5646        #[cfg(not(feature = "openapi"))]
5647        {
5648            quote! {}
5649        }
5650    };
5651
5652    Ok(quote! {
5653        impl ::rustango::serializer::ModelSerializer for #struct_name {
5654            type Model = #model_path;
5655
5656            fn from_model(model: &Self::Model) -> Self {
5657                Self {
5658                    #( #from_model_fields ),*
5659                }
5660            }
5661
5662            fn writable_fields() -> &'static [&'static str] {
5663                &[ #( #writable_lits ),* ]
5664            }
5665        }
5666
5667        impl ::serde::Serialize for #struct_name {
5668            fn serialize<S>(&self, serializer: S)
5669                -> ::core::result::Result<S::Ok, S::Error>
5670            where
5671                S: ::serde::Serializer,
5672            {
5673                use ::serde::ser::SerializeStruct;
5674                let mut __state = serializer.serialize_struct(
5675                    #struct_name_lit,
5676                    #output_field_count,
5677                )?;
5678                #( #serialize_fields )*
5679                __state.end()
5680            }
5681        }
5682
5683        #openapi_impl
5684
5685        #validate_method
5686
5687        #many_setters_impl
5688    })
5689}
5690
5691/// Returns true if `ty` looks like `Option<T>` (any path ending in `Option`).
5692/// Only used by the `openapi`-gated emission of `OpenApiSchema`; muted
5693/// when the feature is off.
5694#[cfg_attr(not(feature = "openapi"), allow(dead_code))]
5695fn is_option(ty: &syn::Type) -> bool {
5696    if let syn::Type::Path(p) = ty {
5697        if let Some(last) = p.path.segments.last() {
5698            return last.ident == "Option";
5699        }
5700    }
5701    false
5702}