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/// Resolve the consumer's local name for the `rustango` crate so the
18/// macro-emitted code keeps compiling when a downstream `Cargo.toml`
19/// renames the dep (`[dependencies] orm = { package = "rustango", … }`)
20/// or when the standalone `rustango-orm` crate ships in a future
21/// slice of the [orm-extract epic](https://github.com/ujeenet/rustango/issues/149).
22///
23/// Returns one of:
24/// - `quote!(::rustango)` — the consumer IS the `rustango` crate
25///   itself. We emit the absolute path `::rustango` (NOT `crate`)
26///   because examples and integration tests inside the rustango
27///   package compile as separate binaries — their own `crate::`
28///   namespace is the example/test file, not rustango's lib root.
29///   The absolute `::rustango` resolves correctly in both contexts
30///   (rustango lib code AND rustango/examples/*.rs).
31/// - `quote!(::ident)` — the consumer renamed the dep; emit the
32///   user's chosen ident.
33/// - `quote!(::rustango)` — fallback when `proc-macro-crate` can't
34///   read the manifest (rare; preserves today's behavior).
35///
36/// Issue [#142](https://github.com/ujeenet/rustango/issues/142).
37fn rustango_root() -> TokenStream2 {
38    use proc_macro_crate::{crate_name, FoundCrate};
39    match crate_name("rustango") {
40        Ok(FoundCrate::Itself) => quote!(::rustango),
41        Ok(FoundCrate::Name(name)) => {
42            let ident = proc_macro2::Ident::new(&name, proc_macro2::Span::call_site());
43            quote!(::#ident)
44        }
45        Err(_) => quote!(::rustango),
46    }
47}
48
49/// Derive a `Model` impl. See crate docs for the supported attributes.
50#[proc_macro_derive(Model, attributes(rustango))]
51pub fn derive_model(input: TokenStream) -> TokenStream {
52    let input = parse_macro_input!(input as DeriveInput);
53    expand(&input)
54        .unwrap_or_else(syn::Error::into_compile_error)
55        .into()
56}
57
58/// Derive a `router(prefix, pool) -> axum::Router` associated method on a
59/// marker struct, wiring the full CRUD ViewSet in one annotation.
60///
61/// ```ignore
62/// #[derive(ViewSet)]
63/// #[viewset(
64///     model        = Post,
65///     fields       = "id, title, body, author_id",
66///     filter_fields = "author_id",
67///     search_fields = "title, body",
68///     ordering     = "-published_at",
69///     page_size    = 20,
70/// )]
71/// pub struct PostViewSet;
72///
73/// // Mount into your app:
74/// let app = Router::new()
75///     .merge(PostViewSet::router("/api/posts", pool.clone()));
76/// ```
77///
78/// Attributes:
79/// * `model = TypeName` — *required*. The `#[derive(Model)]` struct whose
80///   `SCHEMA` constant drives the endpoints.
81/// * `fields = "a, b, c"` — scalar fields included in list/retrieve JSON
82///   and accepted on create/update (default: all scalar fields).
83/// * `filter_fields = "a, b"` — fields filterable via `?a=v` query params.
84/// * `search_fields = "a, b"` — fields searched by `?search=...`.
85/// * `ordering = "a, -b"` — default list ordering; prefix `-` for DESC.
86/// * `page_size = N` — default page size (default: 20, max: 1000).
87/// * `read_only` — flag; wires only `list` + `retrieve` (no mutations).
88/// * `serializer = SomeSerializer` — render list / retrieve / create
89///   responses through a `#[derive(Serializer)]` type instead of the
90///   default field-level projection (`read_only` / `source` / `method`
91///   / `write_only` overrides apply). Tri-dialect. Requires the
92///   `serializer` feature.
93/// * `permissions(list = "...", retrieve = "...", create = "...",
94///   update = "...", destroy = "...")` — codenames required per action.
95#[proc_macro_derive(ViewSet, attributes(viewset))]
96pub fn derive_viewset(input: TokenStream) -> TokenStream {
97    let input = parse_macro_input!(input as DeriveInput);
98    expand_viewset(&input)
99        .unwrap_or_else(syn::Error::into_compile_error)
100        .into()
101}
102
103/// Derive `rustango::forms::Form` (slice 8.4B). Generates a
104/// `parse(&HashMap<String, String>) -> Result<Self, FormErrors>` impl
105/// that walks every named field and:
106///
107/// * Parses the string value into the field's Rust type (`String`,
108///   `i32`, `i64`, `f32`, `f64`, `bool`, plus `Option<T>` for the
109///   nullable case).
110/// * Applies any `#[form(min = ..)]` / `#[form(max = ..)]` /
111///   `#[form(min_length = ..)]` / `#[form(max_length = ..)]`
112///   validators in declaration order, returning `FormError::Parse`
113///   on the first failure.
114///
115/// Example:
116///
117/// ```ignore
118/// #[derive(Form)]
119/// pub struct CreateItemForm {
120///     #[form(min_length = 1, max_length = 64)]
121///     pub name: String,
122///     #[form(min = 0, max = 150)]
123///     pub age: i32,
124///     pub active: bool,
125///     pub email: Option<String>,
126/// }
127///
128/// let parsed = CreateItemForm::parse(&form_map)?;
129/// ```
130#[proc_macro_derive(Form, attributes(form))]
131pub fn derive_form(input: TokenStream) -> TokenStream {
132    let input = parse_macro_input!(input as DeriveInput);
133    expand_form(&input)
134        .unwrap_or_else(syn::Error::into_compile_error)
135        .into()
136}
137
138/// Derive `rustango::serializer::ModelSerializer` for a struct.
139/// (intra-doc link disabled — the macro crate doesn't depend on
140/// `rustango` itself, so rustdoc can't resolve the path.)
141///
142/// # Container attribute (required)
143/// `#[serializer(model = TypeName)]` — the [`Model`] type this serializer maps from.
144///
145/// # Field attributes
146/// - `#[serializer(read_only)]` — mapped from model; included in JSON output; excluded from `writable_fields()`
147/// - `#[serializer(write_only)]` — `Default::default()` in `from_model`; excluded from JSON output; included in `writable_fields()`
148/// - `#[serializer(source = "field_name")]` — reads from `model.field_name` instead of `model.<field_ident>`
149/// - `#[serializer(skip)]` — `Default::default()` in `from_model`; included in JSON output; excluded from `writable_fields()` (user sets manually)
150/// - `#[serializer(method = "fn_name")]` — computed field: calls `Self::fn_name(&model)` for the field value; excluded from `writable_fields()`
151/// - `#[serializer(nested)]` / `nested(strict)` — auto-resolves nested serializer from a loaded `ForeignKey`; excluded from `writable_fields()`
152/// - `#[serializer(many = ChildSerializer)]` — collection of nested serializers; populated via macro-emitted `set_<field>(&[Child::Model])`; excluded from `writable_fields()`
153/// - `#[serializer(slug = "name")]` — render a relation as one of its fields: clones `model.<source>.value()?.name`; excluded from `writable_fields()` (v0.44)
154/// - `#[serializer(validate = "fn_name")]` — per-field validator surfaced by `Self::validate(&self)`
155/// - `#[serializer(max_length = N)]` / `min_length` / `min` / `max` — declarative bounds checked on
156///   write; auto-inherit from the model's `FieldSchema` (`max_length`/`min`/`max`/`choices`) when
157///   no attr is given, override it when given (`min_length` is serializer-only)
158///
159/// The macro also emits a custom `impl serde::Serialize` — do **not** also `#[derive(Serialize)]`.
160#[proc_macro_derive(Serializer, attributes(serializer))]
161pub fn derive_serializer(input: TokenStream) -> TokenStream {
162    let input = parse_macro_input!(input as DeriveInput);
163    expand_serializer(&input)
164        .unwrap_or_else(syn::Error::into_compile_error)
165        .into()
166}
167
168/// Bake every `*.json` migration file in a directory into the binary
169/// at compile time. Returns a `&'static [(&'static str, &'static str)]`
170/// of `(name, json_content)` pairs, lex-sorted by file stem.
171///
172/// Pair with `rustango::migrate::migrate_embedded` at runtime — same
173/// behaviour as `migrate(pool, dir)` but with no filesystem access.
174/// The path is interpreted relative to the user's `CARGO_MANIFEST_DIR`
175/// (i.e. the crate that invokes the macro). Default is
176/// `"./migrations"` if no argument is supplied.
177///
178/// ```ignore
179/// const EMBEDDED: &[(&str, &str)] = rustango::embed_migrations!();
180/// // or:
181/// const EMBEDDED: &[(&str, &str)] = rustango::embed_migrations!("./migrations");
182///
183/// rustango::migrate::migrate_embedded(&pool, EMBEDDED).await?;
184/// ```
185///
186/// **Compile-time guarantees** (rustango v0.4+, slice 5): every JSON
187/// file's `name` field must equal its file stem, every `prev`
188/// reference must point to another migration in the same directory,
189/// and the JSON must parse. A broken chain — orphan `prev`, missing
190/// predecessor, malformed file — fails at macro-expansion time with
191/// a clear `compile_error!`. *No other Rust web framework
192/// validates migration chains at compile time*: Cot's migrations are
193/// imperative Rust code (no static chain), Loco's are SeaORM
194/// up/down (same), Rwf's are raw SQL (no chain at all).
195///
196/// Each migration is included via `include_str!` so cargo's rebuild
197/// detection picks up file *content* changes. **Caveat:** cargo
198/// doesn't watch directory listings, so adding or removing a
199/// migration file inside the dir won't auto-trigger a rebuild — run
200/// `cargo clean` (or just bump any other source file) when you add
201/// new migrations during embedded development.
202#[proc_macro]
203pub fn embed_migrations(input: TokenStream) -> TokenStream {
204    expand_embed_migrations(input.into())
205        .unwrap_or_else(syn::Error::into_compile_error)
206        .into()
207}
208
209/// `Q!()` — `Model.field__lookup = value` filter syntax, resolved at
210/// compile time against typed columns. Issue #269 / T1.7.
211///
212/// Each invocation lowers to the equivalent typed-column method call:
213///
214/// ```ignore
215/// // These expand identically:
216/// Q!(User.email__icontains = "alice")
217/// User::email.ilike("%alice%")
218/// ```
219///
220/// Field-name typos fail the build (the macro emits `User::no_such_field`
221/// which doesn't exist) — the headline ergonomic win of this slice over
222/// filters keyed by a plain string.
223///
224/// # Supported lookup suffixes
225///
226/// * bare `=` / `__exact` → `.eq(value)`
227/// * `__iexact` → `.ilike(value)` (case-insensitive equality, no wildcards)
228/// * `__ne` → `.ne(value)`
229/// * `__gt` / `__gte` / `__lt` / `__lte` → corresponding comparison
230/// * `__contains` / `__icontains` → `.like("%v%")` / `.ilike("%v%")`
231/// * `__startswith` / `__istartswith` → `.like("v%")` / `.ilike("v%")`
232/// * `__endswith` / `__iendswith` → `.like("%v")` / `.ilike("%v")`
233/// * `__in` → `.is_in(iterable)`
234/// * `__not_in` → `.not_in(iterable)`
235/// * `__isnull = true` → `.is_null()`; `__isnull = false` → `.is_not_null()`
236/// * `__between` accepts a tuple literal `(lo, hi)` → `.between(lo, hi)`
237/// * `__regex` / `__iregex` → `.regex(pattern)` / `.iregex(pattern)`
238///
239/// Unknown suffixes fail the build with a `compile_error!` pointing at
240/// the lookup token.
241///
242/// # Combine
243///
244/// Each `Q!()` returns a `TypedFilter<Model>` — chain via the existing
245/// `.and()` / `.or()` / `.not()` methods:
246///
247/// ```ignore
248/// User::objects()
249///     .where_(
250///         Q!(User.active = true)
251///             .and(Q!(User.email__icontains = "alice"))
252///     )
253///     .fetch(&pool).await?;
254/// ```
255///
256/// All emitted code routes through existing per-dialect writers — no new
257/// SQL emission machinery. Tri-dialect support is inherent.
258#[allow(non_snake_case)]
259#[proc_macro]
260pub fn Q(input: TokenStream) -> TokenStream {
261    expand_q(input.into())
262        .unwrap_or_else(syn::Error::into_compile_error)
263        .into()
264}
265
266/// `#[rustango::main]` — the runserver entrypoint. Wraps
267/// `#[tokio::main]` and a default `tracing_subscriber` initialisation
268/// (env-filter, falling back to `info,sqlx=warn`) so user `main`
269/// functions are zero-boilerplate:
270///
271/// ```ignore
272/// #[rustango::main]
273/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
274///     rustango::server::Builder::from_env().await?
275///         .migrate("migrations").await?
276///         .api(my_app::urls::api())
277///         .seed_with(my_app::seed::run).await?
278///         .serve("0.0.0.0:8080").await
279/// }
280/// ```
281///
282/// Optional `flavor = "current_thread"` passes through to
283/// `#[tokio::main]`; default is the multi-threaded runtime.
284///
285/// `logging = false` suppresses the default subscriber, for apps
286/// that install their own. Needed whenever the body reaches
287/// `Cli::with_logging()` or `logging::Setup`: the subscriber this
288/// macro installs gets there first, and `tracing` keeps the first
289/// one, so the `[logging]` section would otherwise be read and
290/// discarded (#1465).
291///
292/// ```ignore
293/// #[rustango::main(logging = false)]
294/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
295///     rustango::manage::Cli::new()
296///         .with_settings_from_env()
297///         .with_logging()          // now the first installer
298///         .run().await
299/// }
300/// ```
301///
302/// Pulls `tracing-subscriber` into the rustango crate behind the
303/// `runtime` sub-feature (implied by `tenancy`), so apps that opt
304/// out get plain `#[tokio::main]` ergonomics without the dependency.
305#[proc_macro_attribute]
306pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
307    expand_main(args.into(), item.into())
308        .unwrap_or_else(syn::Error::into_compile_error)
309        .into()
310}
311
312fn expand_main(args: TokenStream2, item: TokenStream2) -> syn::Result<TokenStream2> {
313    let mut input: syn::ItemFn = syn::parse2(item)?;
314    if input.sig.asyncness.is_none() {
315        return Err(syn::Error::new(
316            input.sig.ident.span(),
317            "`#[rustango::main]` must wrap an `async fn`",
318        ));
319    }
320
321    // v0.31.1 (#4): hand-roll the tokio runtime instead of delegating
322    // to `#[tokio::main]`. Tokio's proc-macro internally emits
323    // `::tokio::*` paths that resolve against the user crate's deps,
324    // so calling it through the rustango re-export still requires the
325    // user to add tokio to their own Cargo.toml. Building the
326    // runtime ourselves keeps the dep transitive through the
327    // `runtime` feature on rustango.
328    //
329    // Parse optional `flavor = "current_thread"` / `flavor =
330    // "multi_thread"` from the attribute args. Unknown args are
331    // tolerated (forward-compat with tokio's own arg surface).
332    let root = rustango_root();
333    let flavor = parse_flavor(&args);
334    let builder_call = match flavor {
335        Flavor::CurrentThread => quote! {
336            #root::__private_runtime::tokio::runtime::Builder::new_current_thread()
337        },
338        Flavor::MultiThread => quote! {
339            #root::__private_runtime::tokio::runtime::Builder::new_multi_thread()
340        },
341    };
342
343    // Detach the user body and rewrite `main` as a sync fn that
344    // builds the runtime and blocks on the async body.
345    let user_body = input.block.clone();
346    input.sig.asyncness = None;
347
348    // `logging = false` drops the block entirely, so a later
349    // `Cli::with_logging()` is the first installer and its
350    // `[logging]` settings actually take effect (#1465).
351    let logging_prologue = if parse_logging(&args) {
352        quote! {
353            use #root::__private_runtime::tracing_subscriber::{self, EnvFilter};
354            // Colour only when stdout is a terminal, and never under
355            // `NO_COLOR` — `Color::Auto`'s rule, called rather than
356            // copied.
357            //
358            // This was inlined at first, on a comment claiming
359            // `rustango::logging` is gated on `admin` + `tenancy`. It is
360            // not: `pub mod logging` is ungated and its contents are
361            // `runtime`-gated — the same feature that gates this macro
362            // (`pub use rustango_macros::main` is `#[cfg(feature =
363            // "runtime")]`). So wherever this expands, `Color` is
364            // reachable, and the copy was justified by a gate that does
365            // not exist. `should_colour` carries a deliberate
366            // `NO_COLOR`-set-but-empty subtlety that the inline happened
367            // to match today and nothing kept matching tomorrow.
368            //
369            // Without any of it the subscriber inherits
370            // tracing-subscriber's default, `cfg!(feature = "ansi")` —
371            // true since the framework turned that feature on — so
372            // `./app > app.log` and every container redirecting stdout
373            // collected escape codes. `Setup::install` has its own
374            // check; this is the default entrypoint and had none.
375            let __ansi = #root::logging::Color::Auto.should_colour();
376            // `try_init` so duplicate installers (e.g. tests already
377            // holding a subscriber) don't panic.
378            let _ = tracing_subscriber::fmt()
379                .with_env_filter(
380                    EnvFilter::try_from_default_env()
381                        .unwrap_or_else(|_| EnvFilter::new("info,sqlx=warn")),
382                )
383                .with_ansi(__ansi)
384                .try_init();
385        }
386    } else {
387        quote! {}
388    };
389
390    input.block = syn::parse2(quote! {{
391        { #logging_prologue }
392        let __rt = #builder_call
393            .enable_all()
394            .build()
395            .expect("failed to build tokio runtime");
396        __rt.block_on(async move #user_body)
397    }})?;
398
399    Ok(quote! {
400        #input
401    })
402}
403
404enum Flavor {
405    MultiThread,
406    CurrentThread,
407}
408
409fn parse_flavor(args: &TokenStream2) -> Flavor {
410    // Cheap parser: look for the literal token sequence
411    // `flavor = "current_thread"`. Everything else (including
412    // bare `multi_thread` or no args) defaults to multi-thread.
413    let s = args.to_string();
414    if s.contains("current_thread") {
415        Flavor::CurrentThread
416    } else {
417        Flavor::MultiThread
418    }
419}
420
421/// `false` when the attribute carries `logging = false` — the caller
422/// installs their own subscriber, usually via `Cli::with_logging`
423/// (#1465). Same cheap token match as `parse_flavor`.
424fn parse_logging(args: &TokenStream2) -> bool {
425    !args.to_string().replace(' ', "").contains("logging=false")
426}
427
428/// Parse form for `Q!()` — `<TypePath>.<Ident> = <Expr>`.
429struct QInput {
430    base_path: syn::Path,
431    field: syn::Ident,
432    value: syn::Expr,
433}
434
435impl syn::parse::Parse for QInput {
436    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
437        let base_path: syn::Path = input.parse()?;
438        input.parse::<syn::Token![.]>()?;
439        let field: syn::Ident = input.parse()?;
440        input.parse::<syn::Token![=]>()?;
441        let value: syn::Expr = input.parse()?;
442        Ok(QInput {
443            base_path,
444            field,
445            value,
446        })
447    }
448}
449
450fn expand_q(input: TokenStream2) -> syn::Result<TokenStream2> {
451    let q: QInput = syn::parse2(input)?;
452    let root = rustango_root();
453    let field_str = q.field.to_string();
454    let field_span = q.field.span();
455    let (base, suffix) = match field_str.find("__") {
456        Some(idx) => (&field_str[..idx], &field_str[idx + 2..]),
457        None => (field_str.as_str(), ""),
458    };
459    if base.is_empty() {
460        return Err(syn::Error::new(
461            field_span,
462            "Q!(): field name is empty before `__` suffix",
463        ));
464    }
465    let base_ident = syn::Ident::new(base, field_span);
466    let value = &q.value;
467    let path = &q.base_path;
468
469    // Most suffixes map directly to a Column method with the value
470    // forwarded unchanged. Some need value-shape massaging (wildcards
471    // for LIKE-family, tuple destructure for BETWEEN, literal-bool for
472    // ISNULL). Unknown suffixes fail the build.
473    let expanded = match suffix {
474        "" | "exact" => quote! {
475            #root::core::Column::eq(#path::#base_ident, #value)
476        },
477        "ne" => quote! {
478            #root::core::Column::ne(#path::#base_ident, #value)
479        },
480        "gt" => quote! {
481            #root::core::Column::gt(#path::#base_ident, #value)
482        },
483        "gte" => quote! {
484            #root::core::Column::gte(#path::#base_ident, #value)
485        },
486        "lt" => quote! {
487            #root::core::Column::lt(#path::#base_ident, #value)
488        },
489        "lte" => quote! {
490            #root::core::Column::lte(#path::#base_ident, #value)
491        },
492        // The escaped-LIKE lookups delegate to the typed Column
493        // methods, which escape the value and pair it with the
494        // *Escaped ops so `%` / `_` match literally on every dialect
495        // (#1257) — the macro no longer owns any pattern wrapping.
496        "iexact" => quote! {
497            #root::core::Column::iexact(#path::#base_ident, ::std::string::ToString::to_string(&(#value)))
498        },
499        "contains" => quote! {
500            #root::core::Column::contains(#path::#base_ident, ::std::string::ToString::to_string(&(#value)))
501        },
502        "icontains" => quote! {
503            #root::core::Column::icontains(#path::#base_ident, ::std::string::ToString::to_string(&(#value)))
504        },
505        "startswith" => quote! {
506            #root::core::Column::startswith(#path::#base_ident, ::std::string::ToString::to_string(&(#value)))
507        },
508        "istartswith" => quote! {
509            #root::core::Column::istartswith(#path::#base_ident, ::std::string::ToString::to_string(&(#value)))
510        },
511        "endswith" => quote! {
512            #root::core::Column::endswith(#path::#base_ident, ::std::string::ToString::to_string(&(#value)))
513        },
514        "iendswith" => quote! {
515            #root::core::Column::iendswith(#path::#base_ident, ::std::string::ToString::to_string(&(#value)))
516        },
517        "in" => quote! {
518            #root::core::Column::is_in(#path::#base_ident, #value)
519        },
520        "not_in" => quote! {
521            #root::core::Column::not_in(#path::#base_ident, #value)
522        },
523        "isnull" => {
524            // Must be a bool literal at macro time so we can route to
525            // is_null vs is_not_null without a runtime branch.
526            let b = match value {
527                syn::Expr::Lit(syn::ExprLit {
528                    lit: syn::Lit::Bool(b),
529                    ..
530                }) => b.value(),
531                _ => {
532                    return Err(syn::Error::new_spanned(
533                        value,
534                        "Q!(): `__isnull` requires a `true` or `false` literal",
535                    ));
536                }
537            };
538            if b {
539                quote! { #root::core::Column::is_null(#path::#base_ident) }
540            } else {
541                quote! { #root::core::Column::is_not_null(#path::#base_ident) }
542            }
543        }
544        "between" => {
545            // Accept a tuple literal `(lo, hi)`.
546            let tuple = match value {
547                syn::Expr::Tuple(t) if t.elems.len() == 2 => t,
548                _ => {
549                    return Err(syn::Error::new_spanned(
550                        value,
551                        "Q!(): `__between` requires a tuple literal `(lo, hi)`",
552                    ));
553                }
554            };
555            let lo = &tuple.elems[0];
556            let hi = &tuple.elems[1];
557            quote! { #root::core::Column::between(#path::#base_ident, #lo, #hi) }
558        }
559        "regex" => quote! {
560            #root::core::Column::regex(#path::#base_ident, #value)
561        },
562        "iregex" => quote! {
563            #root::core::Column::iregex(#path::#base_ident, #value)
564        },
565        _ => {
566            return Err(syn::Error::new(
567                field_span,
568                format!(
569                    "Q!(): unknown lookup suffix `__{}`. Supported: __exact / __iexact / __ne / __gt / __gte / __lt / __lte / __contains / __icontains / __startswith / __istartswith / __endswith / __iendswith / __in / __not_in / __isnull / __between / __regex / __iregex",
570                    suffix
571                ),
572            ));
573        }
574    };
575    Ok(expanded)
576}
577
578fn expand_embed_migrations(input: TokenStream2) -> syn::Result<TokenStream2> {
579    // Default to "./migrations" if invoked without args.
580    let path_str = if input.is_empty() {
581        "./migrations".to_string()
582    } else {
583        let lit: LitStr = syn::parse2(input)?;
584        lit.value()
585    };
586
587    let manifest = std::env::var("CARGO_MANIFEST_DIR").map_err(|_| {
588        syn::Error::new(
589            proc_macro2::Span::call_site(),
590            "embed_migrations! must be invoked during a Cargo build (CARGO_MANIFEST_DIR not set)",
591        )
592    })?;
593    let abs = std::path::Path::new(&manifest).join(&path_str);
594
595    let mut entries: Vec<(String, std::path::PathBuf)> = Vec::new();
596    if abs.is_dir() {
597        let read = std::fs::read_dir(&abs).map_err(|e| {
598            syn::Error::new(
599                proc_macro2::Span::call_site(),
600                format!("embed_migrations!: cannot read {}: {e}", abs.display()),
601            )
602        })?;
603        for entry in read.flatten() {
604            let path = entry.path();
605            if !path.is_file() {
606                continue;
607            }
608            if path.extension().and_then(|s| s.to_str()) != Some("json") {
609                continue;
610            }
611            let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
612                continue;
613            };
614            entries.push((stem.to_owned(), path));
615        }
616    }
617    entries.sort_by(|a, b| a.0.cmp(&b.0));
618
619    // Compile-time chain validation: read each migration's JSON,
620    // pull `name` and `prev` (file-stem-keyed for the chain check),
621    // and verify every `prev` points to another migration in the
622    // slice. Mismatches between the file stem and the embedded
623    // `name` field — and broken `prev` chains — fail at MACRO
624    // EXPANSION time so a misshapen migration set never compiles.
625    //
626    // This is the v0.4 Slice 5 distinguisher: rustango's JSON
627    // migrations + a Rust proc-macro that reads them is a combo no
628    // other Rust web framework matches (Cot's are imperative Rust
629    // code, Loco's are SeaORM up/down, Rwf's are raw SQL — none have
630    // a static chain to validate).
631    let mut chain_names: Vec<String> = Vec::with_capacity(entries.len());
632    let mut prev_refs: Vec<(String, Option<String>)> = Vec::with_capacity(entries.len());
633    for (stem, path) in &entries {
634        let raw = std::fs::read_to_string(path).map_err(|e| {
635            syn::Error::new(
636                proc_macro2::Span::call_site(),
637                format!(
638                    "embed_migrations!: cannot read {} for chain validation: {e}",
639                    path.display()
640                ),
641            )
642        })?;
643        let json: serde_json::Value = serde_json::from_str(&raw).map_err(|e| {
644            syn::Error::new(
645                proc_macro2::Span::call_site(),
646                format!(
647                    "embed_migrations!: {} is not valid JSON: {e}",
648                    path.display()
649                ),
650            )
651        })?;
652        let name = json
653            .get("name")
654            .and_then(|v| v.as_str())
655            .ok_or_else(|| {
656                syn::Error::new(
657                    proc_macro2::Span::call_site(),
658                    format!(
659                        "embed_migrations!: {} is missing the `name` field",
660                        path.display()
661                    ),
662                )
663            })?
664            .to_owned();
665        if name != *stem {
666            return Err(syn::Error::new(
667                proc_macro2::Span::call_site(),
668                format!(
669                    "embed_migrations!: file stem `{stem}` does not match the migration's \
670                     `name` field `{name}` — rename the file or fix the JSON",
671                ),
672            ));
673        }
674        let prev = json.get("prev").and_then(|v| v.as_str()).map(str::to_owned);
675        chain_names.push(name.clone());
676        prev_refs.push((name, prev));
677    }
678
679    let name_set: std::collections::HashSet<&str> =
680        chain_names.iter().map(String::as_str).collect();
681    for (name, prev) in &prev_refs {
682        if let Some(p) = prev {
683            if !name_set.contains(p.as_str()) {
684                return Err(syn::Error::new(
685                    proc_macro2::Span::call_site(),
686                    format!(
687                        "embed_migrations!: broken migration chain — `{name}` declares \
688                         prev=`{p}` but no migration with that name exists in {}",
689                        abs.display()
690                    ),
691                ));
692            }
693        }
694    }
695
696    let pairs: Vec<TokenStream2> = entries
697        .iter()
698        .map(|(name, path)| {
699            let path_lit = path.display().to_string();
700            quote! { (#name, ::core::include_str!(#path_lit)) }
701        })
702        .collect();
703
704    Ok(quote! {
705        {
706            const __RUSTANGO_EMBEDDED: &[(&'static str, &'static str)] = &[#(#pairs),*];
707            __RUSTANGO_EMBEDDED
708        }
709    })
710}
711
712fn expand(input: &DeriveInput) -> syn::Result<TokenStream2> {
713    let root = rustango_root();
714    let struct_name = &input.ident;
715
716    let Data::Struct(data) = &input.data else {
717        return Err(syn::Error::new_spanned(
718            struct_name,
719            "Model can only be derived on structs",
720        ));
721    };
722    let Fields::Named(named) = &data.fields else {
723        return Err(syn::Error::new_spanned(
724            struct_name,
725            "Model requires a struct with named fields",
726        ));
727    };
728
729    let container = parse_container_attrs(input)?;
730    let table = container
731        .table
732        .unwrap_or_else(|| to_snake_case(&struct_name.to_string()));
733    let model_name = struct_name.to_string();
734
735    let collected = collect_fields(named, &table)?;
736
737    // Validate that #[rustango(display = "…")] names a real field.
738    if let Some((ref display, span)) = container.display {
739        if !collected.field_names.iter().any(|n| n == display) {
740            return Err(syn::Error::new(
741                span,
742                format!("`display = \"{display}\"` does not match any field on this struct"),
743            ));
744        }
745    }
746    let display = container.display.map(|(name, _)| name);
747    let app_label = container.app.clone();
748
749    // Validate admin field-name lists against declared field names.
750    // Note: `list_display` is intentionally NOT validated here. As of
751    // v0.32 it may also reference inventory-registered computed
752    // fields (via `register_admin_computed!`) whose existence the
753    // macro can't see at compile time — they're submitted from any
754    // crate that depends on rustango. The runtime list-view resolves
755    // unknown names against the inventory + silently drops the
756    // truly-bogus ones, which is the cheaper trade-off versus
757    // forcing a per-Model attr to opt out.
758    if let Some(admin) = &container.admin {
759        for (label, list) in [
760            ("search_fields", &admin.search_fields),
761            ("readonly_fields", &admin.readonly_fields),
762            ("list_filter", &admin.list_filter),
763        ] {
764            if let Some((names, span)) = list {
765                for name in names {
766                    if !collected.field_names.iter().any(|n| n == name) {
767                        return Err(syn::Error::new(
768                            *span,
769                            format!(
770                                "`{label} = \"{name}\"`: \"{name}\" is not a declared field on this struct"
771                            ),
772                        ));
773                    }
774                }
775            }
776        }
777        if let Some((pairs, span)) = &admin.ordering {
778            for (name, _) in pairs {
779                if !collected.field_names.iter().any(|n| n == name) {
780                    return Err(syn::Error::new(
781                        *span,
782                        format!(
783                            "`ordering = \"{name}\"`: \"{name}\" is not a declared field on this struct"
784                        ),
785                    ));
786                }
787            }
788        }
789        if let Some((groups, span)) = &admin.fieldsets {
790            for (_, fields) in groups {
791                for name in fields {
792                    if !collected.field_names.iter().any(|n| n == name) {
793                        return Err(syn::Error::new(
794                            *span,
795                            format!(
796                                "`fieldsets`: \"{name}\" is not a declared field on this struct"
797                            ),
798                        ));
799                    }
800                }
801            }
802        }
803    }
804    if let Some(audit) = &container.audit {
805        if let Some((names, span)) = &audit.track {
806            for name in names {
807                if !collected.field_names.iter().any(|n| n == name) {
808                    return Err(syn::Error::new(
809                        *span,
810                        format!(
811                            "`audit(track = \"{name}\")`: \"{name}\" is not a declared field on this struct"
812                        ),
813                    ));
814                }
815            }
816        }
817    }
818
819    // Issue #291 / T2.5 — validate each `default_order` column name
820    // against the model's collected fields. Typos fail at macro-expand
821    // time, not at the database.
822    for (col, _desc, span) in &container.default_order {
823        if !collected.field_names.iter().any(|n| n == col) {
824            return Err(syn::Error::new(
825                *span,
826                format!(
827                    "`default_order = \"...\"`: \"{col}\" is not a declared field on this struct"
828                ),
829            ));
830        }
831    }
832
833    // Build the audit_track list for ModelSchema: None when no audit attr,
834    // Some(empty) when audit present without track, Some(names) when explicit.
835    let audit_track_names: Option<Vec<String>> = container.audit.as_ref().map(|audit| {
836        audit
837            .track
838            .as_ref()
839            .map(|(names, _)| names.clone())
840            .unwrap_or_default()
841    });
842
843    // Merge field-level indexes into the container's index list.
844    let mut all_indexes: Vec<IndexAttr> = container.indexes;
845    for field in &named.named {
846        let ident = field.ident.as_ref().expect("named");
847        let col = to_snake_case(&ident.to_string()); // column name fallback
848                                                     // Re-parse field attrs to check for index flag
849        if let Ok(fa) = parse_field_attrs(field) {
850            if fa.index {
851                let col_name = fa.column.clone().unwrap_or_else(|| col.clone());
852                let auto_name = if fa.index_unique {
853                    format!("{table}_{col_name}_uq_idx")
854                } else {
855                    format!("{table}_{col_name}_idx")
856                };
857                all_indexes.push(IndexAttr {
858                    name: fa.index_name.or(Some(auto_name)),
859                    columns: vec![col_name],
860                    unique: fa.index_unique,
861                    method: fa.index_method,
862                    where_clause: None,
863                    include: Vec::new(),
864                });
865            }
866        }
867    }
868
869    let model_impl = model_impl_tokens(
870        struct_name,
871        &model_name,
872        &table,
873        display.as_deref(),
874        app_label.as_deref(),
875        container.admin.as_ref(),
876        &container.default_order,
877        &collected.field_schemas,
878        collected.soft_delete_column.as_deref(),
879        container.permissions,
880        audit_track_names.as_deref(),
881        &container.m2m,
882        &all_indexes,
883        &container.checks,
884        &container.excludes,
885        &container.composite_fks,
886        &container.generic_fks,
887        container.scope.as_deref(),
888        container.is_view,
889        container.verbose_name.as_deref(),
890        container.verbose_name_plural.as_deref(),
891        container.managed,
892        container.base_manager_name.as_deref(),
893        container.order_with_respect_to.as_deref(),
894        container.proxy,
895        &container.required_db_features,
896        container.required_db_vendor.as_deref(),
897        container.default_related_name.as_deref(),
898        container.db_table_comment.as_deref(),
899        container
900            .get_latest_by
901            .as_ref()
902            .map(|(c, d)| (c.as_str(), *d)),
903        &container.extra_permissions,
904        &container.default_permissions,
905        &container.global_scopes,
906        &container.reverse_has_relations,
907        &container.generic_has_relations,
908    );
909    let module_ident = column_module_ident(struct_name);
910    let column_consts = column_const_tokens(&module_ident, &collected.column_entries);
911    let audited_fields: Option<Vec<&ColumnEntry>> = container.audit.as_ref().map(|audit| {
912        let track_set: Option<std::collections::HashSet<&str>> = audit
913            .track
914            .as_ref()
915            .map(|(names, _)| names.iter().map(String::as_str).collect());
916        collected
917            .column_entries
918            .iter()
919            .filter(|c| {
920                track_set
921                    .as_ref()
922                    .map_or(true, |s| s.contains(c.name.as_str()))
923            })
924            .collect()
925    });
926    let inherent_impl = inherent_impl_tokens(
927        struct_name,
928        &collected,
929        collected.primary_key.as_ref(),
930        &column_consts,
931        audited_fields.as_deref(),
932        &all_indexes,
933        &container.manager_fns,
934    );
935    let column_module = column_module_tokens(&module_ident, struct_name, &collected.column_entries);
936    let from_row_impl = from_row_impl_tokens(struct_name, &collected.from_row_inits);
937    let reverse_helpers = reverse_helper_tokens(
938        struct_name,
939        &collected.fk_relations,
940        container.default_related_name.as_deref(),
941    );
942    let m2m_accessors = m2m_accessor_tokens(struct_name, &container.m2m);
943    let generic_m2m_accessors = generic_m2m_accessor_tokens(struct_name, &container.generic_m2m);
944    // Issue #817 — `#[rustango(through(...))]` accessors.
945    let through_accessors = through_accessor_tokens(struct_name, &container.through_relations);
946    // Issue #830 — `#[rustango(reverse_has(...))]` static accessors.
947    let reverse_has_accessors =
948        reverse_has_accessor_tokens(struct_name, &container.reverse_has_relations);
949    let generic_fk_accessors = generic_fk_accessor_tokens(
950        struct_name,
951        &container.generic_fks,
952        &collected.column_entries,
953    );
954
955    // Issue #271 / T1.9 — `#[rustango(manager(ext = "FooManagerExt"))]`
956    // emits an empty extension trait so users can add methods via
957    // `impl FooManagerExt for QuerySet<Foo>` without hand-writing the
958    // trait declaration. See `crates/rustango/src/manager.rs` for the
959    // pattern this replaces.
960    let manager_trait = container.manager_ext.as_ref().map(|name| {
961        let model_name_str = struct_name.to_string();
962        let doc = format!(
963            "Custom-Manager extension trait for [`{model_name_str}`]. \
964             Generated by `#[rustango(manager(ext = ...))]`. Add methods \
965             via `impl {name} for QuerySet<{model_name_str}> {{ ... }}`."
966        );
967        quote! {
968            #[doc = #doc]
969            pub trait #name: ::core::marker::Sized {}
970        }
971    });
972
973    Ok(quote! {
974        #model_impl
975        #inherent_impl
976        #from_row_impl
977        #column_module
978        #reverse_helpers
979        #m2m_accessors
980        #generic_m2m_accessors
981        #through_accessors
982        #reverse_has_accessors
983        #generic_fk_accessors
984        #manager_trait
985
986        #root::core::inventory::submit! {
987            #root::core::ModelEntry {
988                schema: <#struct_name as #root::core::Model>::SCHEMA,
989                // `module_path!()` evaluates at the registration site,
990                // so a Model declared in `crate::blog::models` records
991                // `"<crate>::blog::models"` and `resolved_app_label()`
992                // can infer "blog" without an explicit attribute.
993                module_path: ::core::module_path!(),
994            }
995        }
996    })
997}
998
999/// Emit `impl LoadRelated for #StructName` — slice 9.0d. Pattern-
1000/// matches `field_name` against the model's FK fields and, for a
1001/// match, decodes the FK target via the parent's macro-generated
1002/// `__rustango_from_aliased_row`, reads the parent's PK, and stores
1003/// `ForeignKey::Loaded` on `self`.
1004///
1005/// Always emitted (with empty arms for FK-less models, which
1006/// return `Ok(false)` for any field name) so the `T: LoadRelated`
1007/// trait bound on `fetch_on` is universally satisfied — users
1008/// never have to think about implementing it.
1009fn load_related_impl_tokens(struct_name: &syn::Ident, fk_relations: &[FkRelation]) -> TokenStream2 {
1010    let root = rustango_root();
1011    let arms = fk_relations.iter().map(|rel| {
1012        let parent_ty = &rel.parent_type;
1013        let fk_col = rel.fk_column.as_str();
1014        // FK field's Rust ident matches its SQL column name in v0.8
1015        // (no `column = "..."` rename ships on FK fields).
1016        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
1017        let (variant_ident, default_expr) = rel.pk_kind.sqlvalue_match_arm();
1018        let assign = if rel.nullable {
1019            quote! {
1020                self.#field_ident = ::core::option::Option::Some(
1021                    #root::sql::ForeignKey::loaded(_pk, _parent),
1022                );
1023            }
1024        } else {
1025            quote! {
1026                self.#field_ident = #root::sql::ForeignKey::loaded(_pk, _parent);
1027            }
1028        };
1029        quote! {
1030            #fk_col => {
1031                let mut _parent: #parent_ty = <#parent_ty>::__rustango_from_aliased_row(row, alias)?;
1032                // Audit #451 — multi-hop `select_related("a__b__c")`:
1033                // stitch the deeper relation onto this parent first,
1034                // decoding it at the accumulated `__next_alias`. The
1035                // parent type also impls `LoadRelated`, so this recurses
1036                // the FK chain to arbitrary depth.
1037                if let ::core::option::Option::Some(__r) = __rest {
1038                    let _ = #root::sql::LoadRelated::__rustango_load_related(
1039                        &mut _parent, row, __r, &__next_alias,
1040                    )?;
1041                }
1042                // Loud-in-debug, default-in-release: a divergence
1043                // between the FK field's declared `K` (drives the
1044                // expected `SqlValue::<Variant>`) and the parent's
1045                // `__rustango_pk_value` output is a macro-internal
1046                // invariant break — surfacing the panic in dev
1047                // catches it before users hit silent PK=0 corruption.
1048                let _pk = match <#parent_ty>::__rustango_pk_value(&_parent) {
1049                    #root::core::SqlValue::#variant_ident(v) => v,
1050                    _other => {
1051                        ::core::debug_assert!(
1052                            false,
1053                            "rustango macro bug: load_related on FK `{}` expected \
1054                             SqlValue::{} from parent's __rustango_pk_value but got \
1055                             {:?} — file a bug at https://github.com/ujeenet/rustango",
1056                            #fk_col,
1057                            ::core::stringify!(#variant_ident),
1058                            _other,
1059                        );
1060                        #default_expr
1061                    }
1062                };
1063                #assign
1064                ::core::result::Result::Ok(true)
1065            }
1066        }
1067    });
1068    quote! {
1069        #[cfg(feature = "postgres")]
1070        impl #root::sql::LoadRelated for #struct_name {
1071            #[allow(unused_variables)]
1072            fn __rustango_load_related(
1073                &mut self,
1074                row: &#root::sql::sqlx::postgres::PgRow,
1075                field_name: &str,
1076                alias: &str,
1077            ) -> ::core::result::Result<bool, #root::sql::sqlx::Error> {
1078                // Audit #451 — split the multi-hop path: `base` is the FK
1079                // on THIS model, `__rest` (if any) is the remaining chain
1080                // to stitch onto the loaded parent. `__next_alias` is the
1081                // accumulated join alias the parent's columns live under
1082                // (`{alias}__{next-hop}`), matching `lower_select_related`.
1083                let (__base, __rest): (&str, ::core::option::Option<&str>) =
1084                    match field_name.split_once("__") {
1085                        ::core::option::Option::Some((b, r)) => (b, ::core::option::Option::Some(r)),
1086                        ::core::option::Option::None => (field_name, ::core::option::Option::None),
1087                    };
1088                let __next_alias: ::std::string::String = match __rest {
1089                    ::core::option::Option::Some(__r) => {
1090                        let __rb = __r.split_once("__").map(|(b, _)| b).unwrap_or(__r);
1091                        ::std::format!("{}__{}", alias, __rb)
1092                    }
1093                    ::core::option::Option::None => ::std::string::String::new(),
1094                };
1095                match __base {
1096                    #( #arms )*
1097                    _ => ::core::result::Result::Ok(false),
1098                }
1099            }
1100        }
1101    }
1102}
1103
1104/// MySQL counterpart of [`load_related_impl_tokens`] — v0.23.0-batch8.
1105/// Emits a call to the cfg-gated `__impl_my_load_related!` macro_rules,
1106/// which expands to a `LoadRelatedMy` impl when rustango is built with
1107/// the `mysql` feature, and to nothing otherwise. The decoded parent
1108/// is read via `__rustango_from_aliased_my_row` (the MySQL aliased
1109/// decoder, also batch8) so the dual emission is symmetric across
1110/// backends.
1111fn load_related_impl_my_tokens(
1112    struct_name: &syn::Ident,
1113    fk_relations: &[FkRelation],
1114) -> TokenStream2 {
1115    let root = rustango_root();
1116    let arms = fk_relations.iter().map(|rel| {
1117        let parent_ty = &rel.parent_type;
1118        let fk_col = rel.fk_column.as_str();
1119        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
1120        let (variant_ident, default_expr) = rel.pk_kind.sqlvalue_match_arm();
1121        let assign = if rel.nullable {
1122            quote! {
1123                __self.#field_ident = ::core::option::Option::Some(
1124                    #root::sql::ForeignKey::loaded(_pk, _parent),
1125                );
1126            }
1127        } else {
1128            quote! {
1129                __self.#field_ident = #root::sql::ForeignKey::loaded(_pk, _parent);
1130            }
1131        };
1132        // `self` IS hygiene-tracked through macro_rules — emitted from
1133        // a different context than the `&mut self` parameter inside
1134        // the macro_rules-expanded fn. Pass it through as `__self`
1135        // and let the macro_rules rebind it to the receiver.
1136        quote! {
1137            #fk_col => {
1138                let mut _parent: #parent_ty =
1139                    <#parent_ty>::__rustango_from_aliased_my_row(row, alias)?;
1140                // Audit #451 — multi-hop: stitch the deeper relation onto
1141                // the parent at the accumulated alias (see PG twin).
1142                if let ::core::option::Option::Some(__r) = __rest {
1143                    let _ = #root::sql::LoadRelatedMy::__rustango_load_related_my(
1144                        &mut _parent, row, __r, &__next_alias,
1145                    )?;
1146                }
1147                // See note in `load_related_impl_tokens` (PG twin) —
1148                // the same loud-in-debug invariant guard.
1149                let _pk = match <#parent_ty>::__rustango_pk_value(&_parent) {
1150                    #root::core::SqlValue::#variant_ident(v) => v,
1151                    _other => {
1152                        ::core::debug_assert!(
1153                            false,
1154                            "rustango macro bug: load_related on FK `{}` expected \
1155                             SqlValue::{} from parent's __rustango_pk_value but got \
1156                             {:?} — file a bug at https://github.com/ujeenet/rustango",
1157                            #fk_col,
1158                            ::core::stringify!(#variant_ident),
1159                            _other,
1160                        );
1161                        #default_expr
1162                    }
1163                };
1164                #assign
1165                ::core::result::Result::Ok(true)
1166            }
1167        }
1168    });
1169    quote! {
1170        #root::__impl_my_load_related!(#struct_name, |__self, row, field_name, alias, __rest, __next_alias| {
1171            #( #arms )*
1172        });
1173    }
1174}
1175
1176/// Same shape as [`load_related_impl_my_tokens`] but for SQLite.
1177/// Emits a call to `__impl_sqlite_load_related!` which expands to a
1178/// `LoadRelatedSqlite` impl when the `sqlite` feature is on.
1179fn load_related_impl_sqlite_tokens(
1180    struct_name: &syn::Ident,
1181    fk_relations: &[FkRelation],
1182) -> TokenStream2 {
1183    let root = rustango_root();
1184    let arms = fk_relations.iter().map(|rel| {
1185        let parent_ty = &rel.parent_type;
1186        let fk_col = rel.fk_column.as_str();
1187        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
1188        let (variant_ident, default_expr) = rel.pk_kind.sqlvalue_match_arm();
1189        let assign = if rel.nullable {
1190            quote! {
1191                __self.#field_ident = ::core::option::Option::Some(
1192                    #root::sql::ForeignKey::loaded(_pk, _parent),
1193                );
1194            }
1195        } else {
1196            quote! {
1197                __self.#field_ident = #root::sql::ForeignKey::loaded(_pk, _parent);
1198            }
1199        };
1200        quote! {
1201            #fk_col => {
1202                let mut _parent: #parent_ty =
1203                    <#parent_ty>::__rustango_from_aliased_sqlite_row(row, alias)?;
1204                // Audit #451 — multi-hop: stitch the deeper relation onto
1205                // the parent at the accumulated alias (see PG twin).
1206                if let ::core::option::Option::Some(__r) = __rest {
1207                    let _ = #root::sql::LoadRelatedSqlite::__rustango_load_related_sqlite(
1208                        &mut _parent, row, __r, &__next_alias,
1209                    )?;
1210                }
1211                let _pk = match <#parent_ty>::__rustango_pk_value(&_parent) {
1212                    #root::core::SqlValue::#variant_ident(v) => v,
1213                    _other => {
1214                        ::core::debug_assert!(
1215                            false,
1216                            "rustango macro bug: load_related on FK `{}` expected \
1217                             SqlValue::{} from parent's __rustango_pk_value but got \
1218                             {:?} — file a bug at https://github.com/ujeenet/rustango",
1219                            #fk_col,
1220                            ::core::stringify!(#variant_ident),
1221                            _other,
1222                        );
1223                        #default_expr
1224                    }
1225                };
1226                #assign
1227                ::core::result::Result::Ok(true)
1228            }
1229        }
1230    });
1231    quote! {
1232        #root::__impl_sqlite_load_related!(#struct_name, |__self, row, field_name, alias, __rest, __next_alias| {
1233            #( #arms )*
1234        });
1235    }
1236}
1237
1238/// Emit `impl FkPkAccess for #StructName` — slice 9.0e. Pattern-
1239/// matches `field_name` against the model's FK fields and returns
1240/// the FK's stored PK as `i64`. Used by `fetch_with_prefetch` to
1241/// group children by parent PK.
1242///
1243/// Always emitted (with `_ => None` for FK-less models) so the
1244/// trait bound on `fetch_with_prefetch` is universally satisfied.
1245fn fk_pk_access_impl_tokens(struct_name: &syn::Ident, fk_relations: &[FkRelation]) -> TokenStream2 {
1246    let root = rustango_root();
1247    let arms = fk_relations.iter().map(|rel| {
1248        let fk_col = rel.fk_column.as_str();
1249        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
1250        if rel.pk_kind == DetectedKind::I64 {
1251            // i64 FK — return the stored PK so prefetch_related can
1252            // group children by it. Nullable variant unwraps via
1253            // `as_ref().map(...)`: an unset (NULL) FK column yields
1254            // `None` and that child sits out of the grouping (correct
1255            // semantics — it has no parent to attach to).
1256            if rel.nullable {
1257                quote! {
1258                    #fk_col => self.#field_ident
1259                        .as_ref()
1260                        .map(|fk| #root::sql::ForeignKey::pk(fk)),
1261                }
1262            } else {
1263                quote! {
1264                    #fk_col => ::core::option::Option::Some(self.#field_ident.pk()),
1265                }
1266            }
1267        } else {
1268            // Non-i64 FK PKs (e.g. `ForeignKey<T, String>`,
1269            // `ForeignKey<T, Uuid>`) opt out of `prefetch_related`'s
1270            // i64-keyed grouping path — the trait signature is
1271            // `Option<i64>` and a non-i64 PK can't lower into it.
1272            // The FK still works for everything else (CRUD, lazy
1273            // load via `.get()`, select_related JOINs); only the
1274            // bulk prefetch grouper needs the integer key.
1275            quote! {
1276                #fk_col => ::core::option::Option::None,
1277            }
1278        }
1279    });
1280    // PK-type-agnostic version: every FK arm emits an
1281    // `Option<SqlValue>` so `fetch_with_prefetch` can group by any
1282    // PK type (i64, i32, String, Uuid). Models with non-i64 FK PKs
1283    // opt OUT of the legacy i64 method (it returns None) but opt IN
1284    // here.
1285    let value_arms = fk_relations.iter().map(|rel| {
1286        let fk_col = rel.fk_column.as_str();
1287        let field_ident = syn::Ident::new(fk_col, proc_macro2::Span::call_site());
1288        if rel.nullable {
1289            quote! {
1290                #fk_col => self.#field_ident
1291                    .as_ref()
1292                    .map(|fk| ::core::convert::Into::<#root::core::SqlValue>::into(
1293                        #root::sql::ForeignKey::pk(fk)
1294                    )),
1295            }
1296        } else {
1297            quote! {
1298                #fk_col => ::core::option::Option::Some(
1299                    ::core::convert::Into::<#root::core::SqlValue>::into(
1300                        self.#field_ident.pk()
1301                    )
1302                ),
1303            }
1304        }
1305    });
1306    quote! {
1307        impl #root::sql::FkPkAccess for #struct_name {
1308            #[allow(unused_variables)]
1309            fn __rustango_fk_pk(&self, field_name: &str) -> ::core::option::Option<i64> {
1310                match field_name {
1311                    #( #arms )*
1312                    _ => ::core::option::Option::None,
1313                }
1314            }
1315            #[allow(unused_variables)]
1316            fn __rustango_fk_pk_value(
1317                &self,
1318                field_name: &str,
1319            ) -> ::core::option::Option<#root::core::SqlValue> {
1320                match field_name {
1321                    #( #value_arms )*
1322                    _ => ::core::option::Option::None,
1323                }
1324            }
1325        }
1326    }
1327}
1328
1329/// For every `ForeignKey<Parent>` field on `Child`, emit
1330/// `impl Parent { pub async fn <child_table>_set(&self, executor) -> Vec<Child> }`.
1331/// Reads the parent's PK via the macro-generated `__rustango_pk_value`
1332/// and runs a single `SELECT … FROM <child_table> WHERE <fk_column> = $1`
1333/// — the canonical reverse-FK fetch. One round trip, no N+1.
1334///
1335/// **PG-only emission**: the accessor is bounded on
1336/// `sqlx::Executor<Database = sqlx::Postgres>` and calls `fetch_on`,
1337/// both of which are gated behind the `postgres` cargo feature. The
1338/// emitted code is wrapped in `#[cfg(feature = "postgres")]` so the
1339/// model derive itself compiles on tri-dialect / sqlite-only
1340/// downstream builds — the accessor just isn't materialised. A tri-
1341/// dialect `_set_pool` variant is a separate follow-up.
1342fn reverse_helper_tokens(
1343    child_ident: &syn::Ident,
1344    fk_relations: &[FkRelation],
1345    default_related_name: Option<&str>,
1346) -> TokenStream2 {
1347    let root = rustango_root();
1348    if fk_relations.is_empty() {
1349        return TokenStream2::new();
1350    }
1351    // Method-name resolution per FK (issue #816 + follow-up):
1352    //   1. Field-level `#[rustango(related_name = "...")]` on the FK
1353    //      itself — wins over everything else.
1354    //   2. Container-level `default_related_name = "..."` on the
1355    //      child. Applies to every FK on this model that didn't
1356    //      override.
1357    //   3. Fallback: `<child_snake>_set`. `Post` → `post_set`,
1358    //      `BlogComment` → `blog_comment_set`. Avoids English-plural
1359    //      edge cases.
1360    //
1361    // The PG-on-executor variant keeps the resolved name; the
1362    // tri-dialect `_pool` variant appends `_pool` to it (matches the
1363    // framework's convention for the `&Pool` flavor of every helper).
1364    let default_pg_suffix = default_related_name
1365        .map(str::to_owned)
1366        .unwrap_or_else(|| format!("{}_set", to_snake_case(&child_ident.to_string())));
1367    let impls = fk_relations.iter().map(|rel| {
1368        let pg_suffix = rel
1369            .related_name
1370            .clone()
1371            .unwrap_or_else(|| default_pg_suffix.clone());
1372        let pool_suffix = format!("{}_pool", pg_suffix);
1373        let pg_method_ident = syn::Ident::new(&pg_suffix, child_ident.span());
1374        let pool_method_ident = syn::Ident::new(&pool_suffix, child_ident.span());
1375        let parent_ty = &rel.parent_type;
1376        let fk_col = rel.fk_column.as_str();
1377        let doc = format!(
1378            "Fetch every `{child_ident}` whose `{fk_col}` foreign key points at this row. \
1379             Single SQL query — `SELECT … FROM <{child_ident} table> WHERE {fk_col} = $1` — \
1380             generated from the FK declaration on `{child_ident}::{fk_col}`. Composes with \
1381             further `{child_ident}::objects()` filters via direct queryset use."
1382        );
1383        let pool_doc = format!(
1384            "Tri-dialect counterpart of [`Self::{pg_suffix}`] — takes \
1385             [`#root::sql::Pool`] and dispatches per backend so the \
1386             reverse-FK fetch works on PG / MySQL / SQLite under one method. \
1387             Use this from framework code that holds a `&Pool` (admin, \
1388             tenancy resolver, viewset handlers); reach for the executor- \
1389             bound variant when you already have a typed `sqlx::Executor`."
1390        );
1391        quote! {
1392            #[cfg(feature = "postgres")]
1393            impl #parent_ty {
1394                #[doc = #doc]
1395                ///
1396                /// # Errors
1397                /// Returns [`#root::sql::ExecError`] for SQL-writing
1398                /// or driver failures.
1399                pub async fn #pg_method_ident<'_c, _E>(
1400                    &self,
1401                    _executor: _E,
1402                ) -> ::core::result::Result<
1403                    ::std::vec::Vec<#child_ident>,
1404                    #root::sql::ExecError,
1405                >
1406                where
1407                    _E: #root::sql::sqlx::Executor<
1408                        '_c,
1409                        Database = #root::sql::sqlx::Postgres,
1410                    >,
1411                {
1412                    let _pk: #root::core::SqlValue = self.__rustango_pk_value();
1413                    #root::query::QuerySet::<#child_ident>::new()
1414                        .filter_op(#fk_col, #root::core::Op::Eq, _pk)
1415                        .fetch_on(_executor)
1416                        .await
1417                }
1418            }
1419
1420            impl #parent_ty {
1421                #[doc = #pool_doc]
1422                ///
1423                /// # Errors
1424                /// Returns [`#root::sql::ExecError`] for SQL-writing
1425                /// or driver failures.
1426                pub async fn #pool_method_ident(
1427                    &self,
1428                    pool: &#root::sql::Pool,
1429                ) -> ::core::result::Result<
1430                    ::std::vec::Vec<#child_ident>,
1431                    #root::sql::ExecError,
1432                > {
1433                    use #root::sql::FetcherPool as _;
1434                    let _pk: #root::core::SqlValue = self.__rustango_pk_value();
1435                    #root::query::QuerySet::<#child_ident>::new()
1436                        .filter_op(#fk_col, #root::core::Op::Eq, _pk)
1437                        .fetch(pool)
1438                        .await
1439                }
1440            }
1441        }
1442    });
1443    quote! { #( #impls )* }
1444}
1445
1446/// Emit `<name>_m2m(&self) -> M2MManager` inherent methods for every M2M
1447/// relation declared on the model.
1448/// Emit `{name}_pool` accessor + `set_{name}_for` setter for every
1449/// `#[rustango(generic_fk(name, ct_column, pk_column))]` declaration.
1450///
1451/// Closes #239 + #240 — `comment.content_object` /
1452/// `comment.content_object = post` ergonomics on top of the existing
1453/// `GenericForeignKey { content_type_id, object_pk }` primitive.
1454///
1455/// `column_entries` is passed so we can resolve each `ct_column` /
1456/// `pk_column` SQL name back to its Rust field ident — the macro
1457/// only sees the column-side strings in the attribute, but the
1458/// emitted accessor needs to read the actual struct field.
1459fn generic_fk_accessor_tokens(
1460    struct_name: &syn::Ident,
1461    generic_fks: &[GenericFkAttr],
1462    column_entries: &[ColumnEntry],
1463) -> TokenStream2 {
1464    let root = rustango_root();
1465    if generic_fks.is_empty() {
1466        return TokenStream2::new();
1467    }
1468    let methods = generic_fks.iter().filter_map(|gfk| {
1469        // Resolve `ct_column` + `pk_column` to the struct's Rust
1470        // field idents. A typo (column name doesn't match any field)
1471        // emits no method for that registration — the user will see
1472        // the compiler reject the SCHEMA literal anyway, so there's
1473        // a clear error path without us double-reporting.
1474        let ct_ident = column_entries
1475            .iter()
1476            .find(|c| c.column == gfk.ct_column)
1477            .map(|c| c.ident.clone())?;
1478        let pk_ident = column_entries
1479            .iter()
1480            .find(|c| c.column == gfk.pk_column)
1481            .map(|c| c.ident.clone())?;
1482
1483        let accessor_ident =
1484            syn::Ident::new(&format!("{}_pool", gfk.name), struct_name.span());
1485        let setter_ident =
1486            syn::Ident::new(&format!("set_{}_for", gfk.name), struct_name.span());
1487        let name_literal = gfk.name.as_str();
1488
1489        Some(quote! {
1490            #[doc = concat!(
1491                "Resolve the polymorphic `",
1492                #name_literal,
1493                "` relation. Reads `self.",
1494                stringify!(#ct_ident),
1495                "` + `self.",
1496                stringify!(#pk_ident),
1497                "`, looks up the matching `ContentType`, and fetches the target row as a JSON map.\n\n",
1498                "Returns `Ok(None)` when the ContentType is stale / unseeded or the target row was deleted. Emitted by `#[rustango(generic_fk(name = \"",
1499                #name_literal,
1500                "\", ...))]`."
1501            )]
1502            pub async fn #accessor_ident(
1503                &self,
1504                pool: &#root::sql::Pool,
1505            ) -> ::core::result::Result<
1506                ::core::option::Option<#root::__serde_json::Value>,
1507                #root::sql::ExecError,
1508            > {
1509                let gfk = #root::contenttypes::GenericForeignKey::new(
1510                    self.#ct_ident as i64,
1511                    self.#pk_ident as i64,
1512                );
1513                gfk.get_object(pool).await
1514            }
1515
1516            #[doc = concat!(
1517                "Set the polymorphic `",
1518                #name_literal,
1519                "` target. Looks up the `ContentType` for `T` via the cached registry, then assigns both `self.",
1520                stringify!(#ct_ident),
1521                "` and `self.",
1522                stringify!(#pk_ident),
1523                "`.\n\nFollow with `self.insert(pool)` or `self.update(pool)` to persist. Emitted by `#[rustango(generic_fk(name = \"",
1524                #name_literal,
1525                "\", ...))]`."
1526            )]
1527            pub async fn #setter_ident<T: #root::core::Model>(
1528                &mut self,
1529                pool: &#root::sql::Pool,
1530                target_pk: i64,
1531            ) -> ::core::result::Result<(), #root::sql::ExecError> {
1532                let gfk = #root::contenttypes::GenericForeignKey::for_target::<T>(
1533                    pool,
1534                    target_pk,
1535                ).await?;
1536                self.#ct_ident = gfk.content_type_id as _;
1537                self.#pk_ident = gfk.object_pk as _;
1538                ::core::result::Result::Ok(())
1539            }
1540        })
1541    });
1542    quote! {
1543        impl #struct_name {
1544            #( #methods )*
1545        }
1546    }
1547}
1548
1549fn m2m_accessor_tokens(struct_name: &syn::Ident, m2m_relations: &[M2MAttr]) -> TokenStream2 {
1550    let root = rustango_root();
1551    if m2m_relations.is_empty() {
1552        return TokenStream2::new();
1553    }
1554    let methods = m2m_relations.iter().map(|rel| {
1555        let method_name = format!("{}_m2m", rel.name);
1556        let method_ident = syn::Ident::new(&method_name, struct_name.span());
1557        let through = rel.through.as_str();
1558        let src_col = rel.src.as_str();
1559        let dst_col = rel.dst.as_str();
1560        quote! {
1561            pub fn #method_ident(&self) -> #root::sql::M2MManager {
1562                #root::sql::M2MManager {
1563                    src_pk: self.__rustango_pk_value(),
1564                    through: #through,
1565                    src_col: #src_col,
1566                    dst_col: #dst_col,
1567                }
1568            }
1569        }
1570    });
1571    quote! {
1572        impl #struct_name {
1573            #( #methods )*
1574        }
1575    }
1576}
1577
1578/// Emit `<name>_m2m(&self) -> GenericM2MManager` inherent methods for
1579/// every `#[rustango(generic_m2m(...))]` (polymorphic M2M, issue #818).
1580fn generic_m2m_accessor_tokens(
1581    struct_name: &syn::Ident,
1582    relations: &[GenericM2MAttr],
1583) -> TokenStream2 {
1584    let root = rustango_root();
1585    if relations.is_empty() {
1586        return TokenStream2::new();
1587    }
1588    let methods = relations.iter().map(|rel| {
1589        let method_ident = syn::Ident::new(&format!("{}_m2m", rel.name), struct_name.span());
1590        let through = rel.through.as_str();
1591        let pk_col = rel.pk_column.as_str();
1592        let ct_col = rel.ct_column.as_str();
1593        let related_col = rel.related_column.as_str();
1594        quote! {
1595            pub fn #method_ident(&self) -> #root::sql::GenericM2MManager {
1596                #root::sql::GenericM2MManager {
1597                    src_pk: self.__rustango_pk_value(),
1598                    src_schema: <Self as #root::core::Model>::SCHEMA,
1599                    through: #through,
1600                    pk_col: #pk_col,
1601                    ct_col: #ct_col,
1602                    dst_col: #related_col,
1603                }
1604            }
1605        }
1606    });
1607    quote! {
1608        impl #struct_name {
1609            #( #methods )*
1610        }
1611    }
1612}
1613
1614/// Emit `<name>_exists_expr()` + `<name>_not_exists_expr()`
1615/// associated functions for each `#[rustango(reverse_has(...))]`
1616/// attribute. Issue #830.
1617///
1618/// The two emitted functions return ready-to-use `WhereExpr` nodes
1619/// that downstream callers drop into
1620/// `QuerySet::<Self>::where_raw(...)`:
1621///
1622/// - `<name>_exists_expr()` → `EXISTS (SELECT 1 FROM <child> WHERE
1623///   <child_fk_column> = OuterRef("<self_pk_column>"))`. Eloquent
1624///   `whereHas` parity (without the closure-style sub-predicate
1625///   refinement — that's a follow-up; users can layer additional
1626///   predicates by constructing the SelectQuery themselves and
1627///   calling `where_raw(exists(query))` from `crate::core::subquery`).
1628/// - `<name>_not_exists_expr()` → same but `NOT EXISTS`. Eloquent
1629///   `whereDoesntHave` parity.
1630///
1631/// Tri-dialect: `EXISTS` / `NOT EXISTS` over a correlated subquery
1632/// is portable across PG / MySQL / SQLite. The writer's scope-stack
1633/// machinery threads the outer-table reference through automatically
1634/// (`OuterRef(col)` resolves to `<outer>.<col>` at emit time).
1635fn reverse_has_accessor_tokens(
1636    struct_name: &syn::Ident,
1637    reverse_has_relations: &[ReverseHasAttr],
1638) -> TokenStream2 {
1639    let root = rustango_root();
1640    if reverse_has_relations.is_empty() {
1641        return TokenStream2::new();
1642    }
1643    let methods = reverse_has_relations.iter().map(|rel| {
1644        let exists_name = format!("{}_exists_expr", rel.name);
1645        let not_exists_name = format!("{}_not_exists_expr", rel.name);
1646        let count_name = format!("{}_count", rel.name);
1647        let fetch_name = format!("{}_fetch", rel.name);
1648        let first_name = format!("{}_first", rel.name);
1649        let pluck_name = format!("{}_pluck", rel.name);
1650        let accessor_name = rel.name.as_str();
1651        let exists_ident = syn::Ident::new(&exists_name, struct_name.span());
1652        let not_exists_ident = syn::Ident::new(&not_exists_name, struct_name.span());
1653        let count_ident = syn::Ident::new(&count_name, struct_name.span());
1654        let fetch_ident = syn::Ident::new(&fetch_name, struct_name.span());
1655        let first_ident = syn::Ident::new(&first_name, struct_name.span());
1656        let pluck_ident = syn::Ident::new(&pluck_name, struct_name.span());
1657        let accessor_ident = syn::Ident::new(accessor_name, struct_name.span());
1658        let child = &rel.child;
1659        let child_fk_column = rel.child_fk_column.as_str();
1660        let self_pk_column = rel.self_pk_column.as_str();
1661        let exists_doc = format!(
1662            "Eloquent `whereHas` analog — yields `EXISTS (SELECT 1 \
1663             FROM <{child}> WHERE {child_fk_column} = <outer>.{self_pk_column})`. \
1664             Drop into `QuerySet::<{struct_name}>::where_raw(...)` to \
1665             filter to {struct_name}s with at least one matching child.",
1666        );
1667        let not_exists_doc = format!(
1668            "Eloquent `whereDoesntHave` analog — yields `NOT EXISTS \
1669             (SELECT 1 FROM <{child}> WHERE {child_fk_column} = \
1670             <outer>.{self_pk_column})`. Drop into \
1671             `QuerySet::<{struct_name}>::where_raw(...)` to filter to \
1672             {struct_name}s with **no** matching child.",
1673        );
1674        let count_doc = format!(
1675            "Eloquent `$model->{name}->count()` analog — returns \
1676             the number of `{child}` rows whose `{child_fk_column}` \
1677             matches this `{struct_name}` instance's primary key. \
1678             Issued as `SELECT COUNT(*) FROM <{child}> WHERE \
1679             {child_fk_column} = <self.pk>`.",
1680            name = rel.name,
1681        );
1682        let accessor_doc = format!(
1683            "Eloquent `$model->{name}` accessor — returns a \
1684             `QuerySet<{child}>` filtered to rows whose \
1685             `{child_fk_column}` matches this `{struct_name}` \
1686             instance's primary key. **Chainable**: compose `.filter()` \
1687             / `.order_by()` / `.limit()` etc. on top, then call \
1688             `.fetch(&pool)` (the QuerySet trait method) when \
1689             done. For the simple \"fetch all\" hot path with no \
1690             further composition, prefer the bare-name \
1691             `{name}_fetch(&pool)` companion.",
1692            name = rel.name,
1693        );
1694        let fetch_doc = format!(
1695            "Eloquent `$model->{name}->get()` — bare-name hot-path \
1696             over `{name}(&self).fetch(&pool)`. Use this when \
1697             you don't need further `.filter()` / `.order_by()` \
1698             composition; falls back to the chainable accessor when \
1699             you do. Avoids the `_pool` suffix on the most common \
1700             call-site shape.",
1701            name = rel.name,
1702        );
1703        quote! {
1704            #[doc = #accessor_doc]
1705            pub fn #accessor_ident(&self) -> #root::query::QuerySet<#child> {
1706                #root::query::QuerySet::<#child>::new()
1707                    .filter(#child_fk_column, self.__rustango_pk_value())
1708            }
1709
1710            #[doc = #fetch_doc]
1711            pub async fn #fetch_ident(
1712                &self,
1713                pool: &#root::sql::Pool,
1714            ) -> ::core::result::Result<
1715                ::std::vec::Vec<#child>,
1716                #root::sql::ExecError,
1717            > {
1718                use #root::sql::FetcherPool as _;
1719                self.#accessor_ident().fetch(pool).await
1720            }
1721
1722            /// Eloquent `$model->relation->first()` / `hasOne`
1723            /// semantics — bare-name shortcut over
1724            /// `self.<name>().first(&pool)`. Returns `None` when no
1725            /// child rows match. Useful when the relation is
1726            /// nominally many-to-one in shape but at most one row is
1727            /// expected (latest comment, primary tag, etc.).
1728            pub async fn #first_ident(
1729                &self,
1730                pool: &#root::sql::Pool,
1731            ) -> ::core::result::Result<
1732                ::core::option::Option<#child>,
1733                #root::sql::ExecError,
1734            > {
1735                self.#accessor_ident().first(pool).await
1736            }
1737
1738            /// Eloquent `$model->relation->pluck($col)` — project a
1739            /// single column from the child rows into a `Vec<U>`.
1740            /// Skips the typed `Child` decode, which is cheaper when
1741            /// you only need one column (e.g. `post.comments_pluck::<String>("body", &pool)`).
1742            pub async fn #pluck_ident<U>(
1743                &self,
1744                col: &'static str,
1745                pool: &#root::sql::Pool,
1746            ) -> ::core::result::Result<
1747                ::std::vec::Vec<U>,
1748                #root::sql::ExecError,
1749            >
1750            where
1751                U: #root::sql::MaybePgScalar
1752                    + #root::sql::MaybeMyScalar
1753                    + #root::sql::MaybeSqliteScalar
1754                    + ::core::marker::Send
1755                    + ::core::marker::Unpin,
1756            {
1757                self.#accessor_ident()
1758                    .values_list_flat(col)
1759                    .fetch::<U>(pool)
1760                    .await
1761            }
1762
1763            #[doc = #exists_doc]
1764            pub fn #exists_ident() -> #root::core::WhereExpr {
1765                use #root::core::{Expr, Model as _, Op, SelectQuery, WhereExpr};
1766                let child_schema =
1767                    <#child as #root::core::Model>::SCHEMA;
1768                let inner = SelectQuery {
1769                    where_clause: WhereExpr::ExprCompare {
1770                        lhs: Expr::Column(#child_fk_column),
1771                        op: Op::Eq,
1772                        rhs: Expr::OuterRef(#self_pk_column),
1773                    },
1774                    ..SelectQuery::new(child_schema)
1775                };
1776                WhereExpr::Exists(::std::boxed::Box::new(inner))
1777            }
1778
1779            #[doc = #not_exists_doc]
1780            pub fn #not_exists_ident() -> #root::core::WhereExpr {
1781                use #root::core::{Expr, Model as _, Op, SelectQuery, WhereExpr};
1782                let child_schema =
1783                    <#child as #root::core::Model>::SCHEMA;
1784                let inner = SelectQuery {
1785                    where_clause: WhereExpr::ExprCompare {
1786                        lhs: Expr::Column(#child_fk_column),
1787                        op: Op::Eq,
1788                        rhs: Expr::OuterRef(#self_pk_column),
1789                    },
1790                    ..SelectQuery::new(child_schema)
1791                };
1792                WhereExpr::NotExists(::std::boxed::Box::new(inner))
1793            }
1794
1795            #[doc = #count_doc]
1796            pub async fn #count_ident(
1797                &self,
1798                pool: &#root::sql::Pool,
1799            ) -> ::core::result::Result<
1800                i64,
1801                #root::sql::ExecError,
1802            > {
1803                use #root::sql::CounterPool as _;
1804                #root::query::QuerySet::<#child>::new()
1805                    .filter(#child_fk_column, self.__rustango_pk_value())
1806                    .count(pool)
1807                    .await
1808            }
1809        }
1810    });
1811    quote! {
1812        impl #struct_name {
1813            #( #methods )*
1814        }
1815    }
1816}
1817
1818/// Emit `<name>_through(&self) -> QuerySet<Far>` accessors for each
1819/// `#[rustango(through(...))]` attribute. Issue #817.
1820///
1821/// Each accessor builds a correlated subquery via
1822/// `WhereExpr::InSubquery`: the inner `SelectQuery` reads from the
1823/// intermediate table, filters on the FK column pointing at this
1824/// model, and projects the intermediate PK. The outer queryset
1825/// filters the far model by its FK-to-intermediate column being in
1826/// that set.
1827///
1828/// The returned `QuerySet<Far>` is **chainable** — the subquery
1829/// lives inside a `where_raw` clause so the user's later
1830/// `.filter()` / `.order_by()` / `.limit()` compositions don't
1831/// disturb it.
1832///
1833/// Tri-dialect: `IN (subquery)` is portable across PG / MySQL /
1834/// SQLite — no LATERAL or backend-specific syntax involved.
1835fn through_accessor_tokens(
1836    struct_name: &syn::Ident,
1837    through_relations: &[ThroughAttr],
1838) -> TokenStream2 {
1839    let root = rustango_root();
1840    if through_relations.is_empty() {
1841        return TokenStream2::new();
1842    }
1843    let methods = through_relations.iter().map(|rel| {
1844        let method_name = format!("{}_through", rel.name);
1845        let count_name = format!("{}_through_count", rel.name);
1846        let fetch_name = format!("{}_through_fetch", rel.name);
1847        let first_name = format!("{}_through_first", rel.name);
1848        let pluck_name = format!("{}_through_pluck", rel.name);
1849        let method_ident = syn::Ident::new(&method_name, struct_name.span());
1850        let count_ident = syn::Ident::new(&count_name, struct_name.span());
1851        let fetch_ident = syn::Ident::new(&fetch_name, struct_name.span());
1852        let first_ident = syn::Ident::new(&first_name, struct_name.span());
1853        let pluck_ident = syn::Ident::new(&pluck_name, struct_name.span());
1854        let far = &rel.far;
1855        let intermediate = &rel.intermediate;
1856        let far_fk_column = rel.far_fk_column.as_str();
1857        let intermediate_fk_column = rel.intermediate_fk_column.as_str();
1858        let intermediate_pk_column = rel.intermediate_pk_column.as_str();
1859        let doc = format!(
1860            "Eloquent `hasManyThrough` accessor — returns a \
1861             `QuerySet<{far}>` whose rows reach this `{struct_name}` \
1862             instance through the intermediate `{intermediate}` table. \
1863             Generated SQL shape: \
1864             `… WHERE {far_fk_column} IN (SELECT \
1865             {intermediate_pk_column} FROM <{intermediate}> WHERE \
1866             {intermediate_fk_column} = self.pk)`. Chainable like any \
1867             other QuerySet — compose `.filter()` / `.order_by()` / \
1868             `.limit()` etc. on top.",
1869        );
1870        let count_doc = format!(
1871            "Eloquent `$model->{name}->count()` analog for the \
1872             through-relation — returns the number of `{far}` rows \
1873             reachable through `{intermediate}`. Equivalent to \
1874             `self.{name}_through().count(pool)` but spelled \
1875             as a bare instance method for parity with the \
1876             `reverse_has` `<name>_count` shape.",
1877            name = rel.name,
1878        );
1879        quote! {
1880            #[doc = #doc]
1881            pub fn #method_ident(&self) -> #root::query::QuerySet<#far> {
1882                use #root::core::{Filter, Model as _, Op, SelectQuery, WhereExpr};
1883                let intermediate_schema =
1884                    <#intermediate as #root::core::Model>::SCHEMA;
1885                let sub = SelectQuery {
1886                    where_clause: WhereExpr::Predicate(Filter {
1887                        column: #intermediate_fk_column,
1888                        op: Op::Eq,
1889                        value: self.__rustango_pk_value(),
1890                    }),
1891                    projection: ::core::option::Option::Some(
1892                        ::std::vec![#intermediate_pk_column],
1893                    ),
1894                    ..SelectQuery::new(intermediate_schema)
1895                };
1896                #root::query::QuerySet::<#far>::new().where_raw(
1897                    WhereExpr::InSubquery {
1898                        column: #far_fk_column,
1899                        negated: false,
1900                        subquery: ::std::boxed::Box::new(sub),
1901                    },
1902                )
1903            }
1904
1905            #[doc = #count_doc]
1906            pub async fn #count_ident(
1907                &self,
1908                pool: &#root::sql::Pool,
1909            ) -> ::core::result::Result<
1910                i64,
1911                #root::sql::ExecError,
1912            > {
1913                use #root::sql::CounterPool as _;
1914                self.#method_ident().count(pool).await
1915            }
1916
1917            /// Eloquent `$model->relation->get()` for the
1918            /// through-relation — bare-name hot-path over
1919            /// `self.<name>_through().fetch(&pool)`. Use this
1920            /// when you don't need further `.filter()` /
1921            /// `.order_by()` composition; falls back to the
1922            /// chainable accessor when you do. Avoids the `_pool`
1923            /// suffix on the most common call-site shape.
1924            pub async fn #fetch_ident(
1925                &self,
1926                pool: &#root::sql::Pool,
1927            ) -> ::core::result::Result<
1928                ::std::vec::Vec<#far>,
1929                #root::sql::ExecError,
1930            > {
1931                use #root::sql::FetcherPool as _;
1932                self.#method_ident().fetch(pool).await
1933            }
1934
1935            /// Eloquent `hasOneThrough` analog — bare-name shortcut
1936            /// over `self.<name>_through().first(&pool)`. Returns
1937            /// `None` when no far rows are reachable through the
1938            /// intermediate. Useful when at most one row is
1939            /// expected (latest comment by country, primary tag,
1940            /// etc.).
1941            pub async fn #first_ident(
1942                &self,
1943                pool: &#root::sql::Pool,
1944            ) -> ::core::result::Result<
1945                ::core::option::Option<#far>,
1946                #root::sql::ExecError,
1947            > {
1948                self.#method_ident().first(pool).await
1949            }
1950
1951            /// Pluck a single column from the far rows into `Vec<U>`
1952            /// — cheaper than the typed `<Far>` decode when only one
1953            /// scalar column is needed.
1954            pub async fn #pluck_ident<U>(
1955                &self,
1956                col: &'static str,
1957                pool: &#root::sql::Pool,
1958            ) -> ::core::result::Result<
1959                ::std::vec::Vec<U>,
1960                #root::sql::ExecError,
1961            >
1962            where
1963                U: #root::sql::MaybePgScalar
1964                    + #root::sql::MaybeMyScalar
1965                    + #root::sql::MaybeSqliteScalar
1966                    + ::core::marker::Send
1967                    + ::core::marker::Unpin,
1968            {
1969                self.#method_ident()
1970                    .values_list_flat(col)
1971                    .fetch::<U>(pool)
1972                    .await
1973            }
1974        }
1975    });
1976    quote! {
1977        impl #struct_name {
1978            #( #methods )*
1979        }
1980    }
1981}
1982
1983struct ColumnEntry {
1984    /// The struct field ident, used both for the inherent const name on
1985    /// the model and for the inner column type's name.
1986    ident: syn::Ident,
1987    /// The struct's field type, used as `Column::Value`.
1988    value_ty: Type,
1989    /// Rust-side field name (e.g. `"id"`).
1990    name: String,
1991    /// SQL-side column name (e.g. `"user_id"`).
1992    column: String,
1993    /// `#root::core::FieldType::I64` etc.
1994    field_type_tokens: TokenStream2,
1995}
1996
1997struct CollectedFields {
1998    field_schemas: Vec<TokenStream2>,
1999    from_row_inits: Vec<TokenStream2>,
2000    /// Aliased counterparts of `from_row_inits` — read columns via
2001    /// `format!("{prefix}__{col}")` aliases so a Model can be
2002    /// decoded from a JOINed row's projected target columns.
2003    from_aliased_row_inits: Vec<TokenStream2>,
2004    /// Static column-name list — used by the simple insert path
2005    /// (no `Auto<T>` fields). Aligned with `insert_values`.
2006    insert_columns: Vec<TokenStream2>,
2007    /// Static `Into<SqlValue>` expressions, one per field. Aligned
2008    /// with `insert_columns`. Used by the simple insert path only.
2009    insert_values: Vec<TokenStream2>,
2010    /// Per-field push expressions for the dynamic (Auto-aware)
2011    /// insert path. Each statement either unconditionally pushes
2012    /// `(column, value)` or, for an `Auto<T>` field, conditionally
2013    /// pushes only when `Auto::Set(_)`. Built only when `has_auto`.
2014    insert_pushes: Vec<TokenStream2>,
2015    /// SQL columns for `RETURNING` — one per `Auto<T>` field. Empty
2016    /// when `has_auto == false`.
2017    returning_cols: Vec<TokenStream2>,
2018    /// `self.<field> = Row::try_get(&row, "<col>")?;` for each Auto
2019    /// field. Run after `insert_returning` to populate the model.
2020    auto_assigns: Vec<TokenStream2>,
2021    /// `(ident, column_literal)` pairs for every Auto field. Used by
2022    /// the bulk_insert codegen to rebuild assigns against `_row_mut`
2023    /// instead of `self`.
2024    auto_field_idents: Vec<(syn::Ident, String)>,
2025    /// #1028 — `(ident, column)` for each `generated_as` field. Drives
2026    /// the PG/SQLite RETURNING refresh that decodes the DB-computed value
2027    /// back into the struct after insert (MySQL has no RETURNING → the
2028    /// field stays at its placeholder until the next read).
2029    generated_field_idents: Vec<(syn::Ident, String)>,
2030    /// Inner `T` of the first `Auto<T>` field, for the MySQL
2031    /// `LAST_INSERT_ID()` assignment in `AssignAutoPkPool`.
2032    first_auto_value_ty: Option<Type>,
2033    /// Bulk-insert per-row pushes for **non-Auto fields only**. Used
2034    /// by the all-Auto-Unset bulk path (Auto cols dropped from
2035    /// `columns`).
2036    bulk_pushes_no_auto: Vec<TokenStream2>,
2037    /// Bulk-insert per-row pushes for **all fields including Auto**.
2038    /// Used by the all-Auto-Set bulk path (Auto col included with the
2039    /// caller-supplied value).
2040    bulk_pushes_all: Vec<TokenStream2>,
2041    /// Column-name literals for non-Auto fields only (paired with
2042    /// `bulk_pushes_no_auto`).
2043    bulk_columns_no_auto: Vec<TokenStream2>,
2044    /// Column-name literals for every field including Auto (paired
2045    /// with `bulk_pushes_all`).
2046    bulk_columns_all: Vec<TokenStream2>,
2047    /// `let _i_unset_<n> = matches!(rows[0].<auto_field>, Auto::Unset);`
2048    /// + the loop that asserts every row matches. One pair per Auto
2049    /// field. Empty when `has_auto == false`.
2050    bulk_auto_uniformity: Vec<TokenStream2>,
2051    /// Identifier of the first Auto field, used as the witness for
2052    /// "all rows agree on Set vs Unset". Set only when `has_auto`.
2053    first_auto_ident: Option<syn::Ident>,
2054    /// `true` if any field on the struct is `Auto<T>`.
2055    has_auto: bool,
2056    /// `true` when the primary-key field's Rust type is `Auto<T>`.
2057    /// Gates `save()` codegen — only Auto PKs let us infer
2058    /// insert-vs-update from the in-memory value.
2059    pk_is_auto: bool,
2060    /// `Assignment` constructors for every non-PK column. Drives the
2061    /// UPDATE branch of `save()`.
2062    update_assignments: Vec<TokenStream2>,
2063    /// Column name literals (`"col"`) for every non-PK, non-auto_now_add column.
2064    /// Drives the `ON CONFLICT ... DO UPDATE SET` clause in `upsert_on`.
2065    upsert_update_columns: Vec<TokenStream2>,
2066    primary_key: Option<(syn::Ident, String)>,
2067    column_entries: Vec<ColumnEntry>,
2068    /// Rust-side field names, in declaration order. Used to validate
2069    /// container attributes like `display = "…"`.
2070    field_names: Vec<String>,
2071    /// FK fields on this child model. Drives the reverse-relation
2072    /// helper emit — for each FK, the macro adds an inherent
2073    /// `<parent>::<child_table>_set(&self, executor) -> Vec<Self>`
2074    /// method on the parent type.
2075    fk_relations: Vec<FkRelation>,
2076    /// SQL column name of the `#[rustango(soft_delete)]` field, if
2077    /// the model has one. Drives emission of the `soft_delete_on` /
2078    /// `restore_on` inherent methods. At most one such column per
2079    /// model is allowed; collect_fields rejects duplicates.
2080    soft_delete_column: Option<String>,
2081    /// Rust field ident of the `#[rustango(soft_delete)]` field —
2082    /// companion to `soft_delete_column` for emitting predicates
2083    /// that need to read the field off `&self` (e.g. `trashed()`).
2084    soft_delete_field_ident: Option<syn::Ident>,
2085}
2086
2087#[derive(Clone)]
2088struct FkRelation {
2089    /// Inner type of `ForeignKey<T, K>` — the parent model. The reverse
2090    /// helper is emitted as `impl <ParentType> { … }`.
2091    parent_type: Type,
2092    /// SQL column name on the child table for this FK (e.g. `"author"`).
2093    /// Used in the generated `WHERE <fk_column> = $1` clause.
2094    fk_column: String,
2095    /// `K`'s underlying scalar kind — drives the `match SqlValue { … }`
2096    /// arm emitted by [`load_related_impl_tokens`]. `I64` for the
2097    /// default `ForeignKey<T>` (no explicit K); other kinds when the
2098    /// user wrote `ForeignKey<T, String>`, `ForeignKey<T, Uuid>`, etc.
2099    pk_kind: DetectedKind,
2100    /// `true` when the field is `Option<ForeignKey<T, K>>` (nullable
2101    /// FK column). Drives the `Some(...)` wrapping in load_related
2102    /// assignment and `.as_ref().map(...)` in the FK PK accessor so
2103    /// the codegen matches the field's declared shape.
2104    nullable: bool,
2105    /// `#[rustango(related_name = "...")]` per-FK reverse-accessor
2106    /// override. When set, the reverse helper picks this name instead
2107    /// of `default_related_name` / `<child_snake>_set`. Follow-up to
2108    /// #816 (issue's "Related" note re: per-FK override).
2109    related_name: Option<String>,
2110}
2111
2112fn collect_fields(named: &syn::FieldsNamed, table: &str) -> syn::Result<CollectedFields> {
2113    let root = rustango_root();
2114    let cap = named.named.len();
2115    let mut out = CollectedFields {
2116        field_schemas: Vec::with_capacity(cap),
2117        from_row_inits: Vec::with_capacity(cap),
2118        from_aliased_row_inits: Vec::with_capacity(cap),
2119        insert_columns: Vec::with_capacity(cap),
2120        insert_values: Vec::with_capacity(cap),
2121        insert_pushes: Vec::with_capacity(cap),
2122        returning_cols: Vec::new(),
2123        auto_assigns: Vec::new(),
2124        auto_field_idents: Vec::new(),
2125        generated_field_idents: Vec::new(),
2126        first_auto_value_ty: None,
2127        bulk_pushes_no_auto: Vec::with_capacity(cap),
2128        bulk_pushes_all: Vec::with_capacity(cap),
2129        bulk_columns_no_auto: Vec::with_capacity(cap),
2130        bulk_columns_all: Vec::with_capacity(cap),
2131        bulk_auto_uniformity: Vec::new(),
2132        first_auto_ident: None,
2133        has_auto: false,
2134        pk_is_auto: false,
2135        update_assignments: Vec::with_capacity(cap),
2136        upsert_update_columns: Vec::with_capacity(cap),
2137        primary_key: None,
2138        column_entries: Vec::with_capacity(cap),
2139        field_names: Vec::with_capacity(cap),
2140        fk_relations: Vec::new(),
2141        soft_delete_column: None,
2142        soft_delete_field_ident: None,
2143    };
2144
2145    for field in &named.named {
2146        let info = process_field(field, table)?;
2147        out.field_names.push(info.ident.to_string());
2148        out.field_schemas.push(info.schema);
2149        out.from_row_inits.push(info.from_row_init);
2150        out.from_aliased_row_inits.push(info.from_aliased_row_init);
2151        if let Some(parent_ty) = info.fk_inner.clone() {
2152            out.fk_relations.push(FkRelation {
2153                parent_type: parent_ty,
2154                fk_column: info.column.clone(),
2155                pk_kind: info.fk_pk_kind,
2156                nullable: info.nullable,
2157                related_name: info.related_name.clone(),
2158            });
2159        }
2160        if info.soft_delete {
2161            if out.soft_delete_column.is_some() {
2162                return Err(syn::Error::new_spanned(
2163                    field,
2164                    "only one field may be marked `#[rustango(soft_delete)]`",
2165                ));
2166            }
2167            out.soft_delete_column = Some(info.column.clone());
2168            out.soft_delete_field_ident = Some(info.ident.clone());
2169        }
2170        let column = info.column.as_str();
2171        let ident = info.ident;
2172        // Generated columns (`#[rustango(generated_as = "EXPR")]`)
2173        // skip every write path — Postgres recomputes the value
2174        // from EXPR. Push only the column-entry record (so typed
2175        // column constants still exist for filtering / projection)
2176        // and the schema literal (already pushed above) and move
2177        // on. No insert_columns/values, no insert_pushes, no
2178        // bulk_*, no update_assignments, no upsert_update_columns,
2179        // no returning_cols.
2180        if info.generated_as.is_some() {
2181            out.column_entries.push(ColumnEntry {
2182                ident: ident.clone(),
2183                value_ty: info.value_ty.clone(),
2184                name: ident.to_string(),
2185                column: info.column.clone(),
2186                field_type_tokens: info.field_type_tokens,
2187            });
2188            // #1028 — refresh the DB-computed value after insert on
2189            // RETURNING-capable backends. The column joins `returning_cols`
2190            // (so PG/SQLite `INSERT … RETURNING` includes it) and the
2191            // ident is recorded so the `AssignAutoPkPool` impl decodes it
2192            // back into the struct. MySQL has no `INSERT … RETURNING`, so
2193            // it keeps the placeholder until the next read.
2194            out.returning_cols.push(quote!(#column));
2195            out.generated_field_idents
2196                .push((ident.clone(), info.column.clone()));
2197            continue;
2198        }
2199        out.insert_columns.push(quote!(#column));
2200        out.insert_values.push(quote! {
2201            ::core::convert::Into::<#root::core::SqlValue>::into(
2202                ::core::clone::Clone::clone(&self.#ident)
2203            )
2204        });
2205        if info.auto {
2206            out.has_auto = true;
2207            if out.first_auto_ident.is_none() {
2208                out.first_auto_ident = Some(ident.clone());
2209                out.first_auto_value_ty = auto_inner_type(info.value_ty).cloned();
2210            }
2211            // `default_uuid_v7` (issue #823) generates the PK Rust-side
2212            // before binding, so the value is already in
2213            // `self.#ident` after the insert_push — RETURNING is
2214            // redundant. Skip adding this column to returning_cols /
2215            // auto_assigns / auto_field_idents to avoid (a) an
2216            // unnecessary RETURNING column on every dialect, and (b)
2217            // the MySQL `LAST_INSERT_ID()` path that can only fill an
2218            // integer PK.
2219            // `auto_now_add` / `auto_now` join `default_uuid_v7` here
2220            // for the same reason: they are filled Rust-side below and
2221            // bound, so the value is already in `self` and RETURNING
2222            // would be a redundant column on every dialect.
2223            if !info.default_uuid_v7 && !info.auto_now_add && !info.auto_now {
2224                out.returning_cols.push(quote!(#column));
2225                out.auto_field_idents
2226                    .push((ident.clone(), info.column.clone()));
2227                out.auto_assigns.push(quote! {
2228                    self.#ident = #root::sql::try_get_returning(_returning_row, #column)?;
2229                });
2230            }
2231            if info.default_uuid_v7 {
2232                // Rust-side UUIDv7 generation (issue #823, Eloquent
2233                // `HasUuids`). Auto::Unset → fill with `Uuid::now_v7()`
2234                // and bind; Auto::Set → bind the user's value. The
2235                // column is ALWAYS present in the INSERT statement —
2236                // no RETURNING / no DB DEFAULT needed.
2237                out.insert_pushes.push(quote! {
2238                    if matches!(&self.#ident, #root::sql::Auto::Unset) {
2239                        self.#ident = #root::sql::Auto::Set(
2240                            #root::__uuid::Uuid::now_v7(),
2241                        );
2242                    }
2243                    if let #root::sql::Auto::Set(_v) = &self.#ident {
2244                        _columns.push(#column);
2245                        _values.push(::core::convert::Into::<#root::core::SqlValue>::into(
2246                            ::core::clone::Clone::clone(_v)
2247                        ));
2248                    }
2249                });
2250            } else if info.auto_now_add || info.auto_now {
2251                // Rust-side write timestamp (#1464), mirroring
2252                // `default_uuid_v7` above. `auto_now` has always bound
2253                // `Utc::now()` on UPDATE but not on INSERT, so the
2254                // first write of an `updated_at` took the DB default
2255                // while every later one took the clock — the same
2256                // column, filled two different ways.
2257                //
2258                // The default is the problem. `CREATE TABLE IF NOT
2259                // EXISTS` leaves an upgraded table's
2260                // `DEFAULT CURRENT_TIMESTAMP` in place, and SQLite's
2261                // ALTER TABLE grammar (RENAME/ADD/DROP) has no
2262                // statement that changes it — so every insert relying
2263                // on that default wrote the legacy shape forever, while
2264                // the migrate sweep converted the rows around it. The
2265                // column went permanently mixed and `ORDER BY` inverted
2266                // the admin audit log (#1616 rework review,
2267                // correctness-001 / dialects-005 / security-002).
2268                //
2269                // Binding it here makes the stale default unreachable
2270                // rather than trying to migrate it: the timestamp comes
2271                // from the application, not the database.
2272                out.insert_pushes.push(quote! {
2273                    if matches!(&self.#ident, #root::sql::Auto::Unset) {
2274                        self.#ident = #root::sql::Auto::Set(
2275                            #root::__chrono::Utc::now(),
2276                        );
2277                    }
2278                    if let #root::sql::Auto::Set(_v) = &self.#ident {
2279                        _columns.push(#column);
2280                        _values.push(::core::convert::Into::<#root::core::SqlValue>::into(
2281                            ::core::clone::Clone::clone(_v)
2282                        ));
2283                    }
2284                });
2285            } else {
2286                out.insert_pushes.push(quote! {
2287                    if let #root::sql::Auto::Set(_v) = &self.#ident {
2288                        _columns.push(#column);
2289                        _values.push(::core::convert::Into::<#root::core::SqlValue>::into(
2290                            ::core::clone::Clone::clone(_v)
2291                        ));
2292                    }
2293                });
2294            }
2295            // Bulk: Auto fields appear only in the all-Set path,
2296            // never in the Unset path (we drop them from `columns`).
2297            out.bulk_columns_all.push(quote!(#column));
2298            out.bulk_pushes_all.push(quote! {
2299                _row_vals.push(::core::convert::Into::<#root::core::SqlValue>::into(
2300                    ::core::clone::Clone::clone(&_row.#ident)
2301                ));
2302            });
2303            // …except the timestamp columns, which must appear in BOTH
2304            // paths (#1464). The path is chosen by the *first* Auto
2305            // field — in practice the PK — so a bulk insert of rows
2306            // with an unset PK took the no-auto branch and dropped the
2307            // timestamp column, falling back to the DB default that
2308            // this change exists to stop depending on.
2309            //
2310            // `rows` is borrowed immutably here, so this fills per row
2311            // at push time rather than writing back into the struct. An
2312            // explicitly-Set value is still honoured; only `Unset`
2313            // takes the clock.
2314            if info.auto_now_add || info.auto_now {
2315                out.bulk_columns_no_auto.push(quote!(#column));
2316                out.bulk_pushes_no_auto.push(quote! {
2317                    _row_vals.push(::core::convert::Into::<#root::core::SqlValue>::into(
2318                        match &_row.#ident {
2319                            #root::sql::Auto::Set(_v) => ::core::clone::Clone::clone(_v),
2320                            #root::sql::Auto::Unset => #root::__chrono::Utc::now(),
2321                        }
2322                    ));
2323                });
2324            }
2325            // Uniformity check: every row's Auto state must match the
2326            // first row's. Mixed Set/Unset within one bulk_insert is
2327            // rejected here so the column list stays consistent.
2328            let ident_clone = ident.clone();
2329            out.bulk_auto_uniformity.push(quote! {
2330                for _r in rows.iter().skip(1) {
2331                    if matches!(_r.#ident_clone, #root::sql::Auto::Unset) != _first_unset {
2332                        return ::core::result::Result::Err(
2333                            #root::sql::ExecError::Sql(
2334                                #root::sql::SqlError::BulkAutoMixed
2335                            )
2336                        );
2337                    }
2338                }
2339            });
2340        } else {
2341            out.insert_pushes.push(quote! {
2342                _columns.push(#column);
2343                _values.push(::core::convert::Into::<#root::core::SqlValue>::into(
2344                    ::core::clone::Clone::clone(&self.#ident)
2345                ));
2346            });
2347            // Bulk: non-Auto fields appear in BOTH paths.
2348            out.bulk_columns_no_auto.push(quote!(#column));
2349            out.bulk_columns_all.push(quote!(#column));
2350            let push_expr = quote! {
2351                _row_vals.push(::core::convert::Into::<#root::core::SqlValue>::into(
2352                    ::core::clone::Clone::clone(&_row.#ident)
2353                ));
2354            };
2355            out.bulk_pushes_no_auto.push(push_expr.clone());
2356            out.bulk_pushes_all.push(push_expr);
2357        }
2358        if info.primary_key {
2359            if out.primary_key.is_some() {
2360                return Err(syn::Error::new_spanned(
2361                    field,
2362                    "only one field may be marked `#[rustango(primary_key)]`",
2363                ));
2364            }
2365            out.primary_key = Some((ident.clone(), info.column.clone()));
2366            if info.auto {
2367                out.pk_is_auto = true;
2368            }
2369        } else if info.auto_now_add {
2370            // Immutable post-insert: skip from UPDATE entirely.
2371        } else if info.auto_now {
2372            // `auto_now` columns: bind `chrono::Utc::now()` on every
2373            // UPDATE so the column is always overridden with the
2374            // wall-clock at write time, regardless of what value the
2375            // user left in the struct field.
2376            out.update_assignments.push(quote! {
2377                #root::core::Assignment {
2378                    column: #column,
2379                    value: ::core::convert::Into::<#root::core::Expr>::into(
2380                        ::core::convert::Into::<#root::core::SqlValue>::into(
2381                            #root::__chrono::Utc::now()
2382                        )
2383                    ),
2384                }
2385            });
2386            out.upsert_update_columns.push(quote!(#column));
2387        } else {
2388            out.update_assignments.push(quote! {
2389                #root::core::Assignment {
2390                    column: #column,
2391                    value: ::core::convert::Into::<#root::core::Expr>::into(
2392                        ::core::convert::Into::<#root::core::SqlValue>::into(
2393                            ::core::clone::Clone::clone(&self.#ident)
2394                        )
2395                    ),
2396                }
2397            });
2398            out.upsert_update_columns.push(quote!(#column));
2399        }
2400        out.column_entries.push(ColumnEntry {
2401            ident: ident.clone(),
2402            value_ty: info.value_ty.clone(),
2403            name: ident.to_string(),
2404            column: info.column.clone(),
2405            field_type_tokens: info.field_type_tokens,
2406        });
2407    }
2408    Ok(out)
2409}
2410
2411fn model_impl_tokens(
2412    struct_name: &syn::Ident,
2413    model_name: &str,
2414    table: &str,
2415    display: Option<&str>,
2416    app_label: Option<&str>,
2417    admin: Option<&AdminAttrs>,
2418    default_order: &[(String, bool, proc_macro2::Span)],
2419    field_schemas: &[TokenStream2],
2420    soft_delete_column: Option<&str>,
2421    permissions: bool,
2422    audit_track: Option<&[String]>,
2423    m2m_relations: &[M2MAttr],
2424    indexes: &[IndexAttr],
2425    checks: &[CheckAttr],
2426    excludes: &[ExcludeAttr],
2427    composite_fks: &[CompositeFkAttr],
2428    generic_fks: &[GenericFkAttr],
2429    scope: Option<&str>,
2430    is_view: bool,
2431    verbose_name: Option<&str>,
2432    verbose_name_plural: Option<&str>,
2433    managed: bool,
2434    base_manager_name: Option<&str>,
2435    order_with_respect_to: Option<&str>,
2436    proxy: bool,
2437    required_db_features: &[String],
2438    required_db_vendor: Option<&str>,
2439    default_related_name: Option<&str>,
2440    db_table_comment: Option<&str>,
2441    get_latest_by: Option<(&str, bool)>,
2442    extra_permissions: &[(String, String)],
2443    default_permissions: &[String],
2444    global_scopes: &[GlobalScopeAttr],
2445    reverse_has_relations: &[ReverseHasAttr],
2446    generic_has_relations: &[GenericHasAttr],
2447) -> TokenStream2 {
2448    let root = rustango_root();
2449    let display_tokens = if let Some(name) = display {
2450        quote!(::core::option::Option::Some(#name))
2451    } else {
2452        quote!(::core::option::Option::None)
2453    };
2454    let app_label_tokens = if let Some(name) = app_label {
2455        quote!(::core::option::Option::Some(#name))
2456    } else {
2457        quote!(::core::option::Option::None)
2458    };
2459    let soft_delete_tokens = if let Some(col) = soft_delete_column {
2460        quote!(::core::option::Option::Some(#col))
2461    } else {
2462        quote!(::core::option::Option::None)
2463    };
2464    let audit_track_tokens = match audit_track {
2465        None => quote!(::core::option::Option::None),
2466        Some(names) => {
2467            let lits = names.iter().map(|n| n.as_str());
2468            quote!(::core::option::Option::Some(&[ #(#lits),* ]))
2469        }
2470    };
2471    let admin_tokens = admin_config_tokens(admin);
2472    // Default `tenant` so single-tenant projects (no `scope` attr
2473    // anywhere) keep the v0.24.x behavior. Container-attr parser
2474    // already validated the value is "registry" or "tenant".
2475    let scope_tokens = match scope.map(|s| s.to_ascii_lowercase()).as_deref() {
2476        Some("registry") => quote!(#root::core::ModelScope::Registry),
2477        _ => quote!(#root::core::ModelScope::Tenant),
2478    };
2479    let verbose_name_tokens = optional_str(verbose_name);
2480    let verbose_name_plural_tokens = optional_str(verbose_name_plural);
2481    let base_manager_name_tokens = optional_str(base_manager_name);
2482    let order_with_respect_to_tokens = optional_str(order_with_respect_to);
2483    let required_db_features_lits: Vec<&str> =
2484        required_db_features.iter().map(String::as_str).collect();
2485    let required_db_vendor_tokens = optional_str(required_db_vendor);
2486    let default_related_name_tokens = optional_str(default_related_name);
2487    let db_table_comment_tokens = optional_str(db_table_comment);
2488    let get_latest_by_tokens = match get_latest_by {
2489        Some((col, desc)) => {
2490            quote!(::core::option::Option::Some((#col, #desc)))
2491        }
2492        None => quote!(::core::option::Option::None),
2493    };
2494    let extra_permission_tokens: Vec<_> = extra_permissions
2495        .iter()
2496        .map(|(c, l)| quote!((#c, #l)))
2497        .collect();
2498    let default_permission_tokens: Vec<_> = default_permissions
2499        .iter()
2500        .map(|action| quote!(#action))
2501        .collect();
2502    let indexes_tokens = indexes.iter().map(|idx| {
2503        // When no explicit `name = "..."` was given, derive a stable,
2504        // collision-free name from the table + columns
2505        // (`<table>_<col>_<col>_idx`) instead of a shared literal that
2506        // would clash the moment a model declares two unnamed indexes.
2507        // Capped at Postgres's 63-char identifier limit.
2508        let derived_name = idx.name.clone().unwrap_or_else(|| {
2509            let mut n = format!("{table}_{}_idx", idx.columns.join("_"));
2510            if n.len() > 63 {
2511                n.truncate(63);
2512            }
2513            n
2514        });
2515        let name = derived_name.as_str();
2516        let cols: Vec<&str> = idx.columns.iter().map(String::as_str).collect();
2517        let unique = idx.unique;
2518        // Map the parsed method string onto the IndexMethod enum
2519        // variant — kept at the codegen layer so the IR doesn't
2520        // carry the string form.
2521        let method_variant = match idx.method.as_str() {
2522            "gin" => quote!(#root::core::IndexMethod::Gin),
2523            "gist" => quote!(#root::core::IndexMethod::Gist),
2524            "brin" => quote!(#root::core::IndexMethod::Brin),
2525            "spgist" => quote!(#root::core::IndexMethod::SpGist),
2526            "hash" => quote!(#root::core::IndexMethod::Hash),
2527            "bloom" => quote!(#root::core::IndexMethod::Bloom),
2528            _ => quote!(#root::core::IndexMethod::BTree),
2529        };
2530        let where_clause = match &idx.where_clause {
2531            Some(s) => quote!(::core::option::Option::Some(#s)),
2532            None => quote!(::core::option::Option::None),
2533        };
2534        let include_lits: Vec<&str> = idx.include.iter().map(String::as_str).collect();
2535        quote! {
2536            #root::core::IndexSchema {
2537                name: #name,
2538                columns: &[ #(#cols),* ],
2539                unique: #unique,
2540                method: #method_variant,
2541                where_clause: #where_clause,
2542                include: &[ #(#include_lits),* ],
2543            }
2544        }
2545    });
2546    let checks_tokens = checks.iter().map(|c| {
2547        let name = c.name.as_str();
2548        let expr = c.expr.as_str();
2549        quote! {
2550            #root::core::CheckConstraint {
2551                name: #name,
2552                expr: #expr,
2553            }
2554        }
2555    });
2556    let excludes_tokens = excludes.iter().map(|e| {
2557        let name = e.name.as_str();
2558        let using = e.using.as_str();
2559        let element_tokens = e.elements.iter().map(|(col, op)| {
2560            let col_s = col.as_str();
2561            let op_s = op.as_str();
2562            quote!((#col_s, #op_s))
2563        });
2564        let where_tokens = match e.where_clause.as_deref() {
2565            Some(w) => quote!(::core::option::Option::Some(#w)),
2566            None => quote!(::core::option::Option::None),
2567        };
2568        quote! {
2569            #root::core::ExclusionConstraint {
2570                name: #name,
2571                using: #using,
2572                elements: &[ #(#element_tokens),* ],
2573                where_clause: #where_tokens,
2574            }
2575        }
2576    });
2577    let composite_fk_tokens = composite_fks.iter().map(|rel| {
2578        let name = rel.name.as_str();
2579        let to = rel.to.as_str();
2580        let from_cols: Vec<&str> = rel.from.iter().map(String::as_str).collect();
2581        let on_cols: Vec<&str> = rel.on.iter().map(String::as_str).collect();
2582        quote! {
2583            #root::core::CompositeFkRelation {
2584                name: #name,
2585                to: #to,
2586                from: &[ #(#from_cols),* ],
2587                on: &[ #(#on_cols),* ],
2588            }
2589        }
2590    });
2591    let generic_fk_tokens = generic_fks.iter().map(|rel| {
2592        let name = rel.name.as_str();
2593        let ct_col = rel.ct_column.as_str();
2594        let pk_col = rel.pk_column.as_str();
2595        quote! {
2596            #root::core::GenericRelation {
2597                name: #name,
2598                ct_column: #ct_col,
2599                pk_column: #pk_col,
2600            }
2601        }
2602    });
2603    // Issue #291 / T2.5 — `default_order` slice literal. Empty when
2604    // no `#[rustango(default_order = "...")]` attribute was supplied.
2605    let default_order_tokens = default_order.iter().map(|(col, desc, _)| {
2606        let col_lit = col.as_str();
2607        quote! { (#col_lit, #desc) }
2608    });
2609
2610    // Issue #820 — `global_scopes` slice literal. Empty when no
2611    // `#[rustango(global_scope(...))]` attribute was supplied. The
2612    // `apply` path is re-emitted verbatim so it resolves in the
2613    // consumer's scope; the name is stored as a string literal.
2614    let global_scope_tokens = global_scopes.iter().map(|s| {
2615        let name = s.name.as_str();
2616        let apply = &s.apply;
2617        quote! {
2618            #root::core::GlobalScope {
2619                name: #name,
2620                apply: #apply,
2621            }
2622        }
2623    });
2624
2625    let m2m_tokens = m2m_relations.iter().map(|rel| {
2626        let name = rel.name.as_str();
2627        let to = rel.to.as_str();
2628        let through = rel.through.as_str();
2629        let src = rel.src.as_str();
2630        let dst = rel.dst.as_str();
2631        let auto_create = rel.auto_create;
2632        quote! {
2633            #root::core::M2MRelation {
2634                name: #name,
2635                to: #to,
2636                through: #through,
2637                src_col: #src,
2638                dst_col: #dst,
2639                auto_create: #auto_create,
2640            }
2641        }
2642    });
2643    // Issue #830 sub-piece: emit `Model::reverse_relations()` override
2644    // when the model declares `#[rustango(reverse_has(...))]`. Each
2645    // entry uses `<Child as Model>::SCHEMA.table` so the literal stays
2646    // a const expression. Models without reverse_has fall through to
2647    // the trait's empty default — no override emitted.
2648    let reverse_relations_override = if reverse_has_relations.is_empty() {
2649        quote!()
2650    } else {
2651        let entries = reverse_has_relations.iter().map(|rel| {
2652            let name = rel.name.as_str();
2653            let child = &rel.child;
2654            let child_fk_column = rel.child_fk_column.as_str();
2655            let self_pk_column = rel.self_pk_column.as_str();
2656            quote! {
2657                #root::core::ReverseRelation {
2658                    name: #name,
2659                    child_schema: <#child as #root::core::Model>::SCHEMA,
2660                    child_fk_column: #child_fk_column,
2661                    self_pk_column: #self_pk_column,
2662                }
2663            }
2664        });
2665        quote! {
2666            fn reverse_relations() -> &'static [#root::core::ReverseRelation] {
2667                const RELS: &[#root::core::ReverseRelation] = &[ #(#entries),* ];
2668                RELS
2669            }
2670        }
2671    };
2672    // Issue #830 — `Model::generic_reverse_relations()` override for
2673    // `#[rustango(generic_has(...))]` (the reverse generic-FK arm).
2674    let generic_reverse_relations_override = if generic_has_relations.is_empty() {
2675        quote!()
2676    } else {
2677        let entries = generic_has_relations.iter().map(|rel| {
2678            let name = rel.name.as_str();
2679            let child = &rel.child;
2680            let ct_column = rel.ct_column.as_str();
2681            let pk_column = rel.pk_column.as_str();
2682            let self_pk_column = rel.self_pk_column.as_str();
2683            quote! {
2684                #root::core::GenericReverseRelation {
2685                    name: #name,
2686                    child_schema: <#child as #root::core::Model>::SCHEMA,
2687                    ct_column: #ct_column,
2688                    pk_column: #pk_column,
2689                    self_pk_column: #self_pk_column,
2690                }
2691            }
2692        });
2693        quote! {
2694            fn generic_reverse_relations() -> &'static [#root::core::GenericReverseRelation] {
2695                const RELS: &[#root::core::GenericReverseRelation] = &[ #(#entries),* ];
2696                RELS
2697            }
2698        }
2699    };
2700    quote! {
2701        impl #root::core::Model for #struct_name {
2702            const SCHEMA: &'static #root::core::ModelSchema = &#root::core::ModelSchema {
2703                name: #model_name,
2704                table: #table,
2705                fields: &[ #(#field_schemas),* ],
2706                display: #display_tokens,
2707                app_label: #app_label_tokens,
2708                admin: #admin_tokens,
2709                soft_delete_column: #soft_delete_tokens,
2710                permissions: #permissions,
2711                audit_track: #audit_track_tokens,
2712                m2m: &[ #(#m2m_tokens),* ],
2713                indexes: &[ #(#indexes_tokens),* ],
2714                check_constraints: &[ #(#checks_tokens),* ],
2715                exclusion_constraints: &[ #(#excludes_tokens),* ],
2716                composite_relations: &[ #(#composite_fk_tokens),* ],
2717                generic_relations: &[ #(#generic_fk_tokens),* ],
2718                scope: #scope_tokens,
2719                default_order: &[ #(#default_order_tokens),* ],
2720                is_view: #is_view,
2721                verbose_name: #verbose_name_tokens,
2722                verbose_name_plural: #verbose_name_plural_tokens,
2723                managed: #managed,
2724                base_manager_name: #base_manager_name_tokens,
2725                order_with_respect_to: #order_with_respect_to_tokens,
2726                proxy: #proxy,
2727                required_db_features: &[ #(#required_db_features_lits),* ],
2728                required_db_vendor: #required_db_vendor_tokens,
2729                default_related_name: #default_related_name_tokens,
2730                db_table_comment: #db_table_comment_tokens,
2731                get_latest_by: #get_latest_by_tokens,
2732                extra_permissions: &[ #(#extra_permission_tokens),* ],
2733                default_permissions: &[ #(#default_permission_tokens),* ],
2734                global_scopes: &[ #(#global_scope_tokens),* ],
2735            };
2736
2737            #reverse_relations_override
2738            #generic_reverse_relations_override
2739        }
2740    }
2741}
2742
2743/// Emit the `admin: Option<&'static AdminConfig>` field for the model
2744/// schema. `None` when the user wrote no `#[rustango(admin(...))]`;
2745/// otherwise a static reference to a populated `AdminConfig`.
2746fn admin_config_tokens(admin: Option<&AdminAttrs>) -> TokenStream2 {
2747    let root = rustango_root();
2748    let Some(admin) = admin else {
2749        return quote!(::core::option::Option::None);
2750    };
2751
2752    let list_display = admin
2753        .list_display
2754        .as_ref()
2755        .map(|(v, _)| v.as_slice())
2756        .unwrap_or(&[]);
2757    let list_display_lits = list_display.iter().map(|s| s.as_str());
2758
2759    let search_fields = admin
2760        .search_fields
2761        .as_ref()
2762        .map(|(v, _)| v.as_slice())
2763        .unwrap_or(&[]);
2764    let search_fields_lits = search_fields.iter().map(|s| s.as_str());
2765
2766    let readonly_fields = admin
2767        .readonly_fields
2768        .as_ref()
2769        .map(|(v, _)| v.as_slice())
2770        .unwrap_or(&[]);
2771    let readonly_fields_lits = readonly_fields.iter().map(|s| s.as_str());
2772
2773    let list_filter = admin
2774        .list_filter
2775        .as_ref()
2776        .map(|(v, _)| v.as_slice())
2777        .unwrap_or(&[]);
2778    let list_filter_lits = list_filter.iter().map(|s| s.as_str());
2779
2780    let actions = admin
2781        .actions
2782        .as_ref()
2783        .map(|(v, _)| v.as_slice())
2784        .unwrap_or(&[]);
2785    let actions_lits = actions.iter().map(|s| s.as_str());
2786
2787    let fieldsets = admin
2788        .fieldsets
2789        .as_ref()
2790        .map(|(v, _)| v.as_slice())
2791        .unwrap_or(&[]);
2792    let fieldset_tokens = fieldsets.iter().map(|(title, fields)| {
2793        let title = title.as_str();
2794        let field_lits = fields.iter().map(|s| s.as_str());
2795        quote!(#root::core::Fieldset {
2796            title: #title,
2797            fields: &[ #( #field_lits ),* ],
2798        })
2799    });
2800
2801    let list_display_links = admin
2802        .list_display_links
2803        .as_ref()
2804        .map(|(v, _)| v.as_slice())
2805        .unwrap_or(&[]);
2806    let list_display_links_lits = list_display_links.iter().map(|s| s.as_str());
2807
2808    let search_help_text = admin.search_help_text.as_deref().unwrap_or("");
2809    let actions_on_top = admin.actions_on_top.unwrap_or(true);
2810    let actions_on_bottom = admin.actions_on_bottom.unwrap_or(false);
2811    let date_hierarchy = admin.date_hierarchy.as_deref().unwrap_or("");
2812
2813    let prepopulated = admin
2814        .prepopulated_fields
2815        .as_ref()
2816        .map(|(v, _)| v.as_slice())
2817        .unwrap_or(&[]);
2818    let prepopulated_tokens = prepopulated.iter().map(|(target, sources)| {
2819        let target = target.as_str();
2820        let source_lits = sources.iter().map(|s| s.as_str());
2821        quote!(#root::core::PrepopulatedField {
2822            target: #target,
2823            sources: &[ #( #source_lits ),* ],
2824        })
2825    });
2826
2827    let raw_id_fields = admin
2828        .raw_id_fields
2829        .as_ref()
2830        .map(|(v, _)| v.as_slice())
2831        .unwrap_or(&[]);
2832    let raw_id_fields_lits = raw_id_fields.iter().map(|s| s.as_str());
2833
2834    let autocomplete_fields = admin
2835        .autocomplete_fields
2836        .as_ref()
2837        .map(|(v, _)| v.as_slice())
2838        .unwrap_or(&[]);
2839    let autocomplete_fields_lits = autocomplete_fields.iter().map(|s| s.as_str());
2840
2841    // #352 — list_select_related accepts "all" | "none" | "field, field, …".
2842    let list_select_related_tokens = match admin.list_select_related.as_deref() {
2843        None | Some("all") => quote!(#root::core::ListSelectRelated::All),
2844        Some("none") => quote!(#root::core::ListSelectRelated::None),
2845        Some(raw) => {
2846            let names: Vec<&str> = raw
2847                .split(',')
2848                .map(str::trim)
2849                .filter(|s| !s.is_empty())
2850                .collect();
2851            quote!(#root::core::ListSelectRelated::Only(&[ #( #names ),* ]))
2852        }
2853    };
2854
2855    // #359 — formfield_overrides: parse "field:widget,field2:widget2" into
2856    // a Vec<(String, String)>. Empty / unset → no overrides.
2857    let formfield_pairs: Vec<(&str, &str)> = admin
2858        .formfield_overrides
2859        .as_ref()
2860        .map(|(v, _)| v.iter().map(|(f, w)| (f.as_str(), w.as_str())).collect())
2861        .unwrap_or_default();
2862    let formfield_tokens = formfield_pairs.iter().map(|(field, widget)| {
2863        let field = *field;
2864        let widget = *widget;
2865        quote!((#field, #widget))
2866    });
2867
2868    let list_per_page = admin.list_per_page.unwrap_or(0);
2869
2870    let ordering_pairs = admin
2871        .ordering
2872        .as_ref()
2873        .map(|(v, _)| v.as_slice())
2874        .unwrap_or(&[]);
2875    let ordering_tokens = ordering_pairs.iter().map(|(name, desc)| {
2876        let name = name.as_str();
2877        let desc = *desc;
2878        quote!((#name, #desc))
2879    });
2880
2881    quote! {
2882        ::core::option::Option::Some(&#root::core::AdminConfig {
2883            list_display: &[ #( #list_display_lits ),* ],
2884            search_fields: &[ #( #search_fields_lits ),* ],
2885            list_per_page: #list_per_page,
2886            ordering: &[ #( #ordering_tokens ),* ],
2887            readonly_fields: &[ #( #readonly_fields_lits ),* ],
2888            list_filter: &[ #( #list_filter_lits ),* ],
2889            actions: &[ #( #actions_lits ),* ],
2890            fieldsets: &[ #( #fieldset_tokens ),* ],
2891            list_display_links: &[ #( #list_display_links_lits ),* ],
2892            search_help_text: #search_help_text,
2893            actions_on_top: #actions_on_top,
2894            actions_on_bottom: #actions_on_bottom,
2895            date_hierarchy: #date_hierarchy,
2896            prepopulated_fields: &[ #( #prepopulated_tokens ),* ],
2897            raw_id_fields: &[ #( #raw_id_fields_lits ),* ],
2898            autocomplete_fields: &[ #( #autocomplete_fields_lits ),* ],
2899            list_select_related: #list_select_related_tokens,
2900            formfield_overrides: &[ #( #formfield_tokens ),* ],
2901        })
2902    }
2903}
2904
2905fn inherent_impl_tokens(
2906    struct_name: &syn::Ident,
2907    fields: &CollectedFields,
2908    primary_key: Option<&(syn::Ident, String)>,
2909    column_consts: &TokenStream2,
2910    audited_fields: Option<&[&ColumnEntry]>,
2911    indexes: &[IndexAttr],
2912    manager_fns: &[syn::Ident],
2913) -> TokenStream2 {
2914    let root = rustango_root();
2915    // Audit-emit fragments threaded into write paths. Non-empty only
2916    // when the model carries `#[rustango(audit(...))]`. They reborrow
2917    // `_executor` (a `&mut PgConnection` for audited models — the
2918    // macro switches the signature below) so the data write and the
2919    // audit INSERT both run on the same caller-supplied connection.
2920    let executor_passes_to_data_write = if audited_fields.is_some() {
2921        quote!(&mut *_executor)
2922    } else {
2923        quote!(_executor)
2924    };
2925    let executor_param = if audited_fields.is_some() {
2926        quote!(_executor: &mut #root::sql::sqlx::PgConnection)
2927    } else {
2928        quote!(_executor: _E)
2929    };
2930    let executor_generics = if audited_fields.is_some() {
2931        quote!()
2932    } else {
2933        quote!(<'_c, _E>)
2934    };
2935    let executor_where = if audited_fields.is_some() {
2936        quote!()
2937    } else {
2938        quote! {
2939            where
2940                _E: #root::sql::sqlx::Executor<'_c, Database = #root::sql::sqlx::Postgres>,
2941        }
2942    };
2943    // For audited models the `_on` methods take `&mut PgConnection`, so
2944    // the &PgPool convenience wrappers (`save`, `insert`, `delete`)
2945    // must acquire a connection first. Non-audited models keep the
2946    // direct delegation since `&PgPool` IS an Executor.
2947    let pool_to_save_on = if audited_fields.is_some() {
2948        quote! {
2949            let mut _conn = pool.acquire().await?;
2950            self.save_on(&mut *_conn).await
2951        }
2952    } else {
2953        quote!(self.save_on(pool).await)
2954    };
2955    let pool_to_insert_on = if audited_fields.is_some() {
2956        quote! {
2957            let mut _conn = pool.acquire().await?;
2958            self.insert_on(&mut *_conn).await
2959        }
2960    } else {
2961        quote!(self.insert_on(pool).await)
2962    };
2963    let pool_to_delete_on = if audited_fields.is_some() {
2964        quote! {
2965            let mut _conn = pool.acquire().await?;
2966            self.delete_on(&mut *_conn).await
2967        }
2968    } else {
2969        quote!(self.delete_on(pool).await)
2970    };
2971    let pool_to_bulk_insert_on = if audited_fields.is_some() {
2972        quote! {
2973            let mut _conn = pool.acquire().await?;
2974            Self::bulk_insert_on(rows, &mut *_conn).await
2975        }
2976    } else {
2977        quote!(Self::bulk_insert_on(rows, pool).await)
2978    };
2979    // Pre-existing bug surfaced by batch 22's first audited Auto<T>
2980    // PK test model: `upsert(&PgPool)` body called `self.upsert_on(pool)`
2981    // directly, but `upsert_on` for audited models takes
2982    // `&mut PgConnection` (the audit emit needs a real connection).
2983    // Add the missing acquire shim to keep audited Auto-PK upsert
2984    // compiling.
2985    let pool_to_upsert_on = if audited_fields.is_some() {
2986        quote! {
2987            let mut _conn = pool.acquire().await?;
2988            self.upsert_on(&mut *_conn).await
2989        }
2990    } else {
2991        quote!(self.upsert_on(pool).await)
2992    };
2993
2994    // `insert_pool(&Pool)` — v0.23.0-batch9. Non-audited models only
2995    // (audit-on-connection over &Pool needs a bi-dialect transaction
2996    // helper, deferred). Two body shapes:
2997    // - has_auto: build InsertQuery skipping Auto::Unset columns,
2998    //   request Auto cols in `returning`, dispatch via
2999    //   `insert_returning_pool`, then on the returned `PgRow` /
3000    //   `MySqlAutoId(id)` enum — pull each Auto field from the PG
3001    //   row OR drop the single i64 into the first Auto field on MySQL
3002    //   (multi-Auto models on MySQL error at runtime since
3003    //   `LAST_INSERT_ID()` only reports one)
3004    // - non-Auto: build InsertQuery with explicit columns/values and
3005    //   call `insert_pool` (no returning needed)
3006    // pool_insert_method body for the audited Auto-PK case is moved
3007    // to after audit_pair_tokens / audit_pk_to_string (they live
3008    // ~150 lines below). This block keeps the non-audited and
3009    // non-Auto branches in place — the audited Auto-PK arm is
3010    // computed below and merged via the dispatch helper variable.
3011    let pool_insert_method = if audited_fields.is_some() && !fields.has_auto {
3012        // Audited models with explicit (non-Auto) PKs go through
3013        // the non-Auto insert path below — the audit emit is one
3014        // round-trip after the INSERT inside the same tx via
3015        // audit::save_one_with_audit? No, INSERT semantics
3016        // differ. For non-Auto PK + audited, route through a
3017        // dedicated insert + audit emit on the same tx, but defer
3018        // the macro emission to the audit-bundle-aware block below
3019        // — this `quote!()` placeholder gets overwritten there.
3020        quote!()
3021    } else if audited_fields.is_some() && fields.has_auto {
3022        // Audited Auto-PK insert_pool — assembled after the audit
3023        // bundles. Placeholder; real emission below.
3024        quote!()
3025    } else if fields.has_auto {
3026        let pushes = &fields.insert_pushes;
3027        let returning_cols = &fields.returning_cols;
3028        // When every `Auto<T>` field is filled Rust-side
3029        // (`default_uuid_v7`, issue #823), there is no column to read
3030        // back from the database — `returning_cols` is empty. Route
3031        // through plain `insert_pool` instead of
3032        // `insert_returning_pool` to skip the redundant RETURNING /
3033        // LAST_INSERT_ID round-trip.
3034        if fields.returning_cols.is_empty() {
3035            quote! {
3036                /// Insert this row against either backend. Every
3037                /// `Auto<T>` PK on this model is filled Rust-side
3038                /// (e.g. `default_uuid_v7`) before binding, so no
3039                /// RETURNING round-trip is needed.
3040                ///
3041                /// # Errors
3042                /// As [`Self::insert`].
3043                pub async fn insert_pool(
3044                    &mut self,
3045                    pool: &#root::sql::Pool,
3046                ) -> ::core::result::Result<(), #root::sql::ExecError> {
3047                    let mut _columns: ::std::vec::Vec<&'static str> =
3048                        ::std::vec::Vec::new();
3049                    let mut _values: ::std::vec::Vec<#root::core::SqlValue> =
3050                        ::std::vec::Vec::new();
3051                    #( #pushes )*
3052                    let _query = #root::core::InsertQuery {
3053                        model: <Self as #root::core::Model>::SCHEMA,
3054                        columns: _columns,
3055                        values: _values,
3056                        returning: ::std::vec::Vec::new(),
3057                        on_conflict: ::core::option::Option::None,
3058                    };
3059                    #root::sql::insert_pool(pool, &_query).await
3060                }
3061
3062                /// Eloquent `Model::insertOrIgnore()` — same shape
3063                /// as the auto-PK branch above. Returns `Ok(true)`
3064                /// when inserted, `Ok(false)` when a conflict caused
3065                /// the INSERT to silently skip.
3066                ///
3067                /// # Errors
3068                /// As [`Self::insert`].
3069                pub async fn insert_or_ignore(
3070                    &mut self,
3071                    pool: &#root::sql::Pool,
3072                ) -> ::core::result::Result<bool, #root::sql::ExecError> {
3073                    let mut _columns: ::std::vec::Vec<&'static str> =
3074                        ::std::vec::Vec::new();
3075                    let mut _values: ::std::vec::Vec<#root::core::SqlValue> =
3076                        ::std::vec::Vec::new();
3077                    #( #pushes )*
3078                    let _query = #root::core::InsertQuery {
3079                        model: <Self as #root::core::Model>::SCHEMA,
3080                        columns: _columns,
3081                        values: _values,
3082                        returning: ::std::vec::Vec::new(),
3083                        on_conflict: ::core::option::Option::Some(
3084                            #root::core::ConflictClause::DoNothing,
3085                        ),
3086                    };
3087                    let dialect = pool.dialect();
3088                    let stmt = dialect.compile_insert(&_query)?;
3089                    let rows = #root::sql::raw_execute_pool(
3090                        pool, &stmt.sql, stmt.params,
3091                    ).await?;
3092                    ::core::result::Result::Ok(rows > 0)
3093                }
3094            }
3095        } else {
3096            quote! {
3097                /// Insert this row against either backend, populating any
3098                /// `Auto<T>` PK from the auto-assigned value.
3099                ///
3100                /// # Errors
3101                /// As [`Self::insert`].
3102                pub async fn insert_pool(
3103                    &mut self,
3104                    pool: &#root::sql::Pool,
3105                ) -> ::core::result::Result<(), #root::sql::ExecError> {
3106                    let mut _columns: ::std::vec::Vec<&'static str> =
3107                        ::std::vec::Vec::new();
3108                    let mut _values: ::std::vec::Vec<#root::core::SqlValue> =
3109                        ::std::vec::Vec::new();
3110                    #( #pushes )*
3111                    let _query = #root::core::InsertQuery {
3112                        model: <Self as #root::core::Model>::SCHEMA,
3113                        columns: _columns,
3114                        values: _values,
3115                        returning: ::std::vec![ #( #returning_cols ),* ],
3116                        on_conflict: ::core::option::Option::None,
3117                    };
3118                    let _result = #root::sql::insert_returning_pool(
3119                        pool, &_query,
3120                    ).await?;
3121                    #root::sql::apply_auto_pk(_result, self)
3122                }
3123
3124                /// Eloquent `Model::insertOrIgnore()` — INSERT this
3125                /// row or silently skip on unique-constraint
3126                /// violation. Returns `Ok(true)` when a row was
3127                /// inserted, `Ok(false)` when a conflict caused the
3128                /// INSERT to silently skip.
3129                ///
3130                /// **Caveat on auto-PK models**: when the row is
3131                /// skipped (conflict), this instance's `Auto<T>`
3132                /// fields stay `Unset` — no PK is back-populated
3133                /// because the server didn't auto-assign one. For
3134                /// "insert then read back the PK or the existing
3135                /// row's PK", use the `upsert` family or
3136                /// `get_or_create`.
3137                ///
3138                /// # Errors
3139                /// As [`Self::insert`].
3140                pub async fn insert_or_ignore(
3141                    &mut self,
3142                    pool: &#root::sql::Pool,
3143                ) -> ::core::result::Result<bool, #root::sql::ExecError> {
3144                    let mut _columns: ::std::vec::Vec<&'static str> =
3145                        ::std::vec::Vec::new();
3146                    let mut _values: ::std::vec::Vec<#root::core::SqlValue> =
3147                        ::std::vec::Vec::new();
3148                    #( #pushes )*
3149                    let _query = #root::core::InsertQuery {
3150                        model: <Self as #root::core::Model>::SCHEMA,
3151                        columns: _columns,
3152                        values: _values,
3153                        returning: ::std::vec::Vec::new(),
3154                        on_conflict: ::core::option::Option::Some(
3155                            #root::core::ConflictClause::DoNothing,
3156                        ),
3157                    };
3158                    let dialect = pool.dialect();
3159                    let stmt = dialect.compile_insert(&_query)?;
3160                    let rows = #root::sql::raw_execute_pool(
3161                        pool, &stmt.sql, stmt.params,
3162                    ).await?;
3163                    ::core::result::Result::Ok(rows > 0)
3164                }
3165            }
3166        }
3167    } else {
3168        let insert_columns = &fields.insert_columns;
3169        let insert_values = &fields.insert_values;
3170        quote! {
3171            /// Insert this row into its table against either backend.
3172            /// Equivalent to [`Self::insert`] but takes
3173            /// [`#root::sql::Pool`].
3174            ///
3175            /// # Errors
3176            /// As [`Self::insert`].
3177            pub async fn insert_pool(
3178                &self,
3179                pool: &#root::sql::Pool,
3180            ) -> ::core::result::Result<(), #root::sql::ExecError> {
3181                let _query = #root::core::InsertQuery {
3182                    model: <Self as #root::core::Model>::SCHEMA,
3183                    columns: ::std::vec![ #( #insert_columns ),* ],
3184                    values: ::std::vec![ #( #insert_values ),* ],
3185                    returning: ::std::vec::Vec::new(),
3186                    on_conflict: ::core::option::Option::None,
3187                };
3188                #root::sql::insert_pool(pool, &_query).await
3189            }
3190
3191            /// Eloquent `Model::insertOrIgnore()` — INSERT this row
3192            /// or silently skip on unique-constraint violation. Maps
3193            /// to per-dialect "INSERT ... DO NOTHING on conflict":
3194            /// PG `INSERT … ON CONFLICT DO NOTHING`, SQLite
3195            /// `INSERT … ON CONFLICT DO NOTHING` (3.24+), MySQL
3196            /// `INSERT IGNORE INTO …`.
3197            ///
3198            /// Returns `Ok(true)` when a row was inserted,
3199            /// `Ok(false)` when a conflict caused the INSERT to
3200            /// silently skip.
3201            ///
3202            /// Use for "create-if-absent" patterns where you don't
3203            /// need the row back. For "find-or-create with the row
3204            /// returned", use the queryset-level
3205            /// `crate::sql::get_or_create` free function.
3206            ///
3207            /// # Errors
3208            /// As [`Self::insert`], plus any dialect-specific
3209            /// translation error from the ConflictClause writer.
3210            pub async fn insert_or_ignore(
3211                &self,
3212                pool: &#root::sql::Pool,
3213            ) -> ::core::result::Result<bool, #root::sql::ExecError> {
3214                let _query = #root::core::InsertQuery {
3215                    model: <Self as #root::core::Model>::SCHEMA,
3216                    columns: ::std::vec![ #( #insert_columns ),* ],
3217                    values: ::std::vec![ #( #insert_values ),* ],
3218                    returning: ::std::vec::Vec::new(),
3219                    on_conflict: ::core::option::Option::Some(
3220                        #root::core::ConflictClause::DoNothing,
3221                    ),
3222                };
3223                let dialect = pool.dialect();
3224                let stmt = dialect.compile_insert(&_query)?;
3225                let rows = #root::sql::raw_execute_pool(pool, &stmt.sql, stmt.params).await?;
3226                ::core::result::Result::Ok(rows > 0)
3227            }
3228        }
3229    };
3230
3231    // pool_save_method moved to after audit_pair_tokens /
3232    // audit_pk_to_string (they live ~70 lines below) — needed for
3233    // the audited branch which builds an UpdateQuery + PendingEntry
3234    // and dispatches via audit::save_one_with_audit.
3235
3236    // pool_delete_method moved to after audit_pair_tokens / audit_pk_to_string
3237    // are computed (they live ~80 lines below).
3238
3239    // Build the (column, JSON value) pair list used by every
3240    // snapshot-style audit emission. Reused across delete_on,
3241    // soft_delete_on, restore_on, and (later) bulk paths. Empty
3242    // when the model isn't audited.
3243    let audit_pair_tokens: Vec<TokenStream2> = audited_fields
3244        .map(|tracked| {
3245            tracked
3246                .iter()
3247                .map(|c| {
3248                    let column_lit = c.column.as_str();
3249                    let ident = &c.ident;
3250                    quote! {
3251                        (
3252                            #column_lit,
3253                            #root::__serde_json::to_value(&self.#ident)
3254                                .unwrap_or(#root::__serde_json::Value::Null),
3255                        )
3256                    }
3257                })
3258                .collect()
3259        })
3260        .unwrap_or_default();
3261    let audit_pk_to_string = if let Some((pk_ident, _)) = primary_key {
3262        if fields.pk_is_auto {
3263            quote!(self.#pk_ident.get().map(|v| ::std::format!("{}", v)).unwrap_or_default())
3264        } else {
3265            quote!(::std::format!("{}", &self.#pk_ident))
3266        }
3267    } else {
3268        quote!(::std::string::String::new())
3269    };
3270    let make_op_emit = |op_path: TokenStream2| -> TokenStream2 {
3271        if audited_fields.is_some() {
3272            let pairs = audit_pair_tokens.iter();
3273            let pk_str = audit_pk_to_string.clone();
3274            quote! {
3275                let _audit_entry = #root::audit::PendingEntry {
3276                    entity_table: <Self as #root::core::Model>::SCHEMA.table,
3277                    entity_pk: #pk_str,
3278                    operation: #op_path,
3279                    source: #root::audit::current_source(),
3280                    changes: #root::audit::snapshot_changes(&[
3281                        #( #pairs ),*
3282                    ]),
3283                };
3284                #root::audit::emit_one(&mut *_executor, &_audit_entry).await?;
3285            }
3286        } else {
3287            quote!()
3288        }
3289    };
3290    let audit_insert_emit = make_op_emit(quote!(#root::audit::AuditOp::Create));
3291    let audit_delete_emit = make_op_emit(quote!(#root::audit::AuditOp::Delete));
3292    let audit_softdelete_emit = make_op_emit(quote!(#root::audit::AuditOp::SoftDelete));
3293    let audit_restore_emit = make_op_emit(quote!(#root::audit::AuditOp::Restore));
3294
3295    // `save_pool(&Pool)` — emitted for every model with a PK.
3296    // Audited Auto-PK models are deferred (the Auto::Unset →
3297    // insert_pool path needs the audited-insert flow from a future
3298    // batch). Three body shapes:
3299    // - non-audited, plain PK: build UpdateQuery + dispatch through
3300    //   sql::update_pool
3301    // - non-audited, Auto-PK: same, but Auto::Unset routes to
3302    //   self.insert_pool which already handles RETURNING / LAST_INSERT_ID
3303    // - audited, plain PK: build UpdateQuery + PendingEntry, dispatch
3304    //   through audit::save_one_with_audit (per-backend tx wraps
3305    //   UPDATE + audit emit atomically). Snapshot-style audit (post-
3306    //   write field values) — diff-style audit (with pre-UPDATE
3307    //   SELECT for `before` values) needs per-tracked-column codegen
3308    //   that doesn't fit the runtime-helper pattern; legacy &PgPool
3309    //   `save` keeps the diff for now.
3310    let pool_save_method = if let Some((pk_ident, pk_col)) = primary_key {
3311        let pk_column_lit = pk_col.as_str();
3312        let assignments = &fields.update_assignments;
3313        if audited_fields.is_some() {
3314            if fields.pk_is_auto {
3315                // Auto-PK + audited: defer. The Auto::Unset insert
3316                // path needs a transactional INSERT + LAST_INSERT_ID
3317                // + audit emit flow — that's a follow-up batch.
3318                quote!()
3319            } else {
3320                let pairs = audit_pair_tokens.iter();
3321                let pairs2 = audit_pair_tokens.iter();
3322                let pk_str = audit_pk_to_string.clone();
3323                let pk_str2 = audit_pk_to_string.clone();
3324                quote! {
3325                    /// Save (UPDATE) this row against either backend
3326                    /// with audit emission inside the same transaction.
3327                    /// Bi-dialect counterpart of [`Self::save`] for
3328                    /// audited models with non-`Auto<T>` PKs.
3329                    ///
3330                    /// Captures **post-write** field state (snapshot
3331                    /// audit). The legacy &PgPool [`Self::save`]
3332                    /// captures BEFORE+AFTER for true diff audit;
3333                    /// porting that to the &Pool path needs runtime
3334                    /// per-tracked-column decoding and is deferred.
3335                    ///
3336                    /// # Errors
3337                    /// As [`Self::save`].
3338                    pub async fn save_pool(
3339                        &mut self,
3340                        pool: &#root::sql::Pool,
3341                    ) -> ::core::result::Result<u64, #root::sql::ExecError> {
3342                        let _query = #root::core::UpdateQuery {
3343                            model: <Self as #root::core::Model>::SCHEMA,
3344                            set: ::std::vec![ #( #assignments ),* ],
3345                            where_clause: #root::core::WhereExpr::Predicate(
3346                                #root::core::Filter {
3347                                    column: #pk_column_lit,
3348                                    op: #root::core::Op::Eq,
3349                                    value: ::core::convert::Into::<#root::core::SqlValue>::into(
3350                                        ::core::clone::Clone::clone(&self.#pk_ident)
3351                                    ),
3352                                }
3353                            ),
3354                        };
3355                        let _audit_entry = #root::audit::PendingEntry {
3356                            entity_table: <Self as #root::core::Model>::SCHEMA.table,
3357                            entity_pk: #pk_str,
3358                            operation: #root::audit::AuditOp::Update,
3359                            source: #root::audit::current_source(),
3360                            changes: #root::audit::snapshot_changes(&[
3361                                #( #pairs ),*
3362                            ]),
3363                        };
3364                        let _affected = #root::audit::save_one_with_audit(
3365                            pool, &_query, &_audit_entry,
3366                        ).await?;
3367                        ::core::result::Result::Ok(_affected)
3368                    }
3369
3370                    /// `save_pool` narrowed to a Rust-field allowlist — issue #66.
3371                    /// Audit emission shrinks to the same column set so
3372                    /// the audit log reflects exactly what was written.
3373                    ///
3374                    /// # Errors
3375                    /// As [`Self::save_pool`], plus
3376                    /// [`#root::core::QueryError::UnknownField`] wrapped
3377                    /// in `ExecError::Query` for unknown field names.
3378                    pub async fn save_partial(
3379                        &mut self,
3380                        fields: &[&str],
3381                        pool: &#root::sql::Pool,
3382                    ) -> ::core::result::Result<u64, #root::sql::ExecError> {
3383                        if fields.is_empty() {
3384                            #root::__tracing::warn!(
3385                                target: "rustango::save_partial",
3386                                model = <Self as #root::core::Model>::SCHEMA.name,
3387                                "save_partial called with empty field list — no-op"
3388                            );
3389                            return ::core::result::Result::Ok(0);
3390                        }
3391                        let _schema = <Self as #root::core::Model>::SCHEMA;
3392                        let mut _wanted_cols: ::std::collections::HashSet<&'static str> =
3393                            ::std::collections::HashSet::with_capacity(fields.len());
3394                        for f in fields {
3395                            match _schema.field(f) {
3396                                ::core::option::Option::Some(fs) => {
3397                                    _wanted_cols.insert(fs.column);
3398                                }
3399                                ::core::option::Option::None => {
3400                                    return ::core::result::Result::Err(
3401                                        #root::sql::ExecError::Query(
3402                                            #root::core::QueryError::UnknownField {
3403                                                model: _schema.name,
3404                                                field: (*f).to_owned(),
3405                                            }
3406                                        )
3407                                    );
3408                                }
3409                            }
3410                        }
3411                        let _full: ::std::vec::Vec<#root::core::Assignment> =
3412                            ::std::vec![ #( #assignments ),* ];
3413                        let _filtered: ::std::vec::Vec<#root::core::Assignment> = _full
3414                            .into_iter()
3415                            .filter(|a| _wanted_cols.contains(a.column))
3416                            .collect();
3417                        if _filtered.is_empty() {
3418                            #root::__tracing::warn!(
3419                                target: "rustango::save_partial",
3420                                model = _schema.name,
3421                                "save_partial: every named field maps to a non-assignable column — no-op"
3422                            );
3423                            return ::core::result::Result::Ok(0);
3424                        }
3425                        let _query = #root::core::UpdateQuery {
3426                            model: _schema,
3427                            set: _filtered,
3428                            where_clause: #root::core::WhereExpr::Predicate(
3429                                #root::core::Filter {
3430                                    column: #pk_column_lit,
3431                                    op: #root::core::Op::Eq,
3432                                    value: ::core::convert::Into::<#root::core::SqlValue>::into(
3433                                        ::core::clone::Clone::clone(&self.#pk_ident)
3434                                    ),
3435                                }
3436                            ),
3437                        };
3438                        // Narrow the audit snapshot to the same column set.
3439                        let _all_pairs: ::std::vec::Vec<(&'static str, #root::__serde_json::Value)> =
3440                            ::std::vec![ #( #pairs2 ),* ];
3441                        let _narrowed: ::std::vec::Vec<(&'static str, #root::__serde_json::Value)> =
3442                            _all_pairs
3443                                .into_iter()
3444                                .filter(|(col, _)| _wanted_cols.contains(col))
3445                                .collect();
3446                        let _audit_entry = #root::audit::PendingEntry {
3447                            entity_table: _schema.table,
3448                            entity_pk: #pk_str2,
3449                            operation: #root::audit::AuditOp::Update,
3450                            source: #root::audit::current_source(),
3451                            changes: #root::audit::snapshot_changes(&_narrowed),
3452                        };
3453                        let _affected = #root::audit::save_one_with_audit(
3454                            pool, &_query, &_audit_entry,
3455                        ).await?;
3456                        ::core::result::Result::Ok(_affected)
3457                    }
3458
3459                    /// Typed-column counterpart of [`Self::save_partial`] —
3460                    /// issue #67. `fields` is a tuple of [`Column`]
3461                    /// constants whose `Model` matches `Self`; typos and
3462                    /// model mismatches surface at *compile time*
3463                    /// (`Author::name` inside a `Post::save_partial_typed`
3464                    /// call is a type error, no runtime check).
3465                    ///
3466                    /// ```ignore
3467                    /// post.save_partial_typed((Post::title, Post::slug), &pool).await?;
3468                    /// ```
3469                    ///
3470                    /// Lowers to [`Self::save_partial`] under the hood;
3471                    /// audit narrowing + every other semantic is identical.
3472                    ///
3473                    /// [`Column`]: #root::core::Column
3474                    ///
3475                    /// # Errors
3476                    /// As [`Self::save_partial`].
3477                    pub async fn save_partial_typed<
3478                        L: #root::core::TypedFieldList<Self>,
3479                    >(
3480                        &mut self,
3481                        fields: L,
3482                        pool: &#root::sql::Pool,
3483                    ) -> ::core::result::Result<u64, #root::sql::ExecError> {
3484                        let _names = fields.rust_field_names();
3485                        let _refs: ::std::vec::Vec<&str> =
3486                            _names.iter().copied().collect();
3487                        self.save_partial(&_refs, pool).await
3488                    }
3489                }
3490            }
3491        } else {
3492            let dispatch_unset = if fields.pk_is_auto {
3493                quote! {
3494                    if matches!(self.#pk_ident, #root::sql::Auto::Unset) {
3495                        return self.insert_pool(pool).await.map(|()| 1u64);
3496                    }
3497                }
3498            } else {
3499                quote!()
3500            };
3501            quote! {
3502                /// Save this row to its table against either backend.
3503                /// `INSERT` when the `Auto<T>` PK is `Unset`, else
3504                /// `UPDATE` keyed on the PK.
3505                ///
3506                /// # Errors
3507                /// As [`Self::save`].
3508                pub async fn save_pool(
3509                    &mut self,
3510                    pool: &#root::sql::Pool,
3511                ) -> ::core::result::Result<u64, #root::sql::ExecError> {
3512                    #dispatch_unset
3513                    let _query = #root::core::UpdateQuery {
3514                        model: <Self as #root::core::Model>::SCHEMA,
3515                        set: ::std::vec![ #( #assignments ),* ],
3516                        where_clause: #root::core::WhereExpr::Predicate(
3517                            #root::core::Filter {
3518                                column: #pk_column_lit,
3519                                op: #root::core::Op::Eq,
3520                                value: ::core::convert::Into::<#root::core::SqlValue>::into(
3521                                    ::core::clone::Clone::clone(&self.#pk_ident)
3522                                ),
3523                            }
3524                        ),
3525                    };
3526                    let _affected = #root::sql::update_pool(pool, &_query).await?;
3527                    ::core::result::Result::Ok(_affected)
3528                }
3529
3530                /// Save (UPDATE) only the listed Rust-side fields,
3531                /// leaving every other column untouched. Issue #66.
3532                ///
3533                /// `fields` are Rust-side struct field names; the macro
3534                /// resolves each to its SQL column. Unknown field
3535                /// names return [`#root::core::QueryError::UnknownField`]
3536                /// wrapped in `ExecError::Query`. An empty list is a
3537                /// no-op (returns `Ok(())` and logs a `tracing::warn!`).
3538                ///
3539                /// Use this when:
3540                /// * you only mutated a couple of fields on a wide row
3541                ///   (avoid re-writing every column on every save), or
3542                /// * two writers diverged after their initial read and
3543                ///   you want to preserve the other writer's changes to
3544                ///   columns you didn't touch.
3545                ///
3546                /// Auto-PK models with an unset PK return
3547                /// [`#root::core::QueryError::UnknownField`] with
3548                /// field name `<pk>` — `save_partial` is an
3549                /// UPDATE-only path. Call [`Self::insert_pool`]
3550                /// (or [`Self::save_pool`] which dispatches based on
3551                /// PK state) for the INSERT case.
3552                ///
3553                /// # Errors
3554                /// As [`Self::save_pool`], plus `UnknownField` for
3555                /// unknown / empty / Auto-Unset cases.
3556                pub async fn save_partial(
3557                    &mut self,
3558                    fields: &[&str],
3559                    pool: &#root::sql::Pool,
3560                ) -> ::core::result::Result<u64, #root::sql::ExecError> {
3561                    if fields.is_empty() {
3562                        #root::__tracing::warn!(
3563                            target: "rustango::save_partial",
3564                            model = <Self as #root::core::Model>::SCHEMA.name,
3565                            "save_partial called with empty field list — no-op"
3566                        );
3567                        return ::core::result::Result::Ok(0);
3568                    }
3569                    let _schema = <Self as #root::core::Model>::SCHEMA;
3570                    // Validate field names against the schema.
3571                    let mut _wanted_cols: ::std::collections::HashSet<&'static str> =
3572                        ::std::collections::HashSet::with_capacity(fields.len());
3573                    for f in fields {
3574                        match _schema.field(f) {
3575                            ::core::option::Option::Some(fs) => {
3576                                _wanted_cols.insert(fs.column);
3577                            }
3578                            ::core::option::Option::None => {
3579                                return ::core::result::Result::Err(
3580                                    #root::sql::ExecError::Query(
3581                                        #root::core::QueryError::UnknownField {
3582                                            model: _schema.name,
3583                                            field: (*f).to_owned(),
3584                                        }
3585                                    )
3586                                );
3587                            }
3588                        }
3589                    }
3590                    // Build the full assignment vec, then keep only the
3591                    // assignments whose column is in `_wanted_cols`.
3592                    let _full: ::std::vec::Vec<#root::core::Assignment> =
3593                        ::std::vec![ #( #assignments ),* ];
3594                    let _filtered: ::std::vec::Vec<#root::core::Assignment> = _full
3595                        .into_iter()
3596                        .filter(|a| _wanted_cols.contains(a.column))
3597                        .collect();
3598                    if _filtered.is_empty() {
3599                        // All field names valid, but they all map to
3600                        // non-assignable slots (PK column, computed/
3601                        // virtual fields, relations without an
3602                        // assignment). Same no-op as an empty list.
3603                        #root::__tracing::warn!(
3604                            target: "rustango::save_partial",
3605                            model = _schema.name,
3606                            "save_partial: every named field maps to a non-assignable column — no-op"
3607                        );
3608                        return ::core::result::Result::Ok(0);
3609                    }
3610                    let _query = #root::core::UpdateQuery {
3611                        model: _schema,
3612                        set: _filtered,
3613                        where_clause: #root::core::WhereExpr::Predicate(
3614                            #root::core::Filter {
3615                                column: #pk_column_lit,
3616                                op: #root::core::Op::Eq,
3617                                value: ::core::convert::Into::<#root::core::SqlValue>::into(
3618                                    ::core::clone::Clone::clone(&self.#pk_ident)
3619                                ),
3620                            }
3621                        ),
3622                    };
3623                    let _affected = #root::sql::update_pool(pool, &_query).await?;
3624                    ::core::result::Result::Ok(_affected)
3625                }
3626
3627                /// Typed-column counterpart of [`Self::save_partial`] —
3628                /// issue #67. `fields` is a tuple of [`Column`]
3629                /// constants whose `Model` matches `Self`; typos and
3630                /// model mismatches surface at *compile time*
3631                /// (`Author::name` inside a `Post::save_partial_typed`
3632                /// call is a type error, no runtime check).
3633                ///
3634                /// ```ignore
3635                /// post.save_partial_typed((Post::title, Post::slug), &pool).await?;
3636                /// ```
3637                ///
3638                /// Lowers to [`Self::save_partial`] under the hood — the
3639                /// tuple is reduced to a `&[&str]` slice of Rust-side
3640                /// field names and forwarded.
3641                ///
3642                /// [`Column`]: #root::core::Column
3643                ///
3644                /// # Errors
3645                /// As [`Self::save_partial`].
3646                pub async fn save_partial_typed<
3647                    L: #root::core::TypedFieldList<Self>,
3648                >(
3649                    &mut self,
3650                    fields: L,
3651                    pool: &#root::sql::Pool,
3652                ) -> ::core::result::Result<u64, #root::sql::ExecError> {
3653                    let _names = fields.rust_field_names();
3654                    let _refs: ::std::vec::Vec<&str> =
3655                        _names.iter().copied().collect();
3656                    self.save_partial(&_refs, pool).await
3657                }
3658            }
3659        }
3660    } else {
3661        quote!()
3662    };
3663
3664    // Audited `insert_pool` (overrides the placeholder set higher up
3665    // in the function). v0.23.0-batch22 — both Auto-PK and non-Auto-PK
3666    // audited models get insert_pool routing through
3667    // audit::insert_one_with_audit (per-backend tx wraps INSERT
3668    // + auto-PK readback + audit emit). Snapshot-style audit (the
3669    // PendingEntry's `changes` carries post-write field values).
3670    let pool_insert_method = if audited_fields.is_some() {
3671        if let Some(_) = primary_key {
3672            let pushes = if fields.has_auto {
3673                fields.insert_pushes.clone()
3674            } else {
3675                // For non-Auto-PK models, the macro normally builds
3676                // {columns, values} from fields.insert_columns +
3677                // fields.insert_values rather than insert_pushes.
3678                // Map those into the pushes shape.
3679                fields
3680                    .insert_columns
3681                    .iter()
3682                    .zip(&fields.insert_values)
3683                    .map(|(col, val)| {
3684                        quote! {
3685                            _columns.push(#col);
3686                            _values.push(#val);
3687                        }
3688                    })
3689                    .collect()
3690            };
3691            let returning_cols: Vec<proc_macro2::TokenStream> = if fields.has_auto {
3692                fields.returning_cols.clone()
3693            } else {
3694                // Non-Auto-PK: still need RETURNING something for the
3695                // audit helper's contract (it errors on empty
3696                // returning). Return the PK column so the audit row
3697                // can carry the assigned PK back. Some non-Auto PKs
3698                // are server-side-default (e.g. UUIDv4 default), so
3699                // RETURNING is genuinely useful.
3700                primary_key
3701                    .map(|(_, col)| {
3702                        let lit = col.as_str();
3703                        vec![quote!(#lit)]
3704                    })
3705                    .unwrap_or_default()
3706            };
3707            let pairs = audit_pair_tokens.iter();
3708            let pk_str = audit_pk_to_string.clone();
3709            quote! {
3710                /// Insert this row against either backend with audit
3711                /// emission inside the same transaction. Bi-dialect
3712                /// counterpart of [`Self::insert`] for audited models.
3713                ///
3714                /// Snapshot-style audit (post-write field values).
3715                ///
3716                /// # Errors
3717                /// As [`Self::insert`].
3718                pub async fn insert_pool(
3719                    &mut self,
3720                    pool: &#root::sql::Pool,
3721                ) -> ::core::result::Result<(), #root::sql::ExecError> {
3722                    let mut _columns: ::std::vec::Vec<&'static str> =
3723                        ::std::vec::Vec::new();
3724                    let mut _values: ::std::vec::Vec<#root::core::SqlValue> =
3725                        ::std::vec::Vec::new();
3726                    #( #pushes )*
3727                    let _query = #root::core::InsertQuery {
3728                        model: <Self as #root::core::Model>::SCHEMA,
3729                        columns: _columns,
3730                        values: _values,
3731                        returning: ::std::vec![ #( #returning_cols ),* ],
3732                        on_conflict: ::core::option::Option::None,
3733                    };
3734                    let _audit_entry = #root::audit::PendingEntry {
3735                        entity_table: <Self as #root::core::Model>::SCHEMA.table,
3736                        entity_pk: #pk_str,
3737                        operation: #root::audit::AuditOp::Create,
3738                        source: #root::audit::current_source(),
3739                        changes: #root::audit::snapshot_changes(&[
3740                            #( #pairs ),*
3741                        ]),
3742                    };
3743                    let _result = #root::audit::insert_one_with_audit(
3744                        pool, &_query, &_audit_entry,
3745                    ).await?;
3746                    #root::sql::apply_auto_pk(_result, self)
3747                }
3748            }
3749        } else {
3750            quote!()
3751        }
3752    } else {
3753        // Keep the non-audited pool_insert_method we built earlier.
3754        pool_insert_method
3755    };
3756
3757    // Update audited save_pool: now that insert_pool is wired for
3758    // audited Auto-PK models, save_pool can dispatch Auto::Unset →
3759    // insert_pool. Non-audited save_pool already does this.
3760    // v0.23.0-batch25 — diff-style audit on the audited save_pool path.
3761    // Replaces the snapshot-only emission with a per-backend transaction
3762    // body that:
3763    //  1. SELECTs the tracked columns by PK (typed Row::try_get per
3764    //     column), capturing BEFORE values
3765    //  2. compiles the UPDATE via pool.dialect() and runs it on the tx
3766    //  3. builds AFTER pairs from &self
3767    //  4. diffs BEFORE/AFTER, emits one PendingEntry with
3768    //     AuditOp::Update + diff_changes(...) on the same tx connection
3769    //  5. commits
3770    //
3771    // Per-backend arms inline the SQL string + placeholder shape, then
3772    // share the `audit_before_pair_tokens` decoder block (Row::try_get
3773    // is polymorphic over Row type — the same tokens work against
3774    // PgRow and MySqlRow as long as the field's Rust type implements
3775    // both Decode<Postgres> and Decode<MySql>, which Auto<T> +
3776    // primitives + chrono/uuid/serde_json::Value all do).
3777    let pool_save_method = if let Some(tracked) = audited_fields {
3778        if let Some((pk_ident, pk_col)) = primary_key {
3779            let pk_column_lit = pk_col.as_str();
3780            // Two iterators — quote!'s `#(#var)*` consumes the
3781            // iterator, and we need to splice the same after-pairs
3782            // sequence into both per-backend arms.
3783            let after_pairs_pg = audit_pair_tokens.iter().collect::<Vec<_>>();
3784            let pk_str = audit_pk_to_string.clone();
3785            // Per-tracked-column BEFORE-pair token list. Each entry
3786            // is `(col_lit, try_get_returning<value_ty>(row, col_lit) → Json)`.
3787            // The Row alias resolves to PgRow / MySqlRow per call site,
3788            // so the same template generates both the PG and MySQL bodies.
3789            let mk_before_pairs =
3790                |getter: proc_macro2::TokenStream| -> Vec<proc_macro2::TokenStream> {
3791                    tracked
3792                        .iter()
3793                        .map(|c| {
3794                            let column_lit = c.column.as_str();
3795                            let value_ty = &c.value_ty;
3796                            quote! {
3797                                (
3798                                    #column_lit,
3799                                    match #getter::<#value_ty>(
3800                                        _audit_before_row, #column_lit,
3801                                    ) {
3802                                        ::core::result::Result::Ok(v) => {
3803                                            #root::__serde_json::to_value(&v)
3804                                                .unwrap_or(#root::__serde_json::Value::Null)
3805                                        }
3806                                        ::core::result::Result::Err(_) => #root::__serde_json::Value::Null,
3807                                    },
3808                                )
3809                            }
3810                        })
3811                        .collect()
3812                };
3813            let before_pairs_pg: Vec<proc_macro2::TokenStream> =
3814                mk_before_pairs(quote!(#root::sql::try_get_returning));
3815            let before_pairs_my: Vec<proc_macro2::TokenStream> =
3816                mk_before_pairs(quote!(#root::sql::try_get_returning_my));
3817            let before_pairs_sqlite: Vec<proc_macro2::TokenStream> =
3818                mk_before_pairs(quote!(#root::sql::try_get_returning_sqlite));
3819            let pg_select_cols: String = tracked
3820                .iter()
3821                .map(|c| format!("\"{}\"", c.column.replace('"', "\"\"")))
3822                .collect::<Vec<_>>()
3823                .join(", ");
3824            let my_select_cols: String = tracked
3825                .iter()
3826                .map(|c| format!("`{}`", c.column.replace('`', "``")))
3827                .collect::<Vec<_>>()
3828                .join(", ");
3829            // SQLite uses double-quote identifier quoting (same as
3830            // Postgres in default config), so the column-list shape
3831            // matches PG.
3832            let sqlite_select_cols: String = pg_select_cols.clone();
3833            let pk_value_for_bind = if fields.pk_is_auto {
3834                quote!(self.#pk_ident.get().copied().unwrap_or_default())
3835            } else {
3836                quote!(::core::clone::Clone::clone(&self.#pk_ident))
3837            };
3838            let assignments = &fields.update_assignments;
3839            let unset_dispatch = if fields.has_auto {
3840                quote! {
3841                    if matches!(self.#pk_ident, #root::sql::Auto::Unset) {
3842                        return self.insert_pool(pool).await.map(|()| 1u64);
3843                    }
3844                }
3845            } else {
3846                quote!()
3847            };
3848            quote! {
3849                /// Save this row against either backend with audit
3850                /// emission (diff-style: BEFORE+AFTER) inside the
3851                /// same transaction. Auto::Unset PK routes to
3852                /// insert_pool. Bi-dialect counterpart of
3853                /// [`Self::save`] for audited models.
3854                ///
3855                /// The audit row's `changes` JSON contains one
3856                /// `{ "field": { "before": …, "after": … } }` entry
3857                /// per tracked column whose value actually changed
3858                /// — same shape as the existing &PgPool save() emits.
3859                ///
3860                /// # Errors
3861                /// As [`Self::save`].
3862                pub async fn save_pool(
3863                    &mut self,
3864                    pool: &#root::sql::Pool,
3865                ) -> ::core::result::Result<u64, #root::sql::ExecError> {
3866                    #unset_dispatch
3867                    let _query = #root::core::UpdateQuery {
3868                        model: <Self as #root::core::Model>::SCHEMA,
3869                        set: ::std::vec![ #( #assignments ),* ],
3870                        where_clause: #root::core::WhereExpr::Predicate(
3871                            #root::core::Filter {
3872                                column: #pk_column_lit,
3873                                op: #root::core::Op::Eq,
3874                                value: ::core::convert::Into::<#root::core::SqlValue>::into(
3875                                    ::core::clone::Clone::clone(&self.#pk_ident)
3876                                ),
3877                            }
3878                        ),
3879                    };
3880                    let _after_pairs: ::std::vec::Vec<(&'static str, #root::__serde_json::Value)> =
3881                        ::std::vec![ #( #after_pairs_pg ),* ];
3882                    #root::audit::save_one_with_diff(
3883                        pool,
3884                        &_query,
3885                        #pk_column_lit,
3886                        ::core::convert::Into::<#root::core::SqlValue>::into(
3887                            #pk_value_for_bind,
3888                        ),
3889                        <Self as #root::core::Model>::SCHEMA.table,
3890                        #pk_str,
3891                        _after_pairs,
3892                        #pg_select_cols,
3893                        #my_select_cols,
3894                        #sqlite_select_cols,
3895                        |_audit_before_row| ::std::vec![ #( #before_pairs_pg ),* ],
3896                        |_audit_before_row| ::std::vec![ #( #before_pairs_my ),* ],
3897                        |_audit_before_row| ::std::vec![ #( #before_pairs_sqlite ),* ],
3898                    ).await
3899                }
3900            }
3901        } else {
3902            quote!()
3903        }
3904    } else {
3905        pool_save_method
3906    };
3907
3908    // `delete_pool(&Pool)` — emitted for every model with a PK. Two
3909    // body shapes:
3910    // - non-audited: simple dispatch through `sql::delete_pool`
3911    // - audited: routes through `audit::delete_one_with_audit`,
3912    //   which opens a per-backend transaction wrapping DELETE +
3913    //   audit emit so the data write and audit row commit atomically.
3914    let pool_delete_method = {
3915        let pk_column_lit = primary_key.map(|(_, col)| col.as_str()).unwrap_or("id");
3916        let pk_ident_for_pool = primary_key.map(|(ident, _)| ident);
3917        if let Some(pk_ident) = pk_ident_for_pool {
3918            if audited_fields.is_some() {
3919                let pairs = audit_pair_tokens.iter();
3920                let pk_str = audit_pk_to_string.clone();
3921                quote! {
3922                    /// Delete this row against either backend with audit
3923                    /// emission inside the same transaction. Bi-dialect
3924                    /// counterpart of [`Self::delete`] for audited models.
3925                    ///
3926                    /// # Errors
3927                    /// As [`Self::delete`].
3928                    pub async fn delete_pool(
3929                        &self,
3930                        pool: &#root::sql::Pool,
3931                    ) -> ::core::result::Result<u64, #root::sql::ExecError> {
3932                        let _query = #root::core::DeleteQuery {
3933                            model: <Self as #root::core::Model>::SCHEMA,
3934                            where_clause: #root::core::WhereExpr::Predicate(
3935                                #root::core::Filter {
3936                                    column: #pk_column_lit,
3937                                    op: #root::core::Op::Eq,
3938                                    value: ::core::convert::Into::<#root::core::SqlValue>::into(
3939                                        ::core::clone::Clone::clone(&self.#pk_ident)
3940                                    ),
3941                                }
3942                            ),
3943                        };
3944                        let _audit_entry = #root::audit::PendingEntry {
3945                            entity_table: <Self as #root::core::Model>::SCHEMA.table,
3946                            entity_pk: #pk_str,
3947                            operation: #root::audit::AuditOp::Delete,
3948                            source: #root::audit::current_source(),
3949                            changes: #root::audit::snapshot_changes(&[
3950                                #( #pairs ),*
3951                            ]),
3952                        };
3953                        #root::audit::delete_one_with_audit(
3954                            pool, &_query, &_audit_entry,
3955                        ).await
3956                    }
3957                }
3958            } else {
3959                quote! {
3960                    /// Delete the row identified by this instance's primary key
3961                    /// against either backend. Equivalent to [`Self::delete`] but
3962                    /// takes [`#root::sql::Pool`] and dispatches per backend.
3963                    ///
3964                    /// # Errors
3965                    /// As [`Self::delete`].
3966                    pub async fn delete_pool(
3967                        &self,
3968                        pool: &#root::sql::Pool,
3969                    ) -> ::core::result::Result<u64, #root::sql::ExecError> {
3970                        let _query = #root::core::DeleteQuery {
3971                            model: <Self as #root::core::Model>::SCHEMA,
3972                            where_clause: #root::core::WhereExpr::Predicate(
3973                                #root::core::Filter {
3974                                    column: #pk_column_lit,
3975                                    op: #root::core::Op::Eq,
3976                                    value: ::core::convert::Into::<#root::core::SqlValue>::into(
3977                                        ::core::clone::Clone::clone(&self.#pk_ident)
3978                                    ),
3979                                }
3980                            ),
3981                        };
3982                        #root::sql::delete_pool(pool, &_query).await
3983                    }
3984                }
3985            }
3986        } else {
3987            quote!()
3988        }
3989    };
3990
3991    // `refresh_from_db_pool(&mut self, pool)` — re-SELECT the row
3992    // matching this instance's PK and overwrite the in-memory state
3993    // with the freshly-fetched columns.
3994    // Issue #825. Only emitted when the model declares a PK; non-PK
3995    // models can't address a specific row.
3996    //
3997    // `replicate(&self)` — Eloquent-style clone-as-insertable. Copies
3998    // every field from `self`; resets the PK to `Auto::Unset` when
3999    // `pk_is_auto` so the next `save_pool` / `insert_pool` allocates
4000    // a fresh autoincrement value. Non-Auto PKs preserve the source
4001    // PK — the caller must overwrite before insert. Pure-Rust, no
4002    // I/O, no dialect surface.
4003    let refresh_replicate_methods = if let Some((pk_ident, _)) = primary_key {
4004        let other_field_clones: Vec<TokenStream2> = fields
4005            .column_entries
4006            .iter()
4007            .filter(|c| &c.ident != pk_ident)
4008            .map(|c| {
4009                let ident = &c.ident;
4010                quote! {
4011                    #ident: ::core::clone::Clone::clone(&self.#ident)
4012                }
4013            })
4014            .collect();
4015        let pk_clone_token = if fields.pk_is_auto {
4016            quote! { #pk_ident: #root::sql::Auto::Unset }
4017        } else {
4018            quote! { #pk_ident: ::core::clone::Clone::clone(&self.#pk_ident) }
4019        };
4020        let replicate_doc = if fields.pk_is_auto {
4021            quote! {
4022                /// Eloquent-style `replicate()` — return a clone of this
4023                /// row with the primary key reset to [`Auto::Unset`] so
4024                /// the copy is ready for `insert_pool` / `save_pool` to
4025                /// allocate a fresh autoincrement value. Every other
4026                /// field is `Clone`d verbatim. Issue #825.
4027                ///
4028                /// `auto_now_add` / `auto_now` timestamp fields are
4029                /// **not** reset (Eloquent's `replicate` doesn't reset
4030                /// them either) — pass them through the normal insert
4031                /// path if you want fresh values, or assign them
4032                /// explicitly after the call.
4033            }
4034        } else {
4035            quote! {
4036                /// Eloquent-style `replicate()` — clone this row
4037                /// verbatim. Because the primary key is **not** an
4038                /// `Auto<T>`, the clone keeps the source PK; the
4039                /// caller must overwrite `copy.<pk>` before inserting
4040                /// to avoid a unique-key violation. Issue #825.
4041            }
4042        };
4043        // 2026-06-07 — field-name / shortcut collision guard.
4044        //
4045        // The macro emits both `pub const <field>: <field>_col = ...`
4046        // (per-field typed-column const, used by the typed-builder
4047        // surface as `Post::id.eq(...)`) AND `pub async fn <shortcut>(...)`
4048        // for the Eloquent shortcuts (`count`, `sum`, `min` …). When a
4049        // model has a field named e.g. `count`, both items would land
4050        // in the same inherent impl with the same name, and the
4051        // compiler rejects the derive with "duplicate definitions".
4052        //
4053        // Drop the conflicting shortcut for that model. Callers can
4054        // still reach the same behavior via
4055        // `QuerySet::<Model>::default().count(&pool)`.
4056        let column_names: ::std::collections::HashSet<String> = fields
4057            .column_entries
4058            .iter()
4059            .map(|c| c.ident.to_string())
4060            .collect();
4061        let emit_if_no_field_collision = |name: &str, tokens: TokenStream2| -> TokenStream2 {
4062            if column_names.contains(name) {
4063                quote! {}
4064            } else {
4065                tokens
4066            }
4067        };
4068        let count_method = emit_if_no_field_collision(
4069            "count",
4070            quote! {
4071                /// Count rows of this model — `SELECT COUNT(*) FROM
4072                /// <table>`. Eloquent `Model::count()` parity.
4073                ///
4074                /// Skipped on models that already declare a field named
4075                /// `count`. Drop into `QuerySet::<Self>::default().count(&pool)`
4076                /// in that case.
4077                ///
4078                /// # Errors
4079                /// As [`CounterPool::count`].
4080                ///
4081                /// [`CounterPool::count`]: rustango::sql::CounterPool::count
4082                pub async fn count(
4083                    pool: &#root::sql::Pool,
4084                ) -> ::core::result::Result<i64, #root::sql::ExecError> {
4085                    use #root::sql::CounterPool as _;
4086                    #root::query::QuerySet::<Self>::default()
4087                        .count(pool)
4088                        .await
4089                }
4090            },
4091        );
4092        let value_method = emit_if_no_field_collision(
4093            "value",
4094            quote! {
4095                /// Pluck a single scalar from the first row.
4096                /// Eloquent `Model::query()->value($col)` parity.
4097                ///
4098                /// Skipped on models that already declare a field named
4099                /// `value`. Drop into
4100                /// `QuerySet::<Self>::default().values_list_flat(col).first::<U>(&pool)` instead.
4101                ///
4102                /// # Errors
4103                /// As `ValuesFlatQuerySet::first`.
4104                pub async fn value<U>(
4105                    col: &str,
4106                    pool: &#root::sql::Pool,
4107                ) -> ::core::result::Result<
4108                    ::core::option::Option<U>,
4109                    #root::sql::ExecError,
4110                >
4111                where
4112                    U: #root::sql::MaybePgScalar
4113                        + #root::sql::MaybeMyScalar
4114                        + #root::sql::MaybeSqliteScalar
4115                        + ::core::marker::Send
4116                        + ::core::marker::Unpin,
4117                {
4118                    let _col_static: &'static str = Self::__resolve_col(col)?;
4119                    #root::query::QuerySet::<Self>::default()
4120                        .values_list_flat(_col_static)
4121                        .first::<U>(pool)
4122                        .await
4123                }
4124            },
4125        );
4126        let sum_method = emit_if_no_field_collision(
4127            "sum",
4128            quote! {
4129                /// `SUM(col)` over every row. Eloquent `Model::sum($col)`.
4130                /// Skipped on models that already declare a field named
4131                /// `sum`.
4132                ///
4133                /// # Errors
4134                /// As [`#root::sql::fetch_aggregate_pool`].
4135                pub async fn sum<U>(
4136                    col: &str,
4137                    pool: &#root::sql::Pool,
4138                ) -> ::core::result::Result<
4139                    ::core::option::Option<U>,
4140                    #root::sql::ExecError,
4141                >
4142                where
4143                    (::core::option::Option<U>,): #root::sql::MaybePgFromRow
4144                        + #root::sql::MaybeMyFromRow
4145                        + #root::sql::MaybeSqliteFromRow
4146                        + ::core::marker::Send
4147                        + ::core::marker::Unpin,
4148                {
4149                    Self::__aggregate_one_pool::<U>(
4150                        col,
4151                        |c| #root::core::AggregateExpr::Sum(c),
4152                        pool,
4153                    )
4154                    .await
4155                }
4156            },
4157        );
4158        let avg_method = emit_if_no_field_collision(
4159            "avg",
4160            quote! {
4161                /// `AVG(col)`. Eloquent `Model::avg($col)`. Skipped on
4162                /// models that already declare a field named `avg`.
4163                ///
4164                /// # Errors
4165                /// As [`#root::sql::fetch_aggregate_pool`].
4166                pub async fn avg<U>(
4167                    col: &str,
4168                    pool: &#root::sql::Pool,
4169                ) -> ::core::result::Result<
4170                    ::core::option::Option<U>,
4171                    #root::sql::ExecError,
4172                >
4173                where
4174                    (::core::option::Option<U>,): #root::sql::MaybePgFromRow
4175                        + #root::sql::MaybeMyFromRow
4176                        + #root::sql::MaybeSqliteFromRow
4177                        + ::core::marker::Send
4178                        + ::core::marker::Unpin,
4179                {
4180                    Self::__aggregate_one_pool::<U>(
4181                        col,
4182                        |c| #root::core::AggregateExpr::Avg(c),
4183                        pool,
4184                    )
4185                    .await
4186                }
4187            },
4188        );
4189        let min_method = emit_if_no_field_collision(
4190            "min",
4191            quote! {
4192                /// `MIN(col)`. Eloquent `Model::min($col)`. Skipped on
4193                /// models that already declare a field named `min`.
4194                ///
4195                /// # Errors
4196                /// As [`#root::sql::fetch_aggregate_pool`].
4197                pub async fn min<U>(
4198                    col: &str,
4199                    pool: &#root::sql::Pool,
4200                ) -> ::core::result::Result<
4201                    ::core::option::Option<U>,
4202                    #root::sql::ExecError,
4203                >
4204                where
4205                    (::core::option::Option<U>,): #root::sql::MaybePgFromRow
4206                        + #root::sql::MaybeMyFromRow
4207                        + #root::sql::MaybeSqliteFromRow
4208                        + ::core::marker::Send
4209                        + ::core::marker::Unpin,
4210                {
4211                    Self::__aggregate_one_pool::<U>(
4212                        col,
4213                        |c| #root::core::AggregateExpr::Min(c),
4214                        pool,
4215                    )
4216                    .await
4217                }
4218            },
4219        );
4220        let max_method = emit_if_no_field_collision(
4221            "max",
4222            quote! {
4223                /// `MAX(col)`. Eloquent `Model::max($col)`. Skipped on
4224                /// models that already declare a field named `max`.
4225                ///
4226                /// # Errors
4227                /// As [`#root::sql::fetch_aggregate_pool`].
4228                pub async fn max<U>(
4229                    col: &str,
4230                    pool: &#root::sql::Pool,
4231                ) -> ::core::result::Result<
4232                    ::core::option::Option<U>,
4233                    #root::sql::ExecError,
4234                >
4235                where
4236                    (::core::option::Option<U>,): #root::sql::MaybePgFromRow
4237                        + #root::sql::MaybeMyFromRow
4238                        + #root::sql::MaybeSqliteFromRow
4239                        + ::core::marker::Send
4240                        + ::core::marker::Unpin,
4241                {
4242                    Self::__aggregate_one_pool::<U>(
4243                        col,
4244                        |c| #root::core::AggregateExpr::Max(c),
4245                        pool,
4246                    )
4247                    .await
4248                }
4249            },
4250        );
4251        let first_method = emit_if_no_field_collision(
4252            "first",
4253            quote! {
4254                /// First row of this model. Eloquent `Model::first()`.
4255                /// Skipped on models that already declare a field named
4256                /// `first`. Drop into `QuerySet::<Self>::default().first(&pool)`.
4257                ///
4258                /// # Errors
4259                /// As `QuerySet::first`.
4260                pub async fn first(
4261                    pool: &#root::sql::Pool,
4262                ) -> ::core::result::Result<
4263                    ::core::option::Option<Self>,
4264                    #root::sql::ExecError,
4265                > {
4266                    #root::query::QuerySet::<Self>::default()
4267                        .first(pool)
4268                        .await
4269                }
4270            },
4271        );
4272        let last_method = emit_if_no_field_collision(
4273            "last",
4274            quote! {
4275                /// Last row of this model by primary-key DESC.
4276                /// Eloquent `Model::query()->latest('id')->first()`
4277                /// parity — fetches the highest-PK row without
4278                /// requiring the caller to spell the PK column.
4279                /// Returns `None` on an empty table.
4280                ///
4281                /// Equivalent to `QuerySet::<Self>::default().last(&pool)`.
4282                /// Skipped on models that already declare a field
4283                /// named `last`.
4284                ///
4285                /// # Errors
4286                /// As `QuerySet::last`.
4287                pub async fn last(
4288                    pool: &#root::sql::Pool,
4289                ) -> ::core::result::Result<
4290                    ::core::option::Option<Self>,
4291                    #root::sql::ExecError,
4292                > {
4293                    #root::query::QuerySet::<Self>::default()
4294                        .last(pool)
4295                        .await
4296                }
4297            },
4298        );
4299        quote! {
4300            /// Re-SELECT this row by its primary key and overwrite
4301            /// every in-memory field with the freshly-fetched value.
4302            /// Issue #825.
4303            ///
4304            /// Use this when the row may have been modified by another
4305            /// process / connection / job since you read it — e.g. after
4306            /// a queued task callback, or to re-sync stale UI state
4307            /// before re-saving.
4308            ///
4309            /// Returns [`ExecError::Driver(sqlx::Error::RowNotFound)`]
4310            /// when the primary key no longer matches any row (e.g.
4311            /// the row was deleted concurrently).
4312            ///
4313            /// # Errors
4314            /// As [`FetcherPool::fetch`]; also `RowNotFound` when
4315            /// the PK no longer exists.
4316            ///
4317            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
4318            pub async fn refresh_from_db(
4319                &mut self,
4320                pool: &#root::sql::Pool,
4321            ) -> ::core::result::Result<(), #root::sql::ExecError> {
4322                use #root::sql::FetcherPool as _;
4323                let _pk_val: #root::core::SqlValue = ::core::convert::Into::into(
4324                    ::core::clone::Clone::clone(&self.#pk_ident),
4325                );
4326                let mut _rows: ::std::vec::Vec<Self> =
4327                    #root::query::QuerySet::<Self>::default()
4328                        .filter(::core::stringify!(#pk_ident), _pk_val)
4329                        .limit(1)
4330                        .fetch(pool)
4331                        .await?;
4332                match _rows.into_iter().next() {
4333                    ::core::option::Option::Some(_fresh) => {
4334                        *self = _fresh;
4335                        ::core::result::Result::Ok(())
4336                    }
4337                    ::core::option::Option::None => ::core::result::Result::Err(
4338                        #root::sql::ExecError::Driver(
4339                            #root::sql::sqlx::Error::RowNotFound,
4340                        ),
4341                    ),
4342                }
4343            }
4344
4345            /// Atomically increment the integer column `col` by
4346            /// `by` for this row. Equivalent to
4347            /// `UPDATE <table> SET <col> = <col> + $1 WHERE <pk> = $2`.
4348            ///
4349            /// **Doesn't mutate `self`** — the in-memory copy is now
4350            /// stale; call [`Self::refresh_from_db`] /
4351            /// [`Self::fresh`] to re-sync. Returns the rows-
4352            /// affected count (0 when the PK doesn't match any row,
4353            /// 1 on success).
4354            ///
4355            /// `col` is the Rust field name as a string; unknown
4356            /// fields surface as `UnknownField` at runtime. Negative
4357            /// `by` values atomically decrement (see also
4358            /// [`Self::decrement`]).
4359            ///
4360            /// # Errors
4361            /// As [`UpdaterPool::execute_pool`].
4362            ///
4363            /// [`UpdaterPool::execute_pool`]: rustango::sql::UpdaterPool::execute_pool
4364            pub async fn increment(
4365                &self,
4366                col: &str,
4367                by: i64,
4368                pool: &#root::sql::Pool,
4369            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
4370                Self::__increment_one(self, col, by, pool).await
4371            }
4372
4373            /// Sibling of [`Self::increment`] — atomically
4374            /// decrement this row's `col` by `by`. Eloquent
4375            /// `$model->decrement($col, $by)` parity. Equivalent to
4376            /// `self.increment(col, -by, &pool)`; the separate name
4377            /// keeps call sites readable.
4378            ///
4379            /// # Errors
4380            /// As [`Self::increment`].
4381            pub async fn decrement(
4382                &self,
4383                col: &str,
4384                by: i64,
4385                pool: &#root::sql::Pool,
4386            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
4387                Self::__increment_one(self, col, -by, pool).await
4388            }
4389
4390            /// Bulk-increment: add `by` to `col` on every row of the
4391            /// table. Eloquent `Model::query()->increment($col, $by)`
4392            /// parity. Use for counters, score adjustments, view
4393            /// rollups.
4394            ///
4395            /// # Errors
4396            /// As [`UpdaterPool::execute_pool`].
4397            ///
4398            /// [`UpdaterPool::execute_pool`]: rustango::sql::UpdaterPool::execute_pool
4399            pub async fn increment_each(
4400                col: &str,
4401                by: i64,
4402                pool: &#root::sql::Pool,
4403            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
4404                Self::__increment_all(col, by, pool).await
4405            }
4406
4407            /// Sibling of [`Self::increment_each`] — bulk-decrement.
4408            ///
4409            /// # Errors
4410            /// As [`Self::increment_each`].
4411            pub async fn decrement_each(
4412                col: &str,
4413                by: i64,
4414                pool: &#root::sql::Pool,
4415            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
4416                Self::__increment_all(col, -by, pool).await
4417            }
4418
4419            /// Internal: forward to
4420            /// [`#root::sql::model_shortcuts::increment_one_pool`].
4421            /// One-line wrapper kept as a per-Model method so the
4422            /// macro's emitted `increment` / `decrement` instance
4423            /// calls don't have to thread `Self` through manually.
4424            #[doc(hidden)]
4425            pub async fn __increment_one(
4426                this: &Self,
4427                col: &str,
4428                by: i64,
4429                pool: &#root::sql::Pool,
4430            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
4431                let _pk_val: #root::core::SqlValue = ::core::convert::Into::into(
4432                    ::core::clone::Clone::clone(&this.#pk_ident),
4433                );
4434                #root::sql::model_shortcuts::increment_one_pool::<Self>(
4435                    ::core::stringify!(#pk_ident),
4436                    _pk_val,
4437                    col,
4438                    by,
4439                    pool,
4440                )
4441                .await
4442            }
4443
4444            /// Internal: forward to
4445            /// [`#root::sql::model_shortcuts::increment_all_pool`].
4446            #[doc(hidden)]
4447            pub async fn __increment_all(
4448                col: &str,
4449                by: i64,
4450                pool: &#root::sql::Pool,
4451            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
4452                #root::sql::model_shortcuts::increment_all_pool::<Self>(col, by, pool).await
4453            }
4454
4455            /// Internal: forward to
4456            /// [`#root::sql::model_shortcuts::resolve_col`].
4457            #[doc(hidden)]
4458            pub fn __resolve_col(
4459                col: &str,
4460            ) -> ::core::result::Result<&'static str, #root::sql::ExecError> {
4461                #root::sql::model_shortcuts::resolve_col::<Self>(col)
4462            }
4463
4464            /// Internal: forward to
4465            /// [`#root::sql::model_shortcuts::add_signed_expr`].
4466            #[doc(hidden)]
4467            #[must_use]
4468            pub fn __add_signed_expr(
4469                col_static: &'static str,
4470                signed_by: i64,
4471            ) -> #root::core::Expr {
4472                #root::sql::model_shortcuts::add_signed_expr(col_static, signed_by)
4473            }
4474
4475            /// Re-SELECT this row by its primary key and return a
4476            /// **new** instance with the freshly-fetched fields.
4477            /// Eloquent `Model::fresh()` parity — non-mutating
4478            /// counterpart of [`Self::refresh_from_db`].
4479            ///
4480            /// Returns `Ok(None)` when the row was deleted
4481            /// concurrently — vs [`Self::refresh_from_db`]
4482            /// which surfaces that as `RowNotFound` because
4483            /// in-place mutation has nothing to write to.
4484            ///
4485            /// Useful when you want to compare the in-memory
4486            /// instance against the persisted state (audit-style
4487            /// diffs, conflict detection) without mutating the
4488            /// reference you already hold.
4489            ///
4490            /// # Errors
4491            /// As [`FetcherPool::fetch`].
4492            ///
4493            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
4494            pub async fn fresh(
4495                &self,
4496                pool: &#root::sql::Pool,
4497            ) -> ::core::result::Result<
4498                ::core::option::Option<Self>,
4499                #root::sql::ExecError,
4500            > {
4501                use #root::sql::FetcherPool as _;
4502                let _pk_val: #root::core::SqlValue = ::core::convert::Into::into(
4503                    ::core::clone::Clone::clone(&self.#pk_ident),
4504                );
4505                let _rows: ::std::vec::Vec<Self> =
4506                    #root::query::QuerySet::<Self>::default()
4507                        .filter(::core::stringify!(#pk_ident), _pk_val)
4508                        .limit(1)
4509                        .fetch(pool)
4510                        .await?;
4511                ::core::result::Result::Ok(_rows.into_iter().next())
4512            }
4513
4514            #replicate_doc
4515            #[must_use]
4516            pub fn replicate(&self) -> Self {
4517                Self {
4518                    #pk_clone_token,
4519                    #( #other_field_clones, )*
4520                }
4521            }
4522
4523            #first_method
4524
4525            #last_method
4526
4527            /// Throwing counterpart of [`Self::first`] —
4528            /// errors with `RowNotFound` when the table is empty.
4529            /// Eloquent `Model::firstOrFail()` parity.
4530            ///
4531            /// # Errors
4532            /// As [`Self::first`]; additionally
4533            /// [`sqlx::Error::RowNotFound`] on empty tables.
4534            ///
4535            /// [`sqlx::Error::RowNotFound`]: rustango::sql::sqlx::Error::RowNotFound
4536            pub async fn first_or_fail(
4537                pool: &#root::sql::Pool,
4538            ) -> ::core::result::Result<Self, #root::sql::ExecError> {
4539                // Route through the queryset rather than `Self::first`,
4540                // which is suppressed on models with a field named
4541                // `first` (field/shortcut collision guard).
4542                match #root::query::QuerySet::<Self>::default().first(pool).await? {
4543                    ::core::option::Option::Some(_row) => ::core::result::Result::Ok(_row),
4544                    ::core::option::Option::None => ::core::result::Result::Err(
4545                        #root::sql::ExecError::Driver(
4546                            #root::sql::sqlx::Error::RowNotFound,
4547                        ),
4548                    ),
4549                }
4550            }
4551
4552            /// Single-column projection — `SELECT <col> FROM
4553            /// <table>`. Returns `Vec<U>` where each element is the
4554            /// decoded value of the column. Eloquent
4555            /// `Model::pluck($column)` parity.
4556            ///
4557            /// Thin wrapper over `QuerySet::<Self>::default()
4558            /// .values_list_flat(col).fetch::<U>(pool)`. `U` must
4559            /// be decodable from the column's SQL type on every
4560            /// dialect the binary targets (common picks: `i64` /
4561            /// `i32` / `String` / `bool` / `f64`).
4562            ///
4563            /// # Errors
4564            /// As `ValuesFlatQuerySet::fetch`.
4565            pub async fn pluck<U>(
4566                col: &'static str,
4567                pool: &#root::sql::Pool,
4568            ) -> ::core::result::Result<::std::vec::Vec<U>, #root::sql::ExecError>
4569            where
4570                U: #root::sql::MaybePgScalar
4571                    + #root::sql::MaybeMyScalar
4572                    + #root::sql::MaybeSqliteScalar
4573                    + ::core::marker::Send
4574                    + ::core::marker::Unpin,
4575            {
4576                #root::query::QuerySet::<Self>::default()
4577                    .values_list_flat(col)
4578                    .fetch::<U>(pool)
4579                    .await
4580            }
4581
4582            /// Eloquent `Model::chunk($n, fn ($chunk) { ... })` —
4583            /// stream every row of this model in batches of `n`,
4584            /// invoking the callback once per batch. Stable PK-ASC
4585            /// ordering so the LIMIT/OFFSET pagination is
4586            /// deterministic across drivers.
4587            ///
4588            /// The callback is async — it can do further DB work
4589            /// (writes, related-row lookups, queue dispatch) per
4590            /// batch. Return `Err(...)` from the callback to abort
4591            /// the iteration early; the error bubbles up.
4592            ///
4593            /// **When to use**: bulk processing flows that can't
4594            /// fit the whole table in memory — sending newsletters,
4595            /// running data migrations, computing summary
4596            /// statistics. For small / known-bounded tables, plain
4597            /// `Self::all(&pool)` is simpler.
4598            ///
4599            /// **Caveat**: ascending OFFSET pagination is O(N²) on
4600            /// large tables. For multi-million-row scans prefer
4601            /// keyset-by-PK (the standard "WHERE id > last_seen"
4602            /// shape) over `chunk(...)`.
4603            ///
4604            /// Skipped on models without a primary key — chunking
4605            /// needs a stable order to avoid skipping / repeating
4606            /// rows across batches.
4607            pub async fn chunk<F, Fut>(
4608                n: i64,
4609                pool: &#root::sql::Pool,
4610                mut cb: F,
4611            ) -> ::core::result::Result<(), #root::sql::ExecError>
4612            where
4613                F: ::core::ops::FnMut(::std::vec::Vec<Self>) -> Fut,
4614                Fut: ::core::future::Future<
4615                    Output = ::core::result::Result<(), #root::sql::ExecError>,
4616                >,
4617            {
4618                use #root::sql::FetcherPool as _;
4619                let pk_col = match Self::primary_key_column() {
4620                    ::core::option::Option::Some(c) => c,
4621                    ::core::option::Option::None => {
4622                        return ::core::result::Result::Ok(());
4623                    }
4624                };
4625                let mut offset: i64 = 0;
4626                loop {
4627                    let rows: ::std::vec::Vec<Self> =
4628                        #root::query::QuerySet::<Self>::default()
4629                            .order_by(&[(pk_col, false)])
4630                            .limit(n)
4631                            .offset(offset)
4632                            .fetch(pool)
4633                            .await?;
4634                    if rows.is_empty() {
4635                        return ::core::result::Result::Ok(());
4636                    }
4637                    let len = rows.len() as i64;
4638                    cb(rows).await?;
4639                    if len < n {
4640                        return ::core::result::Result::Ok(());
4641                    }
4642                    offset += n;
4643                }
4644            }
4645
4646            /// Eloquent `Model::chunkById($n, fn (...))` — same
4647            /// per-batch callback shape as [`Self::chunk`], but uses
4648            /// **keyset pagination** (`WHERE pk > last_seen LIMIT n`)
4649            /// instead of OFFSET. O(N) total scan vs OFFSET's O(N²)
4650            /// — the right choice for multi-million-row sweeps.
4651            ///
4652            /// Requires the primary key to be a signed integer type
4653            /// (`i64` / `i32`); the keyset comparison rides on
4654            /// `__rustango_pk_value()` lowering through
4655            /// `SqlValue::I64` / `SqlValue::I32`. Skipped on
4656            /// non-integer PKs (UUID, String) — those should use
4657            /// the OFFSET-shaped [`Self::chunk`] or a hand-rolled
4658            /// keyset loop.
4659            ///
4660            /// Callback errors abort iteration; the error bubbles up
4661            /// unchanged. Empty table → callback invoked zero times.
4662            pub async fn chunk_by_id<F, Fut>(
4663                n: i64,
4664                pool: &#root::sql::Pool,
4665                mut cb: F,
4666            ) -> ::core::result::Result<(), #root::sql::ExecError>
4667            where
4668                F: ::core::ops::FnMut(::std::vec::Vec<Self>) -> Fut,
4669                Fut: ::core::future::Future<
4670                    Output = ::core::result::Result<(), #root::sql::ExecError>,
4671                >,
4672            {
4673                use #root::sql::FetcherPool as _;
4674                let pk_col = match Self::primary_key_column() {
4675                    ::core::option::Option::Some(c) => c,
4676                    ::core::option::Option::None => {
4677                        return ::core::result::Result::Ok(());
4678                    }
4679                };
4680                // Track the largest PK seen so the next batch picks
4681                // up from there. `i64::MIN` as the sentinel — the
4682                // very first iteration's `> MIN` matches every row,
4683                // so the loop entry is uniform with subsequent
4684                // iterations.
4685                let mut last_seen: i64 = i64::MIN;
4686                loop {
4687                    let key = ::std::format!("{}__gt", pk_col);
4688                    let rows: ::std::vec::Vec<Self> =
4689                        #root::query::QuerySet::<Self>::default()
4690                            .filter(key.as_str(), last_seen)
4691                            .order_by(&[(pk_col, false)])
4692                            .limit(n)
4693                            .fetch(pool)
4694                            .await?;
4695                    if rows.is_empty() {
4696                        return ::core::result::Result::Ok(());
4697                    }
4698                    let len = rows.len() as i64;
4699                    // Capture the last row's PK BEFORE moving rows
4700                    // into the callback.
4701                    let max_pk = match rows
4702                        .last()
4703                        .map(|r| r.__rustango_pk_value())
4704                    {
4705                        ::core::option::Option::Some(
4706                            #root::core::SqlValue::I64(v),
4707                        ) => v,
4708                        ::core::option::Option::Some(
4709                            #root::core::SqlValue::I32(v),
4710                        ) => i64::from(v),
4711                        _ => return ::core::result::Result::Ok(()),
4712                    };
4713                    cb(rows).await?;
4714                    if len < n {
4715                        return ::core::result::Result::Ok(());
4716                    }
4717                    last_seen = max_pk;
4718                }
4719            }
4720
4721            /// Eloquent `Model::each(fn ($row) { ... }, $n)` —
4722            /// per-row callback companion to [`Self::chunk`].
4723            /// Streams every row in keyset-paginated batches of
4724            /// `batch` size, calling `cb` once per row.
4725            ///
4726            /// Inherits the keyset-paginated scan of
4727            /// [`Self::chunk_by_id`] (O(N) total, integer PK only —
4728            /// non-integer PKs are silently a no-op).
4729            ///
4730            /// ```ignore
4731            /// Post::each(500, &pool, |p| async move {
4732            ///     reindex(p).await?;
4733            ///     Ok(())
4734            /// }).await?;
4735            /// ```
4736            ///
4737            /// Return `Err(...)` from the callback to abort
4738            /// iteration; the error bubbles up unchanged.
4739            pub async fn each<F, Fut>(
4740                batch: i64,
4741                pool: &#root::sql::Pool,
4742                mut cb: F,
4743            ) -> ::core::result::Result<(), #root::sql::ExecError>
4744            where
4745                F: ::core::ops::FnMut(Self) -> Fut,
4746                Fut: ::core::future::Future<
4747                    Output = ::core::result::Result<(), #root::sql::ExecError>,
4748                >,
4749            {
4750                use #root::sql::FetcherPool as _;
4751                let pk_col = match Self::primary_key_column() {
4752                    ::core::option::Option::Some(c) => c,
4753                    ::core::option::Option::None => {
4754                        return ::core::result::Result::Ok(());
4755                    }
4756                };
4757                let mut last_seen: i64 = i64::MIN;
4758                loop {
4759                    let key = ::std::format!("{}__gt", pk_col);
4760                    let rows: ::std::vec::Vec<Self> =
4761                        #root::query::QuerySet::<Self>::default()
4762                            .filter(key.as_str(), last_seen)
4763                            .order_by(&[(pk_col, false)])
4764                            .limit(batch)
4765                            .fetch(pool)
4766                            .await?;
4767                    if rows.is_empty() {
4768                        return ::core::result::Result::Ok(());
4769                    }
4770                    let len = rows.len() as i64;
4771                    let max_pk = match rows
4772                        .last()
4773                        .map(|r| r.__rustango_pk_value())
4774                    {
4775                        ::core::option::Option::Some(
4776                            #root::core::SqlValue::I64(v),
4777                        ) => v,
4778                        ::core::option::Option::Some(
4779                            #root::core::SqlValue::I32(v),
4780                        ) => i64::from(v),
4781                        _ => return ::core::result::Result::Ok(()),
4782                    };
4783                    for row in rows {
4784                        cb(row).await?;
4785                    }
4786                    if len < batch {
4787                        return ::core::result::Result::Ok(());
4788                    }
4789                    last_seen = max_pk;
4790                }
4791            }
4792
4793            /// Delete every row of this model — `TRUNCATE TABLE
4794            /// <table> RESTART IDENTITY CASCADE` on Postgres,
4795            /// `DELETE FROM <table>` on MySQL / SQLite (which don't
4796            /// support `TRUNCATE` inside foreign-key constraints
4797            /// or — for SQLite — at all). Eloquent `Model::truncate()`
4798            /// parity.
4799            ///
4800            /// **Use only in tests / fixture-reset flows.** Production
4801            /// writes through this would silently bypass the
4802            /// `pre_delete` / `post_delete` signals (no per-row hooks
4803            /// fire on a TRUNCATE / bulk DELETE FROM) and lose every
4804            /// row's audit-log entry.
4805            ///
4806            /// # Errors
4807            /// As [`raw_execute_pool`].
4808            ///
4809            /// [`raw_execute_pool`]: rustango::sql::raw_execute_pool
4810            pub async fn truncate(
4811                pool: &#root::sql::Pool,
4812            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
4813                let _table = <Self as #root::core::Model>::SCHEMA.table;
4814                let _dialect = pool.dialect();
4815                let _quoted = _dialect.quote_ident(_table);
4816                let _sql = if _dialect.name() == "postgres" {
4817                    ::std::format!("TRUNCATE TABLE {} RESTART IDENTITY CASCADE", _quoted)
4818                } else {
4819                    ::std::format!("DELETE FROM {}", _quoted)
4820                };
4821                #root::sql::raw_execute_pool(pool, &_sql, ::std::vec::Vec::new()).await
4822            }
4823
4824            /// Bulk-delete every row whose primary key is in
4825            /// `pks` — `DELETE FROM <table> WHERE <pk> IN (...)`.
4826            /// Returns the affected row count.
4827            ///
4828            /// Eloquent `Model::destroy([1, 2, 3])` parity.
4829            /// Empty `pks` is a no-op (returns 0).
4830            ///
4831            /// Accepts any iterable whose elements are
4832            /// `Into<SqlValue>` — `Vec<i64>`, `&[i64]`,
4833            /// `[i64; N]`, etc.
4834            ///
4835            /// # Errors
4836            /// As `delete_pool`.
4837            pub async fn destroy<V>(
4838                pks: impl ::core::iter::IntoIterator<Item = V>,
4839                pool: &#root::sql::Pool,
4840            ) -> ::core::result::Result<u64, #root::sql::ExecError>
4841            where
4842                V: ::core::convert::Into<#root::core::SqlValue>,
4843            {
4844                let _values: ::std::vec::Vec<#root::core::SqlValue> =
4845                    pks.into_iter().map(::core::convert::Into::into).collect();
4846                if _values.is_empty() {
4847                    return ::core::result::Result::Ok(0);
4848                }
4849                let _query = #root::core::DeleteQuery {
4850                    model: <Self as #root::core::Model>::SCHEMA,
4851                    where_clause: #root::core::WhereExpr::Predicate(
4852                        #root::core::Filter {
4853                            column: <Self as #root::core::Model>::SCHEMA
4854                                .primary_key()
4855                                .ok_or_else(|| {
4856                                    #root::sql::ExecError::Sql(
4857                                        #root::sql::SqlError::MissingPrimaryKey,
4858                                    )
4859                                })?
4860                                .column,
4861                            op: #root::core::Op::In,
4862                            value: #root::core::SqlValue::List(_values),
4863                        },
4864                    ),
4865                };
4866                #root::sql::delete_pool(pool, &_query).await
4867            }
4868
4869            /// Fetch every row where `<col> = <val>`. Eloquent
4870            /// `Model::where($col, $val)->get()` parity.
4871            ///
4872            /// Thin wrapper over `QuerySet::<Self>::default()
4873            /// .filter(col, val).fetch(pool)`. For one row,
4874            /// use [`Self::first_where`]; for a chain that
4875            /// needs further `.filter()` / `.order_by()` /
4876            /// `.limit()`, drop down to `Self::query().filter(...)`
4877            /// directly.
4878            ///
4879            /// `val` accepts any value `Into<SqlValue>` so plain
4880            /// strings, ints, UUIDs, etc. all work.
4881            ///
4882            /// # Errors
4883            /// As [`FetcherPool::fetch`].
4884            ///
4885            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
4886            pub async fn where_(
4887                col: &str,
4888                val: impl ::core::convert::Into<#root::core::SqlValue>,
4889                pool: &#root::sql::Pool,
4890            ) -> ::core::result::Result<
4891                ::std::vec::Vec<Self>,
4892                #root::sql::ExecError,
4893            > {
4894                use #root::sql::FetcherPool as _;
4895                #root::query::QuerySet::<Self>::default()
4896                    .filter(col, val)
4897                    .fetch(pool)
4898                    .await
4899            }
4900
4901            /// Fetch every row where `<col> IN (vals)`. Eloquent
4902            /// `Model::whereIn($col, $vals)->get()` parity. Empty
4903            /// `vals` returns no rows (matches SQL's empty-IN
4904            /// semantics).
4905            ///
4906            /// `vals` accepts any iterable whose items are
4907            /// `Into<SqlValue>` — `Vec<i64>`, `&[&str]`, `[Uuid; N]`,
4908            /// etc.
4909            ///
4910            /// # Errors
4911            /// As [`FetcherPool::fetch`].
4912            ///
4913            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
4914            pub async fn where_in<V>(
4915                col: &str,
4916                vals: impl ::core::iter::IntoIterator<Item = V>,
4917                pool: &#root::sql::Pool,
4918            ) -> ::core::result::Result<
4919                ::std::vec::Vec<Self>,
4920                #root::sql::ExecError,
4921            >
4922            where
4923                V: ::core::convert::Into<#root::core::SqlValue>,
4924            {
4925                use #root::sql::FetcherPool as _;
4926                let _values: ::std::vec::Vec<#root::core::SqlValue> =
4927                    vals.into_iter().map(::core::convert::Into::into).collect();
4928                if _values.is_empty() {
4929                    return ::core::result::Result::Ok(::std::vec::Vec::new());
4930                }
4931                let _key = ::std::format!("{}__in", col);
4932                #root::query::QuerySet::<Self>::default()
4933                    .filter(&_key, #root::core::SqlValue::List(_values))
4934                    .fetch(pool)
4935                    .await
4936            }
4937
4938            /// Fetch every row where `<col> NOT IN (vals)`. Eloquent
4939            /// `Model::whereNotIn($col, $vals)->get()` parity. Empty
4940            /// `vals` returns every row (matches SQL's empty-NOT-IN
4941            /// semantics — vacuously true for every row).
4942            ///
4943            /// # Errors
4944            /// As [`FetcherPool::fetch`].
4945            ///
4946            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
4947            pub async fn where_not_in<V>(
4948                col: &str,
4949                vals: impl ::core::iter::IntoIterator<Item = V>,
4950                pool: &#root::sql::Pool,
4951            ) -> ::core::result::Result<
4952                ::std::vec::Vec<Self>,
4953                #root::sql::ExecError,
4954            >
4955            where
4956                V: ::core::convert::Into<#root::core::SqlValue>,
4957            {
4958                use #root::sql::FetcherPool as _;
4959                let _values: ::std::vec::Vec<#root::core::SqlValue> =
4960                    vals.into_iter().map(::core::convert::Into::into).collect();
4961                if _values.is_empty() {
4962                    return #root::query::QuerySet::<Self>::default()
4963                        .fetch(pool)
4964                        .await;
4965                }
4966                let _key = ::std::format!("{}__not_in", col);
4967                #root::query::QuerySet::<Self>::default()
4968                    .filter(&_key, #root::core::SqlValue::List(_values))
4969                    .fetch(pool)
4970                    .await
4971            }
4972
4973            /// Fetch every row where `<col> IS NULL`. Eloquent
4974            /// `Model::whereNull($col)->get()` parity.
4975            ///
4976            /// # Errors
4977            /// As [`FetcherPool::fetch`].
4978            ///
4979            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
4980            pub async fn where_null(
4981                col: &str,
4982                pool: &#root::sql::Pool,
4983            ) -> ::core::result::Result<
4984                ::std::vec::Vec<Self>,
4985                #root::sql::ExecError,
4986            > {
4987                use #root::sql::FetcherPool as _;
4988                let _key = ::std::format!("{}__isnull", col);
4989                #root::query::QuerySet::<Self>::default()
4990                    .filter(&_key, #root::core::SqlValue::Bool(true))
4991                    .fetch(pool)
4992                    .await
4993            }
4994
4995            /// Fetch every row where `<col> IS NOT NULL`. Eloquent
4996            /// `Model::whereNotNull($col)->get()` parity.
4997            ///
4998            /// # Errors
4999            /// As [`FetcherPool::fetch`].
5000            ///
5001            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5002            pub async fn where_not_null(
5003                col: &str,
5004                pool: &#root::sql::Pool,
5005            ) -> ::core::result::Result<
5006                ::std::vec::Vec<Self>,
5007                #root::sql::ExecError,
5008            > {
5009                use #root::sql::FetcherPool as _;
5010                let _key = ::std::format!("{}__isnull", col);
5011                #root::query::QuerySet::<Self>::default()
5012                    .filter(&_key, #root::core::SqlValue::Bool(false))
5013                    .fetch(pool)
5014                    .await
5015            }
5016
5017            /// Fetch up to `n` rows in random order. Eloquent
5018            /// `Model::inRandomOrder()->limit($n)->get()` /
5019            /// `Model::query()->inRandomOrder()->get()->take($n)`
5020            /// parity. **Performance caveat**: random ordering
5021            /// forces a full table scan + per-row random key sort;
5022            /// the optimizer cannot use an index. Prefer a
5023            /// `pk >= rand_offset LIMIT N` walk for huge tables.
5024            ///
5025            /// # Errors
5026            /// As [`FetcherPool::fetch`].
5027            ///
5028            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5029            pub async fn random_n(
5030                n: i64,
5031                pool: &#root::sql::Pool,
5032            ) -> ::core::result::Result<
5033                ::std::vec::Vec<Self>,
5034                #root::sql::ExecError,
5035            > {
5036                use #root::sql::FetcherPool as _;
5037                #root::query::QuerySet::<Self>::default()
5038                    .order_random()
5039                    .limit(n)
5040                    .fetch(pool)
5041                    .await
5042            }
5043
5044            /// Fetch one row in random order. Eloquent
5045            /// `Model::inRandomOrder()->first()` parity. Same
5046            /// performance caveat as [`Self::random_n`].
5047            ///
5048            /// # Errors
5049            /// As [`FetcherPool::fetch`].
5050            ///
5051            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5052            pub async fn random(
5053                pool: &#root::sql::Pool,
5054            ) -> ::core::result::Result<
5055                ::core::option::Option<Self>,
5056                #root::sql::ExecError,
5057            > {
5058                ::core::result::Result::Ok(
5059                    Self::random_n(1, pool).await?.into_iter().next(),
5060                )
5061            }
5062
5063            /// Fetch every row ordered ASC by `field`. Eloquent
5064            /// `Model::oldest($field)->get()` parity — the multi-row
5065            /// counterpart of [`Self::earliest`].
5066            ///
5067            /// # Errors
5068            /// As [`FetcherPool::fetch`].
5069            ///
5070            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5071            pub async fn oldest(
5072                field: &str,
5073                pool: &#root::sql::Pool,
5074            ) -> ::core::result::Result<
5075                ::std::vec::Vec<Self>,
5076                #root::sql::ExecError,
5077            > {
5078                use #root::sql::FetcherPool as _;
5079                #root::query::QuerySet::<Self>::default()
5080                    .order_by(&[(field, false)])
5081                    .fetch(pool)
5082                    .await
5083            }
5084
5085            /// Fetch every row ordered DESC by `field`. Eloquent
5086            /// `Model::latest($field)->get()` parity — the multi-row
5087            /// counterpart of [`Self::latest`].
5088            ///
5089            /// # Errors
5090            /// As [`FetcherPool::fetch`].
5091            ///
5092            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5093            pub async fn newest(
5094                field: &str,
5095                pool: &#root::sql::Pool,
5096            ) -> ::core::result::Result<
5097                ::std::vec::Vec<Self>,
5098                #root::sql::ExecError,
5099            > {
5100                use #root::sql::FetcherPool as _;
5101                #root::query::QuerySet::<Self>::default()
5102                    .order_by(&[(field, true)])
5103                    .fetch(pool)
5104                    .await
5105            }
5106
5107            /// Fetch every row where `EXTRACT(YEAR FROM <col>) = year`.
5108            /// Eloquent `Model::whereYear($col, $year)->get()` parity.
5109            /// Routes through the existing `__year` lookup suffix
5110            /// (issue #829).
5111            ///
5112            /// # Errors
5113            /// As [`FetcherPool::fetch`].
5114            ///
5115            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5116            pub async fn where_year(
5117                col: &str,
5118                year: i64,
5119                pool: &#root::sql::Pool,
5120            ) -> ::core::result::Result<
5121                ::std::vec::Vec<Self>,
5122                #root::sql::ExecError,
5123            > {
5124                use #root::sql::FetcherPool as _;
5125                let _key = ::std::format!("{}__year", col);
5126                #root::query::QuerySet::<Self>::default()
5127                    .filter(&_key, #root::core::SqlValue::I64(year))
5128                    .fetch(pool)
5129                    .await
5130            }
5131
5132            /// Fetch every row where `EXTRACT(MONTH FROM <col>) = month`.
5133            /// Eloquent `Model::whereMonth($col, $m)->get()` parity.
5134            /// `month` is 1–12.
5135            ///
5136            /// # Errors
5137            /// As [`FetcherPool::fetch`].
5138            ///
5139            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5140            pub async fn where_month(
5141                col: &str,
5142                month: i64,
5143                pool: &#root::sql::Pool,
5144            ) -> ::core::result::Result<
5145                ::std::vec::Vec<Self>,
5146                #root::sql::ExecError,
5147            > {
5148                use #root::sql::FetcherPool as _;
5149                let _key = ::std::format!("{}__month", col);
5150                #root::query::QuerySet::<Self>::default()
5151                    .filter(&_key, #root::core::SqlValue::I64(month))
5152                    .fetch(pool)
5153                    .await
5154            }
5155
5156            /// Fetch every row where `EXTRACT(DAY FROM <col>) = day`.
5157            /// Eloquent `Model::whereDay($col, $d)->get()` parity.
5158            /// `day` is 1–31.
5159            ///
5160            /// # Errors
5161            /// As [`FetcherPool::fetch`].
5162            ///
5163            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5164            pub async fn where_day(
5165                col: &str,
5166                day: i64,
5167                pool: &#root::sql::Pool,
5168            ) -> ::core::result::Result<
5169                ::std::vec::Vec<Self>,
5170                #root::sql::ExecError,
5171            > {
5172                use #root::sql::FetcherPool as _;
5173                let _key = ::std::format!("{}__day", col);
5174                #root::query::QuerySet::<Self>::default()
5175                    .filter(&_key, #root::core::SqlValue::I64(day))
5176                    .fetch(pool)
5177                    .await
5178            }
5179
5180            /// Fetch every row where `EXTRACT(HOUR FROM <col>) = hour`.
5181            /// Eloquent `Model::whereHour($col, $h)->get()` parity.
5182            /// `hour` is 0–23.
5183            ///
5184            /// # Errors
5185            /// As [`FetcherPool::fetch`].
5186            ///
5187            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5188            pub async fn where_hour(
5189                col: &str,
5190                hour: i64,
5191                pool: &#root::sql::Pool,
5192            ) -> ::core::result::Result<
5193                ::std::vec::Vec<Self>,
5194                #root::sql::ExecError,
5195            > {
5196                use #root::sql::FetcherPool as _;
5197                let _key = ::std::format!("{}__hour", col);
5198                #root::query::QuerySet::<Self>::default()
5199                    .filter(&_key, #root::core::SqlValue::I64(hour))
5200                    .fetch(pool)
5201                    .await
5202            }
5203
5204            /// Fetch every row where `EXTRACT(MINUTE FROM <col>) = minute`.
5205            /// Eloquent `Model::whereMinute($col, $m)->get()` parity.
5206            /// `minute` is 0–59.
5207            ///
5208            /// # Errors
5209            /// As [`FetcherPool::fetch`].
5210            ///
5211            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5212            pub async fn where_minute(
5213                col: &str,
5214                minute: i64,
5215                pool: &#root::sql::Pool,
5216            ) -> ::core::result::Result<
5217                ::std::vec::Vec<Self>,
5218                #root::sql::ExecError,
5219            > {
5220                use #root::sql::FetcherPool as _;
5221                let _key = ::std::format!("{}__minute", col);
5222                #root::query::QuerySet::<Self>::default()
5223                    .filter(&_key, #root::core::SqlValue::I64(minute))
5224                    .fetch(pool)
5225                    .await
5226            }
5227
5228            /// Fetch every row where `<col> LIKE <pattern>` —
5229            /// caller-supplied pattern (must include `%` / `_`
5230            /// wildcards manually). Eloquent `Model::whereLike`
5231            /// parity.
5232            ///
5233            /// # Errors
5234            /// As [`FetcherPool::fetch`].
5235            ///
5236            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5237            pub async fn where_like(
5238                col: &str,
5239                pattern: impl ::core::convert::Into<::std::string::String>,
5240                pool: &#root::sql::Pool,
5241            ) -> ::core::result::Result<
5242                ::std::vec::Vec<Self>,
5243                #root::sql::ExecError,
5244            > {
5245                use #root::sql::FetcherPool as _;
5246                let _key = ::std::format!("{}__like", col);
5247                #root::query::QuerySet::<Self>::default()
5248                    .filter(
5249                        &_key,
5250                        #root::core::SqlValue::String(pattern.into()),
5251                    )
5252                    .fetch(pool)
5253                    .await
5254            }
5255
5256            /// Fetch every row where `<col> ILIKE <pattern>` —
5257            /// case-insensitive LIKE (PG native, MySQL/SQLite
5258            /// emulated via `LOWER(col) LIKE LOWER(pattern)`).
5259            ///
5260            /// # Errors
5261            /// As [`FetcherPool::fetch`].
5262            ///
5263            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5264            pub async fn where_ilike(
5265                col: &str,
5266                pattern: impl ::core::convert::Into<::std::string::String>,
5267                pool: &#root::sql::Pool,
5268            ) -> ::core::result::Result<
5269                ::std::vec::Vec<Self>,
5270                #root::sql::ExecError,
5271            > {
5272                use #root::sql::FetcherPool as _;
5273                let _key = ::std::format!("{}__ilike", col);
5274                #root::query::QuerySet::<Self>::default()
5275                    .filter(
5276                        &_key,
5277                        #root::core::SqlValue::String(pattern.into()),
5278                    )
5279                    .fetch(pool)
5280                    .await
5281            }
5282
5283            /// Fetch every row where `<col>` starts with `prefix`
5284            /// (auto-appends `%`). Eloquent
5285            /// `whereLike("col", "$prefix%")` parity.
5286            ///
5287            /// # Errors
5288            /// As [`FetcherPool::fetch`].
5289            ///
5290            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5291            pub async fn where_starts_with(
5292                col: &str,
5293                prefix: impl ::core::convert::Into<::std::string::String>,
5294                pool: &#root::sql::Pool,
5295            ) -> ::core::result::Result<
5296                ::std::vec::Vec<Self>,
5297                #root::sql::ExecError,
5298            > {
5299                use #root::sql::FetcherPool as _;
5300                let _key = ::std::format!("{}__startswith", col);
5301                #root::query::QuerySet::<Self>::default()
5302                    .filter(
5303                        &_key,
5304                        #root::core::SqlValue::String(prefix.into()),
5305                    )
5306                    .fetch(pool)
5307                    .await
5308            }
5309
5310            /// Fetch every row where `<col>` ends with `suffix`
5311            /// (auto-prepends `%`). Eloquent
5312            /// `whereLike("col", "%$suffix")` parity.
5313            ///
5314            /// # Errors
5315            /// As [`FetcherPool::fetch`].
5316            ///
5317            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5318            pub async fn where_ends_with(
5319                col: &str,
5320                suffix: impl ::core::convert::Into<::std::string::String>,
5321                pool: &#root::sql::Pool,
5322            ) -> ::core::result::Result<
5323                ::std::vec::Vec<Self>,
5324                #root::sql::ExecError,
5325            > {
5326                use #root::sql::FetcherPool as _;
5327                let _key = ::std::format!("{}__endswith", col);
5328                #root::query::QuerySet::<Self>::default()
5329                    .filter(
5330                        &_key,
5331                        #root::core::SqlValue::String(suffix.into()),
5332                    )
5333                    .fetch(pool)
5334                    .await
5335            }
5336
5337            /// Fetch every row where `<col>` contains `substr`
5338            /// (auto-wraps with `%`).
5339            /// Eloquent `whereLike("col", "%$substr%")` parity.
5340            ///
5341            /// # Errors
5342            /// As [`FetcherPool::fetch`].
5343            ///
5344            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5345            pub async fn where_contains(
5346                col: &str,
5347                substr: impl ::core::convert::Into<::std::string::String>,
5348                pool: &#root::sql::Pool,
5349            ) -> ::core::result::Result<
5350                ::std::vec::Vec<Self>,
5351                #root::sql::ExecError,
5352            > {
5353                use #root::sql::FetcherPool as _;
5354                let _key = ::std::format!("{}__contains", col);
5355                #root::query::QuerySet::<Self>::default()
5356                    .filter(
5357                        &_key,
5358                        #root::core::SqlValue::String(substr.into()),
5359                    )
5360                    .fetch(pool)
5361                    .await
5362            }
5363
5364            /// Fetch every row where `<col> > val`. Eloquent
5365            /// `Model::where($col, ">", $val)->get()` parity.
5366            ///
5367            /// # Errors
5368            /// As [`FetcherPool::fetch`].
5369            ///
5370            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5371            pub async fn where_gt(
5372                col: &str,
5373                val: impl ::core::convert::Into<#root::core::SqlValue>,
5374                pool: &#root::sql::Pool,
5375            ) -> ::core::result::Result<
5376                ::std::vec::Vec<Self>,
5377                #root::sql::ExecError,
5378            > {
5379                use #root::sql::FetcherPool as _;
5380                let _key = ::std::format!("{}__gt", col);
5381                #root::query::QuerySet::<Self>::default()
5382                    .filter(&_key, val)
5383                    .fetch(pool)
5384                    .await
5385            }
5386
5387            /// Fetch every row where `<col> >= val`. Eloquent
5388            /// `Model::where($col, ">=", $val)->get()` parity.
5389            ///
5390            /// # Errors
5391            /// As [`FetcherPool::fetch`].
5392            ///
5393            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5394            pub async fn where_gte(
5395                col: &str,
5396                val: impl ::core::convert::Into<#root::core::SqlValue>,
5397                pool: &#root::sql::Pool,
5398            ) -> ::core::result::Result<
5399                ::std::vec::Vec<Self>,
5400                #root::sql::ExecError,
5401            > {
5402                use #root::sql::FetcherPool as _;
5403                let _key = ::std::format!("{}__gte", col);
5404                #root::query::QuerySet::<Self>::default()
5405                    .filter(&_key, val)
5406                    .fetch(pool)
5407                    .await
5408            }
5409
5410            /// Fetch every row where `<col> < val`. Eloquent
5411            /// `Model::where($col, "<", $val)->get()` parity.
5412            ///
5413            /// # Errors
5414            /// As [`FetcherPool::fetch`].
5415            ///
5416            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5417            pub async fn where_lt(
5418                col: &str,
5419                val: impl ::core::convert::Into<#root::core::SqlValue>,
5420                pool: &#root::sql::Pool,
5421            ) -> ::core::result::Result<
5422                ::std::vec::Vec<Self>,
5423                #root::sql::ExecError,
5424            > {
5425                use #root::sql::FetcherPool as _;
5426                let _key = ::std::format!("{}__lt", col);
5427                #root::query::QuerySet::<Self>::default()
5428                    .filter(&_key, val)
5429                    .fetch(pool)
5430                    .await
5431            }
5432
5433            /// Fetch every row where `<col> <= val`. Eloquent
5434            /// `Model::where($col, "<=", $val)->get()` parity.
5435            ///
5436            /// # Errors
5437            /// As [`FetcherPool::fetch`].
5438            ///
5439            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5440            pub async fn where_lte(
5441                col: &str,
5442                val: impl ::core::convert::Into<#root::core::SqlValue>,
5443                pool: &#root::sql::Pool,
5444            ) -> ::core::result::Result<
5445                ::std::vec::Vec<Self>,
5446                #root::sql::ExecError,
5447            > {
5448                use #root::sql::FetcherPool as _;
5449                let _key = ::std::format!("{}__lte", col);
5450                #root::query::QuerySet::<Self>::default()
5451                    .filter(&_key, val)
5452                    .fetch(pool)
5453                    .await
5454            }
5455
5456            /// Fetch every row where `<col> <> val`. Eloquent
5457            /// `Model::where($col, "!=", $val)->get()` parity.
5458            ///
5459            /// # Errors
5460            /// As [`FetcherPool::fetch`].
5461            ///
5462            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5463            pub async fn where_ne(
5464                col: &str,
5465                val: impl ::core::convert::Into<#root::core::SqlValue>,
5466                pool: &#root::sql::Pool,
5467            ) -> ::core::result::Result<
5468                ::std::vec::Vec<Self>,
5469                #root::sql::ExecError,
5470            > {
5471                use #root::sql::FetcherPool as _;
5472                let _key = ::std::format!("{}__ne", col);
5473                #root::query::QuerySet::<Self>::default()
5474                    .filter(&_key, val)
5475                    .fetch(pool)
5476                    .await
5477            }
5478
5479            /// Fetch every row matching `<col> = val` for ANY of the
5480            /// listed columns. Eloquent `Model::whereAny($cols, $val)`
5481            /// parity. Empty `cols` returns no rows.
5482            ///
5483            /// Resolves each `&str` column to its SCHEMA-registered
5484            /// `&'static str` once and builds a single OR-composed
5485            /// `Q` expression (`col1 = ? OR col2 = ? OR …`).
5486            ///
5487            /// # Errors
5488            /// As [`FetcherPool::fetch`]; `QueryError::UnknownField`
5489            /// when any column is not declared on the model.
5490            ///
5491            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5492            pub async fn where_any(
5493                cols: &[&str],
5494                val: impl ::core::convert::Into<#root::core::SqlValue>,
5495                pool: &#root::sql::Pool,
5496            ) -> ::core::result::Result<
5497                ::std::vec::Vec<Self>,
5498                #root::sql::ExecError,
5499            > {
5500                Self::__where_multi(cols, val, false, pool).await
5501            }
5502
5503            /// Fetch every row matching `<col> = val` for ALL listed
5504            /// columns. Eloquent `Model::whereAll($cols, $val)` parity.
5505            /// Empty `cols` returns every row (vacuous AND).
5506            ///
5507            /// # Errors
5508            /// As [`Self::where_any`].
5509            pub async fn where_all(
5510                cols: &[&str],
5511                val: impl ::core::convert::Into<#root::core::SqlValue>,
5512                pool: &#root::sql::Pool,
5513            ) -> ::core::result::Result<
5514                ::std::vec::Vec<Self>,
5515                #root::sql::ExecError,
5516            > {
5517                Self::__where_multi(cols, val, true, pool).await
5518            }
5519
5520            /// Internal: build a Q expression composing `cols` via
5521            /// AND (`all`) or OR (`!all`), then fetch. Backs
5522            /// `where_any` / `where_all`.
5523            #[doc(hidden)]
5524            pub async fn __where_multi(
5525                cols: &[&str],
5526                val: impl ::core::convert::Into<#root::core::SqlValue>,
5527                all: bool,
5528                pool: &#root::sql::Pool,
5529            ) -> ::core::result::Result<
5530                ::std::vec::Vec<Self>,
5531                #root::sql::ExecError,
5532            > {
5533                #root::sql::model_shortcuts::where_multi_pool::<Self>(cols, val, all, pool)
5534                    .await
5535            }
5536
5537            /// Fetch up to `n` rows. Eloquent `Model::take($n)->get()`
5538            /// parity. PK-ordered
5539            /// is NOT guaranteed without an explicit `order_by` —
5540            /// drop into `Self::query()` for that.
5541            ///
5542            /// # Errors
5543            /// As [`FetcherPool::fetch`].
5544            ///
5545            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5546            pub async fn take(
5547                n: i64,
5548                pool: &#root::sql::Pool,
5549            ) -> ::core::result::Result<
5550                ::std::vec::Vec<Self>,
5551                #root::sql::ExecError,
5552            > {
5553                use #root::sql::FetcherPool as _;
5554                #root::query::QuerySet::<Self>::default()
5555                    .limit(n)
5556                    .fetch(pool)
5557                    .await
5558            }
5559
5560            /// Fetch the page-th window of `per_page` rows
5561            /// (1-indexed). Eloquent
5562            /// `Model::query()->forPage($page, $perPage)->get()`
5563            /// parity. The DB scans an `OFFSET (page - 1) * per_page
5564            /// LIMIT per_page`; for large offsets this is O(N) —
5565            /// prefer keyset pagination via PK on hot paths.
5566            ///
5567            /// # Errors
5568            /// As [`FetcherPool::fetch`].
5569            ///
5570            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5571            pub async fn for_page(
5572                page: i64,
5573                per_page: i64,
5574                pool: &#root::sql::Pool,
5575            ) -> ::core::result::Result<
5576                ::std::vec::Vec<Self>,
5577                #root::sql::ExecError,
5578            > {
5579                use #root::sql::FetcherPool as _;
5580                let _offset = if page > 1 { (page - 1) * per_page } else { 0 };
5581                #root::query::QuerySet::<Self>::default()
5582                    .limit(per_page)
5583                    .offset(_offset)
5584                    .fetch(pool)
5585                    .await
5586            }
5587
5588            /// Eloquent `Model::paginate($per_page, $page)` — fetch
5589            /// one page of rows AND the total row count in one
5590            /// call. Returns `(rows, total)`. Two queries: a
5591            /// LIMIT/OFFSET SELECT for the page + a `SELECT COUNT(*)`
5592            /// for the total.
5593            ///
5594            /// Useful for paginated UIs that need both the visible
5595            /// rows AND a "Page X of Y" / total-count widget. For
5596            /// large tables prefer keyset pagination + cached count;
5597            /// every call to `paginate` re-counts the full table.
5598            ///
5599            /// Same 1-indexed `page` convention as [`Self::for_page`].
5600            ///
5601            /// # Errors
5602            /// As [`Self::for_page`] and [`Self::count`].
5603            pub async fn paginate(
5604                page: i64,
5605                per_page: i64,
5606                pool: &#root::sql::Pool,
5607            ) -> ::core::result::Result<
5608                (::std::vec::Vec<Self>, i64),
5609                #root::sql::ExecError,
5610            > {
5611                // Route through the queryset rather than `Self::count`:
5612                // the `count` inherent method is suppressed on models
5613                // that declare a field named `count` (field/shortcut
5614                // collision guard), and `paginate` must still compile
5615                // for those models.
5616                let total = {
5617                    use #root::sql::CounterPool as _;
5618                    #root::query::QuerySet::<Self>::default()
5619                        .count(pool)
5620                        .await?
5621                };
5622                let rows = Self::for_page(page, per_page, pool).await?;
5623                ::core::result::Result::Ok((rows, total))
5624            }
5625
5626            /// Bulk-update — set `set_col = set_val` on every row
5627            /// matching `where_col = where_val`. Returns affected row
5628            /// count. Eloquent
5629            /// `Model::where($where_col, $where_val)->update([$set_col => $set_val])`
5630            /// parity.
5631            ///
5632            /// For multi-column updates drop into the queryset
5633            /// builder: `Self::query().filter(...).update().set(...).set(...).execute_pool(&pool)`.
5634            ///
5635            /// # Errors
5636            /// As [`UpdaterPool::execute_pool`].
5637            ///
5638            /// [`UpdaterPool::execute_pool`]: rustango::sql::UpdaterPool::execute_pool
5639            pub async fn update_where(
5640                where_col: &str,
5641                where_val: impl ::core::convert::Into<#root::core::SqlValue>,
5642                set_col: &str,
5643                set_val: impl ::core::convert::Into<#root::core::SqlValue>,
5644                pool: &#root::sql::Pool,
5645            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
5646                use #root::sql::UpdaterPool as _;
5647                #root::query::QuerySet::<Self>::default()
5648                    .filter(where_col, where_val)
5649                    .update()
5650                    .set(set_col, set_val)
5651                    .execute_pool(pool)
5652                    .await
5653            }
5654
5655            /// Bulk-delete — remove every row matching
5656            /// `where_col = where_val`. Returns affected row count.
5657            /// Eloquent
5658            /// `Model::where($where_col, $where_val)->delete()` parity.
5659            ///
5660            /// For more complex filters drop into the queryset
5661            /// builder + `Self::query().filter(...).delete().execute_pool(&pool)`.
5662            ///
5663            /// # Errors
5664            /// As [`#root::sql::delete_pool`].
5665            pub async fn delete_where(
5666                where_col: &str,
5667                where_val: impl ::core::convert::Into<#root::core::SqlValue>,
5668                pool: &#root::sql::Pool,
5669            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
5670                let _query = #root::core::DeleteQuery {
5671                    model: <Self as #root::core::Model>::SCHEMA,
5672                    where_clause: #root::core::WhereExpr::Predicate(
5673                        #root::core::Filter {
5674                            column: <Self as #root::core::Model>::SCHEMA
5675                                .field(where_col)
5676                                .ok_or_else(|| {
5677                                    #root::sql::ExecError::Query(
5678                                        #root::core::QueryError::UnknownField {
5679                                            model: <Self as #root::core::Model>::SCHEMA.name,
5680                                            field: ::std::string::ToString::to_string(where_col),
5681                                        },
5682                                    )
5683                                })?
5684                                .column,
5685                            op: #root::core::Op::Eq,
5686                            value: ::core::convert::Into::into(where_val),
5687                        },
5688                    ),
5689                };
5690                #root::sql::delete_pool(pool, &_query).await
5691            }
5692
5693            /// Bulk-update — set `set_col = set_val` on EVERY row of
5694            /// this model's table. **No WHERE clause** — use with
5695            /// care. Eloquent `Model::query()->update([$col => $val])`
5696            /// parity.
5697            ///
5698            /// Use for backfills, one-shot reset flows, etc. The
5699            /// returned count is rows affected.
5700            ///
5701            /// # Errors
5702            /// As [`UpdaterPool::execute_pool`].
5703            ///
5704            /// [`UpdaterPool::execute_pool`]: rustango::sql::UpdaterPool::execute_pool
5705            pub async fn update_all(
5706                set_col: &str,
5707                set_val: impl ::core::convert::Into<#root::core::SqlValue>,
5708                pool: &#root::sql::Pool,
5709            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
5710                use #root::sql::UpdaterPool as _;
5711                #root::query::QuerySet::<Self>::default()
5712                    .update()
5713                    .set(set_col, set_val)
5714                    .execute_pool(pool)
5715                    .await
5716            }
5717
5718            /// Fetch every row where `<col> NOT LIKE <pattern>`.
5719            /// Eloquent `Model::whereNotLike` parity. Pattern is
5720            /// passed verbatim — caller controls `%` / `_`.
5721            ///
5722            /// # Errors
5723            /// As [`FetcherPool::fetch`].
5724            ///
5725            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5726            pub async fn where_not_like(
5727                col: &str,
5728                pattern: impl ::core::convert::Into<::std::string::String>,
5729                pool: &#root::sql::Pool,
5730            ) -> ::core::result::Result<
5731                ::std::vec::Vec<Self>,
5732                #root::sql::ExecError,
5733            > {
5734                use #root::sql::FetcherPool as _;
5735                let _key = ::std::format!("{}__not_like", col);
5736                #root::query::QuerySet::<Self>::default()
5737                    .filter(
5738                        &_key,
5739                        #root::core::SqlValue::String(pattern.into()),
5740                    )
5741                    .fetch(pool)
5742                    .await
5743            }
5744
5745            /// Fetch every row where `<col> NOT ILIKE <pattern>` —
5746            /// case-insensitive `NOT LIKE` (PG native, MySQL /
5747            /// SQLite emulated via `LOWER(col) NOT LIKE LOWER(pattern)`).
5748            ///
5749            /// # Errors
5750            /// As [`FetcherPool::fetch`].
5751            ///
5752            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5753            pub async fn where_not_ilike(
5754                col: &str,
5755                pattern: impl ::core::convert::Into<::std::string::String>,
5756                pool: &#root::sql::Pool,
5757            ) -> ::core::result::Result<
5758                ::std::vec::Vec<Self>,
5759                #root::sql::ExecError,
5760            > {
5761                use #root::sql::FetcherPool as _;
5762                let _key = ::std::format!("{}__not_ilike", col);
5763                #root::query::QuerySet::<Self>::default()
5764                    .filter(
5765                        &_key,
5766                        #root::core::SqlValue::String(pattern.into()),
5767                    )
5768                    .fetch(pool)
5769                    .await
5770            }
5771
5772            /// Fetch every row where `<col> NOT BETWEEN lo AND hi`.
5773            /// Eloquent `Model::whereNotBetween($col, [$lo, $hi])`
5774            /// parity.
5775            ///
5776            /// # Errors
5777            /// As [`FetcherPool::fetch`].
5778            ///
5779            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5780            pub async fn where_not_between(
5781                col: &str,
5782                lo: impl ::core::convert::Into<#root::core::SqlValue>,
5783                hi: impl ::core::convert::Into<#root::core::SqlValue>,
5784                pool: &#root::sql::Pool,
5785            ) -> ::core::result::Result<
5786                ::std::vec::Vec<Self>,
5787                #root::sql::ExecError,
5788            > {
5789                use #root::sql::FetcherPool as _;
5790                let _key = ::std::format!("{}__not_between", col);
5791                let _vals = #root::core::SqlValue::List(::std::vec![
5792                    ::core::convert::Into::into(lo),
5793                    ::core::convert::Into::into(hi),
5794                ]);
5795                #root::query::QuerySet::<Self>::default()
5796                    .filter(&_key, _vals)
5797                    .fetch(pool)
5798                    .await
5799            }
5800
5801            /// Returns the SQL table name for this model. Eloquent
5802            /// `$model->getTable()` parity.
5803            #[must_use]
5804            pub fn table_name() -> &'static str {
5805                <Self as #root::core::Model>::SCHEMA.table
5806            }
5807
5808            /// Returns the SQL column name of this model's primary
5809            /// key, or `None` when the model has no
5810            /// `#[rustango(primary_key)]`. Eloquent
5811            /// `$model->getKeyName()` parity.
5812            #[must_use]
5813            pub fn primary_key_column() -> ::core::option::Option<&'static str> {
5814                <Self as #root::core::Model>::SCHEMA
5815                    .primary_key()
5816                    .map(|f| f.column)
5817            }
5818
5819            /// Fetch every row where `<col> BETWEEN lo AND hi`
5820            /// (inclusive on both ends — same as SQL). Eloquent
5821            /// `Model::whereBetween($col, [$lo, $hi])->get()` parity.
5822            ///
5823            /// # Errors
5824            /// As [`FetcherPool::fetch`].
5825            ///
5826            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
5827            pub async fn where_between(
5828                col: &str,
5829                lo: impl ::core::convert::Into<#root::core::SqlValue>,
5830                hi: impl ::core::convert::Into<#root::core::SqlValue>,
5831                pool: &#root::sql::Pool,
5832            ) -> ::core::result::Result<
5833                ::std::vec::Vec<Self>,
5834                #root::sql::ExecError,
5835            > {
5836                use #root::sql::FetcherPool as _;
5837                let _key = ::std::format!("{}__between", col);
5838                let _vals = #root::core::SqlValue::List(::std::vec![
5839                    ::core::convert::Into::into(lo),
5840                    ::core::convert::Into::into(hi),
5841                ]);
5842                #root::query::QuerySet::<Self>::default()
5843                    .filter(&_key, _vals)
5844                    .fetch(pool)
5845                    .await
5846            }
5847
5848            /// Fetch the first row where `<col> = <val>`. Returns
5849            /// `Ok(None)` when no row matches. Eloquent
5850            /// `Model::firstWhere($col, $val)` parity.
5851            ///
5852            /// Thin wrapper over `QuerySet::<Self>::default()
5853            /// .filter(col, val).first(pool)`. Use this when you
5854            /// want one row identified by a non-PK column (e.g.
5855            /// `User::first_where_pool("email", "x@y.com", &pool)`).
5856            ///
5857            /// `val` accepts any value `Into<SqlValue>` so plain
5858            /// strings, ints, UUIDs, etc. all work.
5859            ///
5860            /// # Errors
5861            /// As `QuerySet::first`.
5862            pub async fn first_where(
5863                col: &str,
5864                val: impl ::core::convert::Into<#root::core::SqlValue>,
5865                pool: &#root::sql::Pool,
5866            ) -> ::core::result::Result<
5867                ::core::option::Option<Self>,
5868                #root::sql::ExecError,
5869            > {
5870                #root::query::QuerySet::<Self>::default()
5871                    .filter(col, val)
5872                    .first(pool)
5873                    .await
5874            }
5875
5876            #value_method
5877
5878            /// Fetch the row with the largest `field` value —
5879            /// `SELECT … ORDER BY <field> DESC LIMIT 1`. Returns
5880            /// `Ok(None)` for an empty table. Eloquent
5881            /// `Model::latest($field)->first()` parity.
5882            /// Thin wrapper over `QuerySet::<Self>::default()
5883            /// .latest(field, pool)`.
5884            ///
5885            /// **Field name** is the Rust field ident as a string
5886            /// (not the SQL column). It is a runtime `&str`, so an
5887            /// unknown one compiles and surfaces as
5888            /// `ExecError::Query(QueryError::UnknownField)` when the
5889            /// query runs.
5890            ///
5891            /// # Errors
5892            /// As `QuerySet::latest`.
5893            pub async fn latest(
5894                field: &str,
5895                pool: &#root::sql::Pool,
5896            ) -> ::core::result::Result<
5897                ::core::option::Option<Self>,
5898                #root::sql::ExecError,
5899            > {
5900                #root::query::QuerySet::<Self>::default()
5901                    .latest(field, pool)
5902                    .await
5903            }
5904
5905            /// Sibling of [`Self::latest`] — fetches the row
5906            /// with the smallest `field` value (`ORDER BY <field>
5907            /// ASC LIMIT 1`). Eloquent `Model::oldest($field)
5908            /// ->first()` parity.
5909            ///
5910            /// # Errors
5911            /// As [`Self::latest`].
5912            pub async fn earliest(
5913                field: &str,
5914                pool: &#root::sql::Pool,
5915            ) -> ::core::result::Result<
5916                ::core::option::Option<Self>,
5917                #root::sql::ExecError,
5918            > {
5919                #root::query::QuerySet::<Self>::default()
5920                    .earliest(field, pool)
5921                    .await
5922            }
5923
5924            #count_method
5925
5926            /// `true` when the table contains at least one row.
5927            /// Eloquent `Model::query()->exists()` parity. Thin wrapper
5928            /// over `QuerySet::<Self>::default().exists(pool)`.
5929            ///
5930            /// # Errors
5931            /// As [`ExistsPool::exists`].
5932            ///
5933            /// [`ExistsPool::exists`]: rustango::sql::ExistsPool::exists
5934            pub async fn exists(
5935                pool: &#root::sql::Pool,
5936            ) -> ::core::result::Result<bool, #root::sql::ExecError> {
5937                use #root::sql::ExistsPool as _;
5938                #root::query::QuerySet::<Self>::default()
5939                    .exists(pool)
5940                    .await
5941            }
5942
5943            /// Inverse of [`Self::exists`] — returns `true` when
5944            /// the table has zero rows. Eloquent
5945            /// `Model::doesntExist()` parity.
5946            ///
5947            /// # Errors
5948            /// As [`Self::exists`].
5949            pub async fn doesnt_exist(
5950                pool: &#root::sql::Pool,
5951            ) -> ::core::result::Result<bool, #root::sql::ExecError> {
5952                Self::exists(pool).await.map(|e| !e)
5953            }
5954
5955            /// Eloquent `Model::query()->whereKey($pk)->exists()` —
5956            /// `true` when a row with primary key `pk` exists in
5957            /// the table. Sugar over
5958            /// `QuerySet::<Self>::default().contains_pk(pool, pk)`.
5959            ///
5960            /// Differs from [`Self::exists`] (which checks "any row
5961            /// in the table") by checking a specific PK existence.
5962            /// Cheaper than `Self::find(pk, &pool).await?.is_some()`
5963            /// because the row is never materialized — the SQL is
5964            /// `SELECT COUNT(*) > 0 FROM <table> WHERE pk = ?`.
5965            ///
5966            /// # Errors
5967            /// As [`#root::sql::ExistsPool::contains_pk`].
5968            pub async fn contains_pk(
5969                pk: impl ::core::convert::Into<#root::core::SqlValue> + ::core::marker::Send,
5970                pool: &#root::sql::Pool,
5971            ) -> ::core::result::Result<bool, #root::sql::ExecError> {
5972                use #root::sql::ExistsPool as _;
5973                #root::query::QuerySet::<Self>::default()
5974                    .contains_pk(pool, pk)
5975                    .await
5976            }
5977
5978            #sum_method
5979            #avg_method
5980            #min_method
5981            #max_method
5982
5983            /// Internal: forward to
5984            /// [`#root::sql::model_shortcuts::aggregate_one_pool`].
5985            /// Backs `sum` / `avg` / `min` / `max`.
5986            #[doc(hidden)]
5987            pub async fn __aggregate_one_pool<U>(
5988                col: &str,
5989                build: fn(&'static str) -> #root::core::AggregateExpr,
5990                pool: &#root::sql::Pool,
5991            ) -> ::core::result::Result<
5992                ::core::option::Option<U>,
5993                #root::sql::ExecError,
5994            >
5995            where
5996                (::core::option::Option<U>,): #root::sql::MaybePgFromRow
5997                    + #root::sql::MaybeMyFromRow
5998                    + #root::sql::MaybeSqliteFromRow
5999                    + ::core::marker::Send
6000                    + ::core::marker::Unpin,
6001            {
6002                #root::sql::model_shortcuts::aggregate_one_pool::<Self, U>(col, build, pool)
6003                    .await
6004            }
6005
6006            /// Fetch every row of this model from `pool`. Eloquent
6007            /// `Model::all()` parity — a thin wrapper over
6008            /// `QuerySet::<Self>::default().fetch(pool)`.
6009            ///
6010            /// **Use with care on large tables** — there's no
6011            /// pagination or limit; the entire table is materialized
6012            /// into memory. For anything beyond fixture / lookup
6013            /// tables, page through `QuerySet::<Self>::default()
6014            /// .order_by(...).limit(N).offset(M).fetch(pool)`
6015            /// or stream via `.iterator(chunk_size)`.
6016            ///
6017            /// # Errors
6018            /// As [`FetcherPool::fetch`].
6019            ///
6020            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
6021            pub async fn all(
6022                pool: &#root::sql::Pool,
6023            ) -> ::core::result::Result<::std::vec::Vec<Self>, #root::sql::ExecError>
6024            {
6025                use #root::sql::FetcherPool as _;
6026                #root::query::QuerySet::<Self>::default()
6027                    .fetch(pool)
6028                    .await
6029            }
6030
6031            /// Look up every row whose primary key is in `pks`.
6032            /// Returns the matching rows in **inventory** order — NOT
6033            /// the order of `pks`. Empty `pks` returns an empty
6034            /// `Vec`. Eloquent `Model::find([1, 2, 3])` (when called
6035            /// with a list) parity.
6036            ///
6037            /// Thin wrapper over `QuerySet::<Self>::default()
6038            /// .filter("<pk>__in", SqlValue::List([...])).fetch(pool)`.
6039            /// Caller-supplied PKs that don't match a row are
6040            /// silently skipped (the returned vec is shorter than
6041            /// the input list). For an order-preserving / "fail
6042            /// when any missing" variant, build the queryset
6043            /// explicitly with `in_bulk` instead.
6044            ///
6045            /// Accepts any iterable whose elements are
6046            /// `Into<SqlValue>` — `Vec<i64>`, `&[i64]`, `[i64; N]`,
6047            /// `Vec<Uuid>`, etc.
6048            ///
6049            /// # Errors
6050            /// As [`FetcherPool::fetch`].
6051            ///
6052            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
6053            pub async fn find_many<V>(
6054                pks: impl ::core::iter::IntoIterator<Item = V>,
6055                pool: &#root::sql::Pool,
6056            ) -> ::core::result::Result<
6057                ::std::vec::Vec<Self>,
6058                #root::sql::ExecError,
6059            >
6060            where
6061                V: ::core::convert::Into<#root::core::SqlValue>,
6062            {
6063                use #root::sql::FetcherPool as _;
6064                let _values: ::std::vec::Vec<#root::core::SqlValue> =
6065                    pks.into_iter().map(::core::convert::Into::into).collect();
6066                if _values.is_empty() {
6067                    return ::core::result::Result::Ok(::std::vec::Vec::new());
6068                }
6069                let _key = ::std::format!("{}__in", ::core::stringify!(#pk_ident));
6070                #root::query::QuerySet::<Self>::default()
6071                    .filter(&_key, #root::core::SqlValue::List(_values))
6072                    .fetch(pool)
6073                    .await
6074            }
6075
6076            /// Look up the row whose primary key equals `pk`. Returns
6077            /// `Ok(None)` when no row matches, rather than erroring.
6078            /// Eloquent `Model::find`
6079            /// shape — accepts any value `Into<SqlValue>`.
6080            ///
6081            /// One-liner shortcut for the common
6082            /// `QuerySet::<Self>::default().filter("<pk_field>", pk)
6083            /// .limit(1).fetch(pool).await?.into_iter().next()`
6084            /// dance.
6085            ///
6086            /// # Errors
6087            /// As [`FetcherPool::fetch`].
6088            ///
6089            /// [`FetcherPool::fetch`]: rustango::sql::FetcherPool::fetch
6090            pub async fn find(
6091                pk: impl ::core::convert::Into<#root::core::SqlValue>,
6092                pool: &#root::sql::Pool,
6093            ) -> ::core::result::Result<::core::option::Option<Self>, #root::sql::ExecError>
6094            {
6095                use #root::sql::FetcherPool as _;
6096                let _pk_val: #root::core::SqlValue = pk.into();
6097                let mut _rows: ::std::vec::Vec<Self> =
6098                    #root::query::QuerySet::<Self>::default()
6099                        .filter(::core::stringify!(#pk_ident), _pk_val)
6100                        .limit(1)
6101                        .fetch(pool)
6102                        .await?;
6103                ::core::result::Result::Ok(_rows.into_iter().next())
6104            }
6105
6106            /// Look up the row whose primary key equals `pk`. Errors
6107            /// when no row matches — the throwing counterpart of
6108            /// [`Self::find`]. Eloquent `Model::findOrFail`
6109            /// parity.
6110            ///
6111            /// Translates the miss into
6112            /// [`ExecError::Driver`]\([`sqlx::Error::RowNotFound`])\)
6113            /// so callers can `?`-bubble straight through the typical
6114            /// `ExecError` error chain.
6115            ///
6116            /// # Errors
6117            /// As [`Self::find`]; additionally
6118            /// [`sqlx::Error::RowNotFound`] when no row matches.
6119            ///
6120            /// [`ExecError::Driver`]: rustango::sql::ExecError::Driver
6121            /// [`sqlx::Error::RowNotFound`]: rustango::sql::sqlx::Error::RowNotFound
6122            pub async fn find_or_fail(
6123                pk: impl ::core::convert::Into<#root::core::SqlValue>,
6124                pool: &#root::sql::Pool,
6125            ) -> ::core::result::Result<Self, #root::sql::ExecError> {
6126                match Self::find(pk, pool).await? {
6127                    ::core::option::Option::Some(_row) => ::core::result::Result::Ok(_row),
6128                    ::core::option::Option::None => ::core::result::Result::Err(
6129                        #root::sql::ExecError::Driver(
6130                            #root::sql::sqlx::Error::RowNotFound,
6131                        ),
6132                    ),
6133                }
6134            }
6135
6136            /// Look up multiple rows by primary key, **failing** if
6137            /// any requested PK is missing. Eloquent
6138            /// `Model::findOrFail([1, 2, 3])` parity. Returns rows in
6139            /// inventory order (NOT request order — same as
6140            /// [`Self::find_many`]).
6141            ///
6142            /// Empty `pks` returns an empty `Vec` (no rows requested
6143            /// → nothing to fail on).
6144            ///
6145            /// Differs from [`Self::find_many`] in that this method
6146            /// requires every PK to resolve. If even one is missing,
6147            /// the call surfaces `sqlx::Error::RowNotFound` (wrapped
6148            /// in `ExecError::Driver`). Rows are deduped at the SQL
6149            /// layer, so passing the same PK twice in `pks` counts as
6150            /// one expected row.
6151            ///
6152            /// # Errors
6153            /// As [`Self::find_many`], plus `RowNotFound` when the
6154            /// returned row count is less than the count of distinct
6155            /// requested PKs.
6156            pub async fn find_many_or_fail<V>(
6157                pks: impl ::core::iter::IntoIterator<Item = V>,
6158                pool: &#root::sql::Pool,
6159            ) -> ::core::result::Result<
6160                ::std::vec::Vec<Self>,
6161                #root::sql::ExecError,
6162            >
6163            where
6164                V: ::core::convert::Into<#root::core::SqlValue>,
6165            {
6166                let _values: ::std::vec::Vec<#root::core::SqlValue> =
6167                    pks.into_iter().map(::core::convert::Into::into).collect();
6168                if _values.is_empty() {
6169                    return ::core::result::Result::Ok(::std::vec::Vec::new());
6170                }
6171                // Dedup the requested PK list before counting so
6172                // duplicate-PK requests don't false-fail (the SQL
6173                // `IN (...)` clause naturally dedups too).
6174                let mut _seen: ::std::collections::HashSet<
6175                    ::std::string::String,
6176                > = ::std::collections::HashSet::new();
6177                for v in &_values {
6178                    _seen.insert(v.to_display_string());
6179                }
6180                let _expected = _seen.len();
6181                let _rows = Self::find_many(_values, pool).await?;
6182                if _rows.len() < _expected {
6183                    return ::core::result::Result::Err(
6184                        #root::sql::ExecError::Driver(
6185                            #root::sql::sqlx::Error::RowNotFound,
6186                        ),
6187                    );
6188                }
6189                ::core::result::Result::Ok(_rows)
6190            }
6191
6192            /// Find by primary key or run `fallback` to produce a
6193            /// default row to return. Eloquent
6194            /// `Model::findOr($pk, fn() => …)` parity.
6195            ///
6196            /// Unlike [`Self::find_or_fail`] (which raises on
6197            /// miss), this is the "give me something sensible"
6198            /// branch: typical use is "fetch the user's row, else
6199            /// fall back to an anonymous/guest stub".
6200            ///
6201            /// `fallback` runs only when no row matches — the DB
6202            /// round-trip happens unconditionally.
6203            ///
6204            /// # Errors
6205            /// As [`Self::find`].
6206            pub async fn find_or<F>(
6207                pk: impl ::core::convert::Into<#root::core::SqlValue>,
6208                pool: &#root::sql::Pool,
6209                fallback: F,
6210            ) -> ::core::result::Result<Self, #root::sql::ExecError>
6211            where
6212                F: ::core::ops::FnOnce() -> Self,
6213            {
6214                ::core::result::Result::Ok(
6215                    Self::find(pk, pool).await?.unwrap_or_else(fallback),
6216                )
6217            }
6218
6219            /// Same as [`Self::find_or`] but also returns a `bool`
6220            /// indicating whether the row was found in the DB
6221            /// (`true`) or freshly built from `fallback` (`false`).
6222            /// Eloquent `Model::findOrNew($pk, [attrs])` parity —
6223            /// in PHP the returned model also exposes `->exists`;
6224            /// here that's surfaced as the second tuple element.
6225            ///
6226            /// Useful for edit-or-create form handlers where the
6227            /// caller needs to know whether to PATCH or POST when
6228            /// the user submits the form.
6229            ///
6230            /// # Errors
6231            /// As [`Self::find`].
6232            pub async fn find_or_new<F>(
6233                pk: impl ::core::convert::Into<#root::core::SqlValue>,
6234                pool: &#root::sql::Pool,
6235                fallback: F,
6236            ) -> ::core::result::Result<(Self, bool), #root::sql::ExecError>
6237            where
6238                F: ::core::ops::FnOnce() -> Self,
6239            {
6240                match Self::find(pk, pool).await? {
6241                    ::core::option::Option::Some(_row) => ::core::result::Result::Ok((_row, true)),
6242                    ::core::option::Option::None => {
6243                        ::core::result::Result::Ok((fallback(), false))
6244                    }
6245                }
6246            }
6247
6248            /// Eloquent `Model::findOrCreate(pk, defaults)` — like
6249            /// [`Self::find_or_new`] but **persists** the new row
6250            /// when the PK isn't found. Returns `(row, exists: bool)`
6251            /// — `exists=true` when the PK was found,
6252            /// `false` when a fresh row was inserted.
6253            ///
6254            /// ```ignore
6255            /// let (post, found) = Post::find_or_insert(
6256            ///     pk,
6257            ///     &pool,
6258            ///     || Post { id: Auto::default(), title: "new".into() },
6259            /// ).await?;
6260            /// // `found` true → returned existing row;
6261            /// // `found` false → fallback was inserted, `post.id` populated.
6262            /// ```
6263            ///
6264            /// **Caveat**: two concurrent calls that both miss the
6265            /// find can both INSERT, violating uniqueness. Wrap in a
6266            /// transaction or rely on a UNIQUE constraint + handle
6267            /// the conflict error if you need race-free semantics.
6268            ///
6269            /// # Errors
6270            /// As [`Self::find`] and [`Self::save_pool`].
6271            pub async fn find_or_insert<F>(
6272                pk: impl ::core::convert::Into<#root::core::SqlValue>,
6273                pool: &#root::sql::Pool,
6274                fallback: F,
6275            ) -> ::core::result::Result<(Self, bool), #root::sql::ExecError>
6276            where
6277                F: ::core::ops::FnOnce() -> Self,
6278            {
6279                if let ::core::option::Option::Some(_row) = Self::find(pk, pool).await? {
6280                    return ::core::result::Result::Ok((_row, true));
6281                }
6282                let mut _new = fallback();
6283                _new.save_pool(pool).await?;
6284                ::core::result::Result::Ok((_new, false))
6285            }
6286
6287            /// Fetch the first row of the table, or run `fallback`
6288            /// when the table is empty. Eloquent
6289            /// `Model::firstOr(fn() => …)` parity.
6290            ///
6291            /// # Errors
6292            /// As [`Self::first`].
6293            pub async fn first_or<F>(
6294                pool: &#root::sql::Pool,
6295                fallback: F,
6296            ) -> ::core::result::Result<Self, #root::sql::ExecError>
6297            where
6298                F: ::core::ops::FnOnce() -> Self,
6299            {
6300                // Route through the queryset rather than `Self::first`,
6301                // which is suppressed on models with a field named
6302                // `first` (field/shortcut collision guard).
6303                ::core::result::Result::Ok(
6304                    #root::query::QuerySet::<Self>::default()
6305                        .first(pool)
6306                        .await?
6307                        .unwrap_or_else(fallback),
6308                )
6309            }
6310
6311            /// Fetch exactly one row matching `<col> = <val>`. Errors
6312            /// when zero rows match (`ExecError::Driver(RowNotFound)`)
6313            /// or more than one matches
6314            /// (`ExecError::Query(QueryError::Sql(MultipleRowsReturned))`).
6315            /// Eloquent `Model::sole($col, $val)` parity.
6316            ///
6317            /// # Errors
6318            /// As [`Self::where_`] plus the explicit
6319            /// `RowNotFound` / `MultipleRowsReturned` cases above.
6320            pub async fn sole(
6321                col: &str,
6322                val: impl ::core::convert::Into<#root::core::SqlValue>,
6323                pool: &#root::sql::Pool,
6324            ) -> ::core::result::Result<Self, #root::sql::ExecError> {
6325                let mut _rows = Self::where_(col, val, pool).await?;
6326                match _rows.len() {
6327                    0 => ::core::result::Result::Err(
6328                        #root::sql::ExecError::Driver(
6329                            #root::sql::sqlx::Error::RowNotFound,
6330                        ),
6331                    ),
6332                    1 => ::core::result::Result::Ok(_rows.remove(0)),
6333                    n => ::core::result::Result::Err(
6334                        #root::sql::ExecError::MultipleRowsReturned {
6335                            op: "sole",
6336                            table: <Self as #root::core::Model>::SCHEMA.name,
6337                            count: n,
6338                        },
6339                    ),
6340                }
6341            }
6342        }
6343    } else {
6344        quote!()
6345    };
6346
6347    // `_tx` family — `insert_tx`, `save_tx`, `delete_tx`. These mirror
6348    // the non-audited `_pool` methods but execute against an open
6349    // `PoolTx` so the writes participate in the caller's transaction.
6350    // Auditing inside TX is deferred; these always use the plain
6351    // executor primitives regardless of whether the model is audited.
6352    let tx_insert_method = if fields.has_auto {
6353        let pushes = &fields.insert_pushes;
6354        let returning_cols = &fields.returning_cols;
6355        quote! {
6356            /// Insert this row inside an open transaction, populating
6357            /// any `Auto<T>` PK from the auto-assigned value. Works
6358            /// against any backend that `tx` wraps.
6359            ///
6360            /// # Errors
6361            /// As [`Self::insert_pool`].
6362            pub async fn insert_tx(
6363                &mut self,
6364                tx: &mut #root::sql::PoolTx<'_>,
6365            ) -> ::core::result::Result<(), #root::sql::ExecError> {
6366                let mut _columns: ::std::vec::Vec<&'static str> =
6367                    ::std::vec::Vec::new();
6368                let mut _values: ::std::vec::Vec<#root::core::SqlValue> =
6369                    ::std::vec::Vec::new();
6370                #( #pushes )*
6371                let _query = #root::core::InsertQuery {
6372                    model: <Self as #root::core::Model>::SCHEMA,
6373                    columns: _columns,
6374                    values: _values,
6375                    returning: ::std::vec![ #( #returning_cols ),* ],
6376                    on_conflict: ::core::option::Option::None,
6377                };
6378                let _result = #root::sql::insert_returning_tx(tx, &_query).await?;
6379                #root::sql::apply_auto_pk(_result, self)
6380            }
6381        }
6382    } else {
6383        let insert_columns = &fields.insert_columns;
6384        let insert_values = &fields.insert_values;
6385        quote! {
6386            /// Insert this row inside an open transaction.
6387            ///
6388            /// # Errors
6389            /// As [`Self::insert_pool`].
6390            pub async fn insert_tx(
6391                &self,
6392                tx: &mut #root::sql::PoolTx<'_>,
6393            ) -> ::core::result::Result<(), #root::sql::ExecError> {
6394                let _query = #root::core::InsertQuery {
6395                    model: <Self as #root::core::Model>::SCHEMA,
6396                    columns: ::std::vec![ #( #insert_columns ),* ],
6397                    values: ::std::vec![ #( #insert_values ),* ],
6398                    returning: ::std::vec::Vec::new(),
6399                    on_conflict: ::core::option::Option::None,
6400                };
6401                #root::sql::insert_tx(tx, &_query).await
6402            }
6403        }
6404    };
6405
6406    let tx_save_method = if let Some((pk_ident, pk_col)) = primary_key {
6407        let pk_column_lit = pk_col.as_str();
6408        let assignments = &fields.update_assignments;
6409        let dispatch_unset = if fields.pk_is_auto {
6410            quote! {
6411                if matches!(self.#pk_ident, #root::sql::Auto::Unset) {
6412                    return self.insert_tx(tx).await.map(|()| 1u64);
6413                }
6414            }
6415        } else {
6416            quote!()
6417        };
6418        quote! {
6419            /// Save this row inside an open transaction. `INSERT` when
6420            /// the `Auto<T>` PK is `Unset`, else `UPDATE` keyed on the
6421            /// PK. Works against any backend that `tx` wraps.
6422            ///
6423            /// # Errors
6424            /// As [`Self::save_pool`].
6425            pub async fn save_tx(
6426                &mut self,
6427                tx: &mut #root::sql::PoolTx<'_>,
6428            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
6429                #dispatch_unset
6430                let _query = #root::core::UpdateQuery {
6431                    model: <Self as #root::core::Model>::SCHEMA,
6432                    set: ::std::vec![ #( #assignments ),* ],
6433                    where_clause: #root::core::WhereExpr::Predicate(
6434                        #root::core::Filter {
6435                            column: #pk_column_lit,
6436                            op: #root::core::Op::Eq,
6437                            value: ::core::convert::Into::<#root::core::SqlValue>::into(
6438                                ::core::clone::Clone::clone(&self.#pk_ident)
6439                            ),
6440                        }
6441                    ),
6442                };
6443                let _affected = #root::sql::update_tx(tx, &_query).await?;
6444                ::core::result::Result::Ok(_affected)
6445            }
6446        }
6447    } else {
6448        quote!()
6449    };
6450
6451    let tx_delete_method = {
6452        let pk_column_lit = primary_key.map(|(_, col)| col.as_str()).unwrap_or("id");
6453        let pk_ident_for_tx = primary_key.map(|(ident, _)| ident);
6454        if let Some(pk_ident) = pk_ident_for_tx {
6455            quote! {
6456                /// Delete the row identified by this instance's PK
6457                /// inside an open transaction. Works against any backend
6458                /// that `tx` wraps.
6459                ///
6460                /// # Errors
6461                /// As [`Self::delete_pool`].
6462                pub async fn delete_tx(
6463                    &self,
6464                    tx: &mut #root::sql::PoolTx<'_>,
6465                ) -> ::core::result::Result<u64, #root::sql::ExecError> {
6466                    let _query = #root::core::DeleteQuery {
6467                        model: <Self as #root::core::Model>::SCHEMA,
6468                        where_clause: #root::core::WhereExpr::Predicate(
6469                            #root::core::Filter {
6470                                column: #pk_column_lit,
6471                                op: #root::core::Op::Eq,
6472                                value: ::core::convert::Into::<#root::core::SqlValue>::into(
6473                                    ::core::clone::Clone::clone(&self.#pk_ident)
6474                                ),
6475                            }
6476                        ),
6477                    };
6478                    #root::sql::delete_tx(tx, &_query).await
6479                }
6480            }
6481        } else {
6482            quote!()
6483        }
6484    };
6485
6486    // Update emission captures both BEFORE and AFTER state — runs an
6487    // extra SELECT against `_executor` BEFORE the UPDATE, captures
6488    // each tracked field's prior value, then after the UPDATE diffs
6489    // against the in-memory `&self`. `diff_changes` drops unchanged
6490    // columns so the JSON only contains the actual delta.
6491    //
6492    // Two-fragment shape: `audit_update_pre` runs before the UPDATE
6493    // and binds `_audit_before_pairs`; `audit_update_post` runs
6494    // after the UPDATE and emits the PendingEntry.
6495    let (audit_update_pre, audit_update_post): (TokenStream2, TokenStream2) = if let Some(tracked) =
6496        audited_fields
6497    {
6498        if tracked.is_empty() {
6499            (quote!(), quote!())
6500        } else {
6501            let select_cols: String = tracked
6502                .iter()
6503                .map(|c| format!("\"{}\"", c.column.replace('"', "\"\"")))
6504                .collect::<Vec<_>>()
6505                .join(", ");
6506            let pk_column_for_select = primary_key.map(|(_, col)| col.clone()).unwrap_or_default();
6507            let select_cols_lit = select_cols;
6508            let pk_column_lit_for_select = pk_column_for_select;
6509            let pk_value_for_bind = if let Some((pk_ident, _)) = primary_key {
6510                if fields.pk_is_auto {
6511                    quote!(self.#pk_ident.get().copied().unwrap_or_default())
6512                } else {
6513                    quote!(::core::clone::Clone::clone(&self.#pk_ident))
6514                }
6515            } else {
6516                quote!(0_i64)
6517            };
6518            let before_pairs = tracked.iter().map(|c| {
6519                let column_lit = c.column.as_str();
6520                let value_ty = &c.value_ty;
6521                quote! {
6522                    (
6523                        #column_lit,
6524                        match #root::sql::sqlx::Row::try_get::<#value_ty, _>(
6525                            &_audit_before_row, #column_lit,
6526                        ) {
6527                            ::core::result::Result::Ok(v) => {
6528                                #root::__serde_json::to_value(&v)
6529                                    .unwrap_or(#root::__serde_json::Value::Null)
6530                            }
6531                            ::core::result::Result::Err(_) => #root::__serde_json::Value::Null,
6532                        },
6533                    )
6534                }
6535            });
6536            let after_pairs = tracked.iter().map(|c| {
6537                let column_lit = c.column.as_str();
6538                let ident = &c.ident;
6539                quote! {
6540                    (
6541                        #column_lit,
6542                        #root::__serde_json::to_value(&self.#ident)
6543                            .unwrap_or(#root::__serde_json::Value::Null),
6544                    )
6545                }
6546            });
6547            let pk_str = audit_pk_to_string.clone();
6548            let pre = quote! {
6549                let _audit_select_sql = ::std::format!(
6550                    r#"SELECT {} FROM "{}" WHERE "{}" = $1"#,
6551                    #select_cols_lit,
6552                    <Self as #root::core::Model>::SCHEMA.table,
6553                    #pk_column_lit_for_select,
6554                );
6555                let _audit_before_pairs:
6556                    ::std::option::Option<::std::vec::Vec<(&'static str, #root::__serde_json::Value)>> =
6557                    match #root::sql::sqlx::query(&_audit_select_sql)
6558                        .bind(#pk_value_for_bind)
6559                        .fetch_optional(&mut *_executor)
6560                        .await
6561                    {
6562                        ::core::result::Result::Ok(::core::option::Option::Some(_audit_before_row)) => {
6563                            ::core::option::Option::Some(::std::vec![ #( #before_pairs ),* ])
6564                        }
6565                        _ => ::core::option::Option::None,
6566                    };
6567            };
6568            let post = quote! {
6569                if let ::core::option::Option::Some(_audit_before) = _audit_before_pairs {
6570                    let _audit_after:
6571                        ::std::vec::Vec<(&'static str, #root::__serde_json::Value)> =
6572                        ::std::vec![ #( #after_pairs ),* ];
6573                    let _audit_entry = #root::audit::PendingEntry {
6574                        entity_table: <Self as #root::core::Model>::SCHEMA.table,
6575                        entity_pk: #pk_str,
6576                        operation: #root::audit::AuditOp::Update,
6577                        source: #root::audit::current_source(),
6578                        changes: #root::audit::diff_changes(
6579                            &_audit_before,
6580                            &_audit_after,
6581                        ),
6582                    };
6583                    #root::audit::emit_one(&mut *_executor, &_audit_entry).await?;
6584                }
6585            };
6586            (pre, post)
6587        }
6588    } else {
6589        (quote!(), quote!())
6590    };
6591
6592    // Bulk-insert audit: capture every row's tracked fields after the
6593    // RETURNING populates each PK, then push one batched INSERT INTO
6594    // audit_log via `emit_many`. One round-trip regardless of N rows.
6595    let audit_bulk_insert_emit: TokenStream2 = if audited_fields.is_some() {
6596        let row_pk_str = if let Some((pk_ident, _)) = primary_key {
6597            if fields.pk_is_auto {
6598                quote!(_row.#pk_ident.get().map(|v| ::std::format!("{}", v)).unwrap_or_default())
6599            } else {
6600                quote!(::std::format!("{}", &_row.#pk_ident))
6601            }
6602        } else {
6603            quote!(::std::string::String::new())
6604        };
6605        let row_pairs = audited_fields.unwrap_or(&[]).iter().map(|c| {
6606            let column_lit = c.column.as_str();
6607            let ident = &c.ident;
6608            quote! {
6609                (
6610                    #column_lit,
6611                    #root::__serde_json::to_value(&_row.#ident)
6612                        .unwrap_or(#root::__serde_json::Value::Null),
6613                )
6614            }
6615        });
6616        quote! {
6617            let _audit_source = #root::audit::current_source();
6618            let mut _audit_entries:
6619                ::std::vec::Vec<#root::audit::PendingEntry> =
6620                    ::std::vec::Vec::with_capacity(rows.len());
6621            for _row in rows.iter() {
6622                _audit_entries.push(#root::audit::PendingEntry {
6623                    entity_table: <Self as #root::core::Model>::SCHEMA.table,
6624                    entity_pk: #row_pk_str,
6625                    operation: #root::audit::AuditOp::Create,
6626                    source: _audit_source.clone(),
6627                    changes: #root::audit::snapshot_changes(&[
6628                        #( #row_pairs ),*
6629                    ]),
6630                });
6631            }
6632            #root::audit::emit_many(&mut *_executor, &_audit_entries).await?;
6633        }
6634    } else {
6635        quote!()
6636    };
6637
6638    let save_method = if fields.pk_is_auto {
6639        let (pk_ident, pk_column) = primary_key.expect("pk_is_auto implies primary_key is Some");
6640        let pk_column_lit = pk_column.as_str();
6641        let assignments = &fields.update_assignments;
6642        let upsert_cols = &fields.upsert_update_columns;
6643        let upsert_pushes = &fields.insert_pushes;
6644        let upsert_returning = &fields.returning_cols;
6645        let upsert_auto_assigns = &fields.auto_assigns;
6646        // Conflict target: prefer the first declared `unique_together`
6647        // when it exists. Plain `Auto<T>` PKs are server-assigned via
6648        // `BIGSERIAL` and never collide on insert, so a PK-only target
6649        // would silently turn `upsert()` into "always-insert" for
6650        // surrogate-PK models with composite UNIQUE constraints — see
6651        // `RolePermission` / `UserRole` / `UserPermission` in the
6652        // tenancy permission engine. When no `unique_together` is
6653        // declared we keep the PK target (the original behaviour).
6654        let upsert_target_columns: Vec<String> = indexes
6655            .iter()
6656            .find(|i| i.unique && !i.columns.is_empty())
6657            .map(|i| i.columns.clone())
6658            .unwrap_or_else(|| vec![pk_column.clone()]);
6659        let upsert_target_lits = upsert_target_columns
6660            .iter()
6661            .map(String::as_str)
6662            .collect::<Vec<_>>();
6663        let conflict_clause = if fields.upsert_update_columns.is_empty() {
6664            quote!(#root::core::ConflictClause::DoNothing)
6665        } else {
6666            quote!(#root::core::ConflictClause::DoUpdate {
6667                target: ::std::vec![ #( #upsert_target_lits ),* ],
6668                update_columns: ::std::vec![ #( #upsert_cols ),* ],
6669            })
6670        };
6671        Some(quote! {
6672            /// Insert this row if its `Auto<T>` primary key is
6673            /// `Unset`, otherwise update the existing row matching the
6674            /// PK. The caller doesn't need to pick `insert` vs the
6675            /// bulk-update path manually.
6676            ///
6677            /// On the insert branch, populates the PK from `RETURNING`
6678            /// (same behavior as `insert`). On the update branch,
6679            /// writes every non-PK column back; if no row matches the
6680            /// PK, returns `Ok(())` silently.
6681            ///
6682            /// Only generated when the primary key is declared as
6683            /// `Auto<T>`. Models with a manually-managed PK must use
6684            /// `insert` or the QuerySet update builder.
6685            ///
6686            /// **Postgres only — prefer [`Self::save_pool`].** This takes a
6687            /// driver-specific `PgPool`, so it does not exist at all on a
6688            /// build without the `postgres` feature: selecting `sqlite`
6689            /// makes the method vanish rather than fail with anything that
6690            /// names the cause.
6691            ///
6692            /// [`Self::save_pool`] takes `rustango::sql::Pool` and works on
6693            /// all three backends. The naming is inverted — the short name
6694            /// is the narrow one — and that is tracked in #1293.
6695            ///
6696            /// # Errors
6697            /// Returns [`#root::sql::ExecError`] for SQL-writing
6698            /// or driver failures.
6699            #[cfg(feature = "postgres")]
6700            pub async fn save(
6701                &mut self,
6702                pool: &#root::sql::sqlx::PgPool,
6703            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
6704                #pool_to_save_on
6705            }
6706
6707            /// Like [`Self::save`] but accepts any sqlx executor —
6708            /// `&PgPool`, `&mut PgConnection`, or a transaction. The
6709            /// escape hatch for tenant-scoped writes: schema-mode
6710            /// tenants share the registry pool but rely on a per-
6711            /// checkout `SET search_path`, so passing `&PgPool` would
6712            /// silently hit the wrong schema. Acquire a connection
6713            /// via `TenantPools::acquire(&org)` and pass `&mut *conn`.
6714            ///
6715            /// # Errors
6716            /// As [`Self::save`].
6717            #[cfg(feature = "postgres")]
6718            pub async fn save_on #executor_generics (
6719                &mut self,
6720                #executor_param,
6721            ) -> ::core::result::Result<u64, #root::sql::ExecError>
6722            #executor_where
6723            {
6724                // #1029 — INSERT writes exactly one row → 1; UPDATE returns
6725                // the rows-affected count (0 when the PK no longer exists).
6726                if matches!(self.#pk_ident, #root::sql::Auto::Unset) {
6727                    return self.insert_on(#executor_passes_to_data_write).await.map(|()| 1u64);
6728                }
6729                #audit_update_pre
6730                let _query = #root::core::UpdateQuery {
6731                    model: <Self as #root::core::Model>::SCHEMA,
6732                    set: ::std::vec![ #( #assignments ),* ],
6733                    where_clause: #root::core::WhereExpr::Predicate(
6734                        #root::core::Filter {
6735                            column: #pk_column_lit,
6736                            op: #root::core::Op::Eq,
6737                            value: ::core::convert::Into::<#root::core::SqlValue>::into(
6738                                ::core::clone::Clone::clone(&self.#pk_ident)
6739                            ),
6740                        }
6741                    ),
6742                };
6743                let _affected = #root::sql::__macro_internals::update_on(
6744                    #executor_passes_to_data_write,
6745                    &_query,
6746                ).await?;
6747                #audit_update_post
6748                ::core::result::Result::Ok(_affected)
6749            }
6750
6751            /// Per-call override for the audit source. Runs
6752            /// [`Self::save_on`] inside an [`#root::audit::with_source`]
6753            /// scope so the resulting audit entry records `source`
6754            /// instead of the task-local default. Useful for seed
6755            /// scripts and one-off CLI tools that don't sit inside an
6756            /// admin handler. The override applies only to this call;
6757            /// no global state changes.
6758            ///
6759            /// # Errors
6760            /// As [`Self::save_on`].
6761            #[cfg(feature = "postgres")]
6762            pub async fn save_on_with #executor_generics (
6763                &mut self,
6764                #executor_param,
6765                source: #root::audit::AuditSource,
6766            ) -> ::core::result::Result<u64, #root::sql::ExecError>
6767            #executor_where
6768            {
6769                #root::audit::with_source(source, self.save_on(_executor)).await
6770            }
6771
6772            /// Insert this row or update it in-place if the primary key already
6773            /// exists — single round-trip via `INSERT … ON CONFLICT (pk) DO UPDATE`.
6774            ///
6775            /// With `Auto::Unset` PK the server assigns a new key and no conflict
6776            /// can occur (equivalent to `insert`). With `Auto::Set` PK the row is
6777            /// inserted if absent or all non-PK columns are overwritten if present.
6778            ///
6779            /// # Errors
6780            /// As [`Self::insert_on`].
6781            #[cfg(feature = "postgres")]
6782            pub async fn upsert(
6783                &mut self,
6784                pool: &#root::sql::sqlx::PgPool,
6785            ) -> ::core::result::Result<(), #root::sql::ExecError> {
6786                #pool_to_upsert_on
6787            }
6788
6789            /// Like [`Self::upsert`] but accepts any sqlx executor.
6790            /// See [`Self::save_on`] for tenancy-scoped rationale.
6791            ///
6792            /// # Errors
6793            /// As [`Self::upsert`].
6794            #[cfg(feature = "postgres")]
6795            pub async fn upsert_on #executor_generics (
6796                &mut self,
6797                #executor_param,
6798            ) -> ::core::result::Result<(), #root::sql::ExecError>
6799            #executor_where
6800            {
6801                let mut _columns: ::std::vec::Vec<&'static str> =
6802                    ::std::vec::Vec::new();
6803                let mut _values: ::std::vec::Vec<#root::core::SqlValue> =
6804                    ::std::vec::Vec::new();
6805                #( #upsert_pushes )*
6806                let query = #root::core::InsertQuery {
6807                    model: <Self as #root::core::Model>::SCHEMA,
6808                    columns: _columns,
6809                    values: _values,
6810                    returning: ::std::vec![ #( #upsert_returning ),* ],
6811                    on_conflict: ::core::option::Option::Some(#conflict_clause),
6812                };
6813                let _returning_row_v = #root::sql::__macro_internals::insert_returning_on(
6814                    #executor_passes_to_data_write,
6815                    &query,
6816                ).await?;
6817                let _returning_row = &_returning_row_v;
6818                #( #upsert_auto_assigns )*
6819                ::core::result::Result::Ok(())
6820            }
6821        })
6822    } else {
6823        None
6824    };
6825
6826    let pk_methods = primary_key.map(|(pk_ident, pk_column)| {
6827        let pk_column_lit = pk_column.as_str();
6828        // Optional `soft_delete_on` / `restore_on` companions when the
6829        // model has a `#[rustango(soft_delete)]` column. They land
6830        // alongside the regular `delete_on` so callers have both
6831        // options — a hard delete (audit-tracked as a real DELETE) and
6832        // a logical delete (audit-tracked as an UPDATE setting the
6833        // deleted_at column to NOW()).
6834        let soft_delete_methods = if let Some(col) = fields.soft_delete_column.as_deref() {
6835            let col_lit = col;
6836            let sd_field_ident = fields
6837                .soft_delete_field_ident
6838                .clone()
6839                .expect("soft_delete_column without ident");
6840            quote! {
6841                /// Soft-delete this row by setting its
6842                /// `#[rustango(soft_delete)]` column to `NOW()`.
6843                /// The row stays in the table; query helpers can
6844                /// filter it out by checking the column for `IS NOT
6845                /// NULL`.
6846                ///
6847                /// # Errors
6848                /// As [`Self::delete`].
6849                #[cfg(feature = "postgres")]
6850                pub async fn soft_delete_on #executor_generics (
6851                    &self,
6852                    #executor_param,
6853                ) -> ::core::result::Result<u64, #root::sql::ExecError>
6854                #executor_where
6855                {
6856                    let _query = #root::core::UpdateQuery {
6857                        model: <Self as #root::core::Model>::SCHEMA,
6858                        set: ::std::vec![
6859                            #root::core::Assignment {
6860                                column: #col_lit,
6861                                value: ::core::convert::Into::<#root::core::Expr>::into(
6862                                    ::core::convert::Into::<#root::core::SqlValue>::into(
6863                                        #root::__chrono::Utc::now()
6864                                    )
6865                                ),
6866                            },
6867                        ],
6868                        where_clause: #root::core::WhereExpr::Predicate(
6869                            #root::core::Filter {
6870                                column: #pk_column_lit,
6871                                op: #root::core::Op::Eq,
6872                                value: ::core::convert::Into::<#root::core::SqlValue>::into(
6873                                    ::core::clone::Clone::clone(&self.#pk_ident)
6874                                ),
6875                            }
6876                        ),
6877                    };
6878                    let _affected = #root::sql::__macro_internals::update_on(
6879                        #executor_passes_to_data_write,
6880                        &_query,
6881                    ).await?;
6882                    #audit_softdelete_emit
6883                    ::core::result::Result::Ok(_affected)
6884                }
6885
6886                /// Inverse of [`Self::soft_delete_on`] — clears the
6887                /// soft-delete column back to NULL so the row is
6888                /// considered live again.
6889                ///
6890                /// # Errors
6891                /// As [`Self::delete`].
6892                #[cfg(feature = "postgres")]
6893                pub async fn restore_on #executor_generics (
6894                    &self,
6895                    #executor_param,
6896                ) -> ::core::result::Result<u64, #root::sql::ExecError>
6897                #executor_where
6898                {
6899                    let _query = #root::core::UpdateQuery {
6900                        model: <Self as #root::core::Model>::SCHEMA,
6901                        set: ::std::vec![
6902                            #root::core::Assignment {
6903                                column: #col_lit,
6904                                value: ::core::convert::Into::<#root::core::Expr>::into(
6905                                    #root::core::SqlValue::Null
6906                                ),
6907                            },
6908                        ],
6909                        where_clause: #root::core::WhereExpr::Predicate(
6910                            #root::core::Filter {
6911                                column: #pk_column_lit,
6912                                op: #root::core::Op::Eq,
6913                                value: ::core::convert::Into::<#root::core::SqlValue>::into(
6914                                    ::core::clone::Clone::clone(&self.#pk_ident)
6915                                ),
6916                            }
6917                        ),
6918                    };
6919                    let _affected = #root::sql::__macro_internals::update_on(
6920                        #executor_passes_to_data_write,
6921                        &_query,
6922                    ).await?;
6923                    #audit_restore_emit
6924                    ::core::result::Result::Ok(_affected)
6925                }
6926
6927                /// Tri-dialect counterpart of [`Self::soft_delete_on`]
6928                /// — takes [`#root::sql::Pool`] and dispatches per
6929                /// backend. Eloquent `Model::delete()` semantics on
6930                /// soft-delete-enabled models (closes #821 partial).
6931                ///
6932                /// Sets the `#[rustango(soft_delete)]` column to
6933                /// `NOW()` on every backend. Query helpers
6934                /// (`QuerySet::active()` / `only_trashed()`,
6935                /// `soft_delete::active_filter` /
6936                /// `compose_with_active`) filter trashed rows out by
6937                /// reading `IS NULL` on the same column.
6938                ///
6939                /// # Errors
6940                /// As [`#root::sql::update_pool`].
6941                pub async fn soft_delete(
6942                    &self,
6943                    pool: &#root::sql::Pool,
6944                ) -> ::core::result::Result<u64, #root::sql::ExecError> {
6945                    let _query = #root::core::UpdateQuery {
6946                        model: <Self as #root::core::Model>::SCHEMA,
6947                        set: ::std::vec![
6948                            #root::core::Assignment {
6949                                column: #col_lit,
6950                                value: ::core::convert::Into::<#root::core::Expr>::into(
6951                                    ::core::convert::Into::<#root::core::SqlValue>::into(
6952                                        #root::__chrono::Utc::now()
6953                                    )
6954                                ),
6955                            },
6956                        ],
6957                        where_clause: #root::core::WhereExpr::Predicate(
6958                            #root::core::Filter {
6959                                column: #pk_column_lit,
6960                                op: #root::core::Op::Eq,
6961                                value: ::core::convert::Into::<#root::core::SqlValue>::into(
6962                                    ::core::clone::Clone::clone(&self.#pk_ident)
6963                                ),
6964                            }
6965                        ),
6966                    };
6967                    #root::sql::update_pool(pool, &_query).await
6968                }
6969
6970                /// Tri-dialect counterpart of [`Self::restore_on`].
6971                /// Clears the `#[rustango(soft_delete)]` column back
6972                /// to `NULL`, marking the row live again. Eloquent
6973                /// `Model::restore()` parity.
6974                ///
6975                /// # Errors
6976                /// As [`#root::sql::update_pool`].
6977                pub async fn restore(
6978                    &self,
6979                    pool: &#root::sql::Pool,
6980                ) -> ::core::result::Result<u64, #root::sql::ExecError> {
6981                    let _query = #root::core::UpdateQuery {
6982                        model: <Self as #root::core::Model>::SCHEMA,
6983                        set: ::std::vec![
6984                            #root::core::Assignment {
6985                                column: #col_lit,
6986                                value: ::core::convert::Into::<#root::core::Expr>::into(
6987                                    #root::core::SqlValue::Null
6988                                ),
6989                            },
6990                        ],
6991                        where_clause: #root::core::WhereExpr::Predicate(
6992                            #root::core::Filter {
6993                                column: #pk_column_lit,
6994                                op: #root::core::Op::Eq,
6995                                value: ::core::convert::Into::<#root::core::SqlValue>::into(
6996                                    ::core::clone::Clone::clone(&self.#pk_ident)
6997                                ),
6998                            }
6999                        ),
7000                    };
7001                    #root::sql::update_pool(pool, &_query).await
7002                }
7003
7004                /// Hard-delete this row, ignoring the soft-delete
7005                /// column. Eloquent `Model::forceDelete()` parity —
7006                /// the escape hatch when you need to actually purge
7007                /// data (GDPR, fixture cleanup, etc.).
7008                ///
7009                /// Equivalent to [`Self::delete_pool`] (the framework's
7010                /// non-soft delete) — exposed under the Eloquent name
7011                /// for muscle-memory + so soft-delete-enabled models
7012                /// have all three operations (soft / restore / force)
7013                /// in one place.
7014                ///
7015                /// # Errors
7016                /// As [`Self::delete_pool`].
7017                pub async fn force_delete(
7018                    &self,
7019                    pool: &#root::sql::Pool,
7020                ) -> ::core::result::Result<u64, #root::sql::ExecError> {
7021                    Self::delete_pool(self, pool).await
7022                }
7023
7024                /// Returns `true` when this row is soft-deleted (its
7025                /// `#[rustango(soft_delete)]` column is currently
7026                /// set — Eloquent `$model->trashed()` parity).
7027                ///
7028                /// Pure in-memory predicate over `&self`; does not
7029                /// hit the database. Useful in admin/template code
7030                /// like `{% if post.trashed() %}…{% endif %}` and in
7031                /// guard clauses on restore/force-delete flows.
7032                pub fn trashed(&self) -> bool {
7033                    ::core::option::Option::is_some(&self.#sd_field_ident)
7034                }
7035
7036                /// Fetch every row whose `#[rustango(soft_delete)]`
7037                /// column is `NULL` (a.k.a. the live, non-trashed
7038                /// rows). Eloquent's default `Model::all()` behavior on
7039                /// a soft-delete model (Eloquent auto-scopes trashed
7040                /// rows out; rustango doesn't have auto-scoping yet —
7041                /// see issue #820 — so this is the explicit shortcut).
7042                ///
7043                /// One-liner over `QuerySet::<Self>::default()
7044                /// .active().fetch(pool)`. Closes #821 partial.
7045                ///
7046                /// # Errors
7047                /// As [`#root::sql::FetcherPool::fetch`].
7048                pub async fn active(
7049                    pool: &#root::sql::Pool,
7050                ) -> ::core::result::Result<
7051                    ::std::vec::Vec<Self>,
7052                    #root::sql::ExecError,
7053                > {
7054                    use #root::sql::FetcherPool as _;
7055                    #root::query::QuerySet::<Self>::default()
7056                        .active()
7057                        .fetch(pool)
7058                        .await
7059                }
7060
7061                /// Fetch ONLY soft-deleted rows. Eloquent
7062                /// `Model::onlyTrashed()->get()` parity — drives the
7063                /// admin "Trash" page, restore flows, GDPR purge
7064                /// scans, etc.
7065                ///
7066                /// One-liner over `QuerySet::<Self>::default()
7067                /// .only_trashed().fetch(pool)`. Closes #821
7068                /// partial.
7069                ///
7070                /// # Errors
7071                /// As [`#root::sql::FetcherPool::fetch`].
7072                pub async fn only_trashed(
7073                    pool: &#root::sql::Pool,
7074                ) -> ::core::result::Result<
7075                    ::std::vec::Vec<Self>,
7076                    #root::sql::ExecError,
7077                > {
7078                    use #root::sql::FetcherPool as _;
7079                    #root::query::QuerySet::<Self>::default()
7080                        .only_trashed()
7081                        .fetch(pool)
7082                        .await
7083                }
7084
7085                /// Fetch every row, both live and soft-deleted.
7086                /// Eloquent `Model::withTrashed()->get()` parity.
7087                ///
7088                /// Today every queryset already includes trashed rows
7089                /// (rustango has no global-scope tracking yet — issue
7090                /// #820), so this is functionally equivalent to
7091                /// [`Self::all`]. Exposed as a named shortcut so
7092                /// soft-delete-aware code reads `Model::with_trashed_pool`
7093                /// rather than `Model::all_pool` — keeps intent visible
7094                /// in callers and stays correct when auto-scoping lands.
7095                ///
7096                /// Closes #821 partial.
7097                ///
7098                /// # Errors
7099                /// As [`#root::sql::FetcherPool::fetch`].
7100                pub async fn with_trashed(
7101                    pool: &#root::sql::Pool,
7102                ) -> ::core::result::Result<
7103                    ::std::vec::Vec<Self>,
7104                    #root::sql::ExecError,
7105                > {
7106                    use #root::sql::FetcherPool as _;
7107                    #root::query::QuerySet::<Self>::default()
7108                        .with_trashed()
7109                        .fetch(pool)
7110                        .await
7111                }
7112
7113            }
7114        } else {
7115            quote!()
7116        };
7117        quote! {
7118            /// Delete the row identified by this instance's primary key.
7119            ///
7120            /// Returns the number of rows affected (0 or 1).
7121            ///
7122            /// **Postgres only — prefer [`Self::delete_pool`].** This takes
7123            /// a driver-specific `PgPool`, so it does not exist on a build
7124            /// without the `postgres` feature. [`Self::delete_pool`] takes
7125            /// `rustango::sql::Pool` and works on all three. The naming is
7126            /// inverted; tracked in #1293.
7127            ///
7128            /// # Errors
7129            /// Returns [`#root::sql::ExecError`] for SQL-writing or
7130            /// driver failures.
7131            #[cfg(feature = "postgres")]
7132            pub async fn delete(
7133                &self,
7134                pool: &#root::sql::sqlx::PgPool,
7135            ) -> ::core::result::Result<u64, #root::sql::ExecError> {
7136                #pool_to_delete_on
7137            }
7138
7139            /// Like [`Self::delete`] but accepts any sqlx executor —
7140            /// for tenant-scoped deletes against an explicitly-acquired
7141            /// connection. See [`Self::save_on`] for the rationale.
7142            ///
7143            /// # Errors
7144            /// As [`Self::delete`].
7145            #[cfg(feature = "postgres")]
7146            pub async fn delete_on #executor_generics (
7147                &self,
7148                #executor_param,
7149            ) -> ::core::result::Result<u64, #root::sql::ExecError>
7150            #executor_where
7151            {
7152                let query = #root::core::DeleteQuery {
7153                    model: <Self as #root::core::Model>::SCHEMA,
7154                    where_clause: #root::core::WhereExpr::Predicate(
7155                        #root::core::Filter {
7156                            column: #pk_column_lit,
7157                            op: #root::core::Op::Eq,
7158                            value: ::core::convert::Into::<#root::core::SqlValue>::into(
7159                                ::core::clone::Clone::clone(&self.#pk_ident)
7160                            ),
7161                        }
7162                    ),
7163                };
7164                let _affected = #root::sql::__macro_internals::delete_on(
7165                    #executor_passes_to_data_write,
7166                    &query,
7167                ).await?;
7168                #audit_delete_emit
7169                ::core::result::Result::Ok(_affected)
7170            }
7171
7172            /// Per-call audit-source override for [`Self::delete_on`].
7173            /// See [`Self::save_on_with`] for shape rationale.
7174            ///
7175            /// # Errors
7176            /// As [`Self::delete_on`].
7177            #[cfg(feature = "postgres")]
7178            pub async fn delete_on_with #executor_generics (
7179                &self,
7180                #executor_param,
7181                source: #root::audit::AuditSource,
7182            ) -> ::core::result::Result<u64, #root::sql::ExecError>
7183            #executor_where
7184            {
7185                #root::audit::with_source(source, self.delete_on(_executor)).await
7186            }
7187            #pool_delete_method
7188            #pool_insert_method
7189            #pool_save_method
7190            #refresh_replicate_methods
7191            #tx_delete_method
7192            #tx_insert_method
7193            #tx_save_method
7194            #soft_delete_methods
7195
7196            /// Returns `true` when `other` represents the same DB
7197            /// row as `self` — i.e. their primary keys compare
7198            /// equal. Eloquent `$model->is($other)` parity.
7199            ///
7200            /// Because both arguments are typed `&Self`, the
7201            /// model/table check is automatic — `Post::is` cannot
7202            /// be invoked against a `Comment` at compile time. Only
7203            /// the PK has to be compared at runtime.
7204            pub fn is(&self, other: &Self) -> bool {
7205                self.#pk_ident == other.#pk_ident
7206            }
7207
7208            /// Inverse of [`Self::is`]. Eloquent `$model->isNot($other)`
7209            /// parity.
7210            pub fn is_not(&self, other: &Self) -> bool {
7211                self.#pk_ident != other.#pk_ident
7212            }
7213
7214            /// Returns this row's primary-key value as an
7215            /// [`#root::core::SqlValue`]. Eloquent
7216            /// `$model->getKey()` parity.
7217            ///
7218            /// Useful when you need to thread the PK through a
7219            /// generic `Into<SqlValue>`-bound API without knowing the
7220            /// concrete PK type (`i64` vs `Uuid` vs `String`).
7221            #[must_use]
7222            pub fn get_key(&self) -> #root::core::SqlValue {
7223                ::core::convert::Into::into(::core::clone::Clone::clone(&self.#pk_ident))
7224            }
7225
7226        }
7227    });
7228
7229    let insert_method = if fields.has_auto {
7230        let pushes = &fields.insert_pushes;
7231        let returning_cols = &fields.returning_cols;
7232        let auto_assigns = &fields.auto_assigns;
7233        quote! {
7234            /// Insert this row into its table. Skips columns whose
7235            /// `Auto<T>` value is `Unset` so Postgres' SERIAL/BIGSERIAL
7236            /// sequence fills them in, then reads each `Auto` column
7237            /// back via `RETURNING` and stores it on `self`.
7238            ///
7239            /// **Postgres only — prefer [`Self::insert_pool`].** This takes
7240            /// a driver-specific `PgPool`, so it does not exist on a build
7241            /// without the `postgres` feature. [`Self::insert_pool`] takes
7242            /// `rustango::sql::Pool` and works on all three. The naming is
7243            /// inverted; tracked in #1293.
7244            ///
7245            /// # Errors
7246            /// Returns [`#root::sql::ExecError`] for SQL-writing or
7247            /// driver failures.
7248            #[cfg(feature = "postgres")]
7249            pub async fn insert(
7250                &mut self,
7251                pool: &#root::sql::sqlx::PgPool,
7252            ) -> ::core::result::Result<(), #root::sql::ExecError> {
7253                #pool_to_insert_on
7254            }
7255
7256            /// Like [`Self::insert`] but accepts any sqlx executor.
7257            /// See [`Self::save_on`] for tenancy-scoped rationale.
7258            ///
7259            /// # Errors
7260            /// As [`Self::insert`].
7261            #[cfg(feature = "postgres")]
7262            pub async fn insert_on #executor_generics (
7263                &mut self,
7264                #executor_param,
7265            ) -> ::core::result::Result<(), #root::sql::ExecError>
7266            #executor_where
7267            {
7268                let mut _columns: ::std::vec::Vec<&'static str> =
7269                    ::std::vec::Vec::new();
7270                let mut _values: ::std::vec::Vec<#root::core::SqlValue> =
7271                    ::std::vec::Vec::new();
7272                #( #pushes )*
7273                let query = #root::core::InsertQuery {
7274                    model: <Self as #root::core::Model>::SCHEMA,
7275                    columns: _columns,
7276                    values: _values,
7277                    returning: ::std::vec![ #( #returning_cols ),* ],
7278                    on_conflict: ::core::option::Option::None,
7279                };
7280                let _returning_row_v = #root::sql::__macro_internals::insert_returning_on(
7281                    #executor_passes_to_data_write,
7282                    &query,
7283                ).await?;
7284                let _returning_row = &_returning_row_v;
7285                #( #auto_assigns )*
7286                #audit_insert_emit
7287                ::core::result::Result::Ok(())
7288            }
7289
7290            /// Per-call audit-source override for [`Self::insert_on`].
7291            /// See [`Self::save_on_with`] for shape rationale.
7292            ///
7293            /// # Errors
7294            /// As [`Self::insert_on`].
7295            #[cfg(feature = "postgres")]
7296            pub async fn insert_on_with #executor_generics (
7297                &mut self,
7298                #executor_param,
7299                source: #root::audit::AuditSource,
7300            ) -> ::core::result::Result<(), #root::sql::ExecError>
7301            #executor_where
7302            {
7303                #root::audit::with_source(source, self.insert_on(_executor)).await
7304            }
7305        }
7306    } else {
7307        let insert_columns = &fields.insert_columns;
7308        let insert_values = &fields.insert_values;
7309        quote! {
7310            /// Insert this row into its table.
7311            ///
7312            /// # Errors
7313            /// Returns [`#root::sql::ExecError`] for SQL-writing or
7314            /// driver failures.
7315            #[cfg(feature = "postgres")]
7316            pub async fn insert(
7317                &self,
7318                pool: &#root::sql::sqlx::PgPool,
7319            ) -> ::core::result::Result<(), #root::sql::ExecError> {
7320                self.insert_on(pool).await
7321            }
7322
7323            /// Like [`Self::insert`] but accepts any sqlx executor.
7324            /// See [`Self::save_on`] for tenancy-scoped rationale.
7325            ///
7326            /// # Errors
7327            /// As [`Self::insert`].
7328            #[cfg(feature = "postgres")]
7329            pub async fn insert_on<'_c, _E>(
7330                &self,
7331                _executor: _E,
7332            ) -> ::core::result::Result<(), #root::sql::ExecError>
7333            where
7334                _E: #root::sql::sqlx::Executor<'_c, Database = #root::sql::sqlx::Postgres>,
7335            {
7336                let query = #root::core::InsertQuery {
7337                    model: <Self as #root::core::Model>::SCHEMA,
7338                    columns: ::std::vec![ #( #insert_columns ),* ],
7339                    values: ::std::vec![ #( #insert_values ),* ],
7340                    returning: ::std::vec::Vec::new(),
7341                    on_conflict: ::core::option::Option::None,
7342                };
7343                #root::sql::__macro_internals::insert_on(_executor, &query).await
7344            }
7345        }
7346    };
7347
7348    let bulk_insert_method = if fields.has_auto {
7349        let cols_no_auto = &fields.bulk_columns_no_auto;
7350        let cols_all = &fields.bulk_columns_all;
7351        let pushes_no_auto = &fields.bulk_pushes_no_auto;
7352        let pushes_all = &fields.bulk_pushes_all;
7353        let returning_cols = &fields.returning_cols;
7354        let auto_assigns_for_row = bulk_auto_assigns_for_row(fields);
7355        let uniformity = &fields.bulk_auto_uniformity;
7356        let first_auto_ident = fields
7357            .first_auto_ident
7358            .as_ref()
7359            .expect("has_auto implies first_auto_ident is Some");
7360        quote! {
7361            /// Bulk-insert `rows` in a single round-trip. Every row's
7362            /// `Auto<T>` PK fields must uniformly be `Auto::Unset`
7363            /// (sequence fills them in) or uniformly `Auto::Set(_)`
7364            /// (caller-supplied values). Mixed Set/Unset is rejected
7365            /// — call `insert` per row for that case.
7366            ///
7367            /// Empty slice is a no-op. Each row's `Auto` fields are
7368            /// populated from the `RETURNING` clause in input order
7369            /// before this returns.
7370            ///
7371            /// # Errors
7372            /// Returns [`#root::sql::ExecError`] for validation,
7373            /// SQL-writing, mixed-Auto rejection, or driver failures.
7374            #[cfg(feature = "postgres")]
7375            pub async fn bulk_insert(
7376                rows: &mut [Self],
7377                pool: &#root::sql::sqlx::PgPool,
7378            ) -> ::core::result::Result<(), #root::sql::ExecError> {
7379                #pool_to_bulk_insert_on
7380            }
7381
7382            /// Like [`Self::bulk_insert`] but accepts any sqlx executor.
7383            /// See [`Self::save_on`] for tenancy-scoped rationale.
7384            ///
7385            /// # Errors
7386            /// As [`Self::bulk_insert`].
7387            #[cfg(feature = "postgres")]
7388            pub async fn bulk_insert_on #executor_generics (
7389                rows: &mut [Self],
7390                #executor_param,
7391            ) -> ::core::result::Result<(), #root::sql::ExecError>
7392            #executor_where
7393            {
7394                if rows.is_empty() {
7395                    return ::core::result::Result::Ok(());
7396                }
7397                let _first_unset = matches!(
7398                    rows[0].#first_auto_ident,
7399                    #root::sql::Auto::Unset
7400                );
7401                #( #uniformity )*
7402
7403                let mut _all_rows: ::std::vec::Vec<
7404                    ::std::vec::Vec<#root::core::SqlValue>,
7405                > = ::std::vec::Vec::with_capacity(rows.len());
7406                let _columns: ::std::vec::Vec<&'static str> = if _first_unset {
7407                    for _row in rows.iter() {
7408                        let mut _row_vals: ::std::vec::Vec<#root::core::SqlValue> =
7409                            ::std::vec::Vec::new();
7410                        #( #pushes_no_auto )*
7411                        _all_rows.push(_row_vals);
7412                    }
7413                    ::std::vec![ #( #cols_no_auto ),* ]
7414                } else {
7415                    for _row in rows.iter() {
7416                        let mut _row_vals: ::std::vec::Vec<#root::core::SqlValue> =
7417                            ::std::vec::Vec::new();
7418                        #( #pushes_all )*
7419                        _all_rows.push(_row_vals);
7420                    }
7421                    ::std::vec![ #( #cols_all ),* ]
7422                };
7423
7424                let _query = #root::core::BulkInsertQuery {
7425                    model: <Self as #root::core::Model>::SCHEMA,
7426                    columns: _columns,
7427                    rows: _all_rows,
7428                    returning: ::std::vec![ #( #returning_cols ),* ],
7429                    on_conflict: ::core::option::Option::None,
7430                };
7431                let _returned = #root::sql::__macro_internals::bulk_insert_on(
7432                    #executor_passes_to_data_write,
7433                    &_query,
7434                ).await?;
7435                if _returned.len() != rows.len() {
7436                    return ::core::result::Result::Err(
7437                        #root::sql::ExecError::Sql(
7438                            #root::sql::SqlError::BulkInsertReturningMismatch {
7439                                expected: rows.len(),
7440                                actual: _returned.len(),
7441                            }
7442                        )
7443                    );
7444                }
7445                for (_returning_row, _row_mut) in _returned.iter().zip(rows.iter_mut()) {
7446                    #auto_assigns_for_row
7447                }
7448                #audit_bulk_insert_emit
7449                ::core::result::Result::Ok(())
7450            }
7451        }
7452    } else {
7453        let cols_all = &fields.bulk_columns_all;
7454        let pushes_all = &fields.bulk_pushes_all;
7455        quote! {
7456            /// Bulk-insert `rows` in a single round-trip. Every row's
7457            /// fields are written verbatim — there are no `Auto<T>`
7458            /// fields on this model.
7459            ///
7460            /// Empty slice is a no-op.
7461            ///
7462            /// # Errors
7463            /// Returns [`#root::sql::ExecError`] for validation,
7464            /// SQL-writing, or driver failures.
7465            #[cfg(feature = "postgres")]
7466            pub async fn bulk_insert(
7467                rows: &[Self],
7468                pool: &#root::sql::sqlx::PgPool,
7469            ) -> ::core::result::Result<(), #root::sql::ExecError> {
7470                Self::bulk_insert_on(rows, pool).await
7471            }
7472
7473            /// Like [`Self::bulk_insert`] but accepts any sqlx executor.
7474            /// See [`Self::save_on`] for tenancy-scoped rationale.
7475            ///
7476            /// # Errors
7477            /// As [`Self::bulk_insert`].
7478            #[cfg(feature = "postgres")]
7479            pub async fn bulk_insert_on<'_c, _E>(
7480                rows: &[Self],
7481                _executor: _E,
7482            ) -> ::core::result::Result<(), #root::sql::ExecError>
7483            where
7484                _E: #root::sql::sqlx::Executor<'_c, Database = #root::sql::sqlx::Postgres>,
7485            {
7486                if rows.is_empty() {
7487                    return ::core::result::Result::Ok(());
7488                }
7489                let mut _all_rows: ::std::vec::Vec<
7490                    ::std::vec::Vec<#root::core::SqlValue>,
7491                > = ::std::vec::Vec::with_capacity(rows.len());
7492                for _row in rows.iter() {
7493                    let mut _row_vals: ::std::vec::Vec<#root::core::SqlValue> =
7494                        ::std::vec::Vec::new();
7495                    #( #pushes_all )*
7496                    _all_rows.push(_row_vals);
7497                }
7498                let _query = #root::core::BulkInsertQuery {
7499                    model: <Self as #root::core::Model>::SCHEMA,
7500                    columns: ::std::vec![ #( #cols_all ),* ],
7501                    rows: _all_rows,
7502                    returning: ::std::vec::Vec::new(),
7503                    on_conflict: ::core::option::Option::None,
7504                };
7505                let _ = #root::sql::__macro_internals::bulk_insert_on(_executor, &_query).await?;
7506                ::core::result::Result::Ok(())
7507            }
7508        }
7509    };
7510
7511    // Tri-dialect `bulk_upsert_pool` — issue #267 / T1.5. Always emitted
7512    // (no postgres-feature gate); routes through the existing
7513    // `bulk_insert_pool` + per-dialect conflict writer.
7514    //
7515    // Auto<T> PKs are required to be `Auto::Unset` for every row so the
7516    // sequence picks the PK for fresh inserts; the UPDATE branch never
7517    // touches the Auto column.
7518    let bulk_upsert_pool_method = {
7519        // Pick the "no Auto" columns when the model has Auto fields,
7520        // else every column.
7521        let (upsert_cols, upsert_pushes): (Vec<_>, Vec<_>) = if fields.has_auto {
7522            (
7523                fields.bulk_columns_no_auto.clone(),
7524                fields.bulk_pushes_no_auto.clone(),
7525            )
7526        } else {
7527            (
7528                fields.bulk_columns_all.clone(),
7529                fields.bulk_pushes_all.clone(),
7530            )
7531        };
7532        quote! {
7533            /// Tri-dialect bulk insert that updates on conflict — the
7534            /// "import a batch idempotently" shape. Issue #267 / T1.5.
7535            ///
7536            /// Per-row values are extracted and lowered into a
7537            /// [`#root::core::BulkInsertQuery`] with
7538            /// `on_conflict = DoUpdate { target, update_columns }`. The
7539            /// writer dispatches per-dialect:
7540            /// * Postgres / SQLite: `INSERT … ON CONFLICT (target) DO UPDATE SET col = EXCLUDED.col`
7541            /// * MySQL: `INSERT … ON DUPLICATE KEY UPDATE col = VALUES(col)` (target ignored — MySQL matches every UNIQUE index)
7542            ///
7543            /// `target` names the column(s) whose unique constraint
7544            /// defines the conflict (typically a `unique` or
7545            /// `unique_together` natural-key column, NOT the `Auto<T>`
7546            /// PK). `update_cols` names the columns to overwrite on
7547            /// conflict — every other column is left untouched on the
7548            /// existing row.
7549            ///
7550            /// Auto-PK rows must all have `Auto::Unset` (the sequence
7551            /// picks the PK on insert; the update path never touches
7552            /// the Auto column). Auto-set rows trigger a hard error.
7553            /// Empty slice is a no-op.
7554            ///
7555            /// # Errors
7556            /// Returns [`#root::sql::ExecError`] for validation,
7557            /// SQL-writing, or driver failures.
7558            pub async fn bulk_upsert_pool(
7559                rows: &[Self],
7560                target: &[&'static str],
7561                update_cols: &[&'static str],
7562                pool: &#root::sql::Pool,
7563            ) -> ::core::result::Result<(), #root::sql::ExecError> {
7564                if rows.is_empty() {
7565                    return ::core::result::Result::Ok(());
7566                }
7567                let mut _all_rows: ::std::vec::Vec<
7568                    ::std::vec::Vec<#root::core::SqlValue>,
7569                > = ::std::vec::Vec::with_capacity(rows.len());
7570                for _row in rows.iter() {
7571                    let mut _row_vals: ::std::vec::Vec<#root::core::SqlValue> =
7572                        ::std::vec::Vec::new();
7573                    #( #upsert_pushes )*
7574                    _all_rows.push(_row_vals);
7575                }
7576                let _query = #root::core::BulkInsertQuery {
7577                    model: <Self as #root::core::Model>::SCHEMA,
7578                    columns: ::std::vec![ #( #upsert_cols ),* ],
7579                    rows: _all_rows,
7580                    returning: ::std::vec::Vec::new(),
7581                    on_conflict: ::core::option::Option::Some(
7582                        #root::core::ConflictClause::DoUpdate {
7583                            target: target.to_vec(),
7584                            update_columns: update_cols.to_vec(),
7585                        }
7586                    ),
7587                };
7588                #root::sql::bulk_insert_pool(pool, &_query).await
7589            }
7590
7591            /// Tri-dialect `bulk_create(ignore_conflicts=True)` — silently
7592            /// skip rows that would violate a unique constraint. Issue
7593            /// #267 / T1.5. Same per-dialect dispatch as
7594            /// [`Self::bulk_upsert_pool`] but with `ON CONFLICT … DO
7595            /// NOTHING` (Postgres / SQLite) / `ON DUPLICATE KEY UPDATE
7596            /// <pivot> = <pivot>` (MySQL no-op write).
7597            ///
7598            /// # Errors
7599            /// As [`Self::bulk_upsert_pool`].
7600            pub async fn bulk_insert_or_ignore_pool(
7601                rows: &[Self],
7602                pool: &#root::sql::Pool,
7603            ) -> ::core::result::Result<(), #root::sql::ExecError> {
7604                if rows.is_empty() {
7605                    return ::core::result::Result::Ok(());
7606                }
7607                let mut _all_rows: ::std::vec::Vec<
7608                    ::std::vec::Vec<#root::core::SqlValue>,
7609                > = ::std::vec::Vec::with_capacity(rows.len());
7610                for _row in rows.iter() {
7611                    let mut _row_vals: ::std::vec::Vec<#root::core::SqlValue> =
7612                        ::std::vec::Vec::new();
7613                    #( #upsert_pushes )*
7614                    _all_rows.push(_row_vals);
7615                }
7616                let _query = #root::core::BulkInsertQuery {
7617                    model: <Self as #root::core::Model>::SCHEMA,
7618                    columns: ::std::vec![ #( #upsert_cols ),* ],
7619                    rows: _all_rows,
7620                    returning: ::std::vec::Vec::new(),
7621                    on_conflict: ::core::option::Option::Some(
7622                        #root::core::ConflictClause::DoNothing
7623                    ),
7624                };
7625                #root::sql::bulk_insert_pool(pool, &_query).await
7626            }
7627        }
7628    };
7629
7630    // Ergonomic `Model::bulk_update(objs, fields)`.
7631    // The SQL/IR/executor stack
7632    // (`BulkUpdateQuery` + `bulk_update_pool` + the per-dialect
7633    // `write_bulk_update_*` writers) already existed; what was missing
7634    // was the per-model constructor that maps `&[Self]` + a runtime
7635    // column list into rows of `[pk, col_vals…]` so callers don't
7636    // hand-build the IR. Emitted only when the model has a primary key
7637    // (the PK is the join key and can't itself be updated).
7638    let bulk_update_method = match &fields.primary_key {
7639        None => quote! {},
7640        Some((pk_ident, pk_col)) => {
7641            // One pair of match arms per non-PK column: a validation arm
7642            // resolving the runtime name to its `&'static str` column,
7643            // and a value arm pushing that field off the row.
7644            let mut col_arms: Vec<TokenStream2> = Vec::new();
7645            let mut val_arms: Vec<TokenStream2> = Vec::new();
7646            for entry in &fields.column_entries {
7647                if &entry.column == pk_col {
7648                    continue;
7649                }
7650                let col = &entry.column;
7651                let ident = &entry.ident;
7652                col_arms.push(quote! { #col => #col, });
7653                val_arms.push(quote! {
7654                    #col => _row_vals.push(
7655                        ::core::convert::Into::<#root::core::SqlValue>::into(
7656                            ::core::clone::Clone::clone(&_o.#ident)
7657                        )
7658                    ),
7659                });
7660            }
7661            quote! {
7662                /// Write per-row-different values for the named `fields`
7663                /// across every object in `objs` in a single statement,
7664                /// matched by primary key.
7665                ///
7666                /// `fields` names the **columns** to update. The primary
7667                /// key identifies each row and cannot itself be updated
7668                /// (pass it and you get
7669                /// [`#root::core::QueryError::BulkUpdatePrimaryKey`]).
7670                /// Empty `objs` or `fields` is a no-op returning `0`.
7671                /// Objects whose PK matches no row are simply not updated.
7672                /// Returns the number of rows affected.
7673                ///
7674                /// Tri-dialect: lowers to one
7675                /// [`#root::core::BulkUpdateQuery`] and dispatches
7676                /// per-backend — `UPDATE … FROM (VALUES …)` on Postgres,
7677                /// a CTE + correlated subquery on SQLite, an inner
7678                /// `JOIN (VALUES …)` on MySQL.
7679                ///
7680                /// # Errors
7681                /// [`#root::core::QueryError::UnknownField`] for a name
7682                /// that isn't a column on this model,
7683                /// [`#root::core::QueryError::BulkUpdatePrimaryKey`] if
7684                /// `fields` names the PK, or [`#root::sql::ExecError`] for
7685                /// SQL-writing / driver failures.
7686                pub async fn bulk_update(
7687                    objs: &[Self],
7688                    fields: &[&str],
7689                    pool: &#root::sql::Pool,
7690                ) -> ::core::result::Result<u64, #root::sql::ExecError> {
7691                    if objs.is_empty() || fields.is_empty() {
7692                        return ::core::result::Result::Ok(0);
7693                    }
7694                    let _model_name = <Self as #root::core::Model>::SCHEMA.name;
7695                    let mut _update_columns: ::std::vec::Vec<&'static str> =
7696                        ::std::vec::Vec::with_capacity(fields.len());
7697                    for &_f in fields {
7698                        let _col: &'static str = match _f {
7699                            #pk_col => {
7700                                return ::core::result::Result::Err(
7701                                    ::core::convert::Into::into(
7702                                        #root::core::QueryError::BulkUpdatePrimaryKey {
7703                                            model: _model_name,
7704                                            field: ::std::string::ToString::to_string(_f),
7705                                        }
7706                                    )
7707                                );
7708                            }
7709                            #( #col_arms )*
7710                            _ => {
7711                                return ::core::result::Result::Err(
7712                                    ::core::convert::Into::into(
7713                                        #root::core::QueryError::UnknownField {
7714                                            model: _model_name,
7715                                            field: ::std::string::ToString::to_string(_f),
7716                                        }
7717                                    )
7718                                );
7719                            }
7720                        };
7721                        // A model whose only field is the primary key emits no
7722                        // non-PK arms, so every arm above diverges and this push
7723                        // is genuinely unreachable — correct, since such a model
7724                        // has nothing to bulk-update. Scoped to the statement
7725                        // rather than the fn so a real unreachability elsewhere
7726                        // in this body still warns. Without it every PK-only
7727                        // model warns in the *user's* crate, which they cannot
7728                        // act on (#1290).
7729                        #[allow(unreachable_code)]
7730                        _update_columns.push(_col);
7731                    }
7732                    let mut _rows: ::std::vec::Vec<
7733                        ::std::vec::Vec<#root::core::SqlValue>,
7734                    > = ::std::vec::Vec::with_capacity(objs.len());
7735                    for _o in objs.iter() {
7736                        let mut _row_vals: ::std::vec::Vec<#root::core::SqlValue> =
7737                            ::std::vec::Vec::with_capacity(fields.len() + 1);
7738                        // PK first — the writers expect `[pk, …update cols]`.
7739                        _row_vals.push(
7740                            ::core::convert::Into::<#root::core::SqlValue>::into(
7741                                ::core::clone::Clone::clone(&_o.#pk_ident)
7742                            )
7743                        );
7744                        for &_f in fields {
7745                            match _f {
7746                                #( #val_arms )*
7747                                // Unreachable: every name was validated
7748                                // against the same arm set above.
7749                                _ => {}
7750                            }
7751                        }
7752                        _rows.push(_row_vals);
7753                    }
7754                    let _query = #root::core::BulkUpdateQuery {
7755                        model: <Self as #root::core::Model>::SCHEMA,
7756                        update_columns: _update_columns,
7757                        rows: _rows,
7758                    };
7759                    #root::sql::bulk_update_pool(pool, &_query).await
7760                }
7761            }
7762        }
7763    };
7764
7765    let pk_value_helper = primary_key.map(|(pk_ident, _)| {
7766        quote! {
7767            /// Hidden runtime accessor for the primary-key value as a
7768            /// [`SqlValue`]. Used by reverse-relation helpers
7769            /// (`<parent>::<child>_set`) emitted from sibling models'
7770            /// FK fields. Not part of the public API.
7771            #[doc(hidden)]
7772            pub fn __rustango_pk_value(&self) -> #root::core::SqlValue {
7773                ::core::convert::Into::<#root::core::SqlValue>::into(
7774                    ::core::clone::Clone::clone(&self.#pk_ident)
7775                )
7776            }
7777        }
7778    });
7779
7780    let has_pk_value_impl = primary_key.map(|(pk_ident, _)| {
7781        quote! {
7782            impl #root::sql::HasPkValue for #struct_name {
7783                fn __rustango_pk_value_impl(&self) -> #root::core::SqlValue {
7784                    ::core::convert::Into::<#root::core::SqlValue>::into(
7785                        ::core::clone::Clone::clone(&self.#pk_ident)
7786                    )
7787                }
7788            }
7789        }
7790    });
7791
7792    let fk_pk_access_impl = fk_pk_access_impl_tokens(struct_name, &fields.fk_relations);
7793
7794    // Slice 17.1 — `AssignAutoPkPool` impl lets `apply_auto_pk`
7795    // dispatch to the right per-backend body without the macro emitting
7796    // any `#[cfg(feature = …)]` arm into consumer code. Always emitted
7797    // so audited models with non-Auto PKs (which still go through
7798    // `insert_one_with_audit` → `apply_auto_pk`) link.
7799    let assign_auto_pk_pool_impl = {
7800        let auto_assigns = &fields.auto_assigns;
7801        // SQLite ≥ 3.35 supports the same RETURNING shape as Postgres,
7802        // so the body is structurally identical to `auto_assigns` —
7803        // only the helper name swaps from `try_get_returning` to
7804        // `try_get_returning_sqlite` so the closure typechecks against
7805        // a `SqliteRow` instead of a `PgRow`.
7806        let auto_assigns_sqlite: Vec<TokenStream2> = fields
7807            .auto_field_idents
7808            .iter()
7809            .map(|(ident, column)| {
7810                quote! {
7811                    self.#ident = #root::sql::try_get_returning_sqlite(
7812                        _returning_row, #column
7813                    )?;
7814                }
7815            })
7816            .collect();
7817        // #1028 — decode each `generated_as` column from the same
7818        // RETURNING row (PG/SQLite). Plain-typed fields, so the field's
7819        // own type drives the decode (no `Auto<T>` wrapper).
7820        let generated_assigns: Vec<TokenStream2> = fields
7821            .generated_field_idents
7822            .iter()
7823            .map(|(ident, column)| {
7824                quote! {
7825                    self.#ident = #root::sql::try_get_returning(_returning_row, #column)?;
7826                }
7827            })
7828            .collect();
7829        let generated_assigns_sqlite: Vec<TokenStream2> = fields
7830            .generated_field_idents
7831            .iter()
7832            .map(|(ident, column)| {
7833                quote! {
7834                    self.#ident = #root::sql::try_get_returning_sqlite(
7835                        _returning_row, #column
7836                    )?;
7837                }
7838            })
7839            .collect();
7840        let mysql_body = if let Some(first) = fields.first_auto_ident.as_ref() {
7841            // The MySQL `LAST_INSERT_ID()` is always i64. Route through
7842            // `MysqlAutoIdSet` so Auto<i32> narrows safely and
7843            // Auto<Uuid>/etc. fail to link against MySQL (intended —
7844            // those models can't use AUTO_INCREMENT). The trait is only
7845            // touched on the MySQL arm at runtime, so PG-only consumers
7846            // never see the bound failure.
7847            //
7848            // Pre-v0.20: models with multiple `Auto<T>` fields (e.g.
7849            // Auto<i64> PK + auto_now_add timestamp) errored hard at
7850            // runtime with "multi-column RETURNING". MySQL has no
7851            // multi-column RETURNING semantic and a follow-up SELECT
7852            // would need cross-trait plumbing. Pragmatic shape: succeed
7853            // with the FIRST Auto field populated from LAST_INSERT_ID();
7854            // any other Auto fields stay `Auto::Unset`. Callers that
7855            // need the DB-defaulted timestamp / UUID can re-fetch the
7856            // row by PK after `save_pool`. Fixes the cookbook chapter
7857            // 12 dialect divergence.
7858            let value_ty = fields
7859                .first_auto_value_ty
7860                .as_ref()
7861                .expect("first_auto_value_ty set whenever first_auto_ident is");
7862            quote! {
7863                let _converted = <#value_ty as #root::sql::MysqlAutoIdSet>
7864                    ::rustango_from_mysql_auto_id(_id)?;
7865                self.#first = #root::sql::Auto::Set(_converted);
7866                ::core::result::Result::Ok(())
7867            }
7868        } else {
7869            quote! {
7870                let _ = _id;
7871                ::core::result::Result::Ok(())
7872            }
7873        };
7874        quote! {
7875            impl #root::sql::AssignAutoPkPool for #struct_name {
7876                fn __rustango_assign_from_pg_row(
7877                    &mut self,
7878                    _returning_row: &#root::sql::PgReturningRow,
7879                ) -> ::core::result::Result<(), #root::sql::ExecError> {
7880                    #( #auto_assigns )*
7881                    #( #generated_assigns )*
7882                    ::core::result::Result::Ok(())
7883                }
7884                fn __rustango_assign_from_mysql_id(
7885                    &mut self,
7886                    _id: i64,
7887                ) -> ::core::result::Result<(), #root::sql::ExecError> {
7888                    #mysql_body
7889                }
7890                fn __rustango_assign_from_sqlite_row(
7891                    &mut self,
7892                    _returning_row: &#root::sql::SqliteReturningRow,
7893                ) -> ::core::result::Result<(), #root::sql::ExecError> {
7894                    #( #auto_assigns_sqlite )*
7895                    #( #generated_assigns_sqlite )*
7896                    ::core::result::Result::Ok(())
7897                }
7898            }
7899        }
7900    };
7901
7902    let from_aliased_row_inits = &fields.from_aliased_row_inits;
7903    let aliased_row_helper = quote! {
7904        /// Decode a row's aliased target columns (produced by
7905        /// `select_related`'s LEFT JOIN) into a fresh instance of
7906        /// this model. Reads each column via
7907        /// `format!("{prefix}__{col}")`, matching the alias the
7908        /// SELECT writer emitted. Slice 9.0d.
7909        #[doc(hidden)]
7910        #[cfg(feature = "postgres")]
7911        pub fn __rustango_from_aliased_row(
7912            row: &#root::sql::sqlx::postgres::PgRow,
7913            prefix: &str,
7914        ) -> ::core::result::Result<Self, #root::sql::sqlx::Error> {
7915            ::core::result::Result::Ok(Self {
7916                #( #from_aliased_row_inits ),*
7917            })
7918        }
7919    };
7920    // v0.23.0-batch8 — MySQL counterpart, gated through the
7921    // cfg-aware macro_rules so PG-only builds expand to nothing.
7922    let aliased_row_helper_my = quote! {
7923        #root::__impl_my_aliased_row_decoder!(#struct_name, |row, prefix| {
7924            #( #from_aliased_row_inits ),*
7925        });
7926    };
7927
7928    // v0.27 Phase 3 — SQLite counterpart, same hygiene-aware closure
7929    // pattern + cfg gate on the `sqlite` feature.
7930    let aliased_row_helper_sqlite = quote! {
7931        #root::__impl_sqlite_aliased_row_decoder!(#struct_name, |row, prefix| {
7932            #( #from_aliased_row_inits ),*
7933        });
7934    };
7935
7936    let load_related_impl = load_related_impl_tokens(struct_name, &fields.fk_relations);
7937    let load_related_impl_my = load_related_impl_my_tokens(struct_name, &fields.fk_relations);
7938    let load_related_impl_sqlite =
7939        load_related_impl_sqlite_tokens(struct_name, &fields.fk_relations);
7940
7941    // Issue #289 / T2.6 — `#[rustango(manager_fn = "active")]` emits
7942    // extra `Self::<name>() -> QuerySet<Self>` accessors next to the
7943    // default `Self::objects()`. Each accessor returns a fresh
7944    // QuerySet that resolves any `impl <FooManagerExt> for QuerySet<Foo>`
7945    // methods the user defined.
7946    let extra_manager_fns: Vec<TokenStream2> = manager_fns
7947        .iter()
7948        .map(|fn_ident| {
7949            let model_name_str = struct_name.to_string();
7950            let fn_name_str = fn_ident.to_string();
7951            let doc = format!(
7952                "Custom-named QuerySet accessor for [`{model_name_str}`]. \
7953                 Generated by `#[rustango(manager_fn = \"{fn_name_str}\")]` — \
7954                 equivalent to `Self::objects()`. Chains with any \
7955                 `impl ... for QuerySet<{model_name_str}> {{ ... }}` \
7956                 extension methods."
7957            );
7958            quote! {
7959                #[doc = #doc]
7960                #[must_use]
7961                pub fn #fn_ident() -> #root::query::QuerySet<#struct_name> {
7962                    #root::query::QuerySet::new()
7963                }
7964            }
7965        })
7966        .collect();
7967
7968    quote! {
7969        impl #struct_name {
7970            /// Start a new `QuerySet` over this model.
7971            #[must_use]
7972            pub fn objects() -> #root::query::QuerySet<#struct_name> {
7973                #root::query::QuerySet::new()
7974            }
7975
7976            /// Eloquent-shape alias of [`Self::objects`]. Returns
7977            /// a fresh `QuerySet<Self>` ready for `.filter()` /
7978            /// `.where_()` / etc. Matches Laravel muscle-memory:
7979            ///
7980            /// ```ignore
7981            /// // Eloquent:    Post::query()->where('published', true)
7982            /// // rustango:    Post::query().filter("published", true)
7983            /// //         or:  Post::objects().filter("published", true)
7984            /// ```
7985            ///
7986            /// Both names point at the same underlying constructor;
7987            /// neither is preferred.
7988            #[must_use]
7989            pub fn query() -> #root::query::QuerySet<#struct_name> {
7990                #root::query::QuerySet::new()
7991            }
7992
7993            #( #extra_manager_fns )*
7994
7995            #insert_method
7996
7997            #bulk_insert_method
7998
7999            #bulk_upsert_pool_method
8000
8001            #bulk_update_method
8002
8003            #save_method
8004
8005            #pk_methods
8006
8007            #pk_value_helper
8008
8009            #aliased_row_helper
8010
8011            #column_consts
8012        }
8013
8014        #aliased_row_helper_my
8015
8016        #aliased_row_helper_sqlite
8017
8018        #load_related_impl
8019
8020        #load_related_impl_my
8021
8022        #load_related_impl_sqlite
8023
8024        #has_pk_value_impl
8025
8026        #fk_pk_access_impl
8027
8028        #assign_auto_pk_pool_impl
8029    }
8030}
8031
8032/// Per-row Auto-field assigns for `bulk_insert` — equivalent to
8033/// `auto_assigns` but reading from `_returning_row` and writing to
8034/// `_row_mut` instead of `self`.
8035fn bulk_auto_assigns_for_row(fields: &CollectedFields) -> TokenStream2 {
8036    let root = rustango_root();
8037    let lines = fields.auto_field_idents.iter().map(|(ident, column)| {
8038        let col_lit = column.as_str();
8039        quote! {
8040            _row_mut.#ident = #root::sql::sqlx::Row::try_get(
8041                _returning_row,
8042                #col_lit,
8043            )?;
8044        }
8045    });
8046    quote! { #( #lines )* }
8047}
8048
8049/// Emit `pub const id: …Id = …Id;` per field, inside the inherent impl.
8050fn column_const_tokens(module_ident: &syn::Ident, entries: &[ColumnEntry]) -> TokenStream2 {
8051    let lines = entries.iter().map(|e| {
8052        let ident = &e.ident;
8053        let col_ty = column_type_ident(ident);
8054        quote! {
8055            #[allow(non_upper_case_globals)]
8056            pub const #ident: #module_ident::#col_ty = #module_ident::#col_ty;
8057        }
8058    });
8059    quote! { #(#lines)* }
8060}
8061
8062/// Emit a hidden per-model module carrying one zero-sized type per field,
8063/// each with a `Column` impl pointing back at the model.
8064fn column_module_tokens(
8065    module_ident: &syn::Ident,
8066    struct_name: &syn::Ident,
8067    entries: &[ColumnEntry],
8068) -> TokenStream2 {
8069    let root = rustango_root();
8070    let items = entries.iter().map(|e| {
8071        let col_ty = column_type_ident(&e.ident);
8072        let value_ty = &e.value_ty;
8073        let name = &e.name;
8074        let column = &e.column;
8075        let field_type_tokens = &e.field_type_tokens;
8076        quote! {
8077            #[derive(::core::clone::Clone, ::core::marker::Copy)]
8078            pub struct #col_ty;
8079
8080            impl #root::core::Column for #col_ty {
8081                type Model = super::#struct_name;
8082                type Value = #value_ty;
8083                const NAME: &'static str = #name;
8084                const COLUMN: &'static str = #column;
8085                const FIELD_TYPE: #root::core::FieldType = #field_type_tokens;
8086            }
8087        }
8088    });
8089    quote! {
8090        #[doc(hidden)]
8091        #[allow(non_camel_case_types, non_snake_case)]
8092        pub mod #module_ident {
8093            // Re-import the parent scope so field types referencing
8094            // sibling models (e.g. `ForeignKey<Author>`) resolve
8095            // inside this submodule. Without this we'd hit
8096            // `proc_macro_derive_resolution_fallback` warnings.
8097            #[allow(unused_imports)]
8098            use super::*;
8099            #(#items)*
8100        }
8101    }
8102}
8103
8104fn column_type_ident(field_ident: &syn::Ident) -> syn::Ident {
8105    syn::Ident::new(&format!("{field_ident}_col"), field_ident.span())
8106}
8107
8108fn column_module_ident(struct_name: &syn::Ident) -> syn::Ident {
8109    syn::Ident::new(
8110        &format!("__rustango_cols_{struct_name}"),
8111        struct_name.span(),
8112    )
8113}
8114
8115fn from_row_impl_tokens(struct_name: &syn::Ident, from_row_inits: &[TokenStream2]) -> TokenStream2 {
8116    let root = rustango_root();
8117    // The Postgres impl is always emitted — every rustango build pulls in
8118    // sqlx-postgres via the default `postgres` feature. The MySQL impl is
8119    // routed through `#root::__impl_my_from_row!`, a cfg-gated
8120    // macro_rules whose body collapses to nothing when rustango is built
8121    // without the `mysql` feature. No user-facing feature shim required.
8122    //
8123    // The macro_rules pattern expects `[ field: expr, … ]` — we need to
8124    // re-shape `from_row_inits` (each token is `field: row.try_get(...)`)
8125    // back into a comma-separated list inside square brackets. Since each
8126    // entry is already in `field: expr` shape, the existing tokens slot in.
8127    quote! {
8128        #[cfg(feature = "postgres")]
8129        impl<'r> #root::sql::sqlx::FromRow<'r, #root::sql::sqlx::postgres::PgRow>
8130            for #struct_name
8131        {
8132            fn from_row(
8133                row: &'r #root::sql::sqlx::postgres::PgRow,
8134            ) -> ::core::result::Result<Self, #root::sql::sqlx::Error> {
8135                ::core::result::Result::Ok(Self {
8136                    #( #from_row_inits ),*
8137                })
8138            }
8139        }
8140
8141        #root::__impl_my_from_row!(#struct_name, |row| {
8142            #( #from_row_inits ),*
8143        });
8144
8145        #root::__impl_sqlite_from_row!(#struct_name, |row| {
8146            #( #from_row_inits ),*
8147        });
8148    }
8149}
8150
8151struct ContainerAttrs {
8152    table: Option<String>,
8153    display: Option<(String, proc_macro2::Span)>,
8154    /// Explicit app label from `#[rustango(app = "blog")]`.
8155    /// Recorded on the emitted `ModelSchema.app_label`. When unset,
8156    /// `ModelEntry::resolved_app_label()` infers from `module_path!()`
8157    /// at runtime — this attribute is the override for cases where
8158    /// the inference is wrong (e.g. a model that conceptually belongs
8159    /// to one app but is physically in another module).
8160    app: Option<String>,
8161    /// Per-model admin knobs from
8162    /// `#[rustango(admin(...))]`. `None` when the user didn't write the
8163    /// attribute — the emitted `ModelSchema.admin` becomes `None` and
8164    /// admin code falls back to `AdminConfig::DEFAULT`.
8165    admin: Option<AdminAttrs>,
8166    /// Per-model audit configuration from `#[rustango(audit(...))]`.
8167    /// `None` when the model isn't audited — write paths emit no
8168    /// audit entries. When present, single-row writes capture
8169    /// before/after for the listed fields and bulk writes batch
8170    /// snapshots into one INSERT into `rustango_audit_log`.
8171    audit: Option<AuditAttrs>,
8172    /// `true` when `#[rustango(permissions)]` is present. Signals that
8173    /// `auto_create_permissions` should seed the four CRUD codenames for
8174    /// this model.
8175    permissions: bool,
8176    /// Many-to-many relations declared via
8177    /// `#[rustango(m2m(name = "tags", to = "app_tags", through = "post_tags",
8178    ///                 src = "post_id", dst = "tag_id"))]`.
8179    m2m: Vec<M2MAttr>,
8180    /// Polymorphic M2M relations declared via
8181    /// `#[rustango(generic_m2m(name = "tags", through = "taggables",
8182    ///   pk_column = "taggable_id", ct_column = "taggable_type",
8183    ///   related_column = "tag_id"))]` (issue #818).
8184    generic_m2m: Vec<GenericM2MAttr>,
8185    /// Composite indexes declared via
8186    /// `#[rustango(index("col1, col2"))]` or
8187    /// `#[rustango(index("col1, col2", unique, name = "my_idx"))]`.
8188    /// Single-column indexes from `#[rustango(index)]` on fields are
8189    /// accumulated here during field collection.
8190    indexes: Vec<IndexAttr>,
8191    /// Table-level CHECK constraints declared via
8192    /// `#[rustango(check(name = "…", expr = "…"))]`.
8193    checks: Vec<CheckAttr>,
8194    /// Table-level PG `EXCLUDE` constraints declared via
8195    /// `#[rustango(exclude(name = "…", using = "gist", elements =
8196    /// "col WITH op, col WITH op", where = "…"))]`. PG-only — the
8197    /// migration writer renders them on Postgres and skips with a
8198    /// warning on MySQL/SQLite. Issue #319.
8199    excludes: Vec<ExcludeAttr>,
8200    /// Composite (multi-column) FKs declared via
8201    /// `#[rustango(fk_composite(name = "…", to = "…", on = (…), from = (…)))]`.
8202    /// Sub-slice F.2 of the v0.15.0 ContentType plan.
8203    composite_fks: Vec<CompositeFkAttr>,
8204    /// Generic ("any model") FKs declared via
8205    /// `#[rustango(generic_fk(name = "…", ct_column = "…", pk_column = "…"))]`.
8206    /// Sub-slice F.4 of the v0.15.0 ContentType plan.
8207    generic_fks: Vec<GenericFkAttr>,
8208    /// Where this model lives in a tenancy deployment, declared via
8209    /// `#[rustango(scope = "registry")]` or `#[rustango(scope = "tenant")]`.
8210    /// Defaults to `"tenant"` when unset; `makemigrations` uses this
8211    /// to partition diff output between registry-scoped and
8212    /// tenant-scoped migration files.
8213    scope: Option<String>,
8214    /// Custom-Manager extension-trait name from
8215    /// `#[rustango(manager(ext = "FooManagerExt"))]`. Issue #271 / T1.9.
8216    /// When set, the macro emits an empty `pub trait <name>: Sized {}`
8217    /// adjacent to the model so users can write
8218    /// `impl FooManagerExt for QuerySet<Foo> { fn published(self) -> Self ... }`
8219    /// and discover the convention from the model definition.
8220    manager_ext: Option<syn::Ident>,
8221    /// Extra QuerySet accessor names from
8222    /// `#[rustango(manager_fn = "active")]`. Issue #289 / T2.6.
8223    /// Each value adds a `pub fn <name>() -> QuerySet<Self>` next to
8224    /// the default `Self::objects()`. Multiple attributes allowed.
8225    manager_fns: Vec<syn::Ident>,
8226    /// Default ordering declared via `#[rustango(default_order =
8227    /// "-created_at, status")]`. Issue #291 / T2.5. Each entry is
8228    /// `(column_name, desc_flag, span_for_error_reporting)` — the
8229    /// `-` prefix means descending; the `+` prefix or no prefix means
8230    /// ascending.
8231    default_order: Vec<(String, bool, proc_macro2::Span)>,
8232    /// `true` when `#[rustango(view)]` is present. Issue #293 / T2.10.
8233    /// Routes the emitted schema's `is_view = true` so the migration
8234    /// snapshot skips this model (its underlying SQL view is operator-
8235    /// managed, not rustango-managed).
8236    is_view: bool,
8237    /// `#[rustango(managed = false)]` — who owns the table.
8238    /// Issue #321. Defaults to `true`; when explicitly set to `false`,
8239    /// the migration snapshot skips this model so `makemigrations` /
8240    /// `migrate` never emit `CREATE TABLE` / `ALTER TABLE` / `DROP
8241    /// TABLE` against it (operator-managed schema).
8242    managed: bool,
8243    /// Name of the model's base manager, from
8244    /// `#[rustango(base_manager_name = "...")]`. Threaded into
8245    /// `ModelSchema::base_manager_name`. Declarative-only today.
8246    base_manager_name: Option<String>,
8247    /// `#[rustango(order_with_respect_to = "...")]`. Names the FK
8248    /// field this model's instances are ordered relative to.
8249    /// Declarative-only today; threaded onto
8250    /// `ModelSchema::order_with_respect_to`.
8251    order_with_respect_to: Option<String>,
8252    /// `#[rustango(proxy)]` / `#[rustango(proxy = true)]`.
8253    /// Marks the model as a proxy that
8254    /// shares its DB table with another struct. Threaded into
8255    /// `ModelSchema::proxy` so future codegen can skip table-owning
8256    /// behavior for proxies.
8257    proxy: bool,
8258    /// `#[rustango(required_db_features = "json_extract,window_functions")]`.
8259    /// Each comma-separated capability token surfaces on
8260    /// `ModelSchema::required_db_features` so `manage check --deploy`
8261    /// can warn when the active dialect lacks one.
8262    required_db_features: Vec<String>,
8263    /// `#[rustango(required_db_vendor = "postgres|mysql|sqlite")]`.
8264    /// Normalized to the dialect name `manage check --deploy`
8265    /// compares against `Settings.database.backend`. Aliases
8266    /// (`postgresql` / `pg` / `mariadb` / `sqlite3`) accepted but
8267    /// stored under the canonical name.
8268    required_db_vendor: Option<String>,
8269    /// `#[rustango(default_related_name = "...")]`. Threaded into
8270    /// `ModelSchema::default_related_name`. Reverse-relation accessor
8271    /// name to use when an FK / M2M field doesn't override it.
8272    /// Today rustango doesn't auto-emit reverse managers; the
8273    /// metadata is the foundation for that work.
8274    default_related_name: Option<String>,
8275    /// `#[rustango(db_table_comment = "...")]`. Threaded into
8276    /// `ModelSchema::db_table_comment` so the DDL writer attaches the
8277    /// comment to the underlying table (PG: `COMMENT ON TABLE`, MySQL:
8278    /// inline `COMMENT='...'`, SQLite: no-op).
8279    db_table_comment: Option<String>,
8280    /// `#[rustango(get_latest_by = "created_at")]` /
8281    /// `#[rustango(get_latest_by = "-priority")]`. Parsed into
8282    /// `(column, descending)` where `descending = true` when the
8283    /// attribute value starts with `-`. Threaded into
8284    /// `ModelSchema::get_latest_by`.
8285    get_latest_by: Option<(String, bool)>,
8286    /// Extra `(codename, label)` permissions
8287    /// from `#[rustango(extra_permissions = "approve:Can approve,
8288    /// archive:Can archive")]`. Comma-separated `codename:label`
8289    /// pairs. Threaded into `ModelSchema::extra_permissions`.
8290    extra_permissions: Vec<(String, String)>,
8291    /// Which CRUD codenames (`"add"` / `"change"` / `"delete"` /
8292    /// `"view"`) the framework
8293    /// auto-creates. Empty `Vec` (default) means **all four**. Set via
8294    /// `#[rustango(default_permissions = "view,change")]` to opt out.
8295    /// Validated at parse time; unknown actions fail with a span-pointing
8296    /// error.
8297    default_permissions: Vec<String>,
8298    /// `#[rustango(verbose_name = "blog post")]` — the
8299    /// human-readable singular label for the model. Threaded into
8300    /// `ModelSchema::verbose_name` so admin section headers /
8301    /// breadcrumbs / "Add X" buttons can prefer the friendly caption
8302    /// over the Rust struct identifier.
8303    verbose_name: Option<String>,
8304    /// `#[rustango(verbose_name_plural = "blog posts")]` — explicit
8305    /// plural form. Threaded into `ModelSchema::verbose_name_plural`.
8306    /// When unset, `display_label_plural()` auto-suffixes `s`.
8307    verbose_name_plural: Option<String>,
8308    /// Eloquent-shape **global scopes** from `#[rustango(global_scope(name
8309    /// = "...", apply = path::to::fn))]` — issue #820. Each entry pairs
8310    /// a name (used by `QuerySet::without_global_scope`) with a
8311    /// `fn() -> WhereExpr` path that the macro emits into
8312    /// `ModelSchema::global_scopes`. Multiple attributes accumulate.
8313    global_scopes: Vec<GlobalScopeAttr>,
8314    /// Eloquent `hasManyThrough` / `hasOneThrough` declarations from
8315    /// `#[rustango(through(name, far, far_fk_column, intermediate,
8316    /// intermediate_fk_column, intermediate_pk_column))]` — issue
8317    /// [#817](https://github.com/ujeenet/rustango/issues/817). Each
8318    /// entry emits an inherent `<name>_through(&self)` accessor that
8319    /// returns a `QuerySet<Far>` filtered via a correlated subquery
8320    /// (`WHERE far_fk_column IN (SELECT intermediate_pk_column FROM
8321    /// intermediate WHERE intermediate_fk_column = <my_pk>)`).
8322    through_relations: Vec<ThroughAttr>,
8323    /// Eloquent `whereHas` / `whereDoesntHave` declarations from
8324    /// `#[rustango(reverse_has(name, child, child_fk_column))]` —
8325    /// issue [#830](https://github.com/ujeenet/rustango/issues/830).
8326    /// Each entry emits two associated functions on the parent —
8327    /// `<name>_exists_expr()` and `<name>_not_exists_expr()` —
8328    /// returning a `WhereExpr::Exists` / `WhereExpr::NotExists`
8329    /// over a correlated subquery against the child table. Users
8330    /// drop the result into `QuerySet::where_raw(...)`.
8331    reverse_has_relations: Vec<ReverseHasAttr>,
8332    /// `#[rustango(generic_has(...))]` reverse generic-FK declarations —
8333    /// issue #830. Each emits a `Model::generic_reverse_relations()`
8334    /// entry so the relation-existence family resolves polymorphic
8335    /// children by name.
8336    generic_has_relations: Vec<GenericHasAttr>,
8337}
8338
8339/// Parsed `#[rustango(global_scope(name = "...", apply = fn_path))]`
8340/// declaration. Each entry becomes one `core::GlobalScope` in the
8341/// emitted schema literal; `apply` resolves at macro-expand time
8342/// against the consumer's scope so the function must be in scope at
8343/// the use site. Issue #820.
8344struct GlobalScopeAttr {
8345    name: String,
8346    apply: syn::Path,
8347}
8348
8349/// Parsed `#[rustango(through(...))]` declaration. Issue
8350/// [#817](https://github.com/ujeenet/rustango/issues/817) — Eloquent
8351/// `hasManyThrough` / `hasOneThrough` parity.
8352///
8353/// `Country hasManyThrough Post via User` declares as:
8354///
8355/// ```ignore
8356/// #[rustango(through(
8357///     name                   = "posts",
8358///     far                    = "Post",
8359///     far_fk_column          = "author_id",
8360///     intermediate           = "User",
8361///     intermediate_fk_column = "country_id",
8362/// ))]
8363/// struct Country { ... }
8364/// ```
8365///
8366/// The macro emits `Country::posts_through(&self) -> QuerySet<Post>`
8367/// which returns a queryset filtered via a correlated subquery —
8368/// `Post WHERE author_id IN (SELECT id FROM tr_user WHERE country_id
8369/// = <my_pk>)`. The returned `QuerySet<Post>` is **chainable**:
8370/// `.filter()` / `.order_by()` / `.limit()` etc. compose normally
8371/// because the subquery lives inside a `WhereExpr::InSubquery` node
8372/// and the outer queryset's pending list stays empty.
8373///
8374/// All four required arguments use **SQL column / table names**
8375/// (not Rust field names) to sidestep the multi-hop-filter substrate
8376/// gap. Once that substrate lands, a higher-level Rust-field-name
8377/// shorthand can be added without breaking this surface.
8378struct ThroughAttr {
8379    /// Accessor method name. `name = "posts"` → emits `posts_through()`.
8380    name: String,
8381    /// Far model type identifier. `far = "Post"` → returns
8382    /// `QuerySet<Post>`. Resolved verbatim against the scope where
8383    /// the derive expands.
8384    far: syn::Ident,
8385    /// SQL column on the far model's table that references the
8386    /// intermediate model's primary key. For `Post`'s
8387    /// `author: ForeignKey<User>` the column is `"author_id"` (rustango's
8388    /// default `<field>_id` convention) or whatever the user
8389    /// declared via `#[rustango(db_column = "...")]`.
8390    far_fk_column: String,
8391    /// Intermediate model type identifier. Needed to look up its
8392    /// `SCHEMA` so the subquery's `FROM` clause points at the
8393    /// intermediate table. `intermediate = "User"`.
8394    intermediate: syn::Ident,
8395    /// SQL column on the intermediate's table that references the
8396    /// source (this) model's primary key. For `User`'s
8397    /// `country: ForeignKey<Country>` the column is `"country_id"`.
8398    intermediate_fk_column: String,
8399    /// SQL primary-key column on the intermediate's table — the
8400    /// column the subquery projects. Optional; defaults to `"id"`
8401    /// (rustango's default PK column name). Override when the
8402    /// intermediate declares a custom PK column.
8403    intermediate_pk_column: String,
8404}
8405
8406/// Parsed `#[rustango(reverse_has(name = "...", child = "...",
8407/// child_fk_column = "..."))]` declaration. Issue
8408/// [#830](https://github.com/ujeenet/rustango/issues/830) — Eloquent
8409/// `whereHas` / `whereDoesntHave` parity.
8410///
8411/// `Post hasMany Comment` declares as:
8412///
8413/// ```ignore
8414/// #[rustango(reverse_has(
8415///     name             = "comments",
8416///     child            = "Comment",
8417///     child_fk_column  = "post_id",
8418/// ))]
8419/// struct Post { ... }
8420/// ```
8421///
8422/// The macro emits two associated functions on `Post`:
8423///
8424/// - `Post::comments_exists_expr() -> WhereExpr` — yields
8425///   `EXISTS (SELECT … FROM comment WHERE comment.post_id =
8426///   <outer>.<self_pk_column>)`.
8427/// - `Post::comments_not_exists_expr() -> WhereExpr` — same shape
8428///   but `NOT EXISTS`, the `whereDoesntHave` analog.
8429///
8430/// User code:
8431///
8432/// ```ignore
8433/// // Posts with at least one comment:
8434/// Post::objects().where_raw(Post::comments_exists_expr()).fetch(&pool)
8435/// // Posts with no comments:
8436/// Post::objects().where_raw(Post::comments_not_exists_expr()).fetch(&pool)
8437/// ```
8438///
8439/// As with #817, all column / table identifiers are **SQL names**
8440/// (not Rust field names) so the substrate is independent of the
8441/// outstanding multi-hop filter resolver gap. The emitted
8442/// `Expr::OuterRef("…")` resolves to the outer queryset's table at
8443/// SQL-emit time via the writer's scope stack.
8444struct ReverseHasAttr {
8445    /// Accessor name. `name = "comments"` → emits
8446    /// `comments_exists_expr()` + `comments_not_exists_expr()`.
8447    name: String,
8448    /// Child model type identifier. `child = "Comment"` — needed to
8449    /// look up the child's `SCHEMA` so the subquery's `FROM` clause
8450    /// points at the child table.
8451    child: syn::Ident,
8452    /// SQL column on the child's table that references this model's
8453    /// primary key. For `Comment`'s `post: ForeignKey<Post>` the
8454    /// column is `"post_id"`.
8455    child_fk_column: String,
8456    /// SQL primary-key column on **this** model's table — the column
8457    /// the `OuterRef` resolves to. Optional; defaults to `"id"`
8458    /// (rustango's default PK column name).
8459    self_pk_column: String,
8460}
8461
8462/// Parsed `#[rustango(generic_has(name, child, ct_column, pk_column
8463/// [, self_pk_column]))]` — the reverse generic-FK (GFK) arm of the
8464/// relation-existence family (issue #830). The child is a polymorphic,
8465/// content-type-discriminated model; emits a `Model::
8466/// generic_reverse_relations()` entry the queryset resolves by name.
8467struct GenericHasAttr {
8468    /// Accessor name, e.g. `name = "tags"`.
8469    name: String,
8470    /// Child model type identifier (`child = "Tag"`) — looked up for its
8471    /// `SCHEMA` so the subquery's `FROM` points at the child table.
8472    child: syn::Ident,
8473    /// Column on the child table holding the parent's content-type id.
8474    /// Optional; defaults to `"content_type_id"`.
8475    ct_column: String,
8476    /// Column on the child table holding the parent's PK value.
8477    /// Optional; defaults to `"object_pk"`.
8478    pk_column: String,
8479    /// SQL primary-key column on **this** (parent) model's table.
8480    /// Optional; defaults to `"id"`.
8481    self_pk_column: String,
8482}
8483
8484/// Parsed form of one index declaration (field-level or container-level).
8485struct IndexAttr {
8486    /// Index name; auto-derived when `None` at parse time.
8487    name: Option<String>,
8488    /// Column names in the index.
8489    columns: Vec<String>,
8490    /// `true` for `CREATE UNIQUE INDEX`.
8491    unique: bool,
8492    /// Access method token (`"btree"`, `"gin"`, `"gist"`, `"brin"`,
8493    /// `"spgist"`, `"hash"`, `"bloom"`). Issue #34. Defaults to
8494    /// `"btree"` when the attribute is absent — the DDL writer omits
8495    /// the `USING` clause and the backend uses its own default
8496    /// (btree on every supported dialect).
8497    method: String,
8498    /// Optional `WHERE <expr>` clause for partial indexes. Issue #265 /
8499    /// T1.3. Set via `#[rustango(unique_when(columns = "...",
8500    /// condition = "...", name = "..."))]`. `None` for plain indexes.
8501    where_clause: Option<String>,
8502    /// Covering-index columns (PG 11+ `INCLUDE (...)` clause).
8503    /// Empty `Vec` (the default) means "no covering columns".
8504    include: Vec<String>,
8505}
8506
8507/// Parsed form of one `#[rustango(check(name = "…", expr = "…"))]` declaration.
8508struct CheckAttr {
8509    name: String,
8510    expr: String,
8511}
8512
8513/// Parsed form of one `#[rustango(exclude(name = "…", using = "gist",
8514/// elements = "col WITH op, col WITH op", where = "…"))]` declaration.
8515/// PG-only — surfaced on every backend in the macro emit; the migration
8516/// writer skips the op on MySQL/SQLite. Issue #319.
8517struct ExcludeAttr {
8518    /// Constraint name (free-form Rust identifier).
8519    name: String,
8520    /// Index method — `"gist"` (default), `"btree_gist"`, `"spgist"`.
8521    using: String,
8522    /// Comma-separated `(column, operator)` pairs, in declaration
8523    /// order. Parsed from `"col WITH op, col WITH op"`.
8524    elements: Vec<(String, String)>,
8525    /// Optional `WHERE` predicate (raw SQL).
8526    where_clause: Option<String>,
8527}
8528
8529/// Parsed form of one `#[rustango(fk_composite(name = "audit_target",
8530/// to = "rustango_audit_log", on = ("entity_table", "entity_pk"),
8531/// from = ("table_name", "row_pk")))]` declaration. Sub-slice F.2 of
8532/// the v0.15.0 ContentType plan — multi-column foreign keys live on
8533/// the model, not the field.
8534struct CompositeFkAttr {
8535    /// Logical relation name (free-form Rust identifier).
8536    name: String,
8537    /// SQL table name of the target.
8538    to: String,
8539    /// Source-side column names, in declaration order.
8540    from: Vec<String>,
8541    /// Target-side column names, same length / order as `from`.
8542    on: Vec<String>,
8543}
8544
8545/// Parsed form of one `#[rustango(generic_fk(name = "target",
8546/// ct_column = "content_type_id", pk_column = "object_pk"))]`
8547/// declaration. Sub-slice F.4 of the v0.15.0 ContentType plan —
8548/// generic ("any model") FKs live on the model, not the field.
8549struct GenericFkAttr {
8550    /// Logical relation name (free-form Rust identifier).
8551    name: String,
8552    /// Source-side column carrying the `content_type_id` value.
8553    ct_column: String,
8554    /// Source-side column carrying the target row's primary key.
8555    pk_column: String,
8556}
8557
8558/// Parsed form of one `#[rustango(m2m(...))]` declaration.
8559struct M2MAttr {
8560    /// Accessor suffix: `tags` → generates `tags_m2m()`.
8561    name: String,
8562    /// Target table (e.g. `"app_tags"`).
8563    to: String,
8564    /// Junction table (e.g. `"post_tags"`).
8565    through: String,
8566    /// Source FK column in the junction table (e.g. `"post_id"`).
8567    src: String,
8568    /// Destination FK column in the junction table (e.g. `"tag_id"`).
8569    dst: String,
8570    /// Whether the migration writer should auto-create the junction
8571    /// table. Default `true`. Set `auto_create = false` (#324) when
8572    /// the operator declares the through table as its own
8573    /// `#[derive(Model)]` struct with extra columns.
8574    auto_create: bool,
8575}
8576
8577/// Parsed form of one `#[rustango(generic_m2m(...))]` declaration —
8578/// polymorphic many-to-many (Eloquent `morphToMany`, issue #818). The
8579/// junction carries a ContentType discriminator so unrelated models
8580/// share one pivot + related set.
8581struct GenericM2MAttr {
8582    /// Accessor suffix: `tags` → generates `tags_m2m()`.
8583    name: String,
8584    /// Polymorphic junction table (e.g. `"taggables"`).
8585    through: String,
8586    /// Junction column holding the owning instance PK (e.g. `"taggable_id"`).
8587    pk_column: String,
8588    /// Junction column holding the owning model's `content_type_id`
8589    /// discriminator (e.g. `"taggable_type"`).
8590    ct_column: String,
8591    /// Junction column holding the related model PK (e.g. `"tag_id"`).
8592    related_column: String,
8593}
8594
8595/// Parsed shape of `#[rustango(audit(track = "name, body", source =
8596/// "user"))]`. `track` is a comma-separated list of field names whose
8597/// before/after values land in the JSONB `changes` column. `source`
8598/// is informational only — it pins a default source when the model
8599/// is written outside any `audit::with_source(...)` scope (rare).
8600#[derive(Default)]
8601struct AuditAttrs {
8602    /// Field names to capture in the `changes` JSONB. Validated
8603    /// against declared scalar fields at compile time. Empty means
8604    /// "track every scalar field".
8605    track: Option<(Vec<String>, proc_macro2::Span)>,
8606}
8607
8608/// Parsed shape of `#[rustango(admin(list_display = "…", search_fields =
8609/// "…", list_per_page = N, ordering = "…"))]`. Field-name lists are
8610/// comma-separated strings; we validate each ident against the model's
8611/// declared fields at compile time.
8612#[derive(Default)]
8613struct AdminAttrs {
8614    list_display: Option<(Vec<String>, proc_macro2::Span)>,
8615    search_fields: Option<(Vec<String>, proc_macro2::Span)>,
8616    list_per_page: Option<usize>,
8617    ordering: Option<(Vec<(String, bool)>, proc_macro2::Span)>,
8618    readonly_fields: Option<(Vec<String>, proc_macro2::Span)>,
8619    list_filter: Option<(Vec<String>, proc_macro2::Span)>,
8620    /// Bulk action names. No field-validation against model fields —
8621    /// these are action handlers, not column references.
8622    actions: Option<(Vec<String>, proc_macro2::Span)>,
8623    /// Form fieldsets — `Vec<(title, [field_names])>`. Pipe-separated
8624    /// sections, comma-separated fields per section, optional
8625    /// `Title:` prefix. Empty title omits the `<legend>`.
8626    fieldsets: Option<(Vec<(String, Vec<String>)>, proc_macro2::Span)>,
8627    /// `admin(list_display_links = "title")`. Names
8628    /// from `list_display` whose cells should link to detail/edit.
8629    /// Issue #350.
8630    list_display_links: Option<(Vec<String>, proc_macro2::Span)>,
8631    /// `admin(search_help_text = "...")`. Short
8632    /// caption rendered beside the admin list view's search box.
8633    /// Issue #353.
8634    search_help_text: Option<String>,
8635    /// `admin(actions_on_top = false)`. Hides the
8636    /// action-bar above the table. Default `true`. Issue #354.
8637    actions_on_top: Option<bool>,
8638    /// `admin(actions_on_bottom = true)`. Renders an
8639    /// additional action-bar below the table. Default `false`.
8640    /// Issue #354.
8641    actions_on_bottom: Option<bool>,
8642    /// `admin(date_hierarchy = "created_at")`. Name of
8643    /// a date / datetime field whose values render as a clickable
8644    /// year / month / day drill-down strip above the list table.
8645    /// Empty / unset disables the strip. Issue #355.
8646    date_hierarchy: Option<String>,
8647    /// `admin(prepopulated_fields = "slug:title")`.
8648    /// Each entry is `target:source[+source2]`; multiple entries are
8649    /// comma-separated, e.g. `"slug:title,short_code:section+title"`.
8650    /// The admin change-form emits JS that slugifies the source values
8651    /// into the target field on every keystroke. Issue #356.
8652    prepopulated_fields: Option<(Vec<(String, Vec<String>)>, proc_macro2::Span)>,
8653    /// `admin(raw_id_fields = "parent, owner")`. Names
8654    /// of FK fields whose change-form widget renders a lookup link
8655    /// next to the input. Issue #357.
8656    raw_id_fields: Option<(Vec<String>, proc_macro2::Span)>,
8657    /// `admin(autocomplete_fields = "author_id")`.
8658    /// Names of FK fields whose change-form widget renders an
8659    /// Ajax-driven typeahead populated from a `__autocomplete`
8660    /// endpoint on the target model. Issue #358.
8661    autocomplete_fields: Option<(Vec<String>, proc_macro2::Span)>,
8662    /// `admin(list_select_related = "all" | "none" | "author, …")`
8663    /// — tunes the admin list view's FK auto-JOIN
8664    /// policy. Default `"all"` matches rustango's join-everything
8665    /// behavior; `"none"` opts out; CSV restricts. Issue #352.
8666    list_select_related: Option<String>,
8667    /// `admin(formfield_overrides = "field:widget, field2:widget2")`.
8668    /// Each entry is `field_name:widget_name`; multiple
8669    /// entries comma-separated. Empty / unset → no overrides. The
8670    /// list of widget names supported is documented on
8671    /// `AdminConfig::formfield_overrides`. Issue #359.
8672    formfield_overrides: Option<(Vec<(String, String)>, proc_macro2::Span)>,
8673}
8674
8675fn parse_container_attrs(input: &DeriveInput) -> syn::Result<ContainerAttrs> {
8676    let mut out = ContainerAttrs {
8677        table: None,
8678        display: None,
8679        app: None,
8680        admin: None,
8681        audit: None,
8682        // Default `permissions = true` so every `#[derive(Model)]`
8683        // gets the four CRUD codenames seeded by `auto_create_permissions`
8684        // and is visible to non-superusers in the tenant admin without
8685        // manual per-model annotation. Models that intentionally don't
8686        // want permission rows (registry-internal types, framework
8687        // tables operators shouldn't manage directly) opt out via
8688        // `#[rustango(permissions = false)]`. v0.27.2 — fixes the
8689        // out-of-the-box admin invisibility regression (#62).
8690        permissions: true,
8691        m2m: Vec::new(),
8692        generic_m2m: Vec::new(),
8693        indexes: Vec::new(),
8694        checks: Vec::new(),
8695        excludes: Vec::new(),
8696        composite_fks: Vec::new(),
8697        generic_fks: Vec::new(),
8698        scope: None,
8699        manager_ext: None,
8700        manager_fns: Vec::new(),
8701        default_order: Vec::new(),
8702        is_view: false,
8703        managed: true,
8704        verbose_name: None,
8705        verbose_name_plural: None,
8706        base_manager_name: None,
8707        order_with_respect_to: None,
8708        proxy: false,
8709        required_db_features: Vec::new(),
8710        required_db_vendor: None,
8711        default_related_name: None,
8712        db_table_comment: None,
8713        get_latest_by: None,
8714        extra_permissions: Vec::new(),
8715        default_permissions: Vec::new(),
8716        global_scopes: Vec::new(),
8717        through_relations: Vec::new(),
8718        reverse_has_relations: Vec::new(),
8719        generic_has_relations: Vec::new(),
8720    };
8721    for attr in &input.attrs {
8722        if !attr.path().is_ident("rustango") {
8723            continue;
8724        }
8725        attr.parse_nested_meta(|meta| {
8726            if meta.path.is_ident("table") {
8727                let s: LitStr = meta.value()?.parse()?;
8728                let name = s.value();
8729                // v0.27.3 (#65) — macro-time guard against table names
8730                // that compile but break SQL downstream. Hyphens are
8731                // the common footgun: PostgreSQL accepts a quoted
8732                // `"intermediate-region"` in CREATE TABLE, but the
8733                // FK / index name derivation in `migrate::ddl`
8734                // emits `intermediate-region_field_fkey` unquoted,
8735                // which then fails the SQL parser. Same shape rule
8736                // as Postgres regular identifiers so the safe path
8737                // is the only path.
8738                validate_table_name(&name, s.span())?;
8739                out.table = Some(name);
8740                return Ok(());
8741            }
8742            if meta.path.is_ident("display") {
8743                let s: LitStr = meta.value()?.parse()?;
8744                out.display = Some((s.value(), s.span()));
8745                return Ok(());
8746            }
8747            if meta.path.is_ident("app") {
8748                let s: LitStr = meta.value()?.parse()?;
8749                out.app = Some(s.value());
8750                return Ok(());
8751            }
8752            if meta.path.is_ident("scope") {
8753                let s: LitStr = meta.value()?.parse()?;
8754                let val = s.value();
8755                if !matches!(val.to_ascii_lowercase().as_str(), "registry" | "tenant") {
8756                    return Err(meta.error(format!(
8757                        "`scope` must be \"registry\" or \"tenant\", got {val:?}"
8758                    )));
8759                }
8760                out.scope = Some(val);
8761                return Ok(());
8762            }
8763            if meta.path.is_ident("admin") {
8764                let mut admin = AdminAttrs::default();
8765                meta.parse_nested_meta(|inner| {
8766                    if inner.path.is_ident("list_display") {
8767                        let s: LitStr = inner.value()?.parse()?;
8768                        admin.list_display =
8769                            Some((split_field_list(&s.value()), s.span()));
8770                        return Ok(());
8771                    }
8772                    if inner.path.is_ident("search_fields") {
8773                        let s: LitStr = inner.value()?.parse()?;
8774                        admin.search_fields =
8775                            Some((split_field_list(&s.value()), s.span()));
8776                        return Ok(());
8777                    }
8778                    if inner.path.is_ident("readonly_fields") {
8779                        let s: LitStr = inner.value()?.parse()?;
8780                        admin.readonly_fields =
8781                            Some((split_field_list(&s.value()), s.span()));
8782                        return Ok(());
8783                    }
8784                    if inner.path.is_ident("list_per_page") {
8785                        let lit: syn::LitInt = inner.value()?.parse()?;
8786                        admin.list_per_page = Some(lit.base10_parse::<usize>()?);
8787                        return Ok(());
8788                    }
8789                    if inner.path.is_ident("ordering") {
8790                        let s: LitStr = inner.value()?.parse()?;
8791                        admin.ordering = Some((
8792                            parse_ordering_list(&s.value()),
8793                            s.span(),
8794                        ));
8795                        return Ok(());
8796                    }
8797                    if inner.path.is_ident("list_filter") {
8798                        let s: LitStr = inner.value()?.parse()?;
8799                        admin.list_filter =
8800                            Some((split_field_list(&s.value()), s.span()));
8801                        return Ok(());
8802                    }
8803                    if inner.path.is_ident("actions") {
8804                        let s: LitStr = inner.value()?.parse()?;
8805                        admin.actions =
8806                            Some((split_field_list(&s.value()), s.span()));
8807                        return Ok(());
8808                    }
8809                    if inner.path.is_ident("fieldsets") {
8810                        let s: LitStr = inner.value()?.parse()?;
8811                        admin.fieldsets =
8812                            Some((parse_fieldset_list(&s.value()), s.span()));
8813                        return Ok(());
8814                    }
8815                    if inner.path.is_ident("list_display_links") {
8816                        let s: LitStr = inner.value()?.parse()?;
8817                        admin.list_display_links =
8818                            Some((split_field_list(&s.value()), s.span()));
8819                        return Ok(());
8820                    }
8821                    if inner.path.is_ident("search_help_text") {
8822                        let s: LitStr = inner.value()?.parse()?;
8823                        admin.search_help_text = Some(s.value());
8824                        return Ok(());
8825                    }
8826                    if inner.path.is_ident("actions_on_top") {
8827                        let lit: syn::LitBool = inner.value()?.parse()?;
8828                        admin.actions_on_top = Some(lit.value);
8829                        return Ok(());
8830                    }
8831                    if inner.path.is_ident("actions_on_bottom") {
8832                        let lit: syn::LitBool = inner.value()?.parse()?;
8833                        admin.actions_on_bottom = Some(lit.value);
8834                        return Ok(());
8835                    }
8836                    if inner.path.is_ident("date_hierarchy") {
8837                        let s: LitStr = inner.value()?.parse()?;
8838                        admin.date_hierarchy = Some(s.value());
8839                        return Ok(());
8840                    }
8841                    if inner.path.is_ident("prepopulated_fields") {
8842                        let s: LitStr = inner.value()?.parse()?;
8843                        admin.prepopulated_fields =
8844                            Some((parse_prepopulated_list(&s.value()), s.span()));
8845                        return Ok(());
8846                    }
8847                    if inner.path.is_ident("raw_id_fields") {
8848                        let s: LitStr = inner.value()?.parse()?;
8849                        admin.raw_id_fields =
8850                            Some((split_field_list(&s.value()), s.span()));
8851                        return Ok(());
8852                    }
8853                    if inner.path.is_ident("autocomplete_fields") {
8854                        let s: LitStr = inner.value()?.parse()?;
8855                        admin.autocomplete_fields =
8856                            Some((split_field_list(&s.value()), s.span()));
8857                        return Ok(());
8858                    }
8859                    if inner.path.is_ident("list_select_related") {
8860                        let s: LitStr = inner.value()?.parse()?;
8861                        admin.list_select_related = Some(s.value());
8862                        return Ok(());
8863                    }
8864                    if inner.path.is_ident("formfield_overrides") {
8865                        let s: LitStr = inner.value()?.parse()?;
8866                        admin.formfield_overrides =
8867                            Some((parse_formfield_overrides(&s.value()), s.span()));
8868                        return Ok(());
8869                    }
8870                    Err(inner.error(
8871                        "unknown admin attribute (supported: \
8872                         `list_display`, `list_display_links`, \
8873                         `search_fields`, `search_help_text`, \
8874                         `readonly_fields`, \
8875                         `list_filter`, `list_per_page`, `ordering`, `actions`, \
8876                         `actions_on_top`, `actions_on_bottom`, \
8877                         `date_hierarchy`, \
8878                         `prepopulated_fields`, \
8879                         `raw_id_fields`, \
8880                         `autocomplete_fields`, \
8881                         `list_select_related`, \
8882                         `formfield_overrides`, \
8883                         `fieldsets`)",
8884                    ))
8885                })?;
8886                out.admin = Some(admin);
8887                return Ok(());
8888            }
8889            if meta.path.is_ident("manager") {
8890                // `#[rustango(manager(ext = "FooManagerExt"))]`. Issue #271 / T1.9.
8891                // Stretch `from_queryset = "..."` is left as a
8892                // follow-up — the issue's primary acceptance is the
8893                // `ext = ...` trait emission.
8894                meta.parse_nested_meta(|inner| {
8895                    if inner.path.is_ident("ext") {
8896                        let s: LitStr = inner.value()?.parse()?;
8897                        let name = s.value();
8898                        if name.is_empty() {
8899                            return Err(inner.error("manager(ext = \"...\") cannot be empty"));
8900                        }
8901                        out.manager_ext =
8902                            Some(syn::Ident::new(&name, s.span()));
8903                        return Ok(());
8904                    }
8905                    Err(inner.error(
8906                        "unknown manager attribute (supported: `ext = \"TraitName\"`)",
8907                    ))
8908                })?;
8909                return Ok(());
8910            }
8911            if meta.path.is_ident("manager_fn") {
8912                // `#[rustango(manager_fn = "active")]` — issue #289 / T2.6.
8913                // Adds a `pub fn <name>() -> QuerySet<Self>` accessor
8914                // next to the default `Self::objects()`. Multiple
8915                // attributes accumulate.
8916                let s: LitStr = meta.value()?.parse()?;
8917                let name = s.value();
8918                if name.is_empty() {
8919                    return Err(meta.error("`manager_fn = \"...\"` cannot be empty"));
8920                }
8921                if name == "objects" {
8922                    return Err(meta.error(
8923                        "`manager_fn = \"objects\"` collides with the default \
8924                         accessor — pick a different name",
8925                    ));
8926                }
8927                let ident = syn::Ident::new(&name, s.span());
8928                if out.manager_fns.iter().any(|prev| *prev == ident) {
8929                    return Err(meta.error(format!(
8930                        "duplicate `manager_fn = \"{name}\"`"
8931                    )));
8932                }
8933                out.manager_fns.push(ident);
8934                return Ok(());
8935            }
8936            if meta.path.is_ident("default_order") {
8937                // `#[rustango(default_order = "-created_at, status")]`
8938                // — issue #291 / T2.5. Comma-separated list; `-prefix`
8939                // means descending, `+prefix` or bare name means ascending.
8940                // Per-query opt-in via `QuerySet::with_default_order()`.
8941                let s: LitStr = meta.value()?.parse()?;
8942                let raw = s.value();
8943                let span = s.span();
8944                let mut parsed: Vec<(String, bool, proc_macro2::Span)> =
8945                    Vec::new();
8946                for entry in raw.split(',') {
8947                    let trimmed = entry.trim();
8948                    if trimmed.is_empty() {
8949                        return Err(syn::Error::new(
8950                            span,
8951                            "`default_order = \"...\"` has an empty entry — \
8952                             check for a stray comma",
8953                        ));
8954                    }
8955                    let (desc, name) = if let Some(rest) = trimmed.strip_prefix('-') {
8956                        (true, rest.trim().to_owned())
8957                    } else if let Some(rest) = trimmed.strip_prefix('+') {
8958                        (false, rest.trim().to_owned())
8959                    } else {
8960                        (false, trimmed.to_owned())
8961                    };
8962                    if name.is_empty() {
8963                        return Err(syn::Error::new(
8964                            span,
8965                            "`default_order` entry has no column name after the prefix",
8966                        ));
8967                    }
8968                    if parsed.iter().any(|(n, _, _)| *n == name) {
8969                        return Err(syn::Error::new(
8970                            span,
8971                            format!("duplicate column `{name}` in `default_order`"),
8972                        ));
8973                    }
8974                    parsed.push((name, desc, span));
8975                }
8976                if parsed.is_empty() {
8977                    return Err(syn::Error::new(
8978                        span,
8979                        "`default_order = \"...\"` cannot be empty",
8980                    ));
8981                }
8982                out.default_order = parsed;
8983                return Ok(());
8984            }
8985            if meta.path.is_ident("global_scope") {
8986                // `#[rustango(global_scope(name = "active", apply =
8987                //  path::to::fn))]` — issue #820. The apply function
8988                // path resolves at macro-expand time in the consumer's
8989                // scope; the macro re-emits it verbatim into the
8990                // `ModelSchema::global_scopes` slice literal.
8991                let span = meta.path.span();
8992                let mut scope_name: Option<String> = None;
8993                let mut apply_path: Option<syn::Path> = None;
8994                meta.parse_nested_meta(|inner| {
8995                    if inner.path.is_ident("name") {
8996                        let s: LitStr = inner.value()?.parse()?;
8997                        let raw = s.value();
8998                        if raw.trim().is_empty() {
8999                            return Err(syn::Error::new(
9000                                s.span(),
9001                                "`global_scope(name = \"...\")` must not be empty",
9002                            ));
9003                        }
9004                        scope_name = Some(raw);
9005                        return Ok(());
9006                    }
9007                    if inner.path.is_ident("apply") {
9008                        let p: syn::Path = inner.value()?.parse()?;
9009                        apply_path = Some(p);
9010                        return Ok(());
9011                    }
9012                    Err(inner.error(
9013                        "unknown `global_scope` attribute (supported: \
9014                         `name`, `apply`)",
9015                    ))
9016                })?;
9017                let Some(name) = scope_name else {
9018                    return Err(syn::Error::new(
9019                        span,
9020                        "`global_scope` requires `name = \"...\"`",
9021                    ));
9022                };
9023                let Some(apply) = apply_path else {
9024                    return Err(syn::Error::new(
9025                        span,
9026                        "`global_scope` requires `apply = fn_path`",
9027                    ));
9028                };
9029                if out.global_scopes.iter().any(|s| s.name == name) {
9030                    return Err(syn::Error::new(
9031                        span,
9032                        format!(
9033                            "duplicate global scope name `{name}` — \
9034                             pick a unique identifier so \
9035                             `QuerySet::without_global_scope(\"{name}\")` \
9036                             is unambiguous"
9037                        ),
9038                    ));
9039                }
9040                out.global_scopes.push(GlobalScopeAttr { name, apply });
9041                return Ok(());
9042            }
9043            if meta.path.is_ident("through") {
9044                // `#[rustango(through(name = "posts", far = "Post",
9045                //  far_fk_column = "author_id", intermediate = "User",
9046                //  intermediate_fk_column = "country_id"
9047                //  [, intermediate_pk_column = "id"]))]` — issue #817.
9048                let span = meta.path.span();
9049                let mut accessor_name: Option<String> = None;
9050                let mut far_ident: Option<syn::Ident> = None;
9051                let mut far_fk_column: Option<String> = None;
9052                let mut intermediate_ident: Option<syn::Ident> = None;
9053                let mut intermediate_fk_column: Option<String> = None;
9054                let mut intermediate_pk_column: Option<String> = None;
9055                fn parse_nonempty_string(
9056                    inner: &syn::meta::ParseNestedMeta<'_>,
9057                    field: &str,
9058                ) -> syn::Result<String> {
9059                    let s: LitStr = inner.value()?.parse()?;
9060                    let raw = s.value();
9061                    let trimmed = raw.trim();
9062                    if trimmed.is_empty() {
9063                        return Err(syn::Error::new(
9064                            s.span(),
9065                            format!("`through({field} = \"...\")` must not be empty"),
9066                        ));
9067                    }
9068                    Ok(trimmed.to_owned())
9069                }
9070                meta.parse_nested_meta(|inner| {
9071                    if inner.path.is_ident("name") {
9072                        accessor_name = Some(parse_nonempty_string(&inner, "name")?);
9073                        return Ok(());
9074                    }
9075                    if inner.path.is_ident("far") {
9076                        // Far model name accepted as a string literal
9077                        // so the attribute fits inside the existing
9078                        // `parse_nested_meta` shape; parsed back into a
9079                        // `syn::Ident` so the emitted accessor can
9080                        // reference the type directly.
9081                        let s: LitStr = inner.value()?.parse()?;
9082                        let raw = s.value();
9083                        let trimmed = raw.trim();
9084                        if trimmed.is_empty() {
9085                            return Err(syn::Error::new(
9086                                s.span(),
9087                                "`through(far = \"...\")` must not be empty",
9088                            ));
9089                        }
9090                        far_ident = Some(syn::Ident::new(trimmed, s.span()));
9091                        return Ok(());
9092                    }
9093                    if inner.path.is_ident("far_fk_column") {
9094                        far_fk_column =
9095                            Some(parse_nonempty_string(&inner, "far_fk_column")?);
9096                        return Ok(());
9097                    }
9098                    if inner.path.is_ident("intermediate") {
9099                        let s: LitStr = inner.value()?.parse()?;
9100                        let raw = s.value();
9101                        let trimmed = raw.trim();
9102                        if trimmed.is_empty() {
9103                            return Err(syn::Error::new(
9104                                s.span(),
9105                                "`through(intermediate = \"...\")` must not be empty",
9106                            ));
9107                        }
9108                        intermediate_ident = Some(syn::Ident::new(trimmed, s.span()));
9109                        return Ok(());
9110                    }
9111                    if inner.path.is_ident("intermediate_fk_column") {
9112                        intermediate_fk_column =
9113                            Some(parse_nonempty_string(&inner, "intermediate_fk_column")?);
9114                        return Ok(());
9115                    }
9116                    if inner.path.is_ident("intermediate_pk_column") {
9117                        intermediate_pk_column =
9118                            Some(parse_nonempty_string(&inner, "intermediate_pk_column")?);
9119                        return Ok(());
9120                    }
9121                    Err(inner.error(
9122                        "unknown `through` attribute (supported: \
9123                         `name`, `far`, `far_fk_column`, \
9124                         `intermediate`, `intermediate_fk_column`, \
9125                         `intermediate_pk_column`)",
9126                    ))
9127                })?;
9128                let Some(name) = accessor_name else {
9129                    return Err(syn::Error::new(
9130                        span,
9131                        "`through` requires `name = \"...\"`",
9132                    ));
9133                };
9134                let Some(far) = far_ident else {
9135                    return Err(syn::Error::new(
9136                        span,
9137                        "`through` requires `far = \"FarModelType\"`",
9138                    ));
9139                };
9140                let Some(far_fk_column) = far_fk_column else {
9141                    return Err(syn::Error::new(
9142                        span,
9143                        "`through` requires `far_fk_column = \"<column>\"`",
9144                    ));
9145                };
9146                let Some(intermediate) = intermediate_ident else {
9147                    return Err(syn::Error::new(
9148                        span,
9149                        "`through` requires `intermediate = \"IntermediateModelType\"`",
9150                    ));
9151                };
9152                let Some(intermediate_fk_column) = intermediate_fk_column else {
9153                    return Err(syn::Error::new(
9154                        span,
9155                        "`through` requires `intermediate_fk_column = \"<column>\"`",
9156                    ));
9157                };
9158                let intermediate_pk_column =
9159                    intermediate_pk_column.unwrap_or_else(|| "id".to_owned());
9160                if out.through_relations.iter().any(|t| t.name == name) {
9161                    return Err(syn::Error::new(
9162                        span,
9163                        format!(
9164                            "duplicate `through(name = \"{name}\")` — \
9165                             pick a unique accessor name"
9166                        ),
9167                    ));
9168                }
9169                out.through_relations.push(ThroughAttr {
9170                    name,
9171                    far,
9172                    far_fk_column,
9173                    intermediate,
9174                    intermediate_fk_column,
9175                    intermediate_pk_column,
9176                });
9177                return Ok(());
9178            }
9179            if meta.path.is_ident("reverse_has") {
9180                // `#[rustango(reverse_has(name = "comments",
9181                //  child = "Comment", child_fk_column = "post_id"
9182                //  [, self_pk_column = "id"]))]` — issue #830.
9183                let span = meta.path.span();
9184                let mut accessor_name: Option<String> = None;
9185                let mut child_ident: Option<syn::Ident> = None;
9186                let mut child_fk_column: Option<String> = None;
9187                let mut self_pk_column: Option<String> = None;
9188                meta.parse_nested_meta(|inner| {
9189                    if inner.path.is_ident("name") {
9190                        let s: LitStr = inner.value()?.parse()?;
9191                        let raw = s.value();
9192                        if raw.trim().is_empty() {
9193                            return Err(syn::Error::new(
9194                                s.span(),
9195                                "`reverse_has(name = \"...\")` must not be empty",
9196                            ));
9197                        }
9198                        accessor_name = Some(raw);
9199                        return Ok(());
9200                    }
9201                    if inner.path.is_ident("child") {
9202                        let s: LitStr = inner.value()?.parse()?;
9203                        let raw = s.value();
9204                        let trimmed = raw.trim();
9205                        if trimmed.is_empty() {
9206                            return Err(syn::Error::new(
9207                                s.span(),
9208                                "`reverse_has(child = \"...\")` must not be empty",
9209                            ));
9210                        }
9211                        child_ident = Some(syn::Ident::new(trimmed, s.span()));
9212                        return Ok(());
9213                    }
9214                    if inner.path.is_ident("child_fk_column") {
9215                        let s: LitStr = inner.value()?.parse()?;
9216                        let raw = s.value();
9217                        let trimmed = raw.trim();
9218                        if trimmed.is_empty() {
9219                            return Err(syn::Error::new(
9220                                s.span(),
9221                                "`reverse_has(child_fk_column = \"...\")` must not be empty",
9222                            ));
9223                        }
9224                        child_fk_column = Some(trimmed.to_owned());
9225                        return Ok(());
9226                    }
9227                    if inner.path.is_ident("self_pk_column") {
9228                        let s: LitStr = inner.value()?.parse()?;
9229                        let raw = s.value();
9230                        let trimmed = raw.trim();
9231                        if trimmed.is_empty() {
9232                            return Err(syn::Error::new(
9233                                s.span(),
9234                                "`reverse_has(self_pk_column = \"...\")` must not be empty",
9235                            ));
9236                        }
9237                        self_pk_column = Some(trimmed.to_owned());
9238                        return Ok(());
9239                    }
9240                    Err(inner.error(
9241                        "unknown `reverse_has` attribute (supported: \
9242                         `name`, `child`, `child_fk_column`, \
9243                         `self_pk_column`)",
9244                    ))
9245                })?;
9246                let Some(name) = accessor_name else {
9247                    return Err(syn::Error::new(
9248                        span,
9249                        "`reverse_has` requires `name = \"...\"`",
9250                    ));
9251                };
9252                let Some(child) = child_ident else {
9253                    return Err(syn::Error::new(
9254                        span,
9255                        "`reverse_has` requires `child = \"ChildModelType\"`",
9256                    ));
9257                };
9258                let Some(child_fk_column) = child_fk_column else {
9259                    return Err(syn::Error::new(
9260                        span,
9261                        "`reverse_has` requires `child_fk_column = \"<column>\"`",
9262                    ));
9263                };
9264                let self_pk_column = self_pk_column.unwrap_or_else(|| "id".to_owned());
9265                if out.reverse_has_relations.iter().any(|r| r.name == name) {
9266                    return Err(syn::Error::new(
9267                        span,
9268                        format!(
9269                            "duplicate `reverse_has(name = \"{name}\")` — \
9270                             pick a unique accessor name"
9271                        ),
9272                    ));
9273                }
9274                out.reverse_has_relations.push(ReverseHasAttr {
9275                    name,
9276                    child,
9277                    child_fk_column,
9278                    self_pk_column,
9279                });
9280                return Ok(());
9281            }
9282            if meta.path.is_ident("generic_has") {
9283                // `#[rustango(generic_has(name = "tags",
9284                //  child = "Tag", ct_column = "content_type_id",
9285                //  pk_column = "object_pk" [, self_pk_column = "id"]))]`
9286                //  — issue #830, the reverse generic-FK (GFK) arm of the
9287                //  relation-existence family.
9288                let span = meta.path.span();
9289                let mut accessor_name: Option<String> = None;
9290                let mut child_ident: Option<syn::Ident> = None;
9291                let mut ct_column: Option<String> = None;
9292                let mut pk_column: Option<String> = None;
9293                let mut self_pk_column: Option<String> = None;
9294                meta.parse_nested_meta(|inner| {
9295                    if inner.path.is_ident("name") {
9296                        let s: LitStr = inner.value()?.parse()?;
9297                        let raw = s.value();
9298                        if raw.trim().is_empty() {
9299                            return Err(syn::Error::new(
9300                                s.span(),
9301                                "`generic_has(name = \"...\")` must not be empty",
9302                            ));
9303                        }
9304                        accessor_name = Some(raw);
9305                        return Ok(());
9306                    }
9307                    if inner.path.is_ident("child") {
9308                        let s: LitStr = inner.value()?.parse()?;
9309                        let trimmed = s.value().trim().to_owned();
9310                        if trimmed.is_empty() {
9311                            return Err(syn::Error::new(
9312                                s.span(),
9313                                "`generic_has(child = \"...\")` must not be empty",
9314                            ));
9315                        }
9316                        child_ident = Some(syn::Ident::new(&trimmed, s.span()));
9317                        return Ok(());
9318                    }
9319                    if inner.path.is_ident("ct_column") {
9320                        let s: LitStr = inner.value()?.parse()?;
9321                        let trimmed = s.value().trim().to_owned();
9322                        if trimmed.is_empty() {
9323                            return Err(syn::Error::new(
9324                                s.span(),
9325                                "`generic_has(ct_column = \"...\")` must not be empty",
9326                            ));
9327                        }
9328                        ct_column = Some(trimmed);
9329                        return Ok(());
9330                    }
9331                    if inner.path.is_ident("pk_column") {
9332                        let s: LitStr = inner.value()?.parse()?;
9333                        let trimmed = s.value().trim().to_owned();
9334                        if trimmed.is_empty() {
9335                            return Err(syn::Error::new(
9336                                s.span(),
9337                                "`generic_has(pk_column = \"...\")` must not be empty",
9338                            ));
9339                        }
9340                        pk_column = Some(trimmed);
9341                        return Ok(());
9342                    }
9343                    if inner.path.is_ident("self_pk_column") {
9344                        let s: LitStr = inner.value()?.parse()?;
9345                        let trimmed = s.value().trim().to_owned();
9346                        if trimmed.is_empty() {
9347                            return Err(syn::Error::new(
9348                                s.span(),
9349                                "`generic_has(self_pk_column = \"...\")` must not be empty",
9350                            ));
9351                        }
9352                        self_pk_column = Some(trimmed);
9353                        return Ok(());
9354                    }
9355                    Err(inner.error(
9356                        "unknown `generic_has` attribute (supported: \
9357                         `name`, `child`, `ct_column`, `pk_column`, \
9358                         `self_pk_column`)",
9359                    ))
9360                })?;
9361                let Some(name) = accessor_name else {
9362                    return Err(syn::Error::new(
9363                        span,
9364                        "`generic_has` requires `name = \"...\"`",
9365                    ));
9366                };
9367                let Some(child) = child_ident else {
9368                    return Err(syn::Error::new(
9369                        span,
9370                        "`generic_has` requires `child = \"ChildModelType\"`",
9371                    ));
9372                };
9373                let ct_column = ct_column.unwrap_or_else(|| "content_type_id".to_owned());
9374                let pk_column = pk_column.unwrap_or_else(|| "object_pk".to_owned());
9375                let self_pk_column = self_pk_column.unwrap_or_else(|| "id".to_owned());
9376                if out.generic_has_relations.iter().any(|r| r.name == name) {
9377                    return Err(syn::Error::new(
9378                        span,
9379                        format!(
9380                            "duplicate `generic_has(name = \"{name}\")` — \
9381                             pick a unique accessor name"
9382                        ),
9383                    ));
9384                }
9385                out.generic_has_relations.push(GenericHasAttr {
9386                    name,
9387                    child,
9388                    ct_column,
9389                    pk_column,
9390                    self_pk_column,
9391                });
9392                return Ok(());
9393            }
9394            if meta.path.is_ident("audit") {
9395                let mut audit = AuditAttrs::default();
9396                meta.parse_nested_meta(|inner| {
9397                    if inner.path.is_ident("track") {
9398                        let s: LitStr = inner.value()?.parse()?;
9399                        audit.track =
9400                            Some((split_field_list(&s.value()), s.span()));
9401                        return Ok(());
9402                    }
9403                    Err(inner.error(
9404                        "unknown audit attribute (supported: `track`)",
9405                    ))
9406                })?;
9407                out.audit = Some(audit);
9408                return Ok(());
9409            }
9410            if meta.path.is_ident("permissions") {
9411                // Two forms accepted:
9412                //   #[rustango(permissions)]          — flag form, true
9413                //   #[rustango(permissions = false)]  — explicit opt-out
9414                //   #[rustango(permissions = true)]   — explicit opt-in
9415                if let Ok(v) = meta.value() {
9416                    let lit: syn::LitBool = v.parse()?;
9417                    out.permissions = lit.value;
9418                } else {
9419                    out.permissions = true;
9420                }
9421                return Ok(());
9422            }
9423            if meta.path.is_ident("view") {
9424                // Issue #293 / T2.10. Two forms accepted, matching
9425                // the `permissions` flag pattern:
9426                //   #[rustango(view)]          — flag form, true
9427                //   #[rustango(view = false)]  — explicit opt-out
9428                //   #[rustango(view = true)]   — explicit opt-in
9429                if let Ok(v) = meta.value() {
9430                    let lit: syn::LitBool = v.parse()?;
9431                    out.is_view = lit.value;
9432                } else {
9433                    out.is_view = true;
9434                }
9435                return Ok(());
9436            }
9437            if meta.path.is_ident("managed") {
9438                // Who owns the table. Issue #321.
9439                //   #[rustango(managed = false)]  — operator-managed table
9440                //   #[rustango(managed = true)]   — rustango-managed (the default)
9441                // Bare-flag form is intentionally not accepted: writing
9442                // `#[rustango(managed)]` reads as "yes please manage it"
9443                // which is already the default. The opt-out is the only
9444                // useful state, so it must be explicit.
9445                let v = meta.value()?;
9446                let lit: syn::LitBool = v.parse()?;
9447                out.managed = lit.value;
9448                return Ok(());
9449            }
9450            if meta.path.is_ident("verbose_name") {
9451                let s: LitStr = meta.value()?.parse()?;
9452                out.verbose_name = Some(s.value());
9453                return Ok(());
9454            }
9455            if meta.path.is_ident("verbose_name_plural") {
9456                let s: LitStr = meta.value()?.parse()?;
9457                out.verbose_name_plural = Some(s.value());
9458                return Ok(());
9459            }
9460            if meta.path.is_ident("db_table_comment") {
9461                // Free-form table-level comment attached to the DB
9462                // catalog.
9463                let s: LitStr = meta.value()?.parse()?;
9464                out.db_table_comment = Some(s.value());
9465                return Ok(());
9466            }
9467            if meta.path.is_ident("proxy") {
9468                // Declarative flag
9469                // marking the struct as a proxy of another model that
9470                // shares its DB table. Stored on `ModelSchema::proxy`
9471                // so future codegen can skip `CreateTable` emission
9472                // for proxies (parent owns the table) and route
9473                // per-instance method resolution to the proxy class.
9474                //
9475                // Accepts `proxy` (bare → true) and `proxy = true/false`.
9476                let value = if meta.input.peek(syn::Token![=]) {
9477                    meta.value()?.parse::<syn::LitBool>()?.value
9478                } else {
9479                    true
9480                };
9481                out.proxy = value;
9482                return Ok(());
9483            }
9484            if meta.path.is_ident("order_with_respect_to") {
9485                // `order_with_respect_to = "parent_fk"` — the model's
9486                // instances are intrinsically ordered relative to
9487                // their parent FK.
9488                //
9489                // rustango stores the FK field name on
9490                // `ModelSchema::order_with_respect_to`. Declarative-only
9491                // today: the migration writer + admin surfaces still
9492                // treat every model identically. Future codegen will
9493                // key off the metadata to auto-emit the `_order`
9494                // column and reorder helpers.
9495                //
9496                // Validated as a Rust-shape identifier so the macro
9497                // can reject typos at derive time.
9498                let s: LitStr = meta.value()?.parse()?;
9499                let raw = s.value();
9500                if raw.is_empty() {
9501                    return Err(syn::Error::new(
9502                        s.span(),
9503                        "`order_with_respect_to` must be a non-empty FK field name",
9504                    ));
9505                }
9506                let valid = raw
9507                    .chars()
9508                    .all(|c| c == '_' || c.is_ascii_alphanumeric())
9509                    && !raw.chars().next().is_some_and(|c| c.is_ascii_digit());
9510                if !valid {
9511                    return Err(syn::Error::new(
9512                        s.span(),
9513                        format!(
9514                            "`order_with_respect_to` must be a valid Rust \
9515                             identifier (letters / digits / underscores, \
9516                             not starting with a digit); got `{raw}`"
9517                        ),
9518                    ));
9519                }
9520                out.order_with_respect_to = Some(raw);
9521                return Ok(());
9522            }
9523            if meta.path.is_ident("required_db_features") {
9524                // Capability tokens the model needs (e.g.
9525                // `"json_extract"`, `"window_functions"`,
9526                // `"row_security"`). Comma-separated.
9527                // `manage check --deploy` walks every model and warns
9528                // when the active backend doesn't advertise the
9529                // capability.
9530                //
9531                // rustango ships a small registry of capability tokens
9532                // each dialect supports — see `Dialect::supports`.
9533                // Unknown tokens still parse (they end up on the
9534                // schema and show up in the warning) so projects can
9535                // declare aspirational capabilities and the check
9536                // verb will keep nagging until the dialect implements
9537                // them.
9538                let s: LitStr = meta.value()?.parse()?;
9539                let raw = s.value();
9540                let features: Vec<String> = raw
9541                    .split(',')
9542                    .map(str::trim)
9543                    .filter(|s| !s.is_empty())
9544                    .map(str::to_owned)
9545                    .collect();
9546                if features.is_empty() {
9547                    return Err(syn::Error::new(
9548                        s.span(),
9549                        "`required_db_features` must list at least one \
9550                         comma-separated capability token",
9551                    ));
9552                }
9553                out.required_db_features = features;
9554                return Ok(());
9555            }
9556            if meta.path.is_ident("required_db_vendor") {
9557                // The model is only meant to run against the named DB
9558                // backend. `manage check --deploy` flags a mismatch so
9559                // ops catches "I forgot to switch DATABASE_URL" at
9560                // deploy time rather than runtime.
9561                //
9562                // Restricted to the three backends rustango ships
9563                // dialects for so the check verb can compare reliably.
9564                let s: LitStr = meta.value()?.parse()?;
9565                let raw = s.value().to_ascii_lowercase();
9566                match raw.as_str() {
9567                    "postgresql" | "postgres" | "pg" => {
9568                        out.required_db_vendor = Some("postgres".to_owned());
9569                    }
9570                    "mysql" | "mariadb" => {
9571                        out.required_db_vendor = Some("mysql".to_owned());
9572                    }
9573                    "sqlite" | "sqlite3" => {
9574                        out.required_db_vendor = Some("sqlite".to_owned());
9575                    }
9576                    _ => {
9577                        return Err(syn::Error::new(
9578                            s.span(),
9579                            format!(
9580                                "unknown required_db_vendor `{raw}` — \
9581                                 expected `postgres` (aliases: `postgresql`, `pg`), \
9582                                 `mysql` (alias: `mariadb`), or `sqlite` \
9583                                 (alias: `sqlite3`)"
9584                            ),
9585                        ));
9586                    }
9587                }
9588                return Ok(());
9589            }
9590            if meta.path.is_ident("base_manager_name") {
9591                // Name of the manager that `<instance>.<relation>_set`
9592                // uses when resolving reverse-relation managers.
9593                // Distinct from `default_manager_name` (what
9594                // `Self::objects()` returns). Stored on
9595                // `ModelSchema::base_manager_name`.
9596                //
9597                // Validated as a Rust identifier so it stays safe to
9598                // re-emit as code in future reverse-manager codegen.
9599                let s: LitStr = meta.value()?.parse()?;
9600                let raw = s.value();
9601                if raw.is_empty() {
9602                    return Err(syn::Error::new(
9603                        s.span(),
9604                        "`base_manager_name` must be a non-empty string",
9605                    ));
9606                }
9607                let valid = raw
9608                    .chars()
9609                    .all(|c| c == '_' || c.is_ascii_alphanumeric())
9610                    && !raw.chars().next().is_some_and(|c| c.is_ascii_digit());
9611                if !valid {
9612                    return Err(syn::Error::new(
9613                        s.span(),
9614                        format!(
9615                            "`base_manager_name` must be a valid Rust \
9616                             identifier (letters / digits / underscores, \
9617                             not starting with a digit); got `{raw}`"
9618                        ),
9619                    ));
9620                }
9621                out.base_manager_name = Some(raw);
9622                return Ok(());
9623            }
9624            if meta.path.is_ident("default_related_name") {
9625                // The name reverse-relation accessors use when callers
9626                // don't override `related_name = "..."` on the FK / M2M
9627                // field. Stored on `ModelSchema::default_related_name`
9628                // so future reverse-manager codegen / schema emit /
9629                // admin templates can pick the right accessor name
9630                // (today rustango doesn't auto-emit reverse managers;
9631                // the metadata is the foundation for that work).
9632                //
9633                // Enforced non-empty + ASCII identifier-shape so the
9634                // string is safe to use as a Rust ident later.
9635                let s: LitStr = meta.value()?.parse()?;
9636                let raw = s.value();
9637                if raw.is_empty() {
9638                    return Err(syn::Error::new(
9639                        s.span(),
9640                        "`default_related_name` must be a non-empty string",
9641                    ));
9642                }
9643                let valid = raw
9644                    .chars()
9645                    .all(|c| c == '_' || c.is_ascii_lowercase() || c.is_ascii_digit())
9646                    && !raw.chars().next().is_some_and(|c| c.is_ascii_digit());
9647                if !valid {
9648                    return Err(syn::Error::new(
9649                        s.span(),
9650                        format!(
9651                            "`default_related_name` must be snake_case ASCII \
9652                             (lowercase letters / digits / underscores, not \
9653                             starting with a digit); got `{raw}`"
9654                        ),
9655                    ));
9656                }
9657                out.default_related_name = Some(raw);
9658                return Ok(());
9659            }
9660            if meta.path.is_ident("extra_permissions") {
9661                // Comma-separated `codename:label` pairs.
9662                let s: LitStr = meta.value()?.parse()?;
9663                let raw = s.value();
9664                let mut pairs = Vec::new();
9665                for entry in raw.split(',') {
9666                    let entry = entry.trim();
9667                    if entry.is_empty() {
9668                        continue;
9669                    }
9670                    let (codename, label) = match entry.split_once(':') {
9671                        Some((c, l)) => (c.trim().to_owned(), l.trim().to_owned()),
9672                        None => (entry.to_owned(), entry.to_owned()),
9673                    };
9674                    if codename.is_empty() {
9675                        return Err(meta.error(
9676                            "`extra_permissions` entries must be `codename:label` pairs",
9677                        ));
9678                    }
9679                    pairs.push((codename, label));
9680                }
9681                if pairs.is_empty() {
9682                    return Err(meta
9683                        .error("`extra_permissions = \"…\"` must list at least one pair"));
9684                }
9685                out.extra_permissions = pairs;
9686                return Ok(());
9687            }
9688            if meta.path.is_ident("default_permissions") {
9689                // Comma-separated subset of the CRUD action set.
9690                // Empty means all four (the framework default).
9691                let s: LitStr = meta.value()?.parse()?;
9692                let raw = s.value();
9693                let mut actions: Vec<String> = Vec::new();
9694                for entry in raw.split(',') {
9695                    let action = entry.trim().to_ascii_lowercase();
9696                    if action.is_empty() {
9697                        continue;
9698                    }
9699                    match action.as_str() {
9700                        "add" | "change" | "delete" | "view" => {}
9701                        other => {
9702                            return Err(syn::Error::new(
9703                                s.span(),
9704                                format!(
9705                                    "unknown default_permissions action `{other}` — \
9706                                     expected one of `add`, `change`, `delete`, `view`"
9707                                ),
9708                            ));
9709                        }
9710                    }
9711                    if !actions.contains(&action) {
9712                        actions.push(action);
9713                    }
9714                }
9715                if actions.is_empty() {
9716                    return Err(syn::Error::new(
9717                        s.span(),
9718                        "`default_permissions = \"…\"` must list at least one action; \
9719                         use `permissions = false` on the container if you want NO \
9720                         permissions seeded for this model.",
9721                    ));
9722                }
9723                out.default_permissions = actions;
9724                return Ok(());
9725            }
9726            if meta.path.is_ident("get_latest_by") {
9727                // The `-` prefix selects descending order.
9728                let s: LitStr = meta.value()?.parse()?;
9729                let raw = s.value();
9730                let trimmed = raw.trim();
9731                if trimmed.is_empty() {
9732                    return Err(meta.error("`get_latest_by` must name a column"));
9733                }
9734                let (col, desc) = if let Some(stripped) = trimmed.strip_prefix('-') {
9735                    (stripped.to_owned(), true)
9736                } else if let Some(stripped) = trimmed.strip_prefix('+') {
9737                    (stripped.to_owned(), false)
9738                } else {
9739                    (trimmed.to_owned(), false)
9740                };
9741                if col.is_empty() {
9742                    return Err(meta.error("`get_latest_by` must name a column"));
9743                }
9744                out.get_latest_by = Some((col, desc));
9745                return Ok(());
9746            }
9747            if meta.path.is_ident("unique_together") {
9748                // Composite UNIQUE index. Two syntaxes:
9749                //
9750                //   #[rustango(unique_together = "org_id, user_id")]                       — auto-derived name
9751                //   #[rustango(unique_together(columns = "org_id, user_id", name = "x"))]  — explicit name
9752                //
9753                // Both produce `CREATE UNIQUE INDEX <name> ON <table>
9754                // (col1, col2)`, where <name> defaults to
9755                // `<table>_<col1>_<col2>_uq` when not supplied.
9756                let (columns, name) = parse_together_attr(&meta, "unique_together")?;
9757                out.indexes.push(IndexAttr {
9758                    name,
9759                    columns,
9760                    unique: true,
9761                    method: "btree".to_owned(),
9762                    where_clause: None,
9763                include: Vec::new(),
9764                });
9765                return Ok(());
9766            }
9767            if meta.path.is_ident("index_together") {
9768                // Composite (non-unique) index. Two syntaxes
9769                // mirroring `unique_together`.
9770                //
9771                //   #[rustango(index_together = "created_at, status")]
9772                //   #[rustango(index_together(columns = "created_at, status", name = "x"))]
9773                let (columns, name) = parse_together_attr(&meta, "index_together")?;
9774                out.indexes.push(IndexAttr {
9775                    name,
9776                    columns,
9777                    unique: false,
9778                    method: "btree".to_owned(),
9779                    where_clause: None,
9780                include: Vec::new(),
9781                });
9782                return Ok(());
9783            }
9784            if meta.path.is_ident("unique_when") {
9785                // Partial unique index. Issue #265 / T1.3.
9786                //
9787                //   #[rustango(unique_when(
9788                //       columns   = "email",
9789                //       condition = "deleted_at IS NULL",
9790                //       name      = "unique_active_email"
9791                //   ))]
9792                //
9793                // → `CREATE UNIQUE INDEX <name> ON <table> (cols) WHERE <condition>`
9794                // on PG / SQLite (both ship partial indexes natively).
9795                // MySQL falls back to a plain UNIQUE index — the
9796                // condition is lost; document the limitation in the
9797                // generated migration.
9798                let mut columns: Option<Vec<String>> = None;
9799                let mut condition: Option<String> = None;
9800                let mut name: Option<String> = None;
9801                let mut include: Vec<String> = Vec::new();
9802                meta.parse_nested_meta(|inner| {
9803                    if inner.path.is_ident("columns") {
9804                        let s: LitStr = inner.value()?.parse()?;
9805                        columns = Some(split_field_list(&s.value()));
9806                        return Ok(());
9807                    }
9808                    if inner.path.is_ident("condition") {
9809                        let s: LitStr = inner.value()?.parse()?;
9810                        condition = Some(s.value());
9811                        return Ok(());
9812                    }
9813                    if inner.path.is_ident("name") {
9814                        let s: LitStr = inner.value()?.parse()?;
9815                        name = Some(s.value());
9816                        return Ok(());
9817                    }
9818                    if inner.path.is_ident("include") {
9819                        // PG 11+ covering-index columns. Non-key columns
9820                        // travel with the index leaf for index-only
9821                        // scans. Dropped on MySQL/SQLite by the writer.
9822                        let s: LitStr = inner.value()?.parse()?;
9823                        include = split_field_list(&s.value());
9824                        return Ok(());
9825                    }
9826                    Err(inner.error(
9827                        "unknown unique_when attribute (supported: \
9828                         `columns = \"...\"`, `condition = \"...\"`, \
9829                         `name = \"...\"`, `include = \"...\"`)",
9830                    ))
9831                })?;
9832                let columns = columns.ok_or_else(|| {
9833                    meta.error("`unique_when(...)` requires `columns = \"...\"`")
9834                })?;
9835                let condition = condition.ok_or_else(|| {
9836                    meta.error("`unique_when(...)` requires `condition = \"...\"`")
9837                })?;
9838                if columns.is_empty() {
9839                    return Err(meta.error("`unique_when(columns = \"\")` is empty"));
9840                }
9841                out.indexes.push(IndexAttr {
9842                    name,
9843                    columns,
9844                    unique: true,
9845                    method: "btree".to_owned(),
9846                    where_clause: Some(condition),
9847                    include,
9848                });
9849                return Ok(());
9850            }
9851            if meta.path.is_ident("index_when") {
9852                // Non-unique partial index. Sibling of `unique_when`
9853                // (which emits `CREATE UNIQUE INDEX ... WHERE ...`).
9854                //
9855                //   #[rustango(index_when(
9856                //       columns   = "status, created_at",
9857                //       condition = "deleted_at IS NULL",
9858                //       name      = "active_status_created_idx"
9859                //   ))]
9860                //
9861                // → `CREATE INDEX <name> ON <table> (cols) WHERE <condition>`
9862                // on PG / SQLite (both ship partial indexes natively).
9863                // MySQL has no native partial-index support — the writer
9864                // emits a plain CREATE INDEX and the condition is lost;
9865                // operators wanting that selectivity on MySQL should
9866                // declare a covering index plus an application-level
9867                // filter.
9868                let mut columns: Option<Vec<String>> = None;
9869                let mut condition: Option<String> = None;
9870                let mut name: Option<String> = None;
9871                let mut method: String = "btree".to_owned();
9872                let mut include: Vec<String> = Vec::new();
9873                meta.parse_nested_meta(|inner| {
9874                    if inner.path.is_ident("columns") {
9875                        let s: LitStr = inner.value()?.parse()?;
9876                        columns = Some(split_field_list(&s.value()));
9877                        return Ok(());
9878                    }
9879                    if inner.path.is_ident("condition") {
9880                        let s: LitStr = inner.value()?.parse()?;
9881                        condition = Some(s.value());
9882                        return Ok(());
9883                    }
9884                    if inner.path.is_ident("name") {
9885                        let s: LitStr = inner.value()?.parse()?;
9886                        name = Some(s.value());
9887                        return Ok(());
9888                    }
9889                    if inner.path.is_ident("method") {
9890                        let s: LitStr = inner.value()?.parse()?;
9891                        method = s.value();
9892                        return Ok(());
9893                    }
9894                    if inner.path.is_ident("include") {
9895                        // PG 11+ covering-index columns; non-key
9896                        // columns travel with the index leaf. Dropped
9897                        // on MySQL/SQLite.
9898                        let s: LitStr = inner.value()?.parse()?;
9899                        include = split_field_list(&s.value());
9900                        return Ok(());
9901                    }
9902                    Err(inner.error(
9903                        "unknown index_when attribute (supported: \
9904                         `columns = \"...\"`, `condition = \"...\"`, \
9905                         `name = \"...\"`, `method = \"btree|gin|gist|...\"`, \
9906                         `include = \"...\"`)",
9907                    ))
9908                })?;
9909                let columns = columns
9910                    .ok_or_else(|| meta.error("`index_when(...)` requires `columns = \"...\"`"))?;
9911                let condition = condition.ok_or_else(|| {
9912                    meta.error("`index_when(...)` requires `condition = \"...\"`")
9913                })?;
9914                if columns.is_empty() {
9915                    return Err(meta.error("`index_when(columns = \"\")` is empty"));
9916                }
9917                out.indexes.push(IndexAttr {
9918                    name,
9919                    columns,
9920                    unique: false,
9921                    method,
9922                    where_clause: Some(condition),
9923                    include,
9924                });
9925                return Ok(());
9926            }
9927            if meta.path.is_ident("index") {
9928                // Container-level composite index. Two syntaxes:
9929                //   #[rustango(index = "col1, col2")]   — bare, non-unique btree
9930                //   #[rustango(index("col1, col2"))]    — call form (same result)
9931                //   #[rustango(index("col1, col2", unique, name = "my_idx", method = "gin"))]
9932                // The call form takes the column list as a leading string
9933                // literal, then optional `unique` / `name = "..."` /
9934                // `method = "..."` flags (a leading literal can't compose
9935                // under `parse_nested_meta`, so the paren body is parsed by
9936                // hand). `unique_together` / `index_together` remain
9937                // aliases for the same feature.
9938                let cols_lit: LitStr;
9939                let mut unique = false;
9940                let mut name: Option<String> = None;
9941                let mut method = "btree".to_owned();
9942                if meta.input.peek(syn::token::Paren) {
9943                    let content;
9944                    syn::parenthesized!(content in meta.input);
9945                    cols_lit = content.parse()?;
9946                    while content.peek(syn::Token![,]) {
9947                        content.parse::<syn::Token![,]>()?;
9948                        if content.is_empty() {
9949                            break;
9950                        }
9951                        let flag: syn::Ident = content.parse()?;
9952                        if flag == "unique" {
9953                            unique = true;
9954                        } else if flag == "name" {
9955                            content.parse::<syn::Token![=]>()?;
9956                            let s: LitStr = content.parse()?;
9957                            name = Some(s.value());
9958                        } else if flag == "method" {
9959                            content.parse::<syn::Token![=]>()?;
9960                            let s: LitStr = content.parse()?;
9961                            let v = s.value();
9962                            match v.as_str() {
9963                                "btree" | "gin" | "gist" | "brin" | "spgist" | "hash"
9964                                | "bloom" => method = v,
9965                                other => {
9966                                    return Err(syn::Error::new(
9967                                        s.span(),
9968                                        format!("unknown index method `{other}` (supported: btree, gin, gist, brin, spgist, hash, bloom)"),
9969                                    ));
9970                                }
9971                            }
9972                        } else {
9973                            return Err(syn::Error::new(
9974                                flag.span(),
9975                                "unknown index flag (supported: `unique`, `name`, `method`)",
9976                            ));
9977                        }
9978                    }
9979                } else {
9980                    cols_lit = meta.value()?.parse()?;
9981                }
9982                let columns = split_field_list(&cols_lit.value());
9983                out.indexes.push(IndexAttr {
9984                    name,
9985                    columns,
9986                    unique,
9987                    method,
9988                    where_clause: None,
9989                    include: Vec::new(),
9990                });
9991                return Ok(());
9992            }
9993            if meta.path.is_ident("check") {
9994                // #[rustango(check(name = "…", expr = "…"))]
9995                let mut name: Option<String> = None;
9996                let mut expr: Option<String> = None;
9997                meta.parse_nested_meta(|inner| {
9998                    if inner.path.is_ident("name") {
9999                        let s: LitStr = inner.value()?.parse()?;
10000                        name = Some(s.value());
10001                        return Ok(());
10002                    }
10003                    if inner.path.is_ident("expr") {
10004                        let s: LitStr = inner.value()?.parse()?;
10005                        expr = Some(s.value());
10006                        return Ok(());
10007                    }
10008                    Err(inner.error("unknown check attribute (supported: `name`, `expr`)"))
10009                })?;
10010                let name = name.ok_or_else(|| meta.error("check requires `name = \"...\"`"))?;
10011                let expr = expr.ok_or_else(|| meta.error("check requires `expr = \"...\"`"))?;
10012                out.checks.push(CheckAttr { name, expr });
10013                return Ok(());
10014            }
10015            if meta.path.is_ident("exclude") {
10016                // #[rustango(exclude(name = "…", using = "gist",
10017                //                    elements = "col WITH op, col WITH op",
10018                //                    where = "…"))]
10019                let mut name: Option<String> = None;
10020                let mut using: Option<String> = None;
10021                let mut elements_raw: Option<(String, proc_macro2::Span)> = None;
10022                let mut where_clause: Option<String> = None;
10023                meta.parse_nested_meta(|inner| {
10024                    if inner.path.is_ident("name") {
10025                        let s: LitStr = inner.value()?.parse()?;
10026                        name = Some(s.value());
10027                        return Ok(());
10028                    }
10029                    if inner.path.is_ident("using") {
10030                        let s: LitStr = inner.value()?.parse()?;
10031                        using = Some(s.value());
10032                        return Ok(());
10033                    }
10034                    if inner.path.is_ident("elements") {
10035                        let s: LitStr = inner.value()?.parse()?;
10036                        elements_raw = Some((s.value(), s.span()));
10037                        return Ok(());
10038                    }
10039                    if inner.path.is_ident("where") || inner.path.is_ident("where_clause") {
10040                        let s: LitStr = inner.value()?.parse()?;
10041                        where_clause = Some(s.value());
10042                        return Ok(());
10043                    }
10044                    Err(inner.error(
10045                        "unknown exclude attribute (supported: `name`, `using`, `elements`, `where`)",
10046                    ))
10047                })?;
10048                let name = name.ok_or_else(|| meta.error("exclude requires `name = \"...\"`"))?;
10049                let using = using.unwrap_or_else(|| "gist".to_owned());
10050                let (elements_str, elements_span) = elements_raw.ok_or_else(|| {
10051                    meta.error(
10052                        "exclude requires `elements = \"col WITH op, col WITH op\"`",
10053                    )
10054                })?;
10055                // Parse `col WITH op` pairs separated by commas.
10056                let mut elements: Vec<(String, String)> = Vec::new();
10057                for pair in elements_str.split(',') {
10058                    let pair = pair.trim();
10059                    if pair.is_empty() {
10060                        continue;
10061                    }
10062                    let mut split = pair.splitn(2, |c: char| c.is_whitespace());
10063                    let col = split.next().unwrap_or("").trim();
10064                    let rest = split.next().unwrap_or("").trim();
10065                    // `WITH op` — case-insensitive on `WITH`, then op.
10066                    let rest_lc = rest.to_ascii_lowercase();
10067                    let op = rest_lc
10068                        .strip_prefix("with")
10069                        .map(|r| r.trim_start())
10070                        .filter(|r| !r.is_empty())
10071                        .map(|_| {
10072                            // Pull the original-case op from `rest` after the
10073                            // `WITH ` token (5 chars).
10074                            rest[4..].trim_start().to_owned()
10075                        });
10076                    let Some(op) = op else {
10077                        return Err(syn::Error::new(
10078                            elements_span,
10079                            format!(
10080                                "exclude elements: `{pair}` must be `<col> WITH <op>` \
10081                                 (e.g. `room_id WITH =` or `during WITH &&`)"
10082                            ),
10083                        ));
10084                    };
10085                    if col.is_empty() || op.is_empty() {
10086                        return Err(syn::Error::new(
10087                            elements_span,
10088                            format!(
10089                                "exclude elements: `{pair}` must be `<col> WITH <op>` \
10090                                 (both sides non-empty)"
10091                            ),
10092                        ));
10093                    }
10094                    elements.push((col.to_owned(), op));
10095                }
10096                if elements.is_empty() {
10097                    return Err(syn::Error::new(
10098                        elements_span,
10099                        "exclude requires at least one `col WITH op` element",
10100                    ));
10101                }
10102                out.excludes.push(ExcludeAttr {
10103                    name,
10104                    using,
10105                    elements,
10106                    where_clause,
10107                });
10108                return Ok(());
10109            }
10110            if meta.path.is_ident("generic_fk") {
10111                let mut gfk = GenericFkAttr {
10112                    name: String::new(),
10113                    ct_column: String::new(),
10114                    pk_column: String::new(),
10115                };
10116                meta.parse_nested_meta(|inner| {
10117                    if inner.path.is_ident("name") {
10118                        let s: LitStr = inner.value()?.parse()?;
10119                        gfk.name = s.value();
10120                        return Ok(());
10121                    }
10122                    if inner.path.is_ident("ct_column") {
10123                        let s: LitStr = inner.value()?.parse()?;
10124                        gfk.ct_column = s.value();
10125                        return Ok(());
10126                    }
10127                    if inner.path.is_ident("pk_column") {
10128                        let s: LitStr = inner.value()?.parse()?;
10129                        gfk.pk_column = s.value();
10130                        return Ok(());
10131                    }
10132                    Err(inner.error(
10133                        "unknown generic_fk attribute (supported: `name`, `ct_column`, `pk_column`)",
10134                    ))
10135                })?;
10136                if gfk.name.is_empty() {
10137                    return Err(meta.error("generic_fk requires `name = \"...\"`"));
10138                }
10139                if gfk.ct_column.is_empty() {
10140                    return Err(meta.error("generic_fk requires `ct_column = \"...\"`"));
10141                }
10142                if gfk.pk_column.is_empty() {
10143                    return Err(meta.error("generic_fk requires `pk_column = \"...\"`"));
10144                }
10145                out.generic_fks.push(gfk);
10146                return Ok(());
10147            }
10148            if meta.path.is_ident("fk_composite") {
10149                let mut fk = CompositeFkAttr {
10150                    name: String::new(),
10151                    to: String::new(),
10152                    from: Vec::new(),
10153                    on: Vec::new(),
10154                };
10155                meta.parse_nested_meta(|inner| {
10156                    if inner.path.is_ident("name") {
10157                        let s: LitStr = inner.value()?.parse()?;
10158                        fk.name = s.value();
10159                        return Ok(());
10160                    }
10161                    if inner.path.is_ident("to") {
10162                        let s: LitStr = inner.value()?.parse()?;
10163                        fk.to = s.value();
10164                        return Ok(());
10165                    }
10166                    // `on = ("col1", "col2", ...)` — parse a parenthesised
10167                    // comma-list of string literals.
10168                    if inner.path.is_ident("on") || inner.path.is_ident("from") {
10169                        let value = inner.value()?;
10170                        let content;
10171                        syn::parenthesized!(content in value);
10172                        let lits: syn::punctuated::Punctuated<syn::LitStr, syn::Token![,]> =
10173                            content.parse_terminated(
10174                                |p| p.parse::<syn::LitStr>(),
10175                                syn::Token![,],
10176                            )?;
10177                        let cols: Vec<String> = lits.iter().map(syn::LitStr::value).collect();
10178                        if inner.path.is_ident("on") {
10179                            fk.on = cols;
10180                        } else {
10181                            fk.from = cols;
10182                        }
10183                        return Ok(());
10184                    }
10185                    Err(inner.error(
10186                        "unknown fk_composite attribute (supported: `name`, `to`, `on`, `from`)",
10187                    ))
10188                })?;
10189                if fk.name.is_empty() {
10190                    return Err(meta.error("fk_composite requires `name = \"...\"`"));
10191                }
10192                if fk.to.is_empty() {
10193                    return Err(meta.error("fk_composite requires `to = \"...\"`"));
10194                }
10195                if fk.from.is_empty() || fk.on.is_empty() {
10196                    return Err(meta.error(
10197                        "fk_composite requires non-empty `from = (...)` and `on = (...)` tuples",
10198                    ));
10199                }
10200                if fk.from.len() != fk.on.len() {
10201                    return Err(meta.error(format!(
10202                        "fk_composite `from` ({} cols) and `on` ({} cols) must be the same length",
10203                        fk.from.len(),
10204                        fk.on.len(),
10205                    )));
10206                }
10207                out.composite_fks.push(fk);
10208                return Ok(());
10209            }
10210            if meta.path.is_ident("m2m") {
10211                let mut m2m = M2MAttr {
10212                    name: String::new(),
10213                    to: String::new(),
10214                    through: String::new(),
10215                    src: String::new(),
10216                    dst: String::new(),
10217                    auto_create: true,
10218                };
10219                meta.parse_nested_meta(|inner| {
10220                    if inner.path.is_ident("name") {
10221                        let s: LitStr = inner.value()?.parse()?;
10222                        m2m.name = s.value();
10223                        return Ok(());
10224                    }
10225                    if inner.path.is_ident("to") {
10226                        let s: LitStr = inner.value()?.parse()?;
10227                        m2m.to = s.value();
10228                        return Ok(());
10229                    }
10230                    if inner.path.is_ident("through") {
10231                        let s: LitStr = inner.value()?.parse()?;
10232                        m2m.through = s.value();
10233                        return Ok(());
10234                    }
10235                    if inner.path.is_ident("src") {
10236                        let s: LitStr = inner.value()?.parse()?;
10237                        m2m.src = s.value();
10238                        return Ok(());
10239                    }
10240                    if inner.path.is_ident("dst") {
10241                        let s: LitStr = inner.value()?.parse()?;
10242                        m2m.dst = s.value();
10243                        return Ok(());
10244                    }
10245                    if inner.path.is_ident("auto_create") {
10246                        let lit: syn::LitBool = inner.value()?.parse()?;
10247                        m2m.auto_create = lit.value;
10248                        return Ok(());
10249                    }
10250                    Err(inner.error("unknown m2m attribute (supported: `name`, `to`, `through`, `src`, `dst`, `auto_create`)"))
10251                })?;
10252                if m2m.name.is_empty() {
10253                    return Err(meta.error("m2m requires `name = \"...\"`"));
10254                }
10255                if m2m.to.is_empty() {
10256                    return Err(meta.error("m2m requires `to = \"...\"`"));
10257                }
10258                if m2m.through.is_empty() {
10259                    return Err(meta.error("m2m requires `through = \"...\"`"));
10260                }
10261                if m2m.src.is_empty() {
10262                    return Err(meta.error("m2m requires `src = \"...\"`"));
10263                }
10264                if m2m.dst.is_empty() {
10265                    return Err(meta.error("m2m requires `dst = \"...\"`"));
10266                }
10267                out.m2m.push(m2m);
10268                return Ok(());
10269            }
10270            if meta.path.is_ident("generic_m2m") {
10271                let mut gm = GenericM2MAttr {
10272                    name: String::new(),
10273                    through: String::new(),
10274                    pk_column: String::new(),
10275                    ct_column: String::new(),
10276                    related_column: String::new(),
10277                };
10278                meta.parse_nested_meta(|inner| {
10279                    let field = |inner: &syn::meta::ParseNestedMeta| -> syn::Result<String> {
10280                        let s: LitStr = inner.value()?.parse()?;
10281                        Ok(s.value())
10282                    };
10283                    if inner.path.is_ident("name") {
10284                        gm.name = field(&inner)?;
10285                        return Ok(());
10286                    }
10287                    if inner.path.is_ident("through") {
10288                        gm.through = field(&inner)?;
10289                        return Ok(());
10290                    }
10291                    if inner.path.is_ident("pk_column") {
10292                        gm.pk_column = field(&inner)?;
10293                        return Ok(());
10294                    }
10295                    if inner.path.is_ident("ct_column") {
10296                        gm.ct_column = field(&inner)?;
10297                        return Ok(());
10298                    }
10299                    if inner.path.is_ident("related_column") {
10300                        gm.related_column = field(&inner)?;
10301                        return Ok(());
10302                    }
10303                    Err(inner.error("unknown generic_m2m attribute (supported: `name`, `through`, `pk_column`, `ct_column`, `related_column`)"))
10304                })?;
10305                for (val, label) in [
10306                    (&gm.name, "name"),
10307                    (&gm.through, "through"),
10308                    (&gm.pk_column, "pk_column"),
10309                    (&gm.ct_column, "ct_column"),
10310                    (&gm.related_column, "related_column"),
10311                ] {
10312                    if val.is_empty() {
10313                        return Err(meta.error(format!("generic_m2m requires `{label} = \"...\"`")));
10314                    }
10315                }
10316                out.generic_m2m.push(gm);
10317                return Ok(());
10318            }
10319            Err(meta.error("unknown rustango container attribute"))
10320        })?;
10321    }
10322    Ok(out)
10323}
10324
10325/// Split a comma-separated field-name list (e.g. `"name, office"`) into
10326/// owned field names, trimming whitespace and skipping empty entries.
10327/// Field-name validation against the model is done by the caller.
10328fn split_field_list(raw: &str) -> Vec<String> {
10329    raw.split(',')
10330        .map(str::trim)
10331        .filter(|s| !s.is_empty())
10332        .map(str::to_owned)
10333        .collect()
10334}
10335
10336/// Shared parser for `unique_together` and `index_together` container
10337/// attrs. Accepts both shapes:
10338///
10339///   * `attr = "col1, col2"`              — auto-derived index name.
10340///   * `attr(columns = "col1, col2", name = "...")` — explicit name.
10341///
10342/// Returns `(columns, name)`.
10343fn parse_together_attr(
10344    meta: &syn::meta::ParseNestedMeta<'_>,
10345    attr: &str,
10346) -> syn::Result<(Vec<String>, Option<String>)> {
10347    // Disambiguate by whether the next token is `=` (key-value) or
10348    // `(` (parenthesized).
10349    if meta.input.peek(syn::Token![=]) {
10350        let cols_lit: LitStr = meta.value()?.parse()?;
10351        let columns = split_field_list(&cols_lit.value());
10352        check_together_columns(meta, attr, &columns)?;
10353        return Ok((columns, None));
10354    }
10355    let mut columns: Option<Vec<String>> = None;
10356    let mut name: Option<String> = None;
10357    meta.parse_nested_meta(|inner| {
10358        if inner.path.is_ident("columns") {
10359            let s: LitStr = inner.value()?.parse()?;
10360            columns = Some(split_field_list(&s.value()));
10361            return Ok(());
10362        }
10363        if inner.path.is_ident("name") {
10364            let s: LitStr = inner.value()?.parse()?;
10365            name = Some(s.value());
10366            return Ok(());
10367        }
10368        Err(inner.error("unknown sub-attribute (supported: `columns`, `name`)"))
10369    })?;
10370    let columns = columns.ok_or_else(|| {
10371        meta.error(format!(
10372            "{attr}(...) requires a `columns = \"col1, col2\"` argument",
10373        ))
10374    })?;
10375    check_together_columns(meta, attr, &columns)?;
10376    Ok((columns, name))
10377}
10378
10379fn check_together_columns(
10380    meta: &syn::meta::ParseNestedMeta<'_>,
10381    attr: &str,
10382    columns: &[String],
10383) -> syn::Result<()> {
10384    if columns.len() < 2 {
10385        let single = if attr == "unique_together" {
10386            "#[rustango(unique)] on the field"
10387        } else {
10388            "#[rustango(index)] on the field"
10389        };
10390        return Err(meta.error(format!(
10391            "{attr} expects two or more columns; for a single-column equivalent use {single}",
10392        )));
10393    }
10394    Ok(())
10395}
10396
10397/// Parse the fieldsets DSL: pipe-separated sections, optional
10398/// `"Title:"` prefix on each, comma-separated field names after.
10399/// Examples:
10400/// * `"name, office"` → one untitled section with two fields
10401/// * `"Identity: name, office | Metadata: created_at"` → two titled
10402///   sections
10403///
10404/// Returns `(title, fields)` pairs. Title is `""` when no prefix.
10405fn parse_fieldset_list(raw: &str) -> Vec<(String, Vec<String>)> {
10406    raw.split('|')
10407        .map(str::trim)
10408        .filter(|s| !s.is_empty())
10409        .map(|section| {
10410            // Split off an optional `Title:` prefix (first colon).
10411            let (title, rest) = match section.split_once(':') {
10412                Some((title, rest)) if !title.contains(',') => (title.trim().to_owned(), rest),
10413                _ => (String::new(), section),
10414            };
10415            let fields = split_field_list(rest);
10416            (title, fields)
10417        })
10418        .collect()
10419}
10420
10421/// Parse `prepopulated_fields = "target:source[+src2,...]"` — each
10422/// comma-separated entry maps a target field to one or more source
10423/// fields joined with `+`. Whitespace around tokens is trimmed.
10424/// Entries missing `:` or with empty target/source lists are dropped.
10425fn parse_prepopulated_list(raw: &str) -> Vec<(String, Vec<String>)> {
10426    raw.split(',')
10427        .map(str::trim)
10428        .filter(|s| !s.is_empty())
10429        .filter_map(|entry| {
10430            let (target, sources_raw) = entry.split_once(':')?;
10431            let target = target.trim().to_owned();
10432            if target.is_empty() {
10433                return None;
10434            }
10435            let sources: Vec<String> = sources_raw
10436                .split('+')
10437                .map(|s| s.trim().to_owned())
10438                .filter(|s| !s.is_empty())
10439                .collect();
10440            if sources.is_empty() {
10441                return None;
10442            }
10443            Some((target, sources))
10444        })
10445        .collect()
10446}
10447
10448/// Parse `formfield_overrides` — `"field:widget,field2:widget2"`
10449/// into `(field_name, widget_name)` pairs. Empty entries, missing `:`,
10450/// and empty halves drop silently — the macro layer only enforces shape,
10451/// not field-name vs. widget-name validity (those checks happen at
10452/// `AdminConfig` consumption time). Issue #359.
10453fn parse_formfield_overrides(raw: &str) -> Vec<(String, String)> {
10454    raw.split(',')
10455        .map(str::trim)
10456        .filter(|s| !s.is_empty())
10457        .filter_map(|entry| {
10458            let (field, widget) = entry.split_once(':')?;
10459            let field = field.trim().to_owned();
10460            let widget = widget.trim().to_owned();
10461            if field.is_empty() || widget.is_empty() {
10462                return None;
10463            }
10464            Some((field, widget))
10465        })
10466        .collect()
10467}
10468
10469/// Parse an ordering list — `"name"` is ASC, `"-name"` is DESC.
10470/// Returns `(field_name, desc)` pairs in the same order as the input.
10471fn parse_ordering_list(raw: &str) -> Vec<(String, bool)> {
10472    raw.split(',')
10473        .map(str::trim)
10474        .filter(|s| !s.is_empty())
10475        .map(|spec| {
10476            spec.strip_prefix('-')
10477                .map_or((spec.to_owned(), false), |rest| {
10478                    (rest.trim().to_owned(), true)
10479                })
10480        })
10481        .collect()
10482}
10483
10484struct FieldAttrs {
10485    column: Option<String>,
10486    primary_key: bool,
10487    fk: Option<String>,
10488    o2o: Option<String>,
10489    on: Option<String>,
10490    /// `#[rustango(on_delete = "cascade" | "restrict" | "set_null" |
10491    /// "set_default" | "no_action")]` — what happens to this row when
10492    /// the row it points at is deleted.
10493    /// Only meaningful when `fk` / `o2o` is
10494    /// also set; the macro errors at compile time if applied to a
10495    /// non-FK field. Threaded into `FieldSchema::fk_on_delete`. The
10496    /// DDL writer renders `ON DELETE <action>` after the constraint
10497    /// clause when this is `Some`; `None` falls back to the database
10498    /// default (NO ACTION on every backend rustango supports).
10499    on_delete: Option<String>,
10500    /// `#[rustango(related_name = "...")]` — per-FK
10501    /// reverse-accessor override. When set, the derive emits
10502    /// `Parent::<related_name>[_pool]` instead of the container-level
10503    /// `default_related_name` or the `<child_snake>_set[_pool]`
10504    /// fallback. Only meaningful when `fk` / `o2o` is also set;
10505    /// silently ignored on non-FK fields. Follow-up to #816.
10506    related_name: Option<String>,
10507    max_length: Option<u32>,
10508    /// `#[rustango(vector(dims = N))]` — pgvector column dimension (#824).
10509    /// Threaded into `FieldType::Vector(N)` at emission. `None` → an
10510    /// unconstrained `vector` column.
10511    vector_dims: Option<u32>,
10512    /// `#[rustango(geometry(srid = N))]` — PostGIS geometry SRID (#443).
10513    /// Threaded into `FieldType::Geometry(N)` at emission. `None` → an
10514    /// unconstrained `geometry(Point)` column (SRID 0).
10515    geometry_srid: Option<u32>,
10516    min: Option<i64>,
10517    max: Option<i64>,
10518    default: Option<String>,
10519    /// `#[rustango(auto_uuid)]` — UUID PK generated by Postgres
10520    /// `gen_random_uuid()`. Implies `auto + primary_key + default =
10521    /// "gen_random_uuid()"`. The Rust field type must be
10522    /// `uuid::Uuid` (or `Auto<Uuid>`); the column is excluded from
10523    /// INSERTs so the DB DEFAULT fires.
10524    auto_uuid: bool,
10525    /// `#[rustango(default_uuid_v7)]` — backend-neutral counterpart of
10526    /// `auto_uuid`. The PK value is generated **Rust-side** at insert
10527    /// time using `uuid::Uuid::now_v7()` (time-sortable UUIDv7) when
10528    /// the field is `Auto::Unset`, then bound as a normal parameter
10529    /// rather than relying on a per-dialect DB function. Issue #823
10530    /// (Eloquent `HasUuids`).
10531    ///
10532    /// Field type must be `Auto<uuid::Uuid>`. Implies `primary_key`.
10533    /// Composes with every backend (PG / MySQL / SQLite) — no
10534    /// `gen_random_uuid()` requirement on the database.
10535    default_uuid_v7: bool,
10536    /// `#[rustango(auto_now_add)]` — `created_at`-shape column.
10537    /// Server-set on insert, immutable from app code afterwards.
10538    /// Implies `auto + default = "now()"`. Field type must be
10539    /// `DateTime<Utc>`.
10540    auto_now_add: bool,
10541    /// `#[rustango(auto_now)]` — `updated_at`-shape column. Set on
10542    /// every insert AND every update. Implies `auto + default =
10543    /// "now()"`; the macro additionally rewrites `update_on` /
10544    /// `save_on` to bind `chrono::Utc::now()` instead of the user's
10545    /// field value.
10546    auto_now: bool,
10547    /// `#[rustango(soft_delete)]` — `deleted_at`-shape column. Type
10548    /// must be `Option<DateTime<Utc>>`. Triggers macro emission of
10549    /// `soft_delete_on(executor)` and `restore_on(executor)`
10550    /// methods on the model.
10551    soft_delete: bool,
10552    /// `#[rustango(unique)]` — adds a `UNIQUE` constraint inline on
10553    /// the column in the generated DDL.
10554    unique: bool,
10555    /// `#[rustango(index)]` or `#[rustango(index(name = "…", unique))]` —
10556    /// generates a `CREATE INDEX` for this column. `unique` here means
10557    /// `CREATE UNIQUE INDEX` (distinct from the `unique` constraint above).
10558    index: bool,
10559    index_unique: bool,
10560    index_name: Option<String>,
10561    /// Index access method (`"btree"` / `"gin"` / …). Defaults to
10562    /// `"btree"`. Issue #34.
10563    index_method: String,
10564    /// `#[rustango(generated_as = "EXPR")]` — emit `GENERATED ALWAYS
10565    /// AS (EXPR) STORED` in the column DDL. Read-only from app code:
10566    /// the macro skips this column from every INSERT and UPDATE
10567    /// path, so the database always recomputes the value from
10568    /// `EXPR`. Backlog item #35.
10569    generated_as: Option<String>,
10570    /// `#[rustango(help_text = "…")]` — help text
10571    /// rendered below the admin form's input. Threaded into
10572    /// `FieldSchema::help_text` so admin / serializer / OpenAPI
10573    /// layers can read it.
10574    help_text: Option<String>,
10575    /// `#[rustango(choices = "value:Label, value:Label")]` — the
10576    /// enumerated allowed values. Threaded into `FieldSchema::choices`
10577    /// as a `&'static [(&'static str, &'static str)]` slice. When
10578    /// present, the admin form renders a `<select>` instead of `<input>`
10579    /// and the validator rejects values not in the list. Only meaningful
10580    /// for `FieldType::String`; the macro errors at compile time if
10581    /// applied to a non-string field.
10582    choices: Option<Vec<(String, String)>>,
10583    /// `#[rustango(db_comment = "…")]` — DB-side column
10584    /// comment. Threaded into `FieldSchema::db_comment`. MySQL inlines
10585    /// the comment in CREATE TABLE; Postgres emits a separate
10586    /// `COMMENT ON COLUMN` statement after the table is created;
10587    /// SQLite silently drops the value (no native column comments).
10588    db_comment: Option<String>,
10589    /// `#[rustango(verbose_name = "…")]` — human-readable
10590    /// label for the field. Threaded into `FieldSchema::verbose_name`
10591    /// so admin column headers, form labels, and other display
10592    /// surfaces can prefer the friendly caption over the Rust
10593    /// identifier. `None` means renderers fall back to the field name.
10594    verbose_name: Option<String>,
10595    /// `#[rustango(editable = false)]` — opt out of
10596    /// auto-generated form rendering. Defaults to `true` so existing
10597    /// fields keep their current admin / form behavior; setting
10598    /// `false` removes the field from the admin change-form entirely
10599    /// (the value is still visible on detail / list views, just not
10600    /// editable).
10601    editable: bool,
10602    /// `#[rustango(blank)]` / `#[rustango(blank = true)]` —
10603    /// "form may submit empty even when DB is NOT NULL". Threaded into
10604    /// `FieldSchema::blank`. Defaults to `false`.
10605    blank: bool,
10606    /// `#[rustango(citext)]` / `#[rustango(citext = true)]` (#344) —
10607    /// case-insensitive text column. Threaded into
10608    /// `FieldSchema::case_insensitive`. Only meaningful for `String`
10609    /// fields; the macro errors at derive time if applied elsewhere.
10610    case_insensitive: bool,
10611    /// `#[rustango(validators = "email,url")]` — the
10612    /// model-level validator chain. Comma-separated names that
10613    /// dispatch to the `validators::*` family in `validate_value`.
10614    /// Empty by default; fires on every typed INSERT/UPDATE.
10615    validators: Vec<String>,
10616}
10617
10618fn parse_field_attrs(field: &syn::Field) -> syn::Result<FieldAttrs> {
10619    let mut out = FieldAttrs {
10620        column: None,
10621        primary_key: false,
10622        fk: None,
10623        o2o: None,
10624        on: None,
10625        on_delete: None,
10626        related_name: None,
10627        max_length: None,
10628        vector_dims: None,
10629        geometry_srid: None,
10630        min: None,
10631        max: None,
10632        default: None,
10633        auto_uuid: false,
10634        default_uuid_v7: false,
10635        auto_now_add: false,
10636        auto_now: false,
10637        soft_delete: false,
10638        unique: false,
10639        index: false,
10640        index_unique: false,
10641        index_name: None,
10642        index_method: "btree".to_owned(),
10643        generated_as: None,
10644        help_text: None,
10645        choices: None,
10646        db_comment: None,
10647        verbose_name: None,
10648        editable: true,
10649        blank: false,
10650        case_insensitive: false,
10651        validators: Vec::new(),
10652    };
10653    for attr in &field.attrs {
10654        if !attr.path().is_ident("rustango") {
10655            continue;
10656        }
10657        attr.parse_nested_meta(|meta| {
10658            if meta.path.is_ident("column") {
10659                let s: LitStr = meta.value()?.parse()?;
10660                let name = s.value();
10661                validate_sql_identifier(&name, "column", s.span())?;
10662                out.column = Some(name);
10663                return Ok(());
10664            }
10665            if meta.path.is_ident("primary_key") {
10666                out.primary_key = true;
10667                return Ok(());
10668            }
10669            if meta.path.is_ident("fk") {
10670                let s: LitStr = meta.value()?.parse()?;
10671                out.fk = Some(s.value());
10672                return Ok(());
10673            }
10674            if meta.path.is_ident("o2o") {
10675                let s: LitStr = meta.value()?.parse()?;
10676                out.o2o = Some(s.value());
10677                return Ok(());
10678            }
10679            if meta.path.is_ident("on") {
10680                let s: LitStr = meta.value()?.parse()?;
10681                out.on = Some(s.value());
10682                return Ok(());
10683            }
10684            if meta.path.is_ident("on_delete") {
10685                let s: LitStr = meta.value()?.parse()?;
10686                let raw = s.value();
10687                let normalized = raw.trim().to_ascii_lowercase();
10688                // Validate at parse time so the user gets a clear span
10689                // rather than a downstream compile error in the emit.
10690                match normalized.as_str() {
10691                    "cascade" | "restrict" | "set_null" | "set_default" | "no_action" => {}
10692                    _ => {
10693                        return Err(syn::Error::new(
10694                            s.span(),
10695                            format!(
10696                                "unknown on_delete action `{raw}`; expected one of \
10697                                 `cascade`, `restrict`, `set_null`, `set_default`, `no_action`"
10698                            ),
10699                        ));
10700                    }
10701                }
10702                out.on_delete = Some(normalized);
10703                return Ok(());
10704            }
10705            if meta.path.is_ident("related_name") {
10706                let s: LitStr = meta.value()?.parse()?;
10707                let raw = s.value();
10708                if raw.trim().is_empty() {
10709                    return Err(syn::Error::new(
10710                        s.span(),
10711                        "`related_name` must be a non-empty identifier",
10712                    ));
10713                }
10714                // Validate as a Rust-ident shape — the value becomes
10715                // a method name on the parent type. Same rule as
10716                // `default_related_name` so the two surfaces match.
10717                if !raw
10718                    .chars()
10719                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
10720                    || raw.starts_with(char::is_numeric)
10721                {
10722                    return Err(syn::Error::new(
10723                        s.span(),
10724                        "`related_name` must be snake_case ASCII (lowercase letters, \
10725                         digits, underscores; no leading digit)",
10726                    ));
10727                }
10728                out.related_name = Some(raw);
10729                return Ok(());
10730            }
10731            if meta.path.is_ident("max_length") {
10732                let lit: syn::LitInt = meta.value()?.parse()?;
10733                out.max_length = Some(lit.base10_parse::<u32>()?);
10734                return Ok(());
10735            }
10736            // `#[rustango(vector(dims = N))]` — pgvector column
10737            // dimension (#824). Nested-meta form so it reads like the
10738            // other typed-column attrs.
10739            if meta.path.is_ident("vector") {
10740                meta.parse_nested_meta(|inner| {
10741                    if inner.path.is_ident("dims") {
10742                        let lit: syn::LitInt = inner.value()?.parse()?;
10743                        out.vector_dims = Some(lit.base10_parse::<u32>()?);
10744                        return Ok(());
10745                    }
10746                    Err(inner.error("unknown `vector` attribute (supported: `dims`)"))
10747                })?;
10748                return Ok(());
10749            }
10750            // `#[rustango(geometry(srid = N))]` — PostGIS geometry SRID
10751            // (#443). Nested-meta form, mirroring `vector(dims = N)`.
10752            if meta.path.is_ident("geometry") {
10753                meta.parse_nested_meta(|inner| {
10754                    if inner.path.is_ident("srid") {
10755                        let lit: syn::LitInt = inner.value()?.parse()?;
10756                        out.geometry_srid = Some(lit.base10_parse::<u32>()?);
10757                        return Ok(());
10758                    }
10759                    Err(inner.error("unknown `geometry` attribute (supported: `srid`)"))
10760                })?;
10761                return Ok(());
10762            }
10763            if meta.path.is_ident("min") {
10764                out.min = Some(parse_signed_i64(&meta)?);
10765                return Ok(());
10766            }
10767            if meta.path.is_ident("max") {
10768                out.max = Some(parse_signed_i64(&meta)?);
10769                return Ok(());
10770            }
10771            if meta.path.is_ident("default") {
10772                let s: LitStr = meta.value()?.parse()?;
10773                out.default = Some(s.value());
10774                return Ok(());
10775            }
10776            if meta.path.is_ident("generated_as") {
10777                let s: LitStr = meta.value()?.parse()?;
10778                out.generated_as = Some(s.value());
10779                return Ok(());
10780            }
10781            if meta.path.is_ident("help_text") {
10782                let s: LitStr = meta.value()?.parse()?;
10783                out.help_text = Some(s.value());
10784                return Ok(());
10785            }
10786            if meta.path.is_ident("choices") {
10787                let s: LitStr = meta.value()?.parse()?;
10788                let raw = s.value();
10789                let mut pairs: Vec<(String, String)> = Vec::new();
10790                for chunk in raw.split(',') {
10791                    let chunk = chunk.trim();
10792                    if chunk.is_empty() {
10793                        continue;
10794                    }
10795                    let (value, label) = match chunk.split_once(':') {
10796                        Some((v, l)) => (v.trim().to_owned(), l.trim().to_owned()),
10797                        None => (chunk.to_owned(), chunk.to_owned()),
10798                    };
10799                    if value.is_empty() {
10800                        return Err(syn::Error::new(
10801                            s.span(),
10802                            "`choices` entry has empty value before `:`",
10803                        ));
10804                    }
10805                    pairs.push((value, label));
10806                }
10807                if pairs.is_empty() {
10808                    return Err(syn::Error::new(
10809                        s.span(),
10810                        "`choices = \"…\"` must contain at least one value",
10811                    ));
10812                }
10813                out.choices = Some(pairs);
10814                return Ok(());
10815            }
10816            if meta.path.is_ident("db_comment") {
10817                let s: LitStr = meta.value()?.parse()?;
10818                out.db_comment = Some(s.value());
10819                return Ok(());
10820            }
10821            if meta.path.is_ident("verbose_name") {
10822                let s: LitStr = meta.value()?.parse()?;
10823                out.verbose_name = Some(s.value());
10824                return Ok(());
10825            }
10826            if meta.path.is_ident("editable") {
10827                // Two forms accepted:
10828                //   #[rustango(editable = false)] / true — explicit
10829                //   #[rustango(editable)] — flag form (= true, the
10830                //   default, so harmless; included for symmetry)
10831                if let Ok(v) = meta.value() {
10832                    let lit: syn::LitBool = v.parse()?;
10833                    out.editable = lit.value;
10834                } else {
10835                    out.editable = true;
10836                }
10837                return Ok(());
10838            }
10839            if meta.path.is_ident("blank") {
10840                // Two forms accepted:
10841                //   #[rustango(blank)] — flag form, true
10842                //   #[rustango(blank = false)] / true — explicit
10843                if let Ok(v) = meta.value() {
10844                    let lit: syn::LitBool = v.parse()?;
10845                    out.blank = lit.value;
10846                } else {
10847                    out.blank = true;
10848                }
10849                return Ok(());
10850            }
10851            if meta.path.is_ident("citext") {
10852                // Case-insensitive text column (#344). Two forms:
10853                //   #[rustango(citext)]          — flag form, true
10854                //   #[rustango(citext = true)]   — explicit
10855                //   #[rustango(citext = false)]  — explicit opt-out
10856                // String-only validation lives in the field-type
10857                // emitter (the FieldType discriminant is computed in
10858                // `detect_type`); the macro records the flag and the
10859                // DDL writer emits dialect-specific COLLATE / CITEXT.
10860                if let Ok(v) = meta.value() {
10861                    let lit: syn::LitBool = v.parse()?;
10862                    out.case_insensitive = lit.value;
10863                } else {
10864                    out.case_insensitive = true;
10865                }
10866                return Ok(());
10867            }
10868            if meta.path.is_ident("validators") {
10869                let s: LitStr = meta.value()?.parse()?;
10870                let raw = s.value();
10871                out.validators = raw
10872                    .split(',')
10873                    .map(str::trim)
10874                    .filter(|s| !s.is_empty())
10875                    .map(str::to_owned)
10876                    .collect();
10877                if out.validators.is_empty() {
10878                    return Err(syn::Error::new(
10879                        s.span(),
10880                        "`validators = \"…\"` must list at least one name",
10881                    ));
10882                }
10883                return Ok(());
10884            }
10885            if meta.path.is_ident("auto_uuid") {
10886                out.auto_uuid = true;
10887                // Implied: PK + auto + DEFAULT gen_random_uuid().
10888                // Each is also explicitly settable; the explicit
10889                // value wins if conflicting.
10890                out.primary_key = true;
10891                if out.default.is_none() {
10892                    out.default = Some("gen_random_uuid()".into());
10893                }
10894                return Ok(());
10895            }
10896            if meta.path.is_ident("default_uuid_v7") {
10897                // Backend-neutral counterpart of `auto_uuid` — issue #823.
10898                // No SQL DEFAULT (the macro fills the value Rust-side
10899                // before binding); just mark the field as PK + Auto
10900                // so the insert path is the `Auto::Unset → generate`
10901                // branch.
10902                out.default_uuid_v7 = true;
10903                out.primary_key = true;
10904                return Ok(());
10905            }
10906            if meta.path.is_ident("auto_now_add") {
10907                out.auto_now_add = true;
10908                if out.default.is_none() {
10909                    out.default = Some("now()".into());
10910                }
10911                return Ok(());
10912            }
10913            if meta.path.is_ident("auto_now") {
10914                out.auto_now = true;
10915                if out.default.is_none() {
10916                    out.default = Some("now()".into());
10917                }
10918                return Ok(());
10919            }
10920            if meta.path.is_ident("soft_delete") {
10921                out.soft_delete = true;
10922                return Ok(());
10923            }
10924            if meta.path.is_ident("unique") {
10925                out.unique = true;
10926                return Ok(());
10927            }
10928            if meta.path.is_ident("index") {
10929                out.index = true;
10930                // Optional sub-attrs: #[rustango(index(unique, name = "…", method = "gin"))]
10931                if meta.input.peek(syn::token::Paren) {
10932                    meta.parse_nested_meta(|inner| {
10933                        if inner.path.is_ident("unique") {
10934                            out.index_unique = true;
10935                            return Ok(());
10936                        }
10937                        if inner.path.is_ident("name") {
10938                            let s: LitStr = inner.value()?.parse()?;
10939                            out.index_name = Some(s.value());
10940                            return Ok(());
10941                        }
10942                        if inner.path.is_ident("method") {
10943                            let s: LitStr = inner.value()?.parse()?;
10944                            let v = s.value();
10945                            match v.as_str() {
10946                                "btree" | "gin" | "gist" | "brin" | "spgist" | "hash" | "bloom" => {
10947                                    out.index_method = v;
10948                                }
10949                                other => {
10950                                    return Err(inner.error(format!(
10951                                        "unknown index method `{other}` (supported: btree, gin, gist, brin, spgist, hash, bloom)",
10952                                    )));
10953                                }
10954                            }
10955                            return Ok(());
10956                        }
10957                        Err(inner.error(
10958                            "unknown index sub-attribute (supported: `unique`, `name`, `method`)",
10959                        ))
10960                    })?;
10961                }
10962                return Ok(());
10963            }
10964            Err(meta.error("unknown rustango field attribute"))
10965        })?;
10966    }
10967    Ok(out)
10968}
10969
10970/// Parse a signed integer literal, accepting optional leading `-`.
10971fn parse_signed_i64(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<i64> {
10972    let expr: syn::Expr = meta.value()?.parse()?;
10973    match expr {
10974        syn::Expr::Lit(syn::ExprLit {
10975            lit: syn::Lit::Int(lit),
10976            ..
10977        }) => lit.base10_parse::<i64>(),
10978        syn::Expr::Unary(syn::ExprUnary {
10979            op: syn::UnOp::Neg(_),
10980            expr,
10981            ..
10982        }) => {
10983            if let syn::Expr::Lit(syn::ExprLit {
10984                lit: syn::Lit::Int(lit),
10985                ..
10986            }) = *expr
10987            {
10988                let v: i64 = lit.base10_parse()?;
10989                Ok(-v)
10990            } else {
10991                Err(syn::Error::new_spanned(expr, "expected integer literal"))
10992            }
10993        }
10994        other => Err(syn::Error::new_spanned(
10995            other,
10996            "expected integer literal (signed)",
10997        )),
10998    }
10999}
11000
11001struct FieldInfo<'a> {
11002    ident: &'a syn::Ident,
11003    column: String,
11004    primary_key: bool,
11005    /// `true` when the Rust type was `Auto<T>` — the INSERT path will
11006    /// skip this column when `Auto::Unset` and emit it under
11007    /// `RETURNING` so Postgres' sequence DEFAULT fills in the value.
11008    auto: bool,
11009    /// The original field type, e.g. `i64` or `Option<String>`. Emitted as
11010    /// the `Column::Value` associated type for typed-column tokens.
11011    value_ty: &'a Type,
11012    /// `FieldType` variant tokens (`#root::core::FieldType::I64`).
11013    field_type_tokens: TokenStream2,
11014    schema: TokenStream2,
11015    from_row_init: TokenStream2,
11016    /// Variant of [`Self::from_row_init`] that reads the column via
11017    /// `format!("{prefix}__{col}")` so a model can be decoded out of
11018    /// the aliased columns of a JOINed row. Drives slice 9.0d's
11019    /// `Self::__rustango_from_aliased_row(row, prefix)` per-Model
11020    /// helper that `select_related` calls when stitching loaded FKs.
11021    from_aliased_row_init: TokenStream2,
11022    /// Inner type from a `ForeignKey<T, K>` field, if any. The reverse-
11023    /// relation helper emit (`Author::<child>_set`) needs to know `T`
11024    /// to point the generated method at the right child model.
11025    fk_inner: Option<Type>,
11026    /// `K`'s scalar kind for a `ForeignKey<T, K>` field. Mirrors
11027    /// `kind` (since ForeignKey detection sets `kind` to K's
11028    /// underlying type) but stored separately for clarity at the
11029    /// `FkRelation` construction site, which only sees the FK's
11030    /// surface fields.
11031    fk_pk_kind: DetectedKind,
11032    /// `true` when the field is `Option<ForeignKey<T, K>>` rather than
11033    /// the bare `ForeignKey<T, K>`. Routes the load_related and
11034    /// fk_pk_access emitters to wrap assignments / accessors in
11035    /// `Some(...)` / `as_ref().map(...)` respectively, so a nullable
11036    /// FK column compiles end-to-end. The DDL writer reads this off
11037    /// the field schema (`nullable` flag); the macro just needs to
11038    /// keep the Rust-side codegen consistent.
11039    nullable: bool,
11040    /// `true` when this column was marked `#[rustango(auto_now)]` —
11041    /// `update_on` / `save_on` bind `chrono::Utc::now()` for this
11042    /// column instead of the user-supplied value, so `updated_at`
11043    /// always reflects the latest write without the caller having
11044    /// to remember to set it.
11045    auto_now: bool,
11046    /// `true` when this column was marked `#[rustango(auto_now_add)]`
11047    /// — the column is server-set on INSERT (DB DEFAULT) and
11048    /// **immutable** afterwards. `update_on` / `save_on` skip the
11049    /// column entirely so a stale `created_at` value in memory never
11050    /// rewrites the persisted timestamp.
11051    auto_now_add: bool,
11052    /// `true` when this column was marked `#[rustango(soft_delete)]`.
11053    /// Triggers emission of `soft_delete_on(executor)` and
11054    /// `restore_on(executor)` on the model's inherent impl. There is
11055    /// at most one such column per model — emission asserts this.
11056    soft_delete: bool,
11057    /// `Some` when this column was marked
11058    /// `#[rustango(generated_as = "EXPR")]`. The macro skips it from
11059    /// every INSERT and UPDATE path; the database recomputes the
11060    /// value from `EXPR`. Backlog item #35.
11061    generated_as: Option<String>,
11062    /// `true` when this column was marked
11063    /// `#[rustango(default_uuid_v7)]`. Routes `collect_fields` to
11064    /// emit an `insert_push` that auto-fills an `Auto::Unset` value
11065    /// with `Uuid::now_v7()` before binding, so the PK is generated
11066    /// Rust-side and the column is always present in the INSERT
11067    /// statement (no DB DEFAULT requirement). Issue #823.
11068    default_uuid_v7: bool,
11069    /// `Some` when this FK field carried `#[rustango(related_name =
11070    /// "...")]`. Threaded into [`FkRelation::related_name`] and
11071    /// consumed by [`reverse_helper_tokens`] to override the default
11072    /// `<child_snake>_set` accessor name. Follow-up to #816.
11073    related_name: Option<String>,
11074}
11075
11076/// Reject table names that won't survive SQL identifier
11077/// derivation downstream. Postgres' regular-identifier rule
11078/// (`[a-zA-Z_][a-zA-Z0-9_]*`) is the safe shape: it round-trips
11079/// through the framework's unquoted FK / index / constraint name
11080/// emission without surprises. We also disallow leading-digit and
11081/// the empty string for clarity.
11082///
11083/// Reserved-word collisions (`select`, `from`, …) aren't flagged
11084/// here — those produce a runtime error from the SQL parser,
11085/// which is loud enough; statically enumerating reserved words
11086/// across the three supported dialects is more friction than help.
11087///
11088/// Backlog item #65.
11089fn validate_table_name(name: &str, span: proc_macro2::Span) -> syn::Result<()> {
11090    validate_sql_identifier(name, "table", span)
11091}
11092
11093/// Reject SQL identifiers that compile but break downstream SQL
11094/// generation. Same rule for tables and columns: `[a-zA-Z_][a-zA-Z0-9_]*`.
11095/// `kind` is "table" / "column" — used for the error message so users
11096/// see which attribute caused the failure.
11097fn validate_sql_identifier(name: &str, kind: &str, span: proc_macro2::Span) -> syn::Result<()> {
11098    if name.is_empty() {
11099        return Err(syn::Error::new(
11100            span,
11101            format!("`{kind} = \"\"` is not a valid SQL identifier"),
11102        ));
11103    }
11104    let mut chars = name.chars();
11105    let first = chars.next().unwrap();
11106    if !(first.is_ascii_alphabetic() || first == '_') {
11107        return Err(syn::Error::new(
11108            span,
11109            format!("{kind} name `{name}` must start with a letter or underscore (got {first:?})"),
11110        ));
11111    }
11112    for c in chars {
11113        if !(c.is_ascii_alphanumeric() || c == '_') {
11114            return Err(syn::Error::new(
11115                span,
11116                format!(
11117                    "{kind} name `{name}` contains invalid character {c:?} — \
11118                     SQL identifiers must match `[a-zA-Z_][a-zA-Z0-9_]*`. \
11119                     Hyphens in particular break FK / index name derivation \
11120                     downstream; use underscores instead (e.g. `{}`)",
11121                    name.replace(|x: char| !x.is_ascii_alphanumeric() && x != '_', "_"),
11122                ),
11123            ));
11124        }
11125    }
11126    Ok(())
11127}
11128
11129fn process_field<'a>(field: &'a syn::Field, table: &str) -> syn::Result<FieldInfo<'a>> {
11130    let root = rustango_root();
11131    let attrs = parse_field_attrs(field)?;
11132    let ident = field
11133        .ident
11134        .as_ref()
11135        .ok_or_else(|| syn::Error::new(field.span(), "tuple structs are not supported"))?;
11136    let name = ident.to_string();
11137    let column = attrs.column.clone().unwrap_or_else(|| name.clone());
11138    let primary_key = attrs.primary_key;
11139    let DetectedType {
11140        kind,
11141        nullable,
11142        auto: detected_auto,
11143        fk_inner,
11144    } = detect_type(&field.ty)?;
11145    check_bound_compatibility(field, &attrs, kind)?;
11146    let auto = detected_auto;
11147    // Mixin attributes piggyback on the existing `Auto<T>` skip-on-
11148    // INSERT path: the user must wrap the field in `Auto<T>`, which
11149    // marks the column as DB-default-supplied. The mixin attrs then
11150    // layer in the SQL default (`now()` / `gen_random_uuid()`) and,
11151    // for `auto_now`, force the value on UPDATE too.
11152    if attrs.auto_uuid {
11153        if kind != DetectedKind::Uuid {
11154            return Err(syn::Error::new_spanned(
11155                field,
11156                "`#[rustango(auto_uuid)]` requires the field type to be \
11157                 `Auto<uuid::Uuid>`",
11158            ));
11159        }
11160        if !detected_auto {
11161            return Err(syn::Error::new_spanned(
11162                field,
11163                "`#[rustango(auto_uuid)]` requires the field type to be \
11164                 wrapped in `Auto<...>` so the macro skips the column on \
11165                 INSERT and the DB DEFAULT (`gen_random_uuid()`) fires",
11166            ));
11167        }
11168    }
11169    if attrs.default_uuid_v7 {
11170        if kind != DetectedKind::Uuid {
11171            return Err(syn::Error::new_spanned(
11172                field,
11173                "`#[rustango(default_uuid_v7)]` requires the field type to be \
11174                 `Auto<uuid::Uuid>`",
11175            ));
11176        }
11177        if !detected_auto {
11178            return Err(syn::Error::new_spanned(
11179                field,
11180                "`#[rustango(default_uuid_v7)]` requires the field type to be \
11181                 wrapped in `Auto<...>` so the macro can detect the \
11182                 unset-vs-set state and fill a fresh UUIDv7 before INSERT",
11183            ));
11184        }
11185        if attrs.auto_uuid {
11186            return Err(syn::Error::new_spanned(
11187                field,
11188                "`#[rustango(default_uuid_v7)]` is mutually exclusive with \
11189                 `#[rustango(auto_uuid)]` — the former generates the UUID \
11190                 Rust-side, the latter relies on the DB's `gen_random_uuid()`. \
11191                 Pick one.",
11192            ));
11193        }
11194    }
11195    if attrs.auto_now_add || attrs.auto_now {
11196        if kind != DetectedKind::DateTime {
11197            return Err(syn::Error::new_spanned(
11198                field,
11199                "`#[rustango(auto_now_add)]` / `#[rustango(auto_now)]` require \
11200                 the field type to be `Auto<chrono::DateTime<chrono::Utc>>`",
11201            ));
11202        }
11203        if !detected_auto {
11204            return Err(syn::Error::new_spanned(
11205                field,
11206                "`#[rustango(auto_now_add)]` / `#[rustango(auto_now)]` require \
11207                 the field type to be wrapped in `Auto<...>` so the macro skips \
11208                 the column on INSERT and the DB DEFAULT (`now()`) fires",
11209            ));
11210        }
11211    }
11212    if attrs.soft_delete && !(kind == DetectedKind::DateTime && nullable) {
11213        return Err(syn::Error::new_spanned(
11214            field,
11215            "`#[rustango(soft_delete)]` requires the field type to be \
11216             `Option<chrono::DateTime<chrono::Utc>>`",
11217        ));
11218    }
11219    let is_mixin_auto =
11220        attrs.auto_uuid || attrs.default_uuid_v7 || attrs.auto_now_add || attrs.auto_now;
11221    if detected_auto && !primary_key && !is_mixin_auto {
11222        return Err(syn::Error::new_spanned(
11223            field,
11224            "`Auto<T>` is only valid on a `#[rustango(primary_key)]` field, \
11225             or on a field carrying one of `auto_uuid`, `auto_now_add`, or \
11226             `auto_now`",
11227        ));
11228    }
11229    if detected_auto && attrs.default.is_some() && !is_mixin_auto {
11230        return Err(syn::Error::new_spanned(
11231            field,
11232            "`#[rustango(default = \"…\")]` is redundant on an `Auto<T>` field — \
11233             SERIAL / BIGSERIAL already supplies a default sequence.",
11234        ));
11235    }
11236    if fk_inner.is_some() && primary_key {
11237        return Err(syn::Error::new_spanned(
11238            field,
11239            "`ForeignKey<T>` is not allowed on a primary-key field — \
11240             a row's PK is its own identity, not a reference to a parent.",
11241        ));
11242    }
11243    if attrs.generated_as.is_some() {
11244        if primary_key {
11245            return Err(syn::Error::new_spanned(
11246                field,
11247                "`#[rustango(generated_as = \"…\")]` is not allowed on a \
11248                 primary-key field — a PK must be writable so the row \
11249                 has an identity at INSERT time.",
11250            ));
11251        }
11252        if attrs.default.is_some() {
11253            return Err(syn::Error::new_spanned(
11254                field,
11255                "`#[rustango(generated_as = \"…\")]` cannot combine with \
11256                 `default = \"…\"` — Postgres rejects DEFAULT on \
11257                 generated columns. The expression IS the default.",
11258            ));
11259        }
11260        if detected_auto {
11261            return Err(syn::Error::new_spanned(
11262                field,
11263                "`#[rustango(generated_as = \"…\")]` is not allowed on \
11264                 an `Auto<T>` field — generated columns are computed \
11265                 by the DB, not server-assigned via a sequence. Use a \
11266                 plain Rust type (e.g. `f64`).",
11267            ));
11268        }
11269        if fk_inner.is_some() {
11270            return Err(syn::Error::new_spanned(
11271                field,
11272                "`#[rustango(generated_as = \"…\")]` is not allowed on a \
11273                 ForeignKey field.",
11274            ));
11275        }
11276    }
11277    let relation = relation_tokens(field, &attrs, fk_inner, table)?;
11278    let column_lit = column.as_str();
11279    // pgvector (#824): the `vector(dims = N)` attribute supplies the
11280    // dimension that the bare `Vector` Rust type can't carry, so emit
11281    // `FieldType::Vector(N)` here rather than the `variant_tokens`
11282    // fallback of `Vector(0)`.
11283    let field_type_tokens = if kind == DetectedKind::Vector {
11284        let root = rustango_root();
11285        let dims = attrs.vector_dims.unwrap_or(0);
11286        quote!(#root::core::FieldType::Vector(#dims))
11287    } else if kind == DetectedKind::Geometry {
11288        // PostGIS (#443): the `geometry(srid = N)` attribute supplies the
11289        // SRID that the bare `Point` Rust type can't carry, so emit
11290        // `FieldType::Geometry(N)` rather than the `Geometry(0)` fallback.
11291        let root = rustango_root();
11292        let srid = attrs.geometry_srid.unwrap_or(0);
11293        quote!(#root::core::FieldType::Geometry(#srid))
11294    } else {
11295        kind.variant_tokens()
11296    };
11297    let max_length = optional_u32(attrs.max_length);
11298    let min = optional_i64(attrs.min);
11299    let max = optional_i64(attrs.max);
11300    let default = optional_str(attrs.default.as_deref());
11301
11302    let unique = attrs.unique;
11303    let generated_as = optional_str(attrs.generated_as.as_deref());
11304    let help_text = optional_str(attrs.help_text.as_deref());
11305    let choices = optional_choices(attrs.choices.as_deref());
11306    let db_comment = optional_str(attrs.db_comment.as_deref());
11307    let verbose_name = optional_str(attrs.verbose_name.as_deref());
11308    let editable = attrs.editable;
11309    let blank = attrs.blank;
11310    let case_insensitive = attrs.case_insensitive;
11311    let validators_lits: Vec<&str> = attrs.validators.iter().map(String::as_str).collect();
11312    if attrs.on_delete.is_some() && attrs.fk.is_none() && attrs.o2o.is_none() {
11313        return Err(syn::Error::new_spanned(
11314            field,
11315            "`#[rustango(on_delete = \"…\")]` requires either `fk = \"<table>\"` \
11316             or `o2o = \"<table>\"` on the same field — it has no meaning on a \
11317             non-FK column.",
11318        ));
11319    }
11320    let fk_on_delete = match attrs.on_delete.as_deref() {
11321        None => quote!(::core::option::Option::None),
11322        Some(action) => {
11323            let variant = match action {
11324                "cascade" => quote!(Cascade),
11325                "restrict" => quote!(Restrict),
11326                "set_null" => quote!(SetNull),
11327                "set_default" => quote!(SetDefault),
11328                "no_action" => quote!(NoAction),
11329                // parse_field_attrs already validated this — guard against future drift.
11330                other => unreachable!("on_delete `{other}` should have been rejected at parse"),
11331            };
11332            quote!(::core::option::Option::Some(
11333                #root::core::OnDeleteAction::#variant
11334            ))
11335        }
11336    };
11337    let schema = quote! {
11338        #root::core::FieldSchema {
11339            name: #name,
11340            column: #column_lit,
11341            ty: #field_type_tokens,
11342            nullable: #nullable,
11343            primary_key: #primary_key,
11344            relation: #relation,
11345            max_length: #max_length,
11346            min: #min,
11347            max: #max,
11348            default: #default,
11349            auto: #auto,
11350            unique: #unique,
11351            generated_as: #generated_as,
11352            help_text: #help_text,
11353            choices: #choices,
11354            db_comment: #db_comment,
11355            verbose_name: #verbose_name,
11356            editable: #editable,
11357            blank: #blank,
11358            case_insensitive: #case_insensitive,
11359            fk_on_delete: #fk_on_delete,
11360            validators: &[ #(#validators_lits),* ],
11361        }
11362    };
11363
11364    let from_row_init = quote! {
11365        #ident: #root::sql::sqlx::Row::try_get(row, #column_lit)?
11366    };
11367    let from_aliased_row_init = quote! {
11368        #ident: #root::sql::sqlx::Row::try_get(
11369            row,
11370            ::std::format!("{}__{}", prefix, #column_lit).as_str(),
11371        )?
11372    };
11373
11374    Ok(FieldInfo {
11375        ident,
11376        column,
11377        primary_key,
11378        auto,
11379        value_ty: &field.ty,
11380        field_type_tokens,
11381        schema,
11382        from_row_init,
11383        from_aliased_row_init,
11384        fk_inner: fk_inner.cloned(),
11385        fk_pk_kind: kind,
11386        nullable,
11387        auto_now: attrs.auto_now,
11388        auto_now_add: attrs.auto_now_add,
11389        soft_delete: attrs.soft_delete,
11390        generated_as: attrs.generated_as.clone(),
11391        default_uuid_v7: attrs.default_uuid_v7,
11392        related_name: attrs.related_name.clone(),
11393    })
11394}
11395
11396fn check_bound_compatibility(
11397    field: &syn::Field,
11398    attrs: &FieldAttrs,
11399    kind: DetectedKind,
11400) -> syn::Result<()> {
11401    if attrs.max_length.is_some() && kind != DetectedKind::String {
11402        return Err(syn::Error::new_spanned(
11403            field,
11404            "`max_length` is only valid on `String` fields (or `Option<String>`)",
11405        ));
11406    }
11407    if attrs.choices.is_some() && kind != DetectedKind::String {
11408        return Err(syn::Error::new_spanned(
11409            field,
11410            "`choices` is only valid on `String` fields (or `Option<String>`) — \
11411             integer-valued enumerations should be modeled with a Rust enum and \
11412             custom (de)serializer for now",
11413        ));
11414    }
11415    if (attrs.min.is_some() || attrs.max.is_some()) && !kind.is_integer() {
11416        return Err(syn::Error::new_spanned(
11417            field,
11418            "`min` / `max` are only valid on integer fields (`i32`, `i64`, optionally Option-wrapped)",
11419        ));
11420    }
11421    if let (Some(min), Some(max)) = (attrs.min, attrs.max) {
11422        if min > max {
11423            return Err(syn::Error::new_spanned(
11424                field,
11425                format!("`min` ({min}) is greater than `max` ({max})"),
11426            ));
11427        }
11428    }
11429    Ok(())
11430}
11431
11432fn optional_u32(value: Option<u32>) -> TokenStream2 {
11433    if let Some(v) = value {
11434        quote!(::core::option::Option::Some(#v))
11435    } else {
11436        quote!(::core::option::Option::None)
11437    }
11438}
11439
11440fn optional_i64(value: Option<i64>) -> TokenStream2 {
11441    if let Some(v) = value {
11442        quote!(::core::option::Option::Some(#v))
11443    } else {
11444        quote!(::core::option::Option::None)
11445    }
11446}
11447
11448fn optional_str(value: Option<&str>) -> TokenStream2 {
11449    if let Some(v) = value {
11450        quote!(::core::option::Option::Some(#v))
11451    } else {
11452        quote!(::core::option::Option::None)
11453    }
11454}
11455
11456fn optional_choices(pairs: Option<&[(String, String)]>) -> TokenStream2 {
11457    let Some(pairs) = pairs else {
11458        return quote!(::core::option::Option::None);
11459    };
11460    let entries = pairs.iter().map(|(v, l)| quote!((#v, #l)));
11461    quote!(::core::option::Option::Some(&[#(#entries),*]))
11462}
11463
11464fn relation_tokens(
11465    field: &syn::Field,
11466    attrs: &FieldAttrs,
11467    fk_inner: Option<&syn::Type>,
11468    table: &str,
11469) -> syn::Result<TokenStream2> {
11470    let root = rustango_root();
11471    if let Some(inner) = fk_inner {
11472        if attrs.fk.is_some() || attrs.o2o.is_some() {
11473            return Err(syn::Error::new_spanned(
11474                field,
11475                "`ForeignKey<T>` already declares the FK target via the type parameter — \
11476                 remove the `fk = \"…\"` / `o2o = \"…\"` attribute.",
11477            ));
11478        }
11479        let on = attrs.on.as_deref().unwrap_or("id");
11480        return Ok(quote! {
11481            ::core::option::Option::Some(#root::core::Relation::Fk {
11482                to: <#inner as #root::core::Model>::SCHEMA.table,
11483                on: #on,
11484            })
11485        });
11486    }
11487    match (&attrs.fk, &attrs.o2o) {
11488        (Some(_), Some(_)) => Err(syn::Error::new_spanned(
11489            field,
11490            "`fk` and `o2o` are mutually exclusive",
11491        )),
11492        (Some(to), None) => {
11493            let on = attrs.on.as_deref().unwrap_or("id");
11494            // Self-FK sentinel — `#[rustango(fk = "self")]` resolves to
11495            // the model's own table. Threaded as a literal string at
11496            // macro-expansion time to sidestep the const-eval cycle
11497            // that `Self::SCHEMA.table` would create when referenced
11498            // inside Self::SCHEMA's own initializer.
11499            let resolved = if to == "self" { table } else { to };
11500            Ok(quote! {
11501                ::core::option::Option::Some(#root::core::Relation::Fk { to: #resolved, on: #on })
11502            })
11503        }
11504        (None, Some(to)) => {
11505            let on = attrs.on.as_deref().unwrap_or("id");
11506            let resolved = if to == "self" { table } else { to };
11507            Ok(quote! {
11508                ::core::option::Option::Some(#root::core::Relation::O2O { to: #resolved, on: #on })
11509            })
11510        }
11511        (None, None) => {
11512            if attrs.on.is_some() {
11513                return Err(syn::Error::new_spanned(
11514                    field,
11515                    "`on` requires `fk` or `o2o`",
11516                ));
11517            }
11518            Ok(quote!(::core::option::Option::None))
11519        }
11520    }
11521}
11522
11523/// Mirrors `rustango_core::FieldType`. Local copy so the macro can reason
11524/// about kinds without depending on `rustango-core` (which would require a
11525/// proc-macro/normal split it doesn't have today).
11526#[derive(Clone, Copy, PartialEq, Eq)]
11527enum DetectedKind {
11528    I16,
11529    I32,
11530    I64,
11531    F32,
11532    F64,
11533    Bool,
11534    String,
11535    DateTime,
11536    Date,
11537    Time,
11538    Uuid,
11539    Json,
11540    Decimal,
11541    Binary,
11542    /// `Array<String>` → PG `text[]` (#341).
11543    ArrayText,
11544    /// `Array<i32>` → PG `integer[]` (#341).
11545    ArrayInt,
11546    /// `Array<i64>` → PG `bigint[]` (#341).
11547    ArrayBigInt,
11548    /// `Range<i32>` → PG `int4range` (#343).
11549    RangeInt,
11550    /// `Range<i64>` → PG `int8range` (#343).
11551    RangeBigInt,
11552    /// `Range<Decimal>` → PG `numrange` (#343).
11553    RangeNumeric,
11554    /// `Range<NaiveDate>` → PG `daterange` (#343).
11555    RangeDate,
11556    /// `Range<DateTime<Utc>>` → PG `tstzrange` (#343).
11557    RangeDateTime,
11558    /// `HStore` → PG `hstore` (#342).
11559    HStore,
11560    /// `Vector` → pgvector `vector(N)` (#824). The dimension `N` comes
11561    /// from the `#[rustango(vector(dims = N))]` field attribute, threaded
11562    /// in at the `FieldType` emission site (not carried on this enum).
11563    Vector,
11564    /// `Point` → PostGIS `geometry(Point, srid)` (#443). The SRID comes
11565    /// from the `#[rustango(geometry(srid = N))]` field attribute,
11566    /// threaded in at the `FieldType` emission site.
11567    Geometry,
11568}
11569
11570impl DetectedKind {
11571    fn variant_tokens(self) -> TokenStream2 {
11572        let root = rustango_root();
11573        match self {
11574            Self::I16 => quote!(#root::core::FieldType::I16),
11575            Self::I32 => quote!(#root::core::FieldType::I32),
11576            Self::I64 => quote!(#root::core::FieldType::I64),
11577            Self::F32 => quote!(#root::core::FieldType::F32),
11578            Self::F64 => quote!(#root::core::FieldType::F64),
11579            Self::Bool => quote!(#root::core::FieldType::Bool),
11580            Self::String => quote!(#root::core::FieldType::String),
11581            Self::DateTime => quote!(#root::core::FieldType::DateTime),
11582            Self::Date => quote!(#root::core::FieldType::Date),
11583            Self::Time => quote!(#root::core::FieldType::Time),
11584            Self::Uuid => quote!(#root::core::FieldType::Uuid),
11585            Self::Json => quote!(#root::core::FieldType::Json),
11586            Self::Decimal => quote!(#root::core::FieldType::Decimal),
11587            Self::Binary => quote!(#root::core::FieldType::Binary),
11588            Self::ArrayText => {
11589                quote!(#root::core::FieldType::Array(#root::core::ArrayElem::Text))
11590            }
11591            Self::ArrayInt => {
11592                quote!(#root::core::FieldType::Array(#root::core::ArrayElem::Int))
11593            }
11594            Self::ArrayBigInt => {
11595                quote!(#root::core::FieldType::Array(#root::core::ArrayElem::BigInt))
11596            }
11597            Self::RangeInt => {
11598                quote!(#root::core::FieldType::Range(#root::core::RangeElem::Int))
11599            }
11600            Self::RangeBigInt => {
11601                quote!(#root::core::FieldType::Range(#root::core::RangeElem::BigInt))
11602            }
11603            Self::RangeNumeric => {
11604                quote!(#root::core::FieldType::Range(#root::core::RangeElem::Numeric))
11605            }
11606            Self::RangeDate => {
11607                quote!(#root::core::FieldType::Range(#root::core::RangeElem::Date))
11608            }
11609            Self::RangeDateTime => {
11610                quote!(#root::core::FieldType::Range(#root::core::RangeElem::DateTime))
11611            }
11612            Self::HStore => quote!(#root::core::FieldType::HStore),
11613            // Dimension comes from the `vector(dims = N)` attribute,
11614            // applied at the emission site; `0` here is just a fallback.
11615            Self::Vector => quote!(#root::core::FieldType::Vector(0)),
11616            // SRID comes from the `geometry(srid = N)` attribute, applied
11617            // at the emission site; `0` here is just a fallback.
11618            Self::Geometry => quote!(#root::core::FieldType::Geometry(0)),
11619        }
11620    }
11621
11622    fn is_integer(self) -> bool {
11623        matches!(self, Self::I16 | Self::I32 | Self::I64)
11624    }
11625
11626    /// `(SqlValue::<Variant>, default expr)` for emitting the
11627    /// `match SqlValue { … }` arm in `LoadRelated::__rustango_load_related`
11628    /// for a `ForeignKey<T, K>` FK whose K maps to `self`. The default
11629    /// fires only when the parent's `__rustango_pk_value` returns a
11630    /// different variant than expected, which is a compile-time bug —
11631    /// but we still need a value-typed fallback to keep the match
11632    /// total.
11633    fn sqlvalue_match_arm(self) -> (TokenStream2, TokenStream2) {
11634        let root = rustango_root();
11635        match self {
11636            Self::I16 => (quote!(I16), quote!(0i16)),
11637            Self::I32 => (quote!(I32), quote!(0i32)),
11638            Self::I64 => (quote!(I64), quote!(0i64)),
11639            Self::F32 => (quote!(F32), quote!(0f32)),
11640            Self::F64 => (quote!(F64), quote!(0f64)),
11641            Self::Bool => (quote!(Bool), quote!(false)),
11642            Self::String => (quote!(String), quote!(::std::string::String::new())),
11643            Self::DateTime => (
11644                quote!(DateTime),
11645                quote!(<#root::__chrono::DateTime<#root::__chrono::Utc> as ::std::default::Default>::default()),
11646            ),
11647            Self::Date => (
11648                quote!(Date),
11649                quote!(<#root::__chrono::NaiveDate as ::std::default::Default>::default()),
11650            ),
11651            Self::Time => (
11652                quote!(Time),
11653                quote!(<#root::__chrono::NaiveTime as ::std::default::Default>::default()),
11654            ),
11655            Self::Uuid => (quote!(Uuid), quote!(#root::__uuid::Uuid::nil())),
11656            Self::Json => (quote!(Json), quote!(#root::__serde_json::Value::Null)),
11657            Self::Decimal => (
11658                quote!(Decimal),
11659                quote!(<#root::__rust_decimal::Decimal as ::std::default::Default>::default()),
11660            ),
11661            Self::Binary => (quote!(Binary), quote!(::std::vec::Vec::<u8>::new())),
11662            // Arrays (#341) can never be a foreign-key primary key, so
11663            // this arm is never reached at runtime — but the match must
11664            // stay total. A bare empty `SqlValue::Array` is the dummy.
11665            Self::ArrayText | Self::ArrayInt | Self::ArrayBigInt => {
11666                (quote!(Array), quote!(::std::vec::Vec::new()))
11667            }
11668            // Ranges (#343) likewise can't be a FK PK — never reached.
11669            Self::RangeInt
11670            | Self::RangeBigInt
11671            | Self::RangeNumeric
11672            | Self::RangeDate
11673            | Self::RangeDateTime => (quote!(RangeLiteral), quote!(::std::string::String::new())),
11674            // HStore (#342) can't be a FK PK — never reached.
11675            Self::HStore => (quote!(HStore), quote!(::std::vec::Vec::new())),
11676            // Vector (#824) can't be a FK PK — never reached.
11677            Self::Vector => (quote!(Vector), quote!(::std::vec::Vec::new())),
11678            // Geometry (#443) can't be a FK PK — never reached (arm is
11679            // exhaustiveness-only; never interpolated into emitted code).
11680            Self::Geometry => (quote!(Geometry), quote!(::std::vec::Vec::new())),
11681        }
11682    }
11683}
11684
11685/// Result of walking a field's Rust type. `kind` is the underlying
11686/// `FieldType`; `nullable` is set by an outer `Option<T>`; `auto` is
11687/// set by an outer `Auto<T>` (server-assigned PK); `fk_inner` is
11688/// `Some(<T>)` when the field was `ForeignKey<T>` (or
11689/// `Option<ForeignKey<T>>`), letting the codegen reach `T::SCHEMA`.
11690#[derive(Clone, Copy)]
11691struct DetectedType<'a> {
11692    kind: DetectedKind,
11693    nullable: bool,
11694    auto: bool,
11695    fk_inner: Option<&'a syn::Type>,
11696}
11697
11698/// Extract the `T` from a `…::Auto<T>` field type. Returns `None` for
11699/// non-`Auto` types — the caller should already have routed Auto-only
11700/// codegen through this helper, so a `None` indicates a macro-internal
11701/// invariant break.
11702fn auto_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
11703    let Type::Path(TypePath { path, qself: None }) = ty else {
11704        return None;
11705    };
11706    let last = path.segments.last()?;
11707    if last.ident != "Auto" {
11708        return None;
11709    }
11710    let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
11711        return None;
11712    };
11713    args.args.iter().find_map(|a| match a {
11714        syn::GenericArgument::Type(t) => Some(t),
11715        _ => None,
11716    })
11717}
11718
11719fn detect_type(ty: &syn::Type) -> syn::Result<DetectedType<'_>> {
11720    let Type::Path(TypePath { path, qself: None }) = ty else {
11721        return Err(syn::Error::new_spanned(ty, "unsupported field type"));
11722    };
11723    let last = path
11724        .segments
11725        .last()
11726        .ok_or_else(|| syn::Error::new_spanned(ty, "empty type path"))?;
11727
11728    if last.ident == "Option" {
11729        let inner = generic_inner(ty, &last.arguments, "Option")?;
11730        let inner_det = detect_type(inner)?;
11731        if inner_det.nullable {
11732            return Err(syn::Error::new_spanned(
11733                ty,
11734                "nested Option is not supported",
11735            ));
11736        }
11737        if inner_det.auto {
11738            return Err(syn::Error::new_spanned(
11739                ty,
11740                "`Option<Auto<T>>` is not supported — Auto fields are server-assigned and cannot be NULL",
11741            ));
11742        }
11743        return Ok(DetectedType {
11744            nullable: true,
11745            ..inner_det
11746        });
11747    }
11748
11749    if last.ident == "Auto" {
11750        let inner = generic_inner(ty, &last.arguments, "Auto")?;
11751        let inner_det = detect_type(inner)?;
11752        if inner_det.auto {
11753            return Err(syn::Error::new_spanned(ty, "nested Auto is not supported"));
11754        }
11755        if inner_det.nullable {
11756            return Err(syn::Error::new_spanned(
11757                ty,
11758                "`Auto<Option<T>>` is not supported — Auto fields are server-assigned and cannot be NULL",
11759            ));
11760        }
11761        if inner_det.fk_inner.is_some() {
11762            return Err(syn::Error::new_spanned(
11763                ty,
11764                "`Auto<ForeignKey<T>>` is not supported — Auto is for server-assigned PKs, ForeignKey is for parent references",
11765            ));
11766        }
11767        if !matches!(
11768            inner_det.kind,
11769            DetectedKind::I32 | DetectedKind::I64 | DetectedKind::Uuid | DetectedKind::DateTime
11770        ) {
11771            return Err(syn::Error::new_spanned(
11772                ty,
11773                "`Auto<T>` only supports integers (`i32` → SERIAL, `i64` → BIGSERIAL), \
11774                 `uuid::Uuid` (DEFAULT gen_random_uuid()), or `chrono::DateTime<chrono::Utc>` \
11775                 (DEFAULT now())",
11776            ));
11777        }
11778        return Ok(DetectedType {
11779            auto: true,
11780            ..inner_det
11781        });
11782    }
11783
11784    if last.ident == "ForeignKey" {
11785        let (inner, key_ty) = generic_pair(ty, &last.arguments, "ForeignKey")?;
11786        // Resolve the FK column's underlying SQL type from `K`. When the
11787        // user wrote `ForeignKey<T>` without a key parameter, the type
11788        // alias defaults to `i64` and we keep the v0.7 BIGINT shape.
11789        // When the user wrote `ForeignKey<T, K>` with an explicit `K`,
11790        // recurse into K so the column DDL emits the right SQL type
11791        // (VARCHAR for String, UUID for Uuid, …) and the load_related
11792        // emitter knows which `SqlValue` variant to match.
11793        let kind = match key_ty {
11794            Some(k) => detect_type(k)?.kind,
11795            None => DetectedKind::I64,
11796        };
11797        return Ok(DetectedType {
11798            kind,
11799            nullable: false,
11800            auto: false,
11801            fk_inner: Some(inner),
11802        });
11803    }
11804
11805    let kind = match last.ident.to_string().as_str() {
11806        "i16" => DetectedKind::I16,
11807        "i32" => DetectedKind::I32,
11808        "i64" => DetectedKind::I64,
11809        "f32" => DetectedKind::F32,
11810        "f64" => DetectedKind::F64,
11811        "bool" => DetectedKind::Bool,
11812        "String" => DetectedKind::String,
11813        "DateTime" => DetectedKind::DateTime,
11814        "NaiveDate" => DetectedKind::Date,
11815        "NaiveTime" => DetectedKind::Time,
11816        "Uuid" => DetectedKind::Uuid,
11817        "Value" => DetectedKind::Json,
11818        "Decimal" => DetectedKind::Decimal,
11819        // `Vec<u8>` → BYTEA / LONGBLOB / BLOB. Reject any other
11820        // `Vec<T>` so we don't silently accept e.g. `Vec<String>`
11821        // — that would emit Binary DDL and decode-fail at runtime.
11822        "Vec" => {
11823            let (inner, _) = generic_pair(ty, &last.arguments, "Vec")?;
11824            if let Type::Path(TypePath { path, qself: None }) = inner {
11825                if let Some(seg) = path.segments.last() {
11826                    if seg.ident == "u8" && seg.arguments.is_empty() {
11827                        return Ok(DetectedType {
11828                            kind: DetectedKind::Binary,
11829                            nullable: false,
11830                            auto: false,
11831                            fk_inner: None,
11832                        });
11833                    }
11834                }
11835            }
11836            return Err(syn::Error::new_spanned(
11837                ty,
11838                "unsupported `Vec<T>` field — only `Vec<u8>` (→ Binary) is supported; \
11839                 for a PostgreSQL array column use `Array<String>` / `Array<i32>` / `Array<i64>`",
11840            ));
11841        }
11842        // `Array<String>` / `Array<i32>` / `Array<i64>` → PG `text[]` /
11843        // `integer[]` / `bigint[]` (#341).
11844        "Array" => {
11845            let (inner, _) = generic_pair(ty, &last.arguments, "Array")?;
11846            let elem = match inner {
11847                Type::Path(TypePath { path, qself: None }) => {
11848                    path.segments.last().map(|s| s.ident.to_string())
11849                }
11850                _ => None,
11851            };
11852            let kind = match elem.as_deref() {
11853                Some("String") => DetectedKind::ArrayText,
11854                Some("i32") => DetectedKind::ArrayInt,
11855                Some("i64") => DetectedKind::ArrayBigInt,
11856                _ => {
11857                    return Err(syn::Error::new_spanned(
11858                        ty,
11859                        "unsupported `Array<T>` element — only `Array<String>` (→ text[]), \
11860                         `Array<i32>` (→ integer[]), and `Array<i64>` (→ bigint[]) are supported (#341)",
11861                    ));
11862                }
11863            };
11864            return Ok(DetectedType {
11865                kind,
11866                nullable: false,
11867                auto: false,
11868                fk_inner: None,
11869            });
11870        }
11871        // `Range<i32>` / `Range<i64>` / `Range<Decimal>` /
11872        // `Range<NaiveDate>` / `Range<DateTime<…>>` → PG `int4range` /
11873        // `int8range` / `numrange` / `daterange` / `tstzrange` (#343).
11874        "Range" => {
11875            let (inner, _) = generic_pair(ty, &last.arguments, "Range")?;
11876            let elem = match inner {
11877                Type::Path(TypePath { path, qself: None }) => {
11878                    path.segments.last().map(|s| s.ident.to_string())
11879                }
11880                _ => None,
11881            };
11882            let kind = match elem.as_deref() {
11883                Some("i32") => DetectedKind::RangeInt,
11884                Some("i64") => DetectedKind::RangeBigInt,
11885                Some("Decimal") => DetectedKind::RangeNumeric,
11886                Some("NaiveDate") => DetectedKind::RangeDate,
11887                Some("DateTime") => DetectedKind::RangeDateTime,
11888                _ => {
11889                    return Err(syn::Error::new_spanned(
11890                        ty,
11891                        "unsupported `Range<T>` element — only `Range<i32>` (→ int4range), \
11892                         `Range<i64>` (→ int8range), `Range<Decimal>` (→ numrange), \
11893                         `Range<NaiveDate>` (→ daterange), and `Range<DateTime<Utc>>` \
11894                         (→ tstzrange) are supported (#343)",
11895                    ));
11896                }
11897            };
11898            return Ok(DetectedType {
11899                kind,
11900                nullable: false,
11901                auto: false,
11902                fk_inner: None,
11903            });
11904        }
11905        // `Cast<C>` → attribute cast (#819). The column is plain `TEXT`
11906        // (the `CastValue` impl bridges logical↔stored); the field's own
11907        // sqlx `Decode` / `Into<SqlValue>` handle the transform, so the
11908        // schema just needs `FieldType::String`.
11909        "Cast" => {
11910            return Ok(DetectedType {
11911                kind: DetectedKind::String,
11912                nullable: false,
11913                auto: false,
11914                fk_inner: None,
11915            });
11916        }
11917        // `HStore` → PG `hstore` (#342). No generic
11918        // parameter — always a string→string map.
11919        "HStore" => {
11920            return Ok(DetectedType {
11921                kind: DetectedKind::HStore,
11922                nullable: false,
11923                auto: false,
11924                fk_inner: None,
11925            });
11926        }
11927        // `Vector` → pgvector `vector(N)` (#824). The dimension is
11928        // supplied by `#[rustango(vector(dims = N))]`, not the type.
11929        "Vector" => {
11930            return Ok(DetectedType {
11931                kind: DetectedKind::Vector,
11932                nullable: false,
11933                auto: false,
11934                fk_inner: None,
11935            });
11936        }
11937        // `Point` → PostGIS `geometry(Point, srid)` (#443). The SRID is
11938        // supplied by `#[rustango(geometry(srid = N))]`, not the type.
11939        "Point" => {
11940            return Ok(DetectedType {
11941                kind: DetectedKind::Geometry,
11942                nullable: false,
11943                auto: false,
11944                fk_inner: None,
11945            });
11946        }
11947        other => {
11948            return Err(syn::Error::new_spanned(
11949                ty,
11950                format!("unsupported field type `{other}`; supports i16/i32/i64/f32/f64/bool/String/DateTime/NaiveDate/NaiveTime/Uuid/serde_json::Value/Decimal/Vec<u8>, optionally wrapped in Option or Auto (Auto only on integers/Uuid/DateTime)"),
11951            ));
11952        }
11953    };
11954    Ok(DetectedType {
11955        kind,
11956        nullable: false,
11957        auto: false,
11958        fk_inner: None,
11959    })
11960}
11961
11962fn generic_inner<'a>(
11963    ty: &'a Type,
11964    arguments: &'a PathArguments,
11965    wrapper: &str,
11966) -> syn::Result<&'a Type> {
11967    let PathArguments::AngleBracketed(args) = arguments else {
11968        return Err(syn::Error::new_spanned(
11969            ty,
11970            format!("{wrapper} requires a generic argument"),
11971        ));
11972    };
11973    args.args
11974        .iter()
11975        .find_map(|a| match a {
11976            GenericArgument::Type(t) => Some(t),
11977            _ => None,
11978        })
11979        .ok_or_else(|| {
11980            syn::Error::new_spanned(ty, format!("{wrapper}<T> requires a type argument"))
11981        })
11982}
11983
11984/// Like [`generic_inner`] but pulls *two* type args — the first is
11985/// required, the second is optional. Used by the `ForeignKey<T, K>`
11986/// detection where K defaults to `i64` when omitted.
11987fn generic_pair<'a>(
11988    ty: &'a Type,
11989    arguments: &'a PathArguments,
11990    wrapper: &str,
11991) -> syn::Result<(&'a Type, Option<&'a Type>)> {
11992    let PathArguments::AngleBracketed(args) = arguments else {
11993        return Err(syn::Error::new_spanned(
11994            ty,
11995            format!("{wrapper} requires a generic argument"),
11996        ));
11997    };
11998    let mut types = args.args.iter().filter_map(|a| match a {
11999        GenericArgument::Type(t) => Some(t),
12000        _ => None,
12001    });
12002    let first = types.next().ok_or_else(|| {
12003        syn::Error::new_spanned(ty, format!("{wrapper}<T> requires a type argument"))
12004    })?;
12005    let second = types.next();
12006    Ok((first, second))
12007}
12008
12009fn to_snake_case(s: &str) -> String {
12010    let mut out = String::with_capacity(s.len() + 4);
12011    for (i, ch) in s.chars().enumerate() {
12012        if ch.is_ascii_uppercase() {
12013            if i > 0 {
12014                out.push('_');
12015            }
12016            out.push(ch.to_ascii_lowercase());
12017        } else {
12018            out.push(ch);
12019        }
12020    }
12021    out
12022}
12023
12024// ============================================================
12025//  #[derive(Form)]  —  slice 8.4B
12026// ============================================================
12027
12028/// Per-field `#[form(...)]` attributes recognised by the derive.
12029#[derive(Default)]
12030struct FormFieldAttrs {
12031    min: Option<i64>,
12032    max: Option<i64>,
12033    min_length: Option<u32>,
12034    max_length: Option<u32>,
12035    /// `#[form(clean = "fn_name")]` — per-field clean hook.
12036    /// The named static method on the form struct is called after the
12037    /// field's typed parse + length/range checks; it gets the parsed
12038    /// value by reference and returns `Result<<FieldType>, String>`.
12039    /// On Ok, the returned value replaces the parsed one; on Err, the
12040    /// message is attached to the field error list. Issue #372.
12041    clean: Option<syn::Ident>,
12042}
12043
12044/// Container-level `#[form(...)]` attributes. Currently only the
12045/// cross-field `validate` hook (issue #373).
12046#[derive(Default)]
12047struct FormContainerAttrs {
12048    /// `#[form(validate = "fn_name")]` — whole-form clean hook.
12049    /// After every per-field parse succeeds, the named method on the
12050    /// form struct is called with `&self` and may return
12051    /// `Result<(), FormErrors>`. Errors merge into the field error
12052    /// list. Issue #373.
12053    validate: Option<syn::Ident>,
12054}
12055
12056/// Detected shape of a form field's Rust type.
12057#[derive(Clone, Copy)]
12058enum FormFieldKind {
12059    String,
12060    I16,
12061    I32,
12062    I64,
12063    F32,
12064    F64,
12065    Bool,
12066}
12067
12068impl FormFieldKind {
12069    fn parse_method(self) -> &'static str {
12070        match self {
12071            Self::I16 => "i16",
12072            Self::I32 => "i32",
12073            Self::I64 => "i64",
12074            Self::F32 => "f32",
12075            Self::F64 => "f64",
12076            // String + Bool don't go through `str::parse`; the codegen
12077            // handles them inline.
12078            Self::String | Self::Bool => "",
12079        }
12080    }
12081}
12082
12083fn expand_form(input: &DeriveInput) -> syn::Result<TokenStream2> {
12084    let root = rustango_root();
12085    let struct_name = &input.ident;
12086
12087    let Data::Struct(data) = &input.data else {
12088        return Err(syn::Error::new_spanned(
12089            struct_name,
12090            "Form can only be derived on structs",
12091        ));
12092    };
12093    let Fields::Named(named) = &data.fields else {
12094        return Err(syn::Error::new_spanned(
12095            struct_name,
12096            "Form requires a struct with named fields",
12097        ));
12098    };
12099
12100    // #373 — container-level `#[form(validate = "fn")]` hook.
12101    let container = parse_form_container_attrs(input)?;
12102    let post_field_clean: Vec<TokenStream2> = Vec::new();
12103    let _ = post_field_clean;
12104
12105    let mut field_blocks: Vec<TokenStream2> = Vec::with_capacity(named.named.len());
12106    let mut field_idents: Vec<&syn::Ident> = Vec::with_capacity(named.named.len());
12107
12108    for field in &named.named {
12109        let ident = field
12110            .ident
12111            .as_ref()
12112            .ok_or_else(|| syn::Error::new(field.span(), "tuple structs are not supported"))?;
12113        let attrs = parse_form_field_attrs(field)?;
12114        let (kind, nullable) = detect_form_field(&field.ty, field.span())?;
12115
12116        let name_lit = ident.to_string();
12117        let parse_block = render_form_field_parse(ident, &name_lit, kind, nullable, &attrs);
12118        // #372 — append the per-field `clean_<field>` call right after
12119        // the parse block when the attribute is set. The clean fn
12120        // takes &T and returns Result<T, String>; on Err we attach
12121        // the message to the field error list without aborting, so
12122        // the caller sees every field error at once.
12123        let clean_block = if let Some(clean_fn) = &attrs.clean {
12124            quote! {
12125                if __errors.fields().get(#name_lit).is_none() {
12126                    match Self::#clean_fn(&#ident) {
12127                        ::core::result::Result::Ok(__cleaned) => { #ident = __cleaned; }
12128                        ::core::result::Result::Err(__msg) => {
12129                            __errors.add(#name_lit, __msg);
12130                        }
12131                    }
12132                }
12133            }
12134        } else {
12135            quote! {}
12136        };
12137        field_blocks.push(quote! {
12138            #parse_block
12139            #clean_block
12140        });
12141        field_idents.push(ident);
12142    }
12143
12144    // #373 — after every per-field parse + clean succeeds, call the
12145    // cross-field validator if declared. Errors merge into the
12146    // outgoing FormErrors via the existing `FormErrors::merge` helper
12147    // (same primitive the serializer cross-field hook uses).
12148    let cross_field_call = if let Some(validate_fn) = &container.validate {
12149        quote! {
12150            if __errors.is_empty() {
12151                let __candidate = Self { #( #field_idents ),* };
12152                if let ::core::result::Result::Err(__other) = Self::#validate_fn(&__candidate) {
12153                    __errors.merge(__other);
12154                }
12155                if !__errors.is_empty() {
12156                    return ::core::result::Result::Err(__errors);
12157                }
12158                return ::core::result::Result::Ok(__candidate);
12159            }
12160        }
12161    } else {
12162        quote! {}
12163    };
12164
12165    Ok(quote! {
12166        impl #root::forms::Form for #struct_name {
12167            fn parse(
12168                data: &::std::collections::HashMap<::std::string::String, ::std::string::String>,
12169            ) -> ::core::result::Result<Self, #root::forms::FormErrors> {
12170                let mut __errors = #root::forms::FormErrors::default();
12171                #( #field_blocks )*
12172                #cross_field_call
12173                if !__errors.is_empty() {
12174                    return ::core::result::Result::Err(__errors);
12175                }
12176                ::core::result::Result::Ok(Self {
12177                    #( #field_idents ),*
12178                })
12179            }
12180        }
12181    })
12182}
12183
12184fn parse_form_container_attrs(input: &DeriveInput) -> syn::Result<FormContainerAttrs> {
12185    let mut out = FormContainerAttrs::default();
12186    for attr in &input.attrs {
12187        if !attr.path().is_ident("form") {
12188            continue;
12189        }
12190        attr.parse_nested_meta(|meta| {
12191            if meta.path.is_ident("validate") {
12192                let s: LitStr = meta.value()?.parse()?;
12193                out.validate = Some(syn::Ident::new(&s.value(), s.span()));
12194                return Ok(());
12195            }
12196            Err(meta.error("unknown form container attribute (supported: `validate`)"))
12197        })?;
12198    }
12199    Ok(out)
12200}
12201
12202fn parse_form_field_attrs(field: &syn::Field) -> syn::Result<FormFieldAttrs> {
12203    let mut out = FormFieldAttrs::default();
12204    for attr in &field.attrs {
12205        if !attr.path().is_ident("form") {
12206            continue;
12207        }
12208        attr.parse_nested_meta(|meta| {
12209            if meta.path.is_ident("min") {
12210                let lit: syn::LitInt = meta.value()?.parse()?;
12211                out.min = Some(lit.base10_parse::<i64>()?);
12212                return Ok(());
12213            }
12214            if meta.path.is_ident("max") {
12215                let lit: syn::LitInt = meta.value()?.parse()?;
12216                out.max = Some(lit.base10_parse::<i64>()?);
12217                return Ok(());
12218            }
12219            if meta.path.is_ident("min_length") {
12220                let lit: syn::LitInt = meta.value()?.parse()?;
12221                out.min_length = Some(lit.base10_parse::<u32>()?);
12222                return Ok(());
12223            }
12224            if meta.path.is_ident("max_length") {
12225                let lit: syn::LitInt = meta.value()?.parse()?;
12226                out.max_length = Some(lit.base10_parse::<u32>()?);
12227                return Ok(());
12228            }
12229            if meta.path.is_ident("clean") {
12230                let s: LitStr = meta.value()?.parse()?;
12231                out.clean = Some(syn::Ident::new(&s.value(), s.span()));
12232                return Ok(());
12233            }
12234            Err(meta.error(
12235                "unknown form field attribute (supported: `min`, `max`, `min_length`, `max_length`, `clean`)",
12236            ))
12237        })?;
12238    }
12239    Ok(out)
12240}
12241
12242fn detect_form_field(ty: &Type, span: proc_macro2::Span) -> syn::Result<(FormFieldKind, bool)> {
12243    let Type::Path(TypePath { path, qself: None }) = ty else {
12244        return Err(syn::Error::new(
12245            span,
12246            "Form field must be a simple typed path (e.g. `String`, `i32`, `Option<String>`)",
12247        ));
12248    };
12249    let last = path
12250        .segments
12251        .last()
12252        .ok_or_else(|| syn::Error::new(span, "empty type path"))?;
12253
12254    if last.ident == "Option" {
12255        let inner = generic_inner(ty, &last.arguments, "Option")?;
12256        let (kind, nested) = detect_form_field(inner, span)?;
12257        if nested {
12258            return Err(syn::Error::new(
12259                span,
12260                "nested Option in Form fields is not supported",
12261            ));
12262        }
12263        return Ok((kind, true));
12264    }
12265
12266    let kind = match last.ident.to_string().as_str() {
12267        "String" => FormFieldKind::String,
12268        "i16" => FormFieldKind::I16,
12269        "i32" => FormFieldKind::I32,
12270        "i64" => FormFieldKind::I64,
12271        "f32" => FormFieldKind::F32,
12272        "f64" => FormFieldKind::F64,
12273        "bool" => FormFieldKind::Bool,
12274        other => {
12275            return Err(syn::Error::new(
12276                span,
12277                format!(
12278                    "Form field type `{other}` is not supported in v0.8 — use String / \
12279                     i16 / i32 / i64 / f32 / f64 / bool, optionally wrapped in Option<…>"
12280                ),
12281            ));
12282        }
12283    };
12284    Ok((kind, false))
12285}
12286
12287#[allow(clippy::too_many_lines)]
12288fn render_form_field_parse(
12289    ident: &syn::Ident,
12290    name_lit: &str,
12291    kind: FormFieldKind,
12292    nullable: bool,
12293    attrs: &FormFieldAttrs,
12294) -> TokenStream2 {
12295    // Pull the raw &str from the payload. Uses variable name `data` to
12296    // match the new `Form::parse(data: &HashMap<…>)` signature.
12297    let lookup = quote! {
12298        let __raw: ::core::option::Option<&::std::string::String> = data.get(#name_lit);
12299    };
12300
12301    let parsed_value = match kind {
12302        FormFieldKind::Bool => quote! {
12303            let __v: bool = match __raw {
12304                ::core::option::Option::None => false,
12305                ::core::option::Option::Some(__s) => !matches!(
12306                    __s.to_ascii_lowercase().as_str(),
12307                    "" | "false" | "0" | "off" | "no"
12308                ),
12309            };
12310        },
12311        FormFieldKind::String => {
12312            if nullable {
12313                quote! {
12314                    let __v: ::core::option::Option<::std::string::String> = match __raw {
12315                        ::core::option::Option::None => ::core::option::Option::None,
12316                        ::core::option::Option::Some(__s) if __s.is_empty() => {
12317                            ::core::option::Option::None
12318                        }
12319                        ::core::option::Option::Some(__s) => {
12320                            ::core::option::Option::Some(::core::clone::Clone::clone(__s))
12321                        }
12322                    };
12323                }
12324            } else {
12325                quote! {
12326                    let __v: ::std::string::String = match __raw {
12327                        ::core::option::Option::Some(__s) if !__s.is_empty() => {
12328                            ::core::clone::Clone::clone(__s)
12329                        }
12330                        _ => {
12331                            __errors.add(#name_lit, "This field is required.");
12332                            ::std::string::String::new()
12333                        }
12334                    };
12335                }
12336            }
12337        }
12338        FormFieldKind::I16
12339        | FormFieldKind::I32
12340        | FormFieldKind::I64
12341        | FormFieldKind::F32
12342        | FormFieldKind::F64 => {
12343            let parse_ty = syn::Ident::new(kind.parse_method(), proc_macro2::Span::call_site());
12344            let ty_lit = kind.parse_method();
12345            let default_val = match kind {
12346                FormFieldKind::I16 => quote! { 0i16 },
12347                FormFieldKind::I32 => quote! { 0i32 },
12348                FormFieldKind::I64 => quote! { 0i64 },
12349                FormFieldKind::F32 => quote! { 0f32 },
12350                FormFieldKind::F64 => quote! { 0f64 },
12351                _ => quote! { Default::default() },
12352            };
12353            if nullable {
12354                quote! {
12355                    let __v: ::core::option::Option<#parse_ty> = match __raw {
12356                        ::core::option::Option::None => ::core::option::Option::None,
12357                        ::core::option::Option::Some(__s) if __s.is_empty() => {
12358                            ::core::option::Option::None
12359                        }
12360                        ::core::option::Option::Some(__s) => {
12361                            match __s.parse::<#parse_ty>() {
12362                                ::core::result::Result::Ok(__n) => {
12363                                    ::core::option::Option::Some(__n)
12364                                }
12365                                ::core::result::Result::Err(__e) => {
12366                                    __errors.add(
12367                                        #name_lit,
12368                                        ::std::format!("Enter a valid {} value: {}", #ty_lit, __e),
12369                                    );
12370                                    ::core::option::Option::None
12371                                }
12372                            }
12373                        }
12374                    };
12375                }
12376            } else {
12377                quote! {
12378                    let __v: #parse_ty = match __raw {
12379                        ::core::option::Option::Some(__s) if !__s.is_empty() => {
12380                            match __s.parse::<#parse_ty>() {
12381                                ::core::result::Result::Ok(__n) => __n,
12382                                ::core::result::Result::Err(__e) => {
12383                                    __errors.add(
12384                                        #name_lit,
12385                                        ::std::format!("Enter a valid {} value: {}", #ty_lit, __e),
12386                                    );
12387                                    #default_val
12388                                }
12389                            }
12390                        }
12391                        _ => {
12392                            __errors.add(#name_lit, "This field is required.");
12393                            #default_val
12394                        }
12395                    };
12396                }
12397            }
12398        }
12399    };
12400
12401    let validators = render_form_validators(name_lit, kind, nullable, attrs);
12402
12403    quote! {
12404        // `mut` so the per-field `clean` hook (#372) can rewrite the
12405        // parsed value in-place when it returns Ok with a normalized
12406        // form (e.g. trim / lowercase).
12407        let mut #ident = {
12408            #lookup
12409            #parsed_value
12410            #validators
12411            __v
12412        };
12413    }
12414}
12415
12416fn render_form_validators(
12417    name_lit: &str,
12418    kind: FormFieldKind,
12419    nullable: bool,
12420    attrs: &FormFieldAttrs,
12421) -> TokenStream2 {
12422    let mut checks: Vec<TokenStream2> = Vec::new();
12423
12424    let val_ref = if nullable {
12425        quote! { __v.as_ref() }
12426    } else {
12427        quote! { ::core::option::Option::Some(&__v) }
12428    };
12429
12430    let is_string = matches!(kind, FormFieldKind::String);
12431    let is_numeric = matches!(
12432        kind,
12433        FormFieldKind::I16
12434            | FormFieldKind::I32
12435            | FormFieldKind::I64
12436            | FormFieldKind::F32
12437            | FormFieldKind::F64
12438    );
12439
12440    if is_string {
12441        if let Some(min_len) = attrs.min_length {
12442            let min_len_usize = min_len as usize;
12443            checks.push(quote! {
12444                if let ::core::option::Option::Some(__s) = #val_ref {
12445                    if __s.len() < #min_len_usize {
12446                        __errors.add(
12447                            #name_lit,
12448                            ::std::format!("Ensure this value has at least {} characters.", #min_len_usize),
12449                        );
12450                    }
12451                }
12452            });
12453        }
12454        if let Some(max_len) = attrs.max_length {
12455            let max_len_usize = max_len as usize;
12456            checks.push(quote! {
12457                if let ::core::option::Option::Some(__s) = #val_ref {
12458                    if __s.len() > #max_len_usize {
12459                        __errors.add(
12460                            #name_lit,
12461                            ::std::format!("Ensure this value has at most {} characters.", #max_len_usize),
12462                        );
12463                    }
12464                }
12465            });
12466        }
12467    }
12468
12469    if is_numeric {
12470        if let Some(min) = attrs.min {
12471            checks.push(quote! {
12472                if let ::core::option::Option::Some(__n) = #val_ref {
12473                    if (*__n as f64) < (#min as f64) {
12474                        __errors.add(
12475                            #name_lit,
12476                            ::std::format!("Ensure this value is greater than or equal to {}.", #min),
12477                        );
12478                    }
12479                }
12480            });
12481        }
12482        if let Some(max) = attrs.max {
12483            checks.push(quote! {
12484                if let ::core::option::Option::Some(__n) = #val_ref {
12485                    if (*__n as f64) > (#max as f64) {
12486                        __errors.add(
12487                            #name_lit,
12488                            ::std::format!("Ensure this value is less than or equal to {}.", #max),
12489                        );
12490                    }
12491                }
12492            });
12493        }
12494    }
12495
12496    quote! { #( #checks )* }
12497}
12498
12499// ============================================================
12500//  #[derive(ViewSet)]
12501// ============================================================
12502
12503struct ViewSetAttrs {
12504    model: syn::Path,
12505    fields: Option<Vec<String>>,
12506    filter_fields: Vec<String>,
12507    search_fields: Vec<String>,
12508    /// (field_name, desc)
12509    ordering: Vec<(String, bool)>,
12510    page_size: Option<usize>,
12511    read_only: bool,
12512    perms: ViewSetPermsAttrs,
12513    /// `#[viewset(serializer = SomeSerializer)]` — render list /
12514    /// retrieve / create responses through this `#[derive(Serializer)]`
12515    /// type instead of the default field-level projection (requires the
12516    /// `serializer` feature). Tri-dialect.
12517    serializer: Option<syn::Path>,
12518}
12519
12520#[derive(Default)]
12521struct ViewSetPermsAttrs {
12522    list: Vec<String>,
12523    retrieve: Vec<String>,
12524    create: Vec<String>,
12525    update: Vec<String>,
12526    destroy: Vec<String>,
12527}
12528
12529fn expand_viewset(input: &DeriveInput) -> syn::Result<TokenStream2> {
12530    let root = rustango_root();
12531    let struct_name = &input.ident;
12532
12533    // Must be a unit struct or an empty named struct.
12534    match &input.data {
12535        Data::Struct(s) => match &s.fields {
12536            Fields::Unit | Fields::Named(_) => {}
12537            Fields::Unnamed(_) => {
12538                return Err(syn::Error::new_spanned(
12539                    struct_name,
12540                    "ViewSet can only be derived on a unit struct or an empty named struct",
12541                ));
12542            }
12543        },
12544        _ => {
12545            return Err(syn::Error::new_spanned(
12546                struct_name,
12547                "ViewSet can only be derived on a struct",
12548            ));
12549        }
12550    }
12551
12552    let attrs = parse_viewset_attrs(input)?;
12553    let model_path = &attrs.model;
12554
12555    // `.fields(&[...])` call — None means skip (use all scalar fields).
12556    let fields_call = if let Some(ref fields) = attrs.fields {
12557        let lits = fields.iter().map(|f| f.as_str());
12558        quote!(.fields(&[ #(#lits),* ]))
12559    } else {
12560        quote!()
12561    };
12562
12563    let filter_fields_call = if attrs.filter_fields.is_empty() {
12564        quote!()
12565    } else {
12566        let lits = attrs.filter_fields.iter().map(|f| f.as_str());
12567        quote!(.filter_fields(&[ #(#lits),* ]))
12568    };
12569
12570    let search_fields_call = if attrs.search_fields.is_empty() {
12571        quote!()
12572    } else {
12573        let lits = attrs.search_fields.iter().map(|f| f.as_str());
12574        quote!(.search_fields(&[ #(#lits),* ]))
12575    };
12576
12577    let ordering_call = if attrs.ordering.is_empty() {
12578        quote!()
12579    } else {
12580        let pairs = attrs.ordering.iter().map(|(f, desc)| {
12581            let f = f.as_str();
12582            quote!((#f, #desc))
12583        });
12584        quote!(.ordering(&[ #(#pairs),* ]))
12585    };
12586
12587    let page_size_call = if let Some(n) = attrs.page_size {
12588        quote!(.page_size(#n))
12589    } else {
12590        quote!()
12591    };
12592
12593    let read_only_call = if attrs.read_only {
12594        quote!(.read_only())
12595    } else {
12596        quote!()
12597    };
12598
12599    // `.serializer::<S>()` — reshape responses through a derived
12600    // serializer. Requires the downstream crate to enable the
12601    // `serializer` feature (the method is gated on it).
12602    let serializer_call = if let Some(ref ser) = attrs.serializer {
12603        quote!(.serializer::<#ser>())
12604    } else {
12605        quote!()
12606    };
12607
12608    let perms = &attrs.perms;
12609    let perms_call = if perms.list.is_empty()
12610        && perms.retrieve.is_empty()
12611        && perms.create.is_empty()
12612        && perms.update.is_empty()
12613        && perms.destroy.is_empty()
12614    {
12615        quote!()
12616    } else {
12617        let list_lits = perms.list.iter().map(|s| s.as_str());
12618        let retrieve_lits = perms.retrieve.iter().map(|s| s.as_str());
12619        let create_lits = perms.create.iter().map(|s| s.as_str());
12620        let update_lits = perms.update.iter().map(|s| s.as_str());
12621        let destroy_lits = perms.destroy.iter().map(|s| s.as_str());
12622        quote! {
12623            .permissions(#root::viewset::ViewSetPerms {
12624                list:     ::std::vec![ #(#list_lits.to_owned()),* ],
12625                retrieve: ::std::vec![ #(#retrieve_lits.to_owned()),* ],
12626                create:   ::std::vec![ #(#create_lits.to_owned()),* ],
12627                update:   ::std::vec![ #(#update_lits.to_owned()),* ],
12628                destroy:  ::std::vec![ #(#destroy_lits.to_owned()),* ],
12629            })
12630        }
12631    };
12632
12633    Ok(quote! {
12634        impl #struct_name {
12635            /// Build an `axum::Router` with the six standard REST endpoints
12636            /// for this ViewSet, mounted at `prefix`.
12637            ///
12638            /// Accepts any backend's pool — a `sqlx::PgPool`,
12639            /// `SqlitePool`, `MySqlPool`, or the [`rustango::sql::Pool`]
12640            /// enum — because they all `Into<Pool>` (#1273). This is why
12641            /// the derive no longer names `PgPool`, which would not
12642            /// exist on a project built without the `postgres` feature.
12643            pub fn router(
12644                prefix: &str,
12645                pool: impl ::core::convert::Into<#root::sql::Pool>,
12646            ) -> #root::__axum::Router {
12647                #root::viewset::ViewSet::for_model(
12648                    <#model_path as #root::core::Model>::SCHEMA
12649                )
12650                    #fields_call
12651                    #filter_fields_call
12652                    #search_fields_call
12653                    #ordering_call
12654                    #page_size_call
12655                    #perms_call
12656                    #read_only_call
12657                    #serializer_call
12658                    .router_pool(prefix, pool.into())
12659            }
12660        }
12661    })
12662}
12663
12664fn parse_viewset_attrs(input: &DeriveInput) -> syn::Result<ViewSetAttrs> {
12665    let mut model: Option<syn::Path> = None;
12666    let mut fields: Option<Vec<String>> = None;
12667    let mut filter_fields: Vec<String> = Vec::new();
12668    let mut search_fields: Vec<String> = Vec::new();
12669    let mut ordering: Vec<(String, bool)> = Vec::new();
12670    let mut page_size: Option<usize> = None;
12671    let mut read_only = false;
12672    let mut perms = ViewSetPermsAttrs::default();
12673    let mut serializer: Option<syn::Path> = None;
12674
12675    for attr in &input.attrs {
12676        if !attr.path().is_ident("viewset") {
12677            continue;
12678        }
12679        attr.parse_nested_meta(|meta| {
12680            if meta.path.is_ident("model") {
12681                let path: syn::Path = meta.value()?.parse()?;
12682                model = Some(path);
12683                return Ok(());
12684            }
12685            if meta.path.is_ident("serializer") {
12686                let path: syn::Path = meta.value()?.parse()?;
12687                serializer = Some(path);
12688                return Ok(());
12689            }
12690            if meta.path.is_ident("fields") {
12691                let s: LitStr = meta.value()?.parse()?;
12692                fields = Some(split_field_list(&s.value()));
12693                return Ok(());
12694            }
12695            if meta.path.is_ident("filter_fields") {
12696                let s: LitStr = meta.value()?.parse()?;
12697                filter_fields = split_field_list(&s.value());
12698                return Ok(());
12699            }
12700            if meta.path.is_ident("search_fields") {
12701                let s: LitStr = meta.value()?.parse()?;
12702                search_fields = split_field_list(&s.value());
12703                return Ok(());
12704            }
12705            if meta.path.is_ident("ordering") {
12706                let s: LitStr = meta.value()?.parse()?;
12707                ordering = parse_ordering_list(&s.value());
12708                return Ok(());
12709            }
12710            if meta.path.is_ident("page_size") {
12711                let lit: syn::LitInt = meta.value()?.parse()?;
12712                page_size = Some(lit.base10_parse::<usize>()?);
12713                return Ok(());
12714            }
12715            if meta.path.is_ident("read_only") {
12716                read_only = true;
12717                return Ok(());
12718            }
12719            if meta.path.is_ident("permissions") {
12720                meta.parse_nested_meta(|inner| {
12721                    let parse_codenames = |inner: &syn::meta::ParseNestedMeta| -> syn::Result<Vec<String>> {
12722                        let s: LitStr = inner.value()?.parse()?;
12723                        Ok(split_field_list(&s.value()))
12724                    };
12725                    if inner.path.is_ident("list") {
12726                        perms.list = parse_codenames(&inner)?;
12727                    } else if inner.path.is_ident("retrieve") {
12728                        perms.retrieve = parse_codenames(&inner)?;
12729                    } else if inner.path.is_ident("create") {
12730                        perms.create = parse_codenames(&inner)?;
12731                    } else if inner.path.is_ident("update") {
12732                        perms.update = parse_codenames(&inner)?;
12733                    } else if inner.path.is_ident("destroy") {
12734                        perms.destroy = parse_codenames(&inner)?;
12735                    } else {
12736                        return Err(inner.error(
12737                            "unknown permissions key (supported: list, retrieve, create, update, destroy)",
12738                        ));
12739                    }
12740                    Ok(())
12741                })?;
12742                return Ok(());
12743            }
12744            Err(meta.error(
12745                "unknown viewset attribute (supported: model, fields, filter_fields, \
12746                 search_fields, ordering, page_size, read_only, serializer, permissions(...))",
12747            ))
12748        })?;
12749    }
12750
12751    let model = model.ok_or_else(|| {
12752        syn::Error::new_spanned(&input.ident, "`#[viewset(model = SomeModel)]` is required")
12753    })?;
12754
12755    Ok(ViewSetAttrs {
12756        model,
12757        fields,
12758        filter_fields,
12759        search_fields,
12760        ordering,
12761        page_size,
12762        read_only,
12763        perms,
12764        serializer,
12765    })
12766}
12767
12768// ============================================================ #[derive(Serializer)]
12769
12770struct SerializerContainerAttrs {
12771    model: syn::Path,
12772    /// `#[serializer(validate = "fn_name")]` on the struct — the
12773    /// cross-field validation hook (#436). The named inherent method
12774    /// must take `&self` and return
12775    /// `Result<(), rustango::forms::FormErrors>`. The macro-emitted
12776    /// `validate()` runs every per-field validator first; then calls
12777    /// the cross-field method if declared; aggregates all errors into
12778    /// one `FormErrors`.
12779    cross_validate: Option<syn::Ident>,
12780}
12781
12782#[derive(Default)]
12783struct SerializerFieldAttrs {
12784    read_only: bool,
12785    write_only: bool,
12786    source: Option<String>,
12787    skip: bool,
12788    /// `#[serializer(method = "fn_name")]` — computed field. The macro
12789    /// emits a `from_model` initializer that calls
12790    /// `Self::fn_name(&model)` and stores the return value.
12791    method: Option<String>,
12792    /// `#[serializer(validate = "fn_name")]` — per-field validator
12793    /// callable run by `Self::validate(&self)`. Must return
12794    /// `Result<(), String>`. Errors land in `FormErrors` keyed by
12795    /// the field name.
12796    validate: Option<String>,
12797    /// `#[serializer(nested)]` on a field whose type is another
12798    /// `Serializer` — the macro emits `from_model` initializer that
12799    /// reads the parent via `model.<source>.value()` then calls the
12800    /// child serializer's `from_model(parent)`. When the FK is
12801    /// unloaded the field falls back to `Default::default()` (does
12802    /// NOT panic) so a missing prefetch in prod degrades gracefully.
12803    /// Source field on the model defaults to the field name; override
12804    /// with `source = "..."`. Combine with `strict` to keep the v0.18.1
12805    /// panic-on-unloaded behavior for tests.
12806    nested: bool,
12807    /// `#[serializer(nested, strict)]` — opt back into the v0.18.1
12808    /// strict behavior: panic when the FK isn't loaded. Useful in
12809    /// test code where forgetting select_related must trip a hard
12810    /// failure rather than render a blank nested object.
12811    nested_strict: bool,
12812    /// `#[serializer(many = TagSerializer)]` — declare the field as
12813    /// a list of nested serializers. Field type must be `Vec<S>`
12814    /// where `S` is the inner serializer. The macro initializes the
12815    /// field to `Vec::new()` in `from_model` and emits a typed
12816    /// `set_<field>(&mut self, models: &[<S::Model>])` helper that
12817    /// maps each model row through `S::from_model`. Auto-load isn't
12818    /// possible (the M2M / one-to-many accessor is async); callers
12819    /// fetch the children + call the setter post-from_model.
12820    many: Option<syn::Type>,
12821    /// `#[serializer(slug = "name")]` — render a relation as one of
12822    /// its fields.
12823    /// Source field on the model must be a `ForeignKey<T>`; the
12824    /// macro emits `from_model` glue that walks
12825    /// `model.<source>.value()?.<slug>` and clones it. Field type on
12826    /// the serializer is typically `String` (whatever type the slug
12827    /// column has). When the FK is unloaded the field falls back to
12828    /// `Default::default()`, same graceful-degrade contract as
12829    /// `nested`. Source defaults to the field name; override with
12830    /// `source = "..."`. v0.44.
12831    slug: Option<String>,
12832    /// `#[serializer(max_length = N)]` — caps
12833    /// the character count of a string field on write. Overrides the
12834    /// model's `max_length`; when absent the model value is inherited.
12835    max_length: Option<u64>,
12836    /// `#[serializer(min_length = N)]` — minimum character count.
12837    /// Serializer-only (the model has no `min_length` column).
12838    min_length: Option<u64>,
12839    /// `#[serializer(min = N)]` — inclusive
12840    /// integer lower bound; overrides the model's `min` when given.
12841    min: Option<i64>,
12842    /// `#[serializer(max = N)]` — inclusive
12843    /// integer upper bound; overrides the model's `max` when given.
12844    max: Option<i64>,
12845}
12846
12847fn parse_serializer_container_attrs(input: &DeriveInput) -> syn::Result<SerializerContainerAttrs> {
12848    let mut model: Option<syn::Path> = None;
12849    let mut cross_validate: Option<syn::Ident> = None;
12850    for attr in &input.attrs {
12851        if !attr.path().is_ident("serializer") {
12852            continue;
12853        }
12854        attr.parse_nested_meta(|meta| {
12855            if meta.path.is_ident("model") {
12856                let _eq: syn::Token![=] = meta.input.parse()?;
12857                model = Some(meta.input.parse()?);
12858                return Ok(());
12859            }
12860            if meta.path.is_ident("validate") {
12861                // #436 — container-level `validate = "fn_name"` for
12862                // cross-field validation. Field-level
12863                // `#[serializer(validate = "...")]` on a field is
12864                // parsed separately in `parse_serializer_field_attrs`.
12865                let s: LitStr = meta.value()?.parse()?;
12866                cross_validate = Some(syn::Ident::new(&s.value(), s.span()));
12867                return Ok(());
12868            }
12869            Err(meta.error(
12870                "unknown serializer container attribute \
12871                 (supported: `model`, `validate`)",
12872            ))
12873        })?;
12874    }
12875    let model = model.ok_or_else(|| {
12876        syn::Error::new_spanned(
12877            &input.ident,
12878            "`#[serializer(model = SomeModel)]` is required",
12879        )
12880    })?;
12881    Ok(SerializerContainerAttrs {
12882        model,
12883        cross_validate,
12884    })
12885}
12886
12887fn parse_serializer_field_attrs(field: &syn::Field) -> syn::Result<SerializerFieldAttrs> {
12888    let mut out = SerializerFieldAttrs::default();
12889    for attr in &field.attrs {
12890        if !attr.path().is_ident("serializer") {
12891            continue;
12892        }
12893        attr.parse_nested_meta(|meta| {
12894            if meta.path.is_ident("read_only") {
12895                out.read_only = true;
12896                return Ok(());
12897            }
12898            if meta.path.is_ident("write_only") {
12899                out.write_only = true;
12900                return Ok(());
12901            }
12902            if meta.path.is_ident("skip") {
12903                out.skip = true;
12904                return Ok(());
12905            }
12906            if meta.path.is_ident("source") {
12907                let s: LitStr = meta.value()?.parse()?;
12908                out.source = Some(s.value());
12909                return Ok(());
12910            }
12911            if meta.path.is_ident("method") {
12912                let s: LitStr = meta.value()?.parse()?;
12913                out.method = Some(s.value());
12914                return Ok(());
12915            }
12916            if meta.path.is_ident("validate") {
12917                let s: LitStr = meta.value()?.parse()?;
12918                out.validate = Some(s.value());
12919                return Ok(());
12920            }
12921            if meta.path.is_ident("many") {
12922                let _eq: syn::Token![=] = meta.input.parse()?;
12923                out.many = Some(meta.input.parse()?);
12924                return Ok(());
12925            }
12926            if meta.path.is_ident("nested") {
12927                out.nested = true;
12928                // Optional strict flag inside parentheses:
12929                //   #[serializer(nested(strict))]
12930                if meta.input.peek(syn::token::Paren) {
12931                    meta.parse_nested_meta(|inner| {
12932                        if inner.path.is_ident("strict") {
12933                            out.nested_strict = true;
12934                            return Ok(());
12935                        }
12936                        Err(inner.error("unknown nested sub-attribute (supported: `strict`)"))
12937                    })?;
12938                }
12939                return Ok(());
12940            }
12941            if meta.path.is_ident("slug") {
12942                let s: LitStr = meta.value()?.parse()?;
12943                out.slug = Some(s.value());
12944                return Ok(());
12945            }
12946            if meta.path.is_ident("max_length") {
12947                let lit: syn::LitInt = meta.value()?.parse()?;
12948                out.max_length = Some(lit.base10_parse::<u64>()?);
12949                return Ok(());
12950            }
12951            if meta.path.is_ident("min_length") {
12952                let lit: syn::LitInt = meta.value()?.parse()?;
12953                out.min_length = Some(lit.base10_parse::<u64>()?);
12954                return Ok(());
12955            }
12956            if meta.path.is_ident("min") {
12957                let lit: syn::LitInt = meta.value()?.parse()?;
12958                out.min = Some(lit.base10_parse::<i64>()?);
12959                return Ok(());
12960            }
12961            if meta.path.is_ident("max") {
12962                let lit: syn::LitInt = meta.value()?.parse()?;
12963                out.max = Some(lit.base10_parse::<i64>()?);
12964                return Ok(());
12965            }
12966            Err(meta.error(
12967                "unknown serializer field attribute (supported: \
12968                 `read_only`, `write_only`, `source`, `skip`, `method`, \
12969                 `validate`, `nested`, `many`, `slug`, `max_length`, \
12970                 `min_length`, `min`, `max`)",
12971            ))
12972        })?;
12973    }
12974    // Validate: read_only + write_only is nonsensical
12975    if out.read_only && out.write_only {
12976        return Err(syn::Error::new_spanned(
12977            field,
12978            "a field cannot be both `read_only` and `write_only`",
12979        ));
12980    }
12981    if out.method.is_some() && out.source.is_some() {
12982        return Err(syn::Error::new_spanned(
12983            field,
12984            "`method` and `source` are mutually exclusive — `method` computes \
12985             the value from a method, `source` reads it from a different model field",
12986        ));
12987    }
12988    if out.slug.is_some() && (out.method.is_some() || out.nested || out.many.is_some()) {
12989        return Err(syn::Error::new_spanned(
12990            field,
12991            "`slug` is mutually exclusive with `method`, `nested`, and `many` \
12992             — pick one strategy for populating the field",
12993        ));
12994    }
12995    Ok(out)
12996}
12997
12998fn expand_serializer(input: &DeriveInput) -> syn::Result<TokenStream2> {
12999    let root = rustango_root();
13000    let struct_name = &input.ident;
13001    let struct_name_lit = struct_name.to_string();
13002
13003    let Data::Struct(data) = &input.data else {
13004        return Err(syn::Error::new_spanned(
13005            struct_name,
13006            "Serializer can only be derived on structs",
13007        ));
13008    };
13009    let Fields::Named(named) = &data.fields else {
13010        return Err(syn::Error::new_spanned(
13011            struct_name,
13012            "Serializer requires a struct with named fields",
13013        ));
13014    };
13015
13016    let container = parse_serializer_container_attrs(input)?;
13017    let model_path = &container.model;
13018
13019    // Classify each field. `ty` is only consumed by the
13020    // `#[cfg(feature = "openapi")]` block below, but we always
13021    // capture it to keep the field-info build a single pass.
13022    #[allow(dead_code)]
13023    struct FieldInfo {
13024        ident: syn::Ident,
13025        ty: syn::Type,
13026        attrs: SerializerFieldAttrs,
13027    }
13028    let mut fields_info: Vec<FieldInfo> = Vec::new();
13029    for field in &named.named {
13030        let ident = field.ident.clone().expect("named field has ident");
13031        let attrs = parse_serializer_field_attrs(field)?;
13032        fields_info.push(FieldInfo {
13033            ident,
13034            ty: field.ty.clone(),
13035            attrs,
13036        });
13037    }
13038
13039    // Generate from_model body: struct literal with each field assigned.
13040    let from_model_fields = fields_info.iter().map(|fi| {
13041        let ident = &fi.ident;
13042        let ty = &fi.ty;
13043        if let Some(_inner) = &fi.attrs.many {
13044            // Many — collection field. Initialize empty; caller
13045            // populates via the macro-emitted set_<field> helper
13046            // after fetching the M2M children.
13047            quote! { #ident: ::std::vec::Vec::new() }
13048        } else if let Some(method) = &fi.attrs.method {
13049            // SerializerMethodField: call Self::<method>(&model) to
13050            // compute the value. Method signature must be
13051            // `fn <method>(model: &T) -> <field type>`.
13052            let method_ident = syn::Ident::new(method, ident.span());
13053            quote! { #ident: Self::#method_ident(model) }
13054        } else if let Some(slug_field) = &fi.attrs.slug {
13055            // v0.44 — SlugRelatedField. Source defaults to the field
13056            // name on this struct; override via `source = "..."`. The
13057            // source field on the model is expected to be a
13058            // `ForeignKey<T>`; the slug field on the parent is named
13059            // by the attribute value. When the FK is unloaded the
13060            // field falls back to `Default::default()` — same
13061            // graceful-degrade contract as `nested`.
13062            let src_name = fi
13063                .attrs
13064                .source
13065                .as_deref()
13066                .unwrap_or(&fi.ident.to_string())
13067                .to_owned();
13068            let src_ident = syn::Ident::new(&src_name, ident.span());
13069            let slug_ident = syn::Ident::new(slug_field, ident.span());
13070            quote! {
13071                #ident: match model.#src_ident.value() {
13072                    ::core::option::Option::Some(__loaded) =>
13073                        ::core::clone::Clone::clone(&__loaded.#slug_ident),
13074                    ::core::option::Option::None =>
13075                        ::core::default::Default::default(),
13076                }
13077            }
13078        } else if fi.attrs.nested {
13079            // Nested serializer. Source defaults to the field name on
13080            // this struct; override via `source = "..."`. The source
13081            // field on the model is expected to be a `ForeignKey<T>`
13082            // whose `.value()` returns `Option<&T>` after lazy-load.
13083            //
13084            // Behavior matrix (tweakable per-field):
13085            //   * FK loaded   → nested object materializes via
13086            //                   ChildSerializer::from_model(parent).
13087            //   * FK unloaded → fall back to ChildSerializer::default()
13088            //                   (so prod doesn't crash on a missing
13089            //                   prefetch — just renders a blank nested
13090            //                   object). Add `#[serializer(nested,
13091            //                   strict)]` to keep the v0.18.1
13092            //                   panic-on-unloaded behavior for tests
13093            //                   that want hard guardrails.
13094            let src_name = fi.attrs.source.as_deref().unwrap_or(&fi.ident.to_string()).to_owned();
13095            let src_ident = syn::Ident::new(&src_name, ident.span());
13096            if fi.attrs.nested_strict {
13097                let panic_msg = format!(
13098                    "nested(strict) serializer for `{ident}` requires `model.{src_name}` to be loaded — \
13099                     call .get(&pool).await? or .select_related(\"{src_name}\") on the model first",
13100                );
13101                quote! {
13102                    #ident: <#ty as #root::serializer::ModelSerializer>::from_model(
13103                        model.#src_ident.value().expect(#panic_msg),
13104                    )
13105                }
13106            } else {
13107                quote! {
13108                    #ident: match model.#src_ident.value() {
13109                        ::core::option::Option::Some(__loaded) =>
13110                            <#ty as #root::serializer::ModelSerializer>::from_model(__loaded),
13111                        ::core::option::Option::None =>
13112                            ::core::default::Default::default(),
13113                    }
13114                }
13115            }
13116        } else if fi.attrs.write_only || fi.attrs.skip {
13117            // Not read from model — use default
13118            quote! { #ident: ::core::default::Default::default() }
13119        } else if let Some(src) = &fi.attrs.source {
13120            let src_ident = syn::Ident::new(src, ident.span());
13121            quote! { #ident: ::core::clone::Clone::clone(&model.#src_ident) }
13122        } else {
13123            quote! { #ident: ::core::clone::Clone::clone(&model.#ident) }
13124        }
13125    });
13126
13127    // is_writable predicate (also used by writable_lits /
13128    // writable_source_lits below).
13129    let is_writable = |fi: &&FieldInfo| {
13130        !fi.attrs.read_only
13131            && !fi.attrs.skip
13132            && fi.attrs.method.is_none()
13133            && !fi.attrs.nested
13134            && fi.attrs.many.is_none()
13135            && fi.attrs.slug.is_none()
13136    };
13137
13138    // Declarative field constraints: one block
13139    // per writable field, run inside `validate()`. Each resolves its
13140    // bounds as the serializer attr when given (`#[serializer(max_length
13141    // = N)]`), else the model's `FieldSchema` (`max_length` / `min` /
13142    // `max` / `choices`), then dispatches on the field's JSON value via
13143    // `forms::validators::check_value` (string → length/choices, integer
13144    // → min/max).
13145    let opt_usize = |v: Option<u64>| match v {
13146        Some(n) => {
13147            let n = n as usize;
13148            quote!(::core::option::Option::Some(#n))
13149        }
13150        None => quote!(::core::option::Option::None),
13151    };
13152    let opt_i64 = |v: Option<i64>| match v {
13153        Some(n) => quote!(::core::option::Option::Some(#n)),
13154        None => quote!(::core::option::Option::None),
13155    };
13156    let constraint_blocks: Vec<_> = fields_info
13157        .iter()
13158        .filter(is_writable)
13159        .map(|fi| {
13160            let ident = &fi.ident;
13161            let fname = ident.to_string();
13162            let mname = fi
13163                .attrs
13164                .source
13165                .clone()
13166                .unwrap_or_else(|| fi.ident.to_string());
13167            let attr_max_len = opt_usize(fi.attrs.max_length);
13168            let attr_min_len = opt_usize(fi.attrs.min_length);
13169            let attr_min = opt_i64(fi.attrs.min);
13170            let attr_max = opt_i64(fi.attrs.max);
13171            quote! {
13172                {
13173                    let __sf = <#model_path as #root::core::Model>::SCHEMA.field(#mname);
13174                    let __max_length: ::core::option::Option<usize> = #attr_max_len
13175                        .or_else(|| __sf.and_then(|__f| __f.max_length).map(|__n| __n as usize));
13176                    let __min_length: ::core::option::Option<usize> = #attr_min_len;
13177                    let __min: ::core::option::Option<i64> =
13178                        #attr_min.or_else(|| __sf.and_then(|__f| __f.min));
13179                    let __max: ::core::option::Option<i64> =
13180                        #attr_max.or_else(|| __sf.and_then(|__f| __f.max));
13181                    let __choices = __sf.and_then(|__f| __f.choices);
13182                    let __v = #root::__serde_json::to_value(&self.#ident)
13183                        .unwrap_or(#root::__serde_json::Value::Null);
13184                    #root::forms::validators::check_value(
13185                        #fname, &__v, __max_length, __min_length, __min, __max, __choices,
13186                        &mut __errors,
13187                    );
13188                }
13189            }
13190        })
13191        .collect();
13192    let has_constraints = !constraint_blocks.is_empty();
13193
13194    // Per-field validators. Emit a
13195    // `validate(&self)` method that runs each user-defined validator
13196    // and aggregates errors into `FormErrors`.
13197    let validator_calls: Vec<_> = fields_info
13198        .iter()
13199        .filter_map(|fi| {
13200            let ident = &fi.ident;
13201            let name_lit = ident.to_string();
13202            let method = fi.attrs.validate.as_ref()?;
13203            let method_ident = syn::Ident::new(method, ident.span());
13204            Some(quote! {
13205                if let ::core::result::Result::Err(__e) = Self::#method_ident(&self.#ident) {
13206                    __errors.add(#name_lit.to_owned(), __e);
13207                }
13208            })
13209        })
13210        .collect();
13211    // #436 — cross-field `validate(&self)`. If the
13212    // container declared `#[serializer(validate = "fn_name")]`,
13213    // the macro-generated `validate(&self)` runs every per-field
13214    // validator first, then calls the user's cross-field method,
13215    // merging its `FormErrors` into the per-field errors. Either
13216    // alone is enough to emit the wrapper.
13217    let cross_validate_call = container.cross_validate.as_ref().map(|method_ident| {
13218        quote! {
13219            // Merge cross-field errors into the per-field bucket so
13220            // a single .validate() call surfaces both layers.
13221            if let ::core::result::Result::Err(__cross) = self.#method_ident() {
13222                __errors.merge(__cross);
13223            }
13224        }
13225    });
13226    let has_validators = !validator_calls.is_empty() || container.cross_validate.is_some();
13227    // Anything to run? Declarative constraints (for any writable field) +
13228    // per-field validators + cross-field hook.
13229    let has_run_validations = has_validators || has_constraints;
13230    // Shared body: declarative field constraints first (length / range /
13231    // choices, serializer-attr-or-model), then per-field validators, then
13232    // the cross-field hook.
13233    let validate_body = quote! {
13234        let mut __errors = #root::forms::FormErrors::default();
13235        #( #constraint_blocks )*
13236        #( #validator_calls )*
13237        #cross_validate_call
13238        if __errors.is_empty() {
13239            ::core::result::Result::Ok(())
13240        } else {
13241            ::core::result::Result::Err(__errors)
13242        }
13243    };
13244    // Inherent `validate(&self)` — kept for back-compat with direct
13245    // `serializer.validate()` calls that don't import `ModelSerializer`.
13246    // Emitted only when the serializer declares per-field/cross-field
13247    // validators (unchanged rule) so it never collides with a
13248    // hand-written inherent `validate`.
13249    let validate_method = if has_validators {
13250        quote! {
13251            impl #struct_name {
13252                /// Run the declarative field constraints, every
13253                /// `#[serializer(validate = "...")]` per-field validator,
13254                /// and (when declared) the container-level cross-field
13255                /// validator. Aggregates errors into `FormErrors` keyed by
13256                /// the field name. Returns `Ok(())` when all pass.
13257                pub fn validate(&self) -> ::core::result::Result<(), #root::forms::FormErrors> {
13258                    #validate_body
13259                }
13260            }
13261        }
13262    } else {
13263        quote! {}
13264    };
13265    // Trait-method override so the type-erased ViewSet write path can
13266    // dispatch `ModelSerializer::validate` generically. Emitted whenever
13267    // there's anything to run (declarative constraints inherited from the
13268    // model count); otherwise the trait's default no-op is used.
13269    let trait_validate_override = if has_run_validations {
13270        quote! {
13271            fn validate(&self) -> ::core::result::Result<(), #root::forms::FormErrors> {
13272                #validate_body
13273            }
13274        }
13275    } else {
13276        quote! {}
13277    };
13278
13279    // For every `#[serializer(many = S)]` field, emit a
13280    // `pub fn set_<field>(&mut self, models: &[<S::Model>]) -> &mut Self`
13281    // helper that maps the parents through `S::from_model`.
13282    let many_setters: Vec<_> = fields_info
13283        .iter()
13284        .filter_map(|fi| {
13285            let many_ty = fi.attrs.many.as_ref()?;
13286            let ident = &fi.ident;
13287            let setter = syn::Ident::new(&format!("set_{ident}"), ident.span());
13288            Some(quote! {
13289                /// Populate this `many` field by mapping each parent model
13290                /// through the inner serializer's `from_model`. Call after
13291                /// fetching the M2M / one-to-many children since
13292                /// `from_model` itself can't await an SQL query.
13293                pub fn #setter(
13294                    &mut self,
13295                    models: &[<#many_ty as #root::serializer::ModelSerializer>::Model],
13296                ) -> &mut Self {
13297                    self.#ident = models.iter()
13298                        .map(<#many_ty as #root::serializer::ModelSerializer>::from_model)
13299                        .collect();
13300                    self
13301                }
13302            })
13303        })
13304        .collect();
13305    let many_setters_impl = if many_setters.is_empty() {
13306        quote! {}
13307    } else {
13308        quote! {
13309            impl #struct_name {
13310                #( #many_setters )*
13311            }
13312        }
13313    };
13314
13315    // Generate custom Serialize: skip write_only fields
13316    let output_fields: Vec<_> = fields_info
13317        .iter()
13318        .filter(|fi| !fi.attrs.write_only)
13319        .collect();
13320    let output_field_count = output_fields.len();
13321    let serialize_fields = output_fields.iter().map(|fi| {
13322        let ident = &fi.ident;
13323        let name_lit = ident.to_string();
13324        quote! { __state.serialize_field(#name_lit, &self.#ident)?; }
13325    });
13326
13327    // writable_fields: normal + write_only.
13328    // Exclude:
13329    //   - `read_only` — server-computed.
13330    //   - `skip` — caller sets manually post-from_model.
13331    //   - `method` — computed from a Self::fn(&model) call; accepting
13332    //     it on write is meaningless.
13333    //   - `nested` / `many` — populated from related-model data, not
13334    //     from a field on the wire body.
13335    // v0.44 fix: pre-v0.44 the macro included `method` / `nested` /
13336    // `many` in `writable_fields()`, which made the ViewSet write
13337    // path accept those fields from the JSON body and try to bind
13338    // them to the SQL UPDATE — a silent no-op at best, a type
13339    // mismatch at worst.
13340    // (`is_writable` is defined above, near the constraint codegen.)
13341    let writable_lits: Vec<_> = fields_info
13342        .iter()
13343        .filter(is_writable)
13344        .map(|fi| fi.ident.to_string())
13345        .collect();
13346
13347    // `writable_source_fields`: the MODEL field names of writable
13348    // serializer fields (source-resolved). The ViewSet write path skips
13349    // every model column NOT in this set, so `read_only` / `method` /
13350    // computed fields a client posts are ignored instead of written.
13351    let writable_source_lits: Vec<String> = fields_info
13352        .iter()
13353        .filter(is_writable)
13354        .map(|fi| {
13355            fi.attrs
13356                .source
13357                .clone()
13358                .unwrap_or_else(|| fi.ident.to_string())
13359        })
13360        .collect();
13361
13362    // `from_writable_json`: build a partial instance for input
13363    // validation. Writable fields are parsed from the JSON body (keyed
13364    // by serializer field name); every other field defaults. Per-field
13365    // type errors collect into `FormErrors` keyed by the field name.
13366    // Construction is field-by-field (not `Self::default()`) so it works
13367    // for serializers regardless of a struct-level `Default`.
13368    let from_writable_json_inits: Vec<_> = fields_info
13369        .iter()
13370        .map(|fi| {
13371            let ident = &fi.ident;
13372            let fname = ident.to_string();
13373            let ty = &fi.ty;
13374            if is_writable(&fi) {
13375                quote! {
13376                    #ident: match __obj.and_then(|__o| __o.get(#fname)) {
13377                        ::core::option::Option::Some(__v) => {
13378                            match #root::__serde_json::from_value::<#ty>(
13379                                ::core::clone::Clone::clone(__v),
13380                            ) {
13381                                ::core::result::Result::Ok(__x) => __x,
13382                                ::core::result::Result::Err(__e) => {
13383                                    __errors.add(#fname.to_owned(), __e.to_string());
13384                                    ::core::default::Default::default()
13385                                }
13386                            }
13387                        }
13388                        ::core::option::Option::None => ::core::default::Default::default(),
13389                    }
13390                }
13391            } else {
13392                quote! { #ident: ::core::default::Default::default() }
13393            }
13394        })
13395        .collect();
13396
13397    // OpenAPI: emit `impl OpenApiSchema` when our `openapi` feature is on.
13398    // Only includes fields shown in JSON output (skips write_only). For each
13399    // `Option<T>` field, omit from `required` and add `.nullable()`.
13400    let openapi_impl = {
13401        #[cfg(feature = "openapi")]
13402        {
13403            let property_calls = output_fields.iter().map(|fi| {
13404                let ident = &fi.ident;
13405                let name_lit = ident.to_string();
13406                let ty = &fi.ty;
13407                let nullable_call = if is_option(ty) {
13408                    quote! { .nullable() }
13409                } else {
13410                    quote! {}
13411                };
13412                quote! {
13413                    .property(
13414                        #name_lit,
13415                        <#ty as #root::openapi::OpenApiSchema>::openapi_schema()
13416                            #nullable_call,
13417                    )
13418                }
13419            });
13420            let required_lits: Vec<_> = output_fields
13421                .iter()
13422                .filter(|fi| !is_option(&fi.ty))
13423                .map(|fi| fi.ident.to_string())
13424                .collect();
13425            quote! {
13426                impl #root::openapi::OpenApiSchema for #struct_name {
13427                    fn openapi_schema() -> #root::openapi::Schema {
13428                        #root::openapi::Schema::object()
13429                            #( #property_calls )*
13430                            .required([ #( #required_lits ),* ])
13431                    }
13432                }
13433            }
13434        }
13435        #[cfg(not(feature = "openapi"))]
13436        {
13437            quote! {}
13438        }
13439    };
13440
13441    Ok(quote! {
13442        impl #root::serializer::ModelSerializer for #struct_name {
13443            type Model = #model_path;
13444
13445            fn from_model(model: &Self::Model) -> Self {
13446                Self {
13447                    #( #from_model_fields ),*
13448                }
13449            }
13450
13451            fn writable_fields() -> &'static [&'static str] {
13452                &[ #( #writable_lits ),* ]
13453            }
13454
13455            fn writable_source_fields() -> &'static [&'static str] {
13456                &[ #( #writable_source_lits ),* ]
13457            }
13458
13459            fn from_writable_json(
13460                __body: &#root::__serde_json::Value,
13461            ) -> ::core::result::Result<Self, #root::forms::FormErrors> {
13462                let mut __errors = #root::forms::FormErrors::default();
13463                let __obj = __body.as_object();
13464                let __out = Self {
13465                    #( #from_writable_json_inits ),*
13466                };
13467                if __errors.is_empty() {
13468                    ::core::result::Result::Ok(__out)
13469                } else {
13470                    ::core::result::Result::Err(__errors)
13471                }
13472            }
13473
13474            #trait_validate_override
13475        }
13476
13477        impl #root::__serde::Serialize for #struct_name {
13478            fn serialize<S>(&self, serializer: S)
13479                -> ::core::result::Result<S::Ok, S::Error>
13480            where
13481                S: #root::__serde::Serializer,
13482            {
13483                use #root::__serde::ser::SerializeStruct;
13484                let mut __state = serializer.serialize_struct(
13485                    #struct_name_lit,
13486                    #output_field_count,
13487                )?;
13488                #( #serialize_fields )*
13489                __state.end()
13490            }
13491        }
13492
13493        #openapi_impl
13494
13495        #validate_method
13496
13497        #many_setters_impl
13498    })
13499}
13500
13501/// Returns true if `ty` looks like `Option<T>` (any path ending in `Option`).
13502/// Only used by the `openapi`-gated emission of `OpenApiSchema`; muted
13503/// when the feature is off.
13504#[cfg_attr(not(feature = "openapi"), allow(dead_code))]
13505fn is_option(ty: &syn::Type) -> bool {
13506    if let syn::Type::Path(p) = ty {
13507        if let Some(last) = p.path.segments.last() {
13508            return last.ident == "Option";
13509        }
13510    }
13511    false
13512}
13513
13514#[cfg(test)]
13515mod main_attr_tests {
13516    use super::*;
13517
13518    fn expand(args: &str) -> String {
13519        let body = quote! { async fn main() { run().await } };
13520        expand_main(args.parse().unwrap(), body)
13521            .expect("expansion failed")
13522            .to_string()
13523    }
13524
13525    /// Asserts on the expansion rather than on `parse_logging`,
13526    /// because the defect was a subscriber reaching the output, not
13527    /// an argument being misread (#1465).
13528    #[test]
13529    fn logging_false_emits_no_subscriber() {
13530        let out = expand("logging = false");
13531        assert!(
13532            !out.contains("tracing_subscriber"),
13533            "`logging = false` must not install a subscriber:\n{out}",
13534        );
13535        assert!(
13536            out.contains("block_on"),
13537            "the runtime must still be built:\n{out}",
13538        );
13539    }
13540
13541    #[test]
13542    fn default_still_installs_a_subscriber() {
13543        // The control. Without it, an `expand_main` that dropped the
13544        // prologue unconditionally would pass the test above while
13545        // leaving every default project with no logging at all.
13546        let out = expand("");
13547        assert!(
13548            out.contains("tracing_subscriber"),
13549            "the default entrypoint must still install one:\n{out}",
13550        );
13551    }
13552
13553    #[test]
13554    fn logging_false_composes_with_flavor() {
13555        let out = expand("flavor = \"current_thread\", logging = false");
13556        assert!(!out.contains("tracing_subscriber"), "{out}");
13557        assert!(out.contains("new_current_thread"), "{out}");
13558    }
13559
13560    #[test]
13561    fn logging_true_is_the_default_shape() {
13562        // `logging = true` is accepted and means the default, so the
13563        // match must not fire on the substring `logging`.
13564        assert!(parse_logging(&"logging = true".parse().unwrap()));
13565        assert!(!parse_logging(&"logging=false".parse().unwrap()));
13566    }
13567}