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