Skip to main content

toasty_macros/
lib.rs

1//! Procedural macros for the Toasty ORM.
2//!
3//! This crate provides `#[derive(Model)]`, `#[derive(Embed)]`, and related
4//! attribute macros that generate query builders, schema registration, and
5//! database mapping code.
6
7#![warn(missing_docs)]
8
9extern crate proc_macro;
10
11mod create;
12mod model;
13mod query;
14mod update;
15
16use proc_macro::TokenStream;
17
18/// Derive macro that turns a struct into a Toasty model backed by a database
19/// table.
20///
21/// For a tutorial-style introduction, see the [Toasty guide].
22///
23#[doc = include_str!(concat!(env!("OUT_DIR"), "/guide_link.md"))]
24///
25/// # Overview
26///
27/// Applying `#[derive(Model)]` to a named struct generates:
28///
29/// - A [`Model`] trait implementation, including the associated `Query`,
30///   `Create`, and `Update` builder types.
31/// - A [`Load`] implementation for deserializing rows from the database.
32/// - The [`Model`] trait's schema-registration methods (`id`, `schema`,
33///   `register`) used to register the model at runtime.
34/// - Static query methods such as `all()`, `filter(expr)`,
35///   `filter_by_<field>()`, and `get_by_<key>()`.
36/// - Instance methods `update()` and `delete()`.
37/// - A `Fields` struct returned by `<Model>::fields()` for building typed
38///   filter expressions.
39///
40/// The struct must have named fields and no generic parameters.
41///
42/// [`Model`]: toasty::schema::Model
43/// [`Load`]: toasty::schema::Load
44///
45/// # Struct-level attributes
46///
47/// ## `#[key(...)]` — primary key
48///
49/// Defines the primary key at the struct level. Mutually exclusive with
50/// field-level `#[key]`.
51///
52/// **Simple form** — every listed field becomes a partition key:
53///
54/// ```
55/// # use toasty::Model;
56/// #[derive(Model)]
57/// #[key(name)]
58/// struct Widget {
59///     name: String,
60///     value: i64,
61/// }
62/// ```
63///
64/// **Composite key with partition/local scoping:**
65///
66/// ```
67/// # use toasty::Model;
68/// #[derive(Model)]
69/// #[key(partition = user_id, local = id)]
70/// struct Todo {
71///     #[auto]
72///     id: uuid::Uuid,
73///     user_id: String,
74///     title: String,
75/// }
76/// ```
77///
78/// The `partition` fields determine data distribution (relevant for
79/// DynamoDB); `local` fields scope within a partition. For SQL databases
80/// both behave as a regular composite primary key.
81///
82/// Multiple `partition` and `local` fields are allowed using bracket syntax:
83///
84/// ```
85/// # use toasty::Model;
86/// # #[derive(Model)]
87/// #[key(partition = [tenant, org], local = [id])]
88/// # struct Example { tenant: String, org: String, id: String }
89/// ```
90///
91/// When using named `partition`/`local` syntax, at least one of each is
92/// required. You cannot mix the simple and named forms.
93///
94/// ## `#[table = "name"]` — custom table name
95///
96/// Overrides the default table name. Without this attribute the table name
97/// is the pluralized, snake_case form of the struct name (e.g. `User` →
98/// `users`).
99///
100/// ```
101/// # use toasty::Model;
102/// #[derive(Model)]
103/// #[table = "legacy_users"]
104/// struct User {
105///     #[key]
106///     #[auto]
107///     id: i64,
108///     name: String,
109/// }
110/// ```
111///
112/// # Field-level attributes
113///
114/// ## `#[key]` — mark a field as a primary key column
115///
116/// Marks one or more fields as the primary key. When used on multiple
117/// fields each becomes a partition key column (equivalent to listing them
118/// in `#[key(...)]` at the struct level).
119///
120/// Cannot be combined with a struct-level `#[key(...)]` attribute.
121///
122/// ```
123/// # use toasty::Model;
124/// #[derive(Model)]
125/// struct User {
126///     #[key]
127///     #[auto]
128///     id: i64,
129///     name: String,
130/// }
131/// ```
132///
133/// ## `#[auto]` — automatic value generation
134///
135/// Tells Toasty to generate this field's value automatically. The strategy
136/// depends on the field type and optional arguments:
137///
138/// | Syntax | Behavior |
139/// |--------|----------|
140/// | `#[auto]` on `uuid::Uuid` | UUID v7 (timestamp-sortable) |
141/// | `#[auto(uuid(v4))]` | UUID v4 (random) |
142/// | `#[auto(uuid(v7))]` | UUID v7 (explicit) |
143/// | `#[auto]` on integer types (`i8`–`i64`, `u8`–`u64`) | Auto-increment |
144/// | `#[auto(increment)]` | Auto-increment (explicit) |
145/// | `#[auto]` on a field named `created_at` | Expands to `#[default(jiff::Timestamp::now())]` |
146/// | `#[auto]` on a field named `updated_at` | Expands to `#[update(jiff::Timestamp::now())]` |
147///
148/// The `created_at`/`updated_at` expansion requires the `jiff` feature and
149/// a field type compatible with `jiff::Timestamp`.
150///
151/// Cannot be combined with `#[default]` or `#[update]` on the same field.
152///
153/// ## `#[default(expr)]` — default value on create
154///
155/// Sets a default value that is used when the field is not explicitly
156/// provided during creation. The expression is any valid Rust expression.
157///
158/// ```
159/// # use toasty::Model;
160/// # #[derive(Model)]
161/// # struct Example {
162/// #     #[key]
163/// #     #[auto]
164/// #     id: i64,
165/// #[default(0)]
166/// view_count: i64,
167///
168/// #[default("draft".to_string())]
169/// status: String,
170/// # }
171/// ```
172///
173/// The default can be overridden by calling the corresponding setter on the
174/// create builder.
175///
176/// Cannot be combined with `#[auto]` on the same field. Can be combined
177/// with `#[update]` (the default applies on create; the update expression
178/// applies on subsequent updates).
179///
180/// ## `#[update(expr)]` — value applied on create and update
181///
182/// Sets a value that Toasty applies every time a record is created or
183/// updated, unless the field is explicitly set on the builder.
184///
185/// ```
186/// # use toasty::Model;
187/// # #[derive(Model)]
188/// # struct Example {
189/// #     #[key]
190/// #     #[auto]
191/// #     id: i64,
192/// #[update(jiff::Timestamp::now())]
193/// updated_at: jiff::Timestamp,
194/// # }
195/// ```
196///
197/// Cannot be combined with `#[auto]` on the same field.
198///
199/// ## `#[index]` — add a database index
200///
201/// Creates a non-unique index on the field. Toasty generates a
202/// `filter_by_<field>` method for indexed fields.
203///
204/// ```
205/// # use toasty::Model;
206/// # #[derive(Model)]
207/// # struct Example {
208/// #     #[key]
209/// #     #[auto]
210/// #     id: i64,
211/// #[index]
212/// email: String,
213/// # }
214/// ```
215///
216/// ## `#[unique]` — add a unique constraint
217///
218/// Creates a unique index on the field. Like `#[index]`, this generates
219/// `filter_by_<field>`. The database enforces uniqueness.
220///
221/// ```
222/// # use toasty::Model;
223/// # #[derive(Model)]
224/// # struct Example {
225/// #     #[key]
226/// #     #[auto]
227/// #     id: i64,
228/// #[unique]
229/// email: String,
230/// # }
231/// ```
232///
233/// ## `#[column(...)]` — customize the database column
234///
235/// Overrides the column name and/or type for a field.
236///
237/// **Custom name:**
238///
239/// ```
240/// # use toasty::Model;
241/// # #[derive(Model)]
242/// # struct Example {
243/// #     #[key]
244/// #     #[auto]
245/// #     id: i64,
246/// #[column("user_email")]
247/// email: String,
248/// # }
249/// ```
250///
251/// **Custom type:**
252///
253/// ```
254/// # use toasty::Model;
255/// # #[derive(Model)]
256/// # struct Example {
257/// #     #[key]
258/// #     #[auto]
259/// #     id: i64,
260/// #[column(type = varchar(255))]
261/// email: String,
262/// # }
263/// ```
264///
265/// **Both:**
266///
267/// ```
268/// # use toasty::Model;
269/// # #[derive(Model)]
270/// # struct Example {
271/// #     #[key]
272/// #     #[auto]
273/// #     id: i64,
274/// #[column("user_email", type = varchar(255))]
275/// email: String,
276/// # }
277/// ```
278///
279/// ### Supported column types
280///
281/// | Syntax | Description |
282/// |--------|-------------|
283/// | `boolean` | Boolean |
284/// | `i8`, `i16`, `i32`, `i64` | Signed integer (1/2/4/8 bytes) |
285/// | `int(N)` | Signed integer with N-byte width |
286/// | `u8`, `u16`, `u32`, `u64` | Unsigned integer (1/2/4/8 bytes) |
287/// | `uint(N)` | Unsigned integer with N-byte width |
288/// | `text` | Unbounded text |
289/// | `varchar(N)` | Text with max length N |
290/// | `numeric` | Arbitrary-precision numeric |
291/// | `numeric(P, S)` | Numeric with precision P and scale S |
292/// | `binary(N)` | Fixed-size binary with N bytes |
293/// | `blob` | Variable-length binary |
294/// | `timestamp(P)` | Timestamp with P fractional-second digits |
295/// | `date` | Date without time |
296/// | `time(P)` | Time with P fractional-second digits |
297/// | `datetime(P)` | Date and time with P fractional-second digits |
298/// | `"custom"` | Arbitrary type string passed through to the driver |
299///
300/// Cannot be used on relation fields.
301///
302/// ## JSON-encoded fields via [`Json<T>`](toasty::stmt::Json)
303///
304/// Wrap a serde-typed value in [`toasty::Json<T>`](toasty::stmt::Json) to
305/// store it as a JSON string in the database. Requires the `serde` feature
306/// and that `T` implements `serde::Serialize` and `serde::Deserialize`.
307///
308/// ```
309/// # use toasty::Model;
310/// # #[derive(Model)]
311/// # struct Example {
312/// #     #[key]
313/// #     #[auto]
314/// #     id: i64,
315/// tags: toasty::Json<Vec<String>>,
316/// # }
317/// ```
318///
319/// For nullable JSON columns, wrap `Json<T>` in `Option` — `None` maps to
320/// SQL `NULL`:
321///
322/// ```
323/// # use toasty::Model;
324/// # use std::collections::HashMap;
325/// # #[derive(Model)]
326/// # struct Example {
327/// #     #[key]
328/// #     #[auto]
329/// #     id: i64,
330/// metadata: Option<toasty::Json<HashMap<String, String>>>,
331/// # }
332/// ```
333///
334/// To instead store `None` as the JSON literal `"null"` (no SQL `NULL`),
335/// wrap the other way: `Json<Option<T>>`.
336///
337/// # Relation attributes
338///
339/// Relation fields can be lazy or eager. Wrap the relation value in
340/// `toasty::Deferred<_>` for lazy loading; ordinary queries leave the field
341/// unloaded until the generated relation accessor or `.include(...)` loads it.
342/// Use the relation value directly for eager loading; every query that returns
343/// the model loads the relation as if the query included that field.
344///
345/// | Attribute | Lazy field type | Eager field type |
346/// |-----------|-----------------|------------------|
347/// | `#[belongs_to]` | `toasty::Deferred<T>` or `toasty::Deferred<Option<T>>` | `T` or `Option<T>` |
348/// | `#[has_many]` | `toasty::Deferred<Vec<T>>` | `Vec<T>` |
349/// | `#[has_one]` | `toasty::Deferred<T>` or `toasty::Deferred<Option<T>>` | `T` or `Option<T>` |
350///
351/// Toasty rejects schemas with eager-load cycles. If two relation paths point
352/// back to each other, wrap at least one field in `toasty::Deferred<_>`.
353///
354/// ## `#[belongs_to(...)]` — foreign-key reference
355///
356/// Declares a many-to-one (or one-to-one) association through a foreign
357/// key stored on this model.
358///
359/// ```
360/// # use toasty::Model;
361/// # #[derive(Model)]
362/// # struct User {
363/// #     #[key]
364/// #     #[auto]
365/// #     id: i64,
366/// # }
367/// # #[derive(Model)]
368/// # struct Example {
369/// #     #[key]
370/// #     #[auto]
371/// #     id: i64,
372/// #     user_id: i64,
373/// #[belongs_to(key = user_id, references = id)]
374/// user: toasty::Deferred<User>,
375/// # }
376/// ```
377///
378/// To load the relation with every `Example` query, omit `Deferred`:
379///
380/// ```ignore
381/// #[belongs_to(key = user_id, references = id)]
382/// user: User,
383/// ```
384///
385/// | Parameter | Meaning |
386/// |-----------|---------|
387/// | `key = <field>` | Local field holding the foreign key value |
388/// | `references = <field>` | Field on the target model being referenced |
389///
390/// For composite foreign keys, pass arrays to `key` and `references`:
391///
392/// ```
393/// # use toasty::Model;
394/// # #[derive(Model)]
395/// # #[key(id, tenant_id)]
396/// # struct Org {
397/// #     id: i64,
398/// #     tenant_id: i64,
399/// # }
400/// # #[derive(Model)]
401/// # struct Example {
402/// #     #[key]
403/// #     #[auto]
404/// #     id: i64,
405/// #     org_id: i64,
406/// #     tenant_id: i64,
407/// #[belongs_to(key = [org_id, tenant_id], references = [id, tenant_id])]
408/// org: toasty::Deferred<Org>,
409/// # }
410/// ```
411///
412/// The number of fields in `key` must equal the number of fields in
413/// `references`.
414///
415/// Wrap the target type in `Option` for an optional (nullable) foreign key:
416///
417/// ```
418/// # use toasty::Model;
419/// # #[derive(Model)]
420/// # struct User {
421/// #     #[key]
422/// #     #[auto]
423/// #     id: i64,
424/// # }
425/// # #[derive(Model)]
426/// # struct Example {
427/// #     #[key]
428/// #     #[auto]
429/// #     id: i64,
430/// #[index]
431/// manager_id: Option<i64>,
432///
433/// #[belongs_to(key = manager_id, references = id)]
434/// manager: toasty::Deferred<Option<User>>,
435/// # }
436/// ```
437///
438/// ## `#[has_many]` — one-to-many association
439///
440/// Declares a collection of related models. The target model must have a
441/// `#[belongs_to]` field pointing back to this model.
442///
443/// ```
444/// # use toasty::Model;
445/// # #[derive(Model)]
446/// # struct Post {
447/// #     #[key]
448/// #     #[auto]
449/// #     id: i64,
450/// #     #[index]
451/// #     example_id: i64,
452/// #     #[belongs_to(key = example_id, references = id)]
453/// #     example: toasty::Deferred<Example>,
454/// # }
455/// # #[derive(Model)]
456/// # struct Example {
457/// #     #[key]
458/// #     #[auto]
459/// #     id: i64,
460/// #[has_many]
461/// posts: toasty::Deferred<Vec<Post>>,
462/// # }
463/// ```
464///
465/// To load the collection with every `Example` query, use `Vec<Post>`:
466///
467/// ```ignore
468/// #[has_many]
469/// posts: Vec<Post>,
470/// ```
471///
472/// Toasty generates an accessor method (e.g. `.posts()`) and an insert
473/// helper (e.g. `.insert_post()`), where the insert helper name is the
474/// auto-singularized field name.
475///
476/// ### `pair` — disambiguate self-referential or multiple relations
477///
478/// When the target model has more than one `#[belongs_to]` pointing to
479/// the same model (or points to itself), use `pair` to specify which
480/// `belongs_to` field this `has_many` corresponds to:
481///
482/// ```
483/// # use toasty::Model;
484/// # #[derive(Model)]
485/// # struct Person {
486/// #     #[key]
487/// #     #[auto]
488/// #     id: i64,
489/// #     #[index]
490/// #     parent_id: Option<i64>,
491/// #     #[belongs_to(key = parent_id, references = id)]
492/// #     parent: toasty::Deferred<Option<Self>>,
493/// #[has_many(pair = parent)]
494/// children: toasty::Deferred<Vec<Person>>,
495/// # }
496/// ```
497///
498/// ### `via` — multi-step relations
499///
500/// Instead of pairing with a `belongs_to`, a `has_many` can reach its target
501/// through a path of existing relations with `via`. The path is a dotted
502/// chain of relation fields, read left to right starting from this model. A
503/// `via` relation owns no foreign key — it is derived from the relations it
504/// traverses — so it takes no `pair`:
505///
506/// ```
507/// # use toasty::Model;
508/// # #[derive(Model)]
509/// # struct Comment {
510/// #     #[key]
511/// #     #[auto]
512/// #     id: i64,
513/// #     #[index]
514/// #     user_id: i64,
515/// #     #[belongs_to(key = user_id, references = id)]
516/// #     user: toasty::Deferred<User>,
517/// #     #[index]
518/// #     article_id: i64,
519/// #     #[belongs_to(key = article_id, references = id)]
520/// #     article: toasty::Deferred<Article>,
521/// # }
522/// # #[derive(Model)]
523/// # struct Article {
524/// #     #[key]
525/// #     #[auto]
526/// #     id: i64,
527/// #     #[has_many]
528/// #     comments: toasty::Deferred<Vec<Comment>>,
529/// # }
530/// # #[derive(Model)]
531/// # struct User {
532/// #     #[key]
533/// #     #[auto]
534/// #     id: i64,
535/// #     #[has_many]
536/// #     comments: toasty::Deferred<Vec<Comment>>,
537/// // User → comments → article
538/// #[has_many(via = comments.article)]
539/// commented_articles: toasty::Deferred<Vec<Article>>,
540/// # }
541/// ```
542///
543/// The target type is `Article` because the path `comments.article` ends
544/// there. A `via` relation is read-only and yields distinct targets — a target
545/// reached through several intermediates appears once. Query, filter, and order
546/// it like any other relation. Preloading it with `.include()` or projecting it
547/// with `.select()` is supported on SQL backends; both are not yet available on
548/// DynamoDB.
549///
550/// ## `#[has_one]` — one-to-one association
551///
552/// Declares a single related model. The target model must have a
553/// `#[belongs_to]` field pointing back to this model.
554///
555/// ```
556/// # use toasty::Model;
557/// # #[derive(Model)]
558/// # struct Profile {
559/// #     #[key]
560/// #     #[auto]
561/// #     id: i64,
562/// #     #[index]
563/// #     example_id: i64,
564/// #     #[belongs_to(key = example_id, references = id)]
565/// #     example: toasty::Deferred<Example>,
566/// # }
567/// # #[derive(Model)]
568/// # struct Example {
569/// #     #[key]
570/// #     #[auto]
571/// #     id: i64,
572/// #[has_one]
573/// profile: toasty::Deferred<Profile>,
574/// # }
575/// ```
576///
577/// To load the relation with every `Example` query, omit `Deferred`:
578///
579/// ```ignore
580/// #[has_one]
581/// profile: Profile,
582/// ```
583///
584/// Wrap in `Option` for an optional association:
585///
586/// ```
587/// # use toasty::Model;
588/// # #[derive(Model)]
589/// # struct Profile {
590/// #     #[key]
591/// #     #[auto]
592/// #     id: i64,
593/// #     #[index]
594/// #     example_id: i64,
595/// #     #[belongs_to(key = example_id, references = id)]
596/// #     example: toasty::Deferred<Example>,
597/// # }
598/// # #[derive(Model)]
599/// # struct Example {
600/// #     #[key]
601/// #     #[auto]
602/// #     id: i64,
603/// #[has_one]
604/// profile: toasty::Deferred<Option<Profile>>,
605/// # }
606/// ```
607///
608/// The eager optional form is `Option<Profile>`.
609///
610/// ### `via` — multi-step relations
611///
612/// Like `#[has_many]`, a `#[has_one]` can reach its target through a path of
613/// existing relations with `via` (see the `#[has_many]` `via` section above for
614/// the full rules). Declare it when the path is expected to reach at most one
615/// target:
616///
617/// ```
618/// # use toasty::Model;
619/// # #[derive(Model)]
620/// # struct Subscription {
621/// #     #[key]
622/// #     #[auto]
623/// #     id: i64,
624/// #     #[unique]
625/// #     account_id: Option<i64>,
626/// #     #[belongs_to(key = account_id, references = id)]
627/// #     account: toasty::Deferred<Option<Account>>,
628/// # }
629/// # #[derive(Model)]
630/// # struct Account {
631/// #     #[key]
632/// #     #[auto]
633/// #     id: i64,
634/// #     #[unique]
635/// #     user_id: Option<i64>,
636/// #     #[belongs_to(key = user_id, references = id)]
637/// #     user: toasty::Deferred<Option<User>>,
638/// #     #[has_one]
639/// #     subscription: toasty::Deferred<Option<Subscription>>,
640/// # }
641/// # #[derive(Model)]
642/// # struct User {
643/// #     #[key]
644/// #     #[auto]
645/// #     id: i64,
646/// #     #[has_one]
647/// #     account: toasty::Deferred<Option<Account>>,
648/// // User → account → subscription
649/// #[has_one(via = account.subscription)]
650/// subscription: toasty::Deferred<Option<Subscription>>,
651/// # }
652/// ```
653///
654/// # Constraints
655///
656/// - The struct must have named fields (tuple structs are not supported).
657/// - Generic parameters are not supported.
658/// - Every root model must have a primary key, defined either by a
659///   struct-level `#[key(...)]` or by one or more field-level `#[key]`
660///   attributes, but not both.
661/// - `#[auto]` cannot be combined with `#[default]` or `#[update]` on the
662///   same field.
663/// - `#[column]`, `#[default]`, and `#[update]` cannot be used on relation
664///   fields (`BelongsTo`, `HasMany`, `HasOne`).
665/// - A field can have at most one relation attribute.
666/// - Eager relation fields cannot form a cycle. Use `toasty::Deferred<_>` on at
667///   least one edge of a bidirectional relation.
668/// - `Self` can be used as a type in relation fields for self-referential
669///   models.
670///
671/// # Full example
672///
673/// ```
674/// #[derive(Debug, toasty::Model)]
675/// struct User {
676///     #[key]
677///     #[auto]
678///     id: i64,
679///
680///     #[unique]
681///     email: String,
682///
683///     name: String,
684///
685///     #[default(jiff::Timestamp::now())]
686///     created_at: jiff::Timestamp,
687///
688///     #[update(jiff::Timestamp::now())]
689///     updated_at: jiff::Timestamp,
690///
691///     #[has_many]
692///     posts: toasty::Deferred<Vec<Post>>,
693/// }
694///
695/// #[derive(Debug, toasty::Model)]
696/// struct Post {
697///     #[key]
698///     #[auto]
699///     id: i64,
700///
701///     title: String,
702///
703///     tags: toasty::Json<Vec<String>>,
704///
705///     #[index]
706///     user_id: i64,
707///
708///     #[belongs_to(key = user_id, references = id)]
709///     user: toasty::Deferred<User>,
710/// }
711/// ```
712#[proc_macro_derive(
713    Model,
714    attributes(
715        key, auto, default, update, column, index, unique, table, has_many, has_one, belongs_to,
716        version
717    )
718)]
719pub fn derive_model(input: TokenStream) -> TokenStream {
720    match model::generate_model(input.into()) {
721        Ok(output) => output.into(),
722        Err(e) => e.to_compile_error().into(),
723    }
724}
725
726/// Derive macro that turns a struct or enum into an embedded type stored
727/// inline in a parent model's table.
728///
729/// Embedded types do not have their own tables or primary keys. Their
730/// fields are flattened into the parent model's columns. Use `Embed` for
731/// value objects (addresses, coordinates, metadata) and enums
732/// (status codes, contact info variants).
733///
734/// # Structs
735///
736/// An embedded struct's fields become columns in the parent table, prefixed
737/// with the field name. For example, an `address: Address` field with
738/// `street` and `city` produces columns `address_street` and
739/// `address_city`.
740///
741/// ```
742/// #[derive(toasty::Embed)]
743/// struct Address {
744///     street: String,
745///     city: String,
746/// }
747///
748/// #[derive(toasty::Model)]
749/// struct User {
750///     #[key]
751///     #[auto]
752///     id: i64,
753///     name: String,
754///     address: Address,
755/// }
756/// ```
757///
758/// Applying `#[derive(Embed)]` to a struct generates:
759///
760/// - An [`Embed`] trait implementation (`id` and `schema` methods).
761/// - A `Fields` struct returned by `<Type>::fields()` for building
762///   filter expressions on individual fields.
763/// - An `Update` struct used by the parent model's update builder for
764///   partial field updates.
765///
766/// ## Nesting
767///
768/// Embedded structs can contain other embedded types. Columns are
769/// flattened with chained prefixes:
770///
771/// ```
772/// #[derive(toasty::Embed)]
773/// struct Location {
774///     lat: i64,
775///     lon: i64,
776/// }
777///
778/// #[derive(toasty::Embed)]
779/// struct Address {
780///     street: String,
781///     city: Location,
782/// }
783/// ```
784///
785/// When `Address` is embedded as `address` in a parent model, this
786/// produces columns `address_street`, `address_city_lat`, and
787/// `address_city_lon`.
788///
789/// # Enums
790///
791/// An embedded enum stores a discriminant value identifying the active
792/// variant. Each variant must have a `#[column(variant = N)]` attribute
793/// assigning a stable integer discriminant.
794///
795/// **Unit-only enum:**
796///
797/// ```
798/// #[derive(toasty::Embed)]
799/// enum Status {
800///     #[column(variant = 1)]
801///     Pending,
802///     #[column(variant = 2)]
803///     Active,
804///     #[column(variant = 3)]
805///     Archived,
806/// }
807/// ```
808///
809/// A unit-only enum occupies a single column in the parent table. The
810/// column stores the discriminant as an integer.
811///
812/// **Data-carrying enum:**
813///
814/// ```
815/// #[derive(toasty::Embed)]
816/// enum ContactInfo {
817///     #[column(variant = 1)]
818///     Email { address: String },
819///     #[column(variant = 2)]
820///     Phone { number: String },
821/// }
822/// ```
823///
824/// A data-carrying enum stores the discriminant column plus one nullable
825/// column per variant field. For example, a `contact: ContactInfo` field
826/// produces columns `contact` (discriminant), `contact_address`, and
827/// `contact_number`. Only the columns belonging to the active variant
828/// contain values; the rest are `NULL`.
829///
830/// **Mixed enum** (unit and data variants together):
831///
832/// ```
833/// #[derive(toasty::Embed)]
834/// enum Status {
835///     #[column(variant = 1)]
836///     Pending,
837///     #[column(variant = 2)]
838///     Failed { reason: String },
839///     #[column(variant = 3)]
840///     Done,
841/// }
842/// ```
843///
844/// Applying `#[derive(Embed)]` to an enum generates:
845///
846/// - An [`Embed`] trait implementation (`id` and `schema` methods).
847/// - A `Fields` struct with `is_<variant>()` methods and comparison
848///   methods (`eq`, `ne`, `in_list`).
849/// - For data-carrying variants, per-variant handle types with a
850///   `matches(closure)` method for pattern matching and field access.
851///
852/// # Newtype `Auto` proxying
853///
854/// A tuple-newtype embedded struct (one unnamed field) automatically
855/// implements `Auto` whenever its inner type does — no annotation
856/// required. Toasty emits a `NewtypeOf` marker carrying the inner type
857/// and a blanket `Auto` impl resolves through it:
858///
859/// ```
860/// #[derive(toasty::Embed)]
861/// struct UserId(uuid::Uuid);
862///
863/// #[derive(toasty::Model)]
864/// struct User {
865///     #[key]
866///     #[auto]
867///     id: UserId,
868///     name: String,
869/// }
870/// ```
871///
872/// Newtypes wrapping non-`Auto` types stay non-`Auto`; nesting works
873/// transparently (`Outer(Inner(u64))` proxies through both layers).
874///
875/// # Field-level attributes
876///
877/// ## `#[column(...)]` — customize the database column
878///
879/// **On struct fields**, overrides the column name and/or type:
880///
881/// ```
882/// #[derive(toasty::Embed)]
883/// struct Address {
884///     #[column("addr_street")]
885///     street: String,
886///
887///     #[column(type = varchar(255))]
888///     city: String,
889/// }
890/// ```
891///
892/// See [`Model`][`derive@Model`] for the full list of supported column
893/// types.
894///
895/// **On enum variants**, `#[column(variant = N)]` is **required** and
896/// assigns the integer discriminant stored in the database:
897///
898/// ```
899/// # #[derive(toasty::Embed)]
900/// # enum Example {
901/// #[column(variant = 1)]
902/// Pending,
903/// # }
904/// ```
905///
906/// Discriminant values must be unique across all variants of the enum.
907/// They are stored as `i64`.
908///
909/// ## `#[index]` — add a database index
910///
911/// Creates a non-unique index on the field's flattened column.
912///
913/// ```
914/// #[derive(toasty::Embed)]
915/// struct Contact {
916///     #[index]
917///     country: String,
918/// }
919/// ```
920///
921/// ## `#[unique]` — add a unique constraint
922///
923/// Creates a unique index on the field's flattened column. The database
924/// enforces uniqueness.
925///
926/// ```
927/// #[derive(toasty::Embed)]
928/// struct Contact {
929///     #[unique]
930///     email: String,
931/// }
932/// ```
933///
934/// # Using embedded types in a model
935///
936/// Reference an embedded type as a field on a [`Model`][`derive@Model`]
937/// struct. The parent model's create and update builders gain a setter for
938/// the embedded field. Partial updates of individual sub-fields use
939/// `stmt::patch`:
940///
941/// ```no_run
942/// # #[derive(toasty::Embed)]
943/// # struct Address { street: String, city: String }
944/// # #[derive(toasty::Model)]
945/// # struct User {
946/// #     #[key]
947/// #     #[auto]
948/// #     id: i64,
949/// #     name: String,
950/// #     address: Address,
951/// # }
952/// # async fn example(mut db: toasty::Db, mut user: User) -> toasty::Result<()> {
953/// use toasty::stmt;
954///
955/// // Full replacement
956/// user.update()
957///     .address(Address { street: "456 Oak Ave".into(), city: "Seattle".into() })
958///     .exec(&mut db).await?;
959///
960/// // Partial update — updates city, leaves street unchanged
961/// user.update()
962///     .address(stmt::patch(Address::fields().city(), "Portland"))
963///     .exec(&mut db).await?;
964/// # Ok(())
965/// # }
966/// ```
967///
968/// Embedded struct fields are queryable through the parent model's
969/// `fields()` accessor:
970///
971/// ```no_run
972/// # #[derive(toasty::Embed)]
973/// # struct Address { street: String, city: String }
974/// # #[derive(toasty::Model)]
975/// # struct User {
976/// #     #[key]
977/// #     #[auto]
978/// #     id: i64,
979/// #     name: String,
980/// #     address: Address,
981/// # }
982/// # async fn example(mut db: toasty::Db) -> toasty::Result<()> {
983/// let users = User::filter(User::fields().address().city().eq("Seattle"))
984///     .exec(&mut db).await?;
985/// # Ok(())
986/// # }
987/// ```
988///
989/// # Constraints
990///
991/// - Embedded structs must have named fields (tuple structs are not
992///   supported).
993/// - Generic parameters are not supported.
994/// - Every enum variant must have a `#[column(variant = N)]` attribute
995///   with a unique discriminant value.
996/// - Enum variants may be unit variants or have named fields. Tuple
997///   variants are not supported.
998/// - Embedded types cannot have primary keys, relations, `#[auto]`,
999///   `#[default]`, or `#[update]` attributes.
1000///
1001/// # Full example
1002///
1003/// ```no_run
1004/// # async fn example(mut db: toasty::Db) -> toasty::Result<()> {
1005/// #[derive(Debug, PartialEq, toasty::Embed)]
1006/// enum Priority {
1007///     #[column(variant = 1)]
1008///     Low,
1009///     #[column(variant = 2)]
1010///     Normal,
1011///     #[column(variant = 3)]
1012///     High,
1013/// }
1014///
1015/// #[derive(Debug, toasty::Embed)]
1016/// struct Metadata {
1017///     version: i64,
1018///     status: String,
1019///     priority: Priority,
1020/// }
1021///
1022/// #[derive(Debug, toasty::Model)]
1023/// struct Document {
1024///     #[key]
1025///     #[auto]
1026///     id: i64,
1027///
1028///     title: String,
1029///
1030///     #[unique]
1031///     slug: String,
1032///
1033///     meta: Metadata,
1034/// }
1035///
1036/// // Create
1037/// let mut doc = Document::create()
1038///     .title("Design doc")
1039///     .slug("design-doc")
1040///     .meta(Metadata {
1041///         version: 1,
1042///         status: "draft".to_string(),
1043///         priority: Priority::Normal,
1044///     })
1045///     .exec(&mut db).await?;
1046///
1047/// // Query by embedded field
1048/// let drafts = Document::filter(
1049///     Document::fields().meta().status().eq("draft")
1050/// ).exec(&mut db).await?;
1051///
1052/// // Partial update
1053/// use toasty::stmt;
1054/// doc.update()
1055///     .meta(stmt::apply([
1056///         stmt::patch(Metadata::fields().version(), 2),
1057///         stmt::patch(Metadata::fields().status(), "published"),
1058///     ]))
1059///     .exec(&mut db).await?;
1060/// # Ok(())
1061/// # }
1062/// ```
1063///
1064/// [`Embed`]: toasty::Embed
1065#[proc_macro_derive(Embed, attributes(column, index, unique))]
1066pub fn derive_embed(input: TokenStream) -> TokenStream {
1067    match model::generate_embed(input.into()) {
1068        Ok(output) => output.into(),
1069        Err(e) => e.to_compile_error().into(),
1070    }
1071}
1072
1073/// Builds a query using the Toasty query language. The macro expands into
1074/// the equivalent method-chain calls on the query builder API. It does
1075/// not execute the query — chain `.exec(&mut db).await?` on the result to run
1076/// it.
1077///
1078/// # Syntax
1079///
1080/// ```text
1081/// query!(Source [FILTER expr] [ORDER BY .field ASC|DESC] [OFFSET n] [LIMIT n])
1082/// ```
1083///
1084/// `Source` is a model type path (e.g., `User`). All clauses are optional and
1085/// can appear in any combination, but must follow the order shown above when
1086/// present. All keywords are case-insensitive: `FILTER`, `filter`, and `Filter`
1087/// all work.
1088///
1089/// # Basic queries
1090///
1091/// With no clauses, `query!` returns all records of the given model.
1092///
1093/// ```
1094/// # #[derive(toasty::Model)]
1095/// # struct User {
1096/// #     #[key]
1097/// #     id: i64,
1098/// #     name: String,
1099/// #     age: i64,
1100/// #     active: bool,
1101/// # }
1102/// // Returns all users — expands to User::all()
1103/// let _ = toasty::query!(User);
1104/// ```
1105///
1106/// # Filter expressions
1107///
1108/// The `FILTER` clause accepts an expression built from field comparisons,
1109/// boolean operators, and external references.
1110///
1111/// ## Comparison operators
1112///
1113/// Dot-prefixed field paths (`.name`, `.age`) refer to fields on the source
1114/// model. The right-hand side is a literal or external reference.
1115///
1116/// | Operator | Expansion         |
1117/// |----------|-------------------|
1118/// | `==`     | `.eq(val)`        |
1119/// | `!=`     | `.ne(val)`        |
1120/// | `>`      | `.gt(val)`        |
1121/// | `>=`     | `.ge(val)`        |
1122/// | `<`      | `.lt(val)`        |
1123/// | `<=`     | `.le(val)`        |
1124///
1125/// ```
1126/// # #[derive(toasty::Model)]
1127/// # struct User {
1128/// #     #[key]
1129/// #     id: i64,
1130/// #     name: String,
1131/// #     age: i64,
1132/// #     active: bool,
1133/// # }
1134/// // Equality — expands to User::filter(User::fields().name().eq("Alice"))
1135/// let _ = toasty::query!(User FILTER .name == "Alice");
1136///
1137/// // Not equal
1138/// let _ = toasty::query!(User FILTER .name != "Bob");
1139///
1140/// // Greater than
1141/// let _ = toasty::query!(User FILTER .age > 18);
1142///
1143/// // Greater than or equal
1144/// let _ = toasty::query!(User FILTER .age >= 21);
1145///
1146/// // Less than
1147/// let _ = toasty::query!(User FILTER .age < 65);
1148///
1149/// // Less than or equal
1150/// let _ = toasty::query!(User FILTER .age <= 99);
1151/// ```
1152///
1153/// ## Boolean operators
1154///
1155/// `AND`, `OR`, and `NOT` combine filter expressions. Precedence follows
1156/// standard boolean logic: `NOT` binds tightest, then `AND`, then `OR`.
1157///
1158/// ```
1159/// # #[derive(toasty::Model)]
1160/// # struct User {
1161/// #     #[key]
1162/// #     id: i64,
1163/// #     name: String,
1164/// #     age: i64,
1165/// #     active: bool,
1166/// # }
1167/// // AND — both conditions must match
1168/// let _ = toasty::query!(User FILTER .name == "Alice" AND .age > 18);
1169///
1170/// // OR — either condition matches
1171/// let _ = toasty::query!(User FILTER .name == "Alice" OR .name == "Bob");
1172///
1173/// // NOT — negates the following expression
1174/// let _ = toasty::query!(User FILTER NOT .active == true);
1175///
1176/// // Combining all three
1177/// let _ = toasty::query!(User FILTER NOT .active == true AND (.name == "Alice" OR .age >= 21));
1178/// ```
1179///
1180/// ## Operator precedence
1181///
1182/// Without parentheses, `NOT` binds tightest, then `AND`, then `OR`. Use
1183/// parentheses to override.
1184///
1185/// ```
1186/// # #[derive(toasty::Model)]
1187/// # struct User {
1188/// #     #[key]
1189/// #     id: i64,
1190/// #     name: String,
1191/// #     age: i64,
1192/// #     active: bool,
1193/// # }
1194/// // Without parens: parsed as (.name == "A" AND .age > 0) OR .active == false
1195/// let _ = toasty::query!(User FILTER .name == "A" AND .age > 0 OR .active == false);
1196///
1197/// // With parens: forces OR to bind first
1198/// let _ = toasty::query!(User FILTER .name == "A" AND (.age > 0 OR .active == false));
1199/// ```
1200///
1201/// ## Boolean and integer literals
1202///
1203/// Boolean fields can be compared against `true` and `false` literals.
1204/// Integer literals work as expected.
1205///
1206/// ```
1207/// # #[derive(toasty::Model)]
1208/// # struct User {
1209/// #     #[key]
1210/// #     id: i64,
1211/// #     name: String,
1212/// #     age: i64,
1213/// #     active: bool,
1214/// # }
1215/// let _ = toasty::query!(User FILTER .active == true);
1216/// let _ = toasty::query!(User FILTER .active == false);
1217/// let _ = toasty::query!(User FILTER .age == 42);
1218/// ```
1219///
1220/// # Referencing surrounding code
1221///
1222/// `#ident` pulls a variable from the surrounding scope. `#(expr)` embeds an
1223/// arbitrary Rust expression.
1224///
1225/// ```
1226/// # #[derive(toasty::Model)]
1227/// # struct User {
1228/// #     #[key]
1229/// #     id: i64,
1230/// #     name: String,
1231/// #     age: i64,
1232/// #     active: bool,
1233/// # }
1234/// // Variable reference — expands to User::filter(User::fields().name().eq(name))
1235/// let name = "Carl";
1236/// let _ = toasty::query!(User FILTER .name == #name);
1237///
1238/// // Expression reference
1239/// fn min_age() -> i64 { 18 }
1240/// let _ = toasty::query!(User FILTER .age > #(min_age()));
1241/// ```
1242///
1243/// # Dot-prefixed field paths
1244///
1245/// A leading `.` starts a field path rooted at the source model's `fields()`
1246/// method. Chained dots navigate multi-segment paths.
1247///
1248/// ```
1249/// # #[derive(toasty::Model)]
1250/// # struct User {
1251/// #     #[key]
1252/// #     id: i64,
1253/// #     name: String,
1254/// #     age: i64,
1255/// #     active: bool,
1256/// # }
1257/// // .name expands to User::fields().name()
1258/// let _ = toasty::query!(User FILTER .name == "Alice");
1259///
1260/// // Multiple fields in a single expression
1261/// let _ = toasty::query!(User FILTER .id == 1 AND .name == "X" AND .age > 0);
1262/// ```
1263///
1264/// # ORDER BY
1265///
1266/// Sort results by a field in ascending (`ASC`) or descending (`DESC`) order.
1267/// If no direction is specified, ascending is the default.
1268///
1269/// ```
1270/// # #[derive(toasty::Model)]
1271/// # struct User {
1272/// #     #[key]
1273/// #     id: i64,
1274/// #     name: String,
1275/// #     age: i64,
1276/// #     active: bool,
1277/// # }
1278/// // Ascending order (explicit)
1279/// let _ = toasty::query!(User ORDER BY .name ASC);
1280///
1281/// // Descending order
1282/// let _ = toasty::query!(User ORDER BY .age DESC);
1283///
1284/// // Combined with filter
1285/// let _ = toasty::query!(User FILTER .active == true ORDER BY .name ASC);
1286/// ```
1287///
1288/// # LIMIT and OFFSET
1289///
1290/// `LIMIT` restricts the number of returned records. `OFFSET` skips a number
1291/// of records before returning. Both accept integer literals, `#ident`
1292/// variables, and `#(expr)` expressions.
1293///
1294/// ```
1295/// # #[derive(toasty::Model)]
1296/// # struct User {
1297/// #     #[key]
1298/// #     id: i64,
1299/// #     name: String,
1300/// #     age: i64,
1301/// #     active: bool,
1302/// # }
1303/// // Return at most 10 records
1304/// let _ = toasty::query!(User LIMIT 10);
1305///
1306/// // Skip 20, then return 10
1307/// let _ = toasty::query!(User OFFSET 20 LIMIT 10);
1308///
1309/// // Variable pagination
1310/// let page_size = 25usize;
1311/// let _ = toasty::query!(User LIMIT #page_size);
1312///
1313/// // Expression pagination
1314/// let _ = toasty::query!(User LIMIT #(5 + 5));
1315/// ```
1316///
1317/// # Combining clauses
1318///
1319/// All clauses can be combined. When present, they must appear in this order:
1320/// `FILTER`, `ORDER BY`, `OFFSET`, `LIMIT`.
1321///
1322/// ```
1323/// # #[derive(toasty::Model)]
1324/// # struct User {
1325/// #     #[key]
1326/// #     id: i64,
1327/// #     name: String,
1328/// #     age: i64,
1329/// #     active: bool,
1330/// # }
1331/// let _ = toasty::query!(User FILTER .active == true ORDER BY .name ASC LIMIT 10);
1332/// let _ = toasty::query!(User FILTER .age > 18 ORDER BY .age DESC OFFSET 0 LIMIT 50);
1333/// ```
1334///
1335/// # Case-insensitive keywords
1336///
1337/// All keywords — `FILTER`, `AND`, `OR`, `NOT`, `ORDER`, `BY`, `ASC`, `DESC`,
1338/// `OFFSET`, `LIMIT` — are matched case-insensitively. Any casing works.
1339///
1340/// ```
1341/// # #[derive(toasty::Model)]
1342/// # struct User {
1343/// #     #[key]
1344/// #     id: i64,
1345/// #     name: String,
1346/// #     age: i64,
1347/// #     active: bool,
1348/// # }
1349/// // These are all equivalent
1350/// let _ = toasty::query!(User FILTER .name == "A");
1351/// let _ = toasty::query!(User filter .name == "A");
1352/// let _ = toasty::query!(User Filter .name == "A");
1353/// ```
1354///
1355/// # Expansion details
1356///
1357/// The macro translates each syntactic element into method-chain calls on the
1358/// query builder.
1359///
1360/// ## No filter
1361///
1362/// ```text
1363/// query!(User)          →  User::all()
1364/// ```
1365///
1366/// ## Filter
1367///
1368/// ```text
1369/// query!(User FILTER .name == "A")
1370///     →  User::filter(User::fields().name().eq("A"))
1371/// ```
1372///
1373/// ## Logical operators
1374///
1375/// ```text
1376/// query!(User FILTER .a == 1 AND .b == 2)
1377///     →  User::filter(User::fields().a().eq(1).and(User::fields().b().eq(2)))
1378///
1379/// query!(User FILTER .a == 1 OR .b == 2)
1380///     →  User::filter(User::fields().a().eq(1).or(User::fields().b().eq(2)))
1381///
1382/// query!(User FILTER NOT .a == 1)
1383///     →  User::filter((User::fields().a().eq(1)).not())
1384/// ```
1385///
1386/// ## ORDER BY
1387///
1388/// ```text
1389/// query!(User ORDER BY .name ASC)
1390///     →  { let mut q = User::all(); q = q.order_by(User::fields().name().asc()); q }
1391/// ```
1392///
1393/// ## LIMIT / OFFSET
1394///
1395/// ```text
1396/// query!(User LIMIT 10)
1397///     →  { let mut q = User::all(); q = q.limit(10); q }
1398///
1399/// query!(User OFFSET 5 LIMIT 10)
1400///     →  { let mut q = User::all(); q = q.limit(10); q = q.offset(5); q }
1401/// ```
1402///
1403/// Note: in the expansion, `limit` is called before `offset` because the
1404/// API requires it.
1405///
1406/// ## External references
1407///
1408/// ```text
1409/// let x = "Carl";
1410/// query!(User FILTER .name == #x)
1411///     →  User::filter(User::fields().name().eq(x))
1412///
1413/// query!(User FILTER .age > #(compute()))
1414///     →  User::filter(User::fields().age().gt(compute()))
1415/// ```
1416///
1417/// # Errors
1418///
1419/// The macro produces compile-time errors for:
1420///
1421/// - **Missing model path**: the first token must be a valid type path.
1422/// - **Unknown fields**: dot-prefixed paths that don't match a field on the
1423///   model produce a type error from the generated `fields()` method.
1424/// - **Type mismatches**: comparing a field to a value of the wrong type
1425///   produces a standard Rust type error (e.g., `.age == "not a number"`).
1426/// - **Unexpected tokens**: tokens after the last recognized clause cause
1427///   `"unexpected tokens after query"`.
1428/// - **Invalid clause order**: placing `FILTER` after `ORDER BY` or `LIMIT`
1429///   before `OFFSET` causes a parse error since the clauses are parsed in
1430///   fixed order.
1431/// - **Missing `BY` after `ORDER`**: writing `ORDER .name` instead of
1432///   `ORDER BY .name` produces `"expected 'BY' after 'ORDER'"`.
1433/// - **Invalid pagination value**: `LIMIT` and `OFFSET` require an integer
1434///   literal, `#variable`, or `#(expression)`.
1435#[proc_macro]
1436pub fn query(input: TokenStream) -> TokenStream {
1437    match query::generate(input.into()) {
1438        Ok(output) => output.into(),
1439        Err(e) => e.to_compile_error().into(),
1440    }
1441}
1442
1443/// Expands struct-literal syntax into create builder method chains. Returns one
1444/// or more create builders — call `.exec(&mut db).await?` to insert the
1445/// record(s).
1446///
1447/// # Syntax forms
1448///
1449/// ## Field syntax
1450///
1451/// Fields inside `{ ... }` can use either explicit or shorthand syntax:
1452///
1453/// - **Explicit:** `field: expr` — sets the field to the given expression.
1454/// - **Shorthand:** `field` — equivalent to `field: field`, using a variable
1455///   with the same name as the field.
1456///
1457/// These can be mixed freely, just like Rust struct literals:
1458///
1459/// ```ignore
1460/// let name = "Alice".to_string();
1461/// toasty::create!(User { name, email: "alice@example.com" })
1462/// ```
1463///
1464/// ## Single creation
1465///
1466/// ```ignore
1467/// toasty::create!(Type { field: value, ... })
1468/// ```
1469///
1470/// Expands to `Type::create().field(value)...` and returns the model's create
1471/// builder (e.g., `UserCreate`).
1472///
1473/// ```no_run
1474/// # #[derive(toasty::Model)]
1475/// # struct User {
1476/// #     #[key]
1477/// #     #[auto]
1478/// #     id: i64,
1479/// #     name: String,
1480/// #     email: String,
1481/// # }
1482/// # async fn example(mut db: toasty::Db) -> toasty::Result<()> {
1483/// let user = toasty::create!(User {
1484///     name: "Alice",
1485///     email: "alice@example.com"
1486/// })
1487/// .exec(&mut db)
1488/// .await?;
1489/// # Ok(())
1490/// # }
1491/// ```
1492///
1493/// ## Scoped creation
1494///
1495/// ```ignore
1496/// toasty::create!(in expr { field: value, ... })
1497/// ```
1498///
1499/// Expands to `expr.create().field(value)...`. Creates a record through a
1500/// relation accessor. The foreign key is set automatically.
1501///
1502/// ```no_run
1503/// # #[derive(toasty::Model)]
1504/// # struct User {
1505/// #     #[key]
1506/// #     #[auto]
1507/// #     id: i64,
1508/// #     name: String,
1509/// #     #[has_many]
1510/// #     todos: toasty::Deferred<Vec<Todo>>,
1511/// # }
1512/// # #[derive(toasty::Model)]
1513/// # struct Todo {
1514/// #     #[key]
1515/// #     #[auto]
1516/// #     id: i64,
1517/// #     title: String,
1518/// #     #[index]
1519/// #     user_id: i64,
1520/// #     #[belongs_to(key = user_id, references = id)]
1521/// #     user: toasty::Deferred<User>,
1522/// # }
1523/// # async fn example(mut db: toasty::Db, user: User) -> toasty::Result<()> {
1524/// let todo = toasty::create!(in user.todos() { title: "buy milk" })
1525///     .exec(&mut db)
1526///     .await?;
1527///
1528/// // todo.user_id == user.id
1529/// # Ok(())
1530/// # }
1531/// ```
1532///
1533/// ## Typed batch
1534///
1535/// ```ignore
1536/// toasty::create!(Type::[ { fields }, { fields }, ... ])
1537/// ```
1538///
1539/// Expands to `toasty::batch([builder1, builder2, ...])` and returns
1540/// `Vec<Type>` when executed:
1541///
1542/// ```no_run
1543/// # #[derive(toasty::Model)]
1544/// # struct User {
1545/// #     #[key]
1546/// #     #[auto]
1547/// #     id: i64,
1548/// #     name: String,
1549/// # }
1550/// # async fn example(mut db: toasty::Db) -> toasty::Result<()> {
1551/// let users = toasty::create!(User::[
1552///     { name: "Alice" },
1553///     { name: "Bob" },
1554/// ])
1555/// .exec(&mut db)
1556/// .await?;
1557/// // users: Vec<User>
1558/// # Ok(())
1559/// # }
1560/// ```
1561///
1562/// ## Tuple
1563///
1564/// ```ignore
1565/// toasty::create!((
1566///     Type1 { fields },
1567///     Type2 { fields },
1568///     ...
1569/// ))
1570/// ```
1571///
1572/// Expands to `toasty::batch((builder1, builder2, ...))` and returns a
1573/// tuple matching the input types:
1574///
1575/// ```no_run
1576/// # #[derive(toasty::Model)]
1577/// # struct User {
1578/// #     #[key]
1579/// #     #[auto]
1580/// #     id: i64,
1581/// #     name: String,
1582/// # }
1583/// # #[derive(toasty::Model)]
1584/// # struct Post {
1585/// #     #[key]
1586/// #     #[auto]
1587/// #     id: i64,
1588/// #     title: String,
1589/// # }
1590/// # async fn example(mut db: toasty::Db) -> toasty::Result<()> {
1591/// let (user, post) = toasty::create!((
1592///     User { name: "Alice" },
1593///     Post { title: "Hello" },
1594/// ))
1595/// .exec(&mut db)
1596/// .await?;
1597/// // (User, Post)
1598/// # Ok(())
1599/// # }
1600/// ```
1601///
1602/// ## Mixed tuple
1603///
1604/// Typed batches and single creates can be mixed inside a tuple:
1605///
1606/// ```no_run
1607/// # #[derive(toasty::Model)]
1608/// # struct User {
1609/// #     #[key]
1610/// #     #[auto]
1611/// #     id: i64,
1612/// #     name: String,
1613/// # }
1614/// # #[derive(toasty::Model)]
1615/// # struct Post {
1616/// #     #[key]
1617/// #     #[auto]
1618/// #     id: i64,
1619/// #     title: String,
1620/// # }
1621/// # async fn example(mut db: toasty::Db) -> toasty::Result<()> {
1622/// let (users, post) = toasty::create!((
1623///     User::[ { name: "Alice" }, { name: "Bob" } ],
1624///     Post { title: "Hello" },
1625/// ))
1626/// .exec(&mut db)
1627/// .await?;
1628/// // (Vec<User>, Post)
1629/// # Ok(())
1630/// # }
1631/// ```
1632///
1633/// # Field values
1634///
1635/// ## Expressions
1636///
1637/// Any Rust expression is valid as a field value — literals, variables, and
1638/// function calls all work. When a variable has the same name as the field,
1639/// you can use the shorthand syntax (just `name` instead of `name: name`):
1640///
1641/// ```
1642/// # #[derive(toasty::Model)]
1643/// # struct User {
1644/// #     #[key]
1645/// #     #[auto]
1646/// #     id: i64,
1647/// #     name: String,
1648/// #     email: String,
1649/// # }
1650/// let name = "Alice";
1651/// let _ = toasty::create!(User { name, email: format!("{}@example.com", name) });
1652/// ```
1653///
1654/// When the variable name differs from the field name, use the explicit
1655/// `field: expr` form:
1656///
1657/// ```
1658/// # #[derive(toasty::Model)]
1659/// # struct User {
1660/// #     #[key]
1661/// #     #[auto]
1662/// #     id: i64,
1663/// #     name: String,
1664/// # }
1665/// let user_name = "Alice";
1666/// let _ = toasty::create!(User { name: user_name });
1667/// ```
1668///
1669/// ## Nested struct (BelongsTo / HasOne)
1670///
1671/// Use `{ ... }` **without** a type prefix to create a related record inline.
1672/// The macro expands the nested fields into a create builder and passes it
1673/// to the field's setter method.
1674///
1675/// ```
1676/// # #[derive(toasty::Model)]
1677/// # struct User {
1678/// #     #[key]
1679/// #     #[auto]
1680/// #     id: i64,
1681/// #     name: String,
1682/// # }
1683/// # #[derive(toasty::Model)]
1684/// # struct Todo {
1685/// #     #[key]
1686/// #     #[auto]
1687/// #     id: i64,
1688/// #     title: String,
1689/// #     #[index]
1690/// #     user_id: i64,
1691/// #     #[belongs_to(key = user_id, references = id)]
1692/// #     user: toasty::Deferred<User>,
1693/// # }
1694/// let _ = toasty::create!(Todo {
1695///     title: "buy milk",
1696///     user: { name: "Alice" }
1697/// });
1698/// // Expands to:
1699/// // Todo::create()
1700/// //     .title("buy milk")
1701/// //     .user(Todo::fields().user().create().name("Alice"))
1702/// ```
1703///
1704/// The related record is created first and the foreign key is set
1705/// automatically.
1706///
1707/// ## Nested list (HasMany)
1708///
1709/// Use `[{ ... }, { ... }]` to create multiple related records. The macro
1710/// expands each entry into a create builder and passes them as an array to
1711/// the plural field setter.
1712///
1713/// ```
1714/// # #[derive(toasty::Model)]
1715/// # struct User {
1716/// #     #[key]
1717/// #     #[auto]
1718/// #     id: i64,
1719/// #     name: String,
1720/// #     #[has_many]
1721/// #     todos: toasty::Deferred<Vec<Todo>>,
1722/// # }
1723/// # #[derive(toasty::Model)]
1724/// # struct Todo {
1725/// #     #[key]
1726/// #     #[auto]
1727/// #     id: i64,
1728/// #     title: String,
1729/// #     #[index]
1730/// #     user_id: i64,
1731/// #     #[belongs_to(key = user_id, references = id)]
1732/// #     user: toasty::Deferred<User>,
1733/// # }
1734/// let _ = toasty::create!(User {
1735///     name: "Alice",
1736///     todos: [{ title: "first" }, { title: "second" }]
1737/// });
1738/// // Expands to:
1739/// // User::create()
1740/// //     .name("Alice")
1741/// //     .todos([
1742/// //         User::fields().todos().create().title("first"),
1743/// //         User::fields().todos().create().title("second"),
1744/// //     ])
1745/// ```
1746///
1747/// Items in a nested list can also be plain expressions (e.g., an existing
1748/// builder value).
1749///
1750/// ## Deep nesting
1751///
1752/// Nesting composes to arbitrary depth:
1753///
1754/// ```
1755/// # #[derive(toasty::Model)]
1756/// # struct User {
1757/// #     #[key]
1758/// #     #[auto]
1759/// #     id: i64,
1760/// #     name: String,
1761/// #     #[has_many]
1762/// #     todos: toasty::Deferred<Vec<Todo>>,
1763/// # }
1764/// # #[derive(toasty::Model)]
1765/// # struct Todo {
1766/// #     #[key]
1767/// #     #[auto]
1768/// #     id: i64,
1769/// #     title: String,
1770/// #     #[index]
1771/// #     user_id: i64,
1772/// #     #[belongs_to(key = user_id, references = id)]
1773/// #     user: toasty::Deferred<User>,
1774/// #     #[has_many]
1775/// #     tags: toasty::Deferred<Vec<Tag>>,
1776/// # }
1777/// # #[derive(toasty::Model)]
1778/// # struct Tag {
1779/// #     #[key]
1780/// #     #[auto]
1781/// #     id: i64,
1782/// #     name: String,
1783/// #     #[index]
1784/// #     todo_id: i64,
1785/// #     #[belongs_to(key = todo_id, references = id)]
1786/// #     todo: toasty::Deferred<Todo>,
1787/// # }
1788/// let _ = toasty::create!(User {
1789///     name: "Alice",
1790///     todos: [{
1791///         title: "task",
1792///         tags: [{ name: "urgent" }, { name: "work" }]
1793///     }]
1794/// });
1795/// ```
1796///
1797/// This creates a `User`, then a `Todo` linked to that user, then two `Tag`
1798/// records linked to that todo.
1799///
1800/// # Fields that can be omitted
1801///
1802/// | Field type | Behavior when omitted |
1803/// |---|---|
1804/// | `#[auto]` | Value generated by the database or Toasty |
1805/// | `Option<T>` | Defaults to `None` (`NULL`) |
1806/// | `#[default(expr)]` | Uses the default expression |
1807/// | `#[update(expr)]` | Uses the expression as the initial value |
1808/// | `#[has_many] Deferred<Vec<T>>` or `#[has_many] Vec<T>` | No related records created |
1809/// | `#[has_one] Deferred<Option<T>>` or `#[has_one] Option<T>` | No related record created |
1810/// | `#[belongs_to] Deferred<Option<T>>` or `#[belongs_to] Option<T>` | Foreign key set to `NULL` |
1811///
1812/// Required fields (`String`, `i64`, non-optional `BelongsTo`, etc.) that are
1813/// missing do not cause a compile-time error. The insert fails at runtime with
1814/// a database constraint violation.
1815///
1816/// # Compile errors
1817///
1818/// **Type prefix on nested struct:**
1819///
1820/// ```compile_fail
1821/// # #[derive(toasty::Model)]
1822/// # struct User {
1823/// #     #[key]
1824/// #     #[auto]
1825/// #     id: i64,
1826/// #     name: String,
1827/// # }
1828/// # #[derive(toasty::Model)]
1829/// # struct Todo {
1830/// #     #[key]
1831/// #     #[auto]
1832/// #     id: i64,
1833/// #     #[index]
1834/// #     user_id: i64,
1835/// #     #[belongs_to(key = user_id, references = id)]
1836/// #     user: toasty::Deferred<User>,
1837/// # }
1838/// // Error: remove the type prefix `User` — use `{ ... }` without a type name
1839/// toasty::create!(Todo { user: User { name: "Alice" } })
1840/// ```
1841///
1842/// Correct:
1843///
1844/// ```
1845/// # #[derive(toasty::Model)]
1846/// # struct User {
1847/// #     #[key]
1848/// #     #[auto]
1849/// #     id: i64,
1850/// #     name: String,
1851/// # }
1852/// # #[derive(toasty::Model)]
1853/// # struct Todo {
1854/// #     #[key]
1855/// #     #[auto]
1856/// #     id: i64,
1857/// #     #[index]
1858/// #     user_id: i64,
1859/// #     #[belongs_to(key = user_id, references = id)]
1860/// #     user: toasty::Deferred<User>,
1861/// # }
1862/// let _ = toasty::create!(Todo { user: { name: "Alice" } });
1863/// ```
1864///
1865/// Nested struct values infer their type from the field.
1866///
1867/// **Nested lists:**
1868///
1869/// ```compile_fail
1870/// # #[derive(toasty::Model)]
1871/// # struct User {
1872/// #     #[key]
1873/// #     #[auto]
1874/// #     id: i64,
1875/// #     field: String,
1876/// # }
1877/// // Error: nested lists are not supported in create!
1878/// toasty::create!(User { field: [[{ }]] })
1879/// ```
1880///
1881/// **Missing braces or batch bracket:**
1882///
1883/// ```compile_fail
1884/// # #[derive(toasty::Model)]
1885/// # struct User {
1886/// #     #[key]
1887/// #     #[auto]
1888/// #     id: i64,
1889/// # }
1890/// // Error: expected `{` for single creation or `::[` for batch creation after type path
1891/// toasty::create!(User)
1892/// ```
1893///
1894/// # Return type
1895///
1896/// | Form | Returns |
1897/// |---|---|
1898/// | `Type { ... }` | `TypeCreate` (single builder) |
1899/// | `in expr { ... }` | Builder for the relation's model |
1900/// | `Type::[ ... ]` | `Batch` — executes to `Vec<Type>` |
1901/// | `( ... )` | `Batch` — executes to tuple of results |
1902///
1903/// Single and scoped forms return a builder — call `.exec(&mut db).await?`.
1904/// Batch and tuple forms return a `Batch` — also call `.exec(&mut db).await?`.
1905#[proc_macro]
1906pub fn create(input: TokenStream) -> TokenStream {
1907    match create::generate(input.into()) {
1908        Ok(output) => output.into(),
1909        Err(e) => e.to_compile_error().into(),
1910    }
1911}
1912
1913/// Expands struct-literal syntax into update-builder method chains. Returns
1914/// the same builder `target.update()` would return — call
1915/// `.exec(&mut db).await?` to execute the update.
1916///
1917/// # Syntax
1918///
1919/// ```ignore
1920/// toasty::update!(target { field: value, ... })
1921/// ```
1922///
1923/// `target` is any expression that has an `.update()` method — a model
1924/// instance, a query builder, or a scoped relation accessor.
1925///
1926/// ```no_run
1927/// # #[derive(toasty::Model)]
1928/// # struct User {
1929/// #     #[key]
1930/// #     #[auto]
1931/// #     id: i64,
1932/// #     name: String,
1933/// # }
1934/// # async fn example(mut db: toasty::Db, mut user: User, id: i64) -> toasty::Result<()> {
1935/// // Instance target
1936/// toasty::update!(user { name: "Alice Smith" })
1937///     .exec(&mut db).await?;
1938///
1939/// // Query target
1940/// toasty::update!(User::filter_by_id(id) { name: "Bob" })
1941///     .exec(&mut db).await?;
1942/// # Ok(())
1943/// # }
1944/// ```
1945///
1946/// Instance targets do not consume the binding — the macro expands to
1947/// `user.update()`, which auto-borrows `&mut user` the same way the
1948/// chain form does. `user` stays owned after the macro returns.
1949///
1950/// # Field shapes
1951///
1952/// ## Explicit
1953///
1954/// `field: expr` sets the field to `expr`:
1955///
1956/// ```no_run
1957/// # #[derive(toasty::Model)]
1958/// # struct User {
1959/// #     #[key]
1960/// #     #[auto]
1961/// #     id: i64,
1962/// #     name: String,
1963/// #     email: String,
1964/// # }
1965/// # async fn example(mut db: toasty::Db, mut user: User) -> toasty::Result<()> {
1966/// toasty::update!(user {
1967///     name: "Alice Smith",
1968///     email: "alice.smith@example.com",
1969/// }).exec(&mut db).await?;
1970/// # Ok(())
1971/// # }
1972/// ```
1973///
1974/// `expr` is any Rust expression. For collection fields, pass a
1975/// `toasty::stmt::*` combinator (e.g. `stmt::push("x")`,
1976/// `stmt::apply([...])`) for non-set semantics.
1977///
1978/// ## Shorthand
1979///
1980/// `field` alone is equivalent to `field: field`, matching Rust struct
1981/// literal shorthand:
1982///
1983/// ```no_run
1984/// # #[derive(toasty::Model)]
1985/// # struct User {
1986/// #     #[key]
1987/// #     #[auto]
1988/// #     id: i64,
1989/// #     name: String,
1990/// # }
1991/// # async fn example(mut db: toasty::Db, mut user: User) -> toasty::Result<()> {
1992/// let name = "Alice Smith";
1993/// toasty::update!(user { name }).exec(&mut db).await?;
1994/// # Ok(())
1995/// # }
1996/// ```
1997///
1998/// ## Method shorthand
1999///
2000/// `field.combinator(args)` is shorthand for
2001/// `field: toasty::stmt::combinator(args)`. Any function in `toasty::stmt`
2002/// works; missing functions surface as ordinary "no function" errors:
2003///
2004/// ```no_run
2005/// # #[derive(toasty::Model)]
2006/// # struct Article {
2007/// #     #[key]
2008/// #     #[auto]
2009/// #     id: i64,
2010/// #     tags: Vec<String>,
2011/// # }
2012/// # async fn example(mut db: toasty::Db, mut article: Article) -> toasty::Result<()> {
2013/// // tags.push("rust") expands to tags: stmt::push("rust")
2014/// toasty::update!(article { tags.push("rust") })
2015///     .exec(&mut db).await?;
2016/// # Ok(())
2017/// # }
2018/// ```
2019///
2020/// The shorthand is one method call deep. For chained expressions, use
2021/// the explicit `field: expr` form.
2022///
2023/// ## Embedded patch
2024///
2025/// `field: { sub: val, ... }` partially updates an embedded struct
2026/// field, leaving sub-fields not listed unchanged. Expands to
2027/// `stmt::apply([stmt::patch(...), ...])`:
2028///
2029/// ```no_run
2030/// # #[derive(toasty::Embed)]
2031/// # struct Metadata { version: i64, status: String }
2032/// # #[derive(toasty::Model)]
2033/// # struct Document {
2034/// #     #[key]
2035/// #     #[auto]
2036/// #     id: i64,
2037/// #     meta: Metadata,
2038/// # }
2039/// # async fn example(mut db: toasty::Db, mut doc: Document) -> toasty::Result<()> {
2040/// toasty::update!(doc {
2041///     meta: { version: 2, status: "published" },
2042/// }).exec(&mut db).await?;
2043/// # Ok(())
2044/// # }
2045/// ```
2046///
2047/// Sub-fields nest to arbitrary depth. To replace an embedded value
2048/// wholesale, pass the typed value directly: `meta: Metadata { ... }`.
2049///
2050/// ## Has-many insert
2051///
2052/// `field: [{ ... }, ...]` inserts new children of a has-many relation.
2053/// Each `{ ... }` becomes a create builder wrapped in
2054/// `stmt::insert(...)`; the whole list is wrapped in
2055/// `stmt::apply([...])`:
2056///
2057/// ```no_run
2058/// # #[derive(toasty::Model)]
2059/// # struct User {
2060/// #     #[key]
2061/// #     #[auto]
2062/// #     id: i64,
2063/// #     name: String,
2064/// #     #[has_many]
2065/// #     todos: toasty::Deferred<Vec<Todo>>,
2066/// # }
2067/// # #[derive(toasty::Model)]
2068/// # struct Todo {
2069/// #     #[key]
2070/// #     #[auto]
2071/// #     id: i64,
2072/// #     title: String,
2073/// #     #[index]
2074/// #     user_id: i64,
2075/// #     #[belongs_to(key = user_id, references = id)]
2076/// #     user: toasty::Deferred<User>,
2077/// # }
2078/// # async fn example(mut db: toasty::Db, mut user: User) -> toasty::Result<()> {
2079/// toasty::update!(user {
2080///     todos: [{ title: "buy milk" }, { title: "walk dog" }],
2081/// }).exec(&mut db).await?;
2082/// # Ok(())
2083/// # }
2084/// ```
2085///
2086/// Items can also be plain expressions, mixed in with builder
2087/// shorthands — useful for combining inserts and removals:
2088///
2089/// ```no_run
2090/// # #[derive(toasty::Model)]
2091/// # struct User {
2092/// #     #[key]
2093/// #     #[auto]
2094/// #     id: i64,
2095/// #     #[has_many]
2096/// #     todos: toasty::Deferred<Vec<Todo>>,
2097/// # }
2098/// # #[derive(toasty::Model)]
2099/// # struct Todo {
2100/// #     #[key]
2101/// #     #[auto]
2102/// #     id: i64,
2103/// #     title: String,
2104/// #     #[index]
2105/// #     user_id: i64,
2106/// #     #[belongs_to(key = user_id, references = id)]
2107/// #     user: toasty::Deferred<User>,
2108/// # }
2109/// # async fn example(mut db: toasty::Db, mut user: User, old: Todo) -> toasty::Result<()> {
2110/// toasty::update!(user {
2111///     todos: [{ title: "new" }, toasty::stmt::remove(&old)],
2112/// }).exec(&mut db).await?;
2113/// # Ok(())
2114/// # }
2115/// ```
2116///
2117/// # Field validation
2118///
2119/// The macro emits a method call per named field on the update builder.
2120/// A field name the model does not expose for update fails with the
2121/// compiler's standard "no method named …" error at the macro call
2122/// site.
2123#[proc_macro]
2124pub fn update(input: TokenStream) -> TokenStream {
2125    match update::generate(input.into()) {
2126        Ok(output) => output.into(),
2127        Err(e) => e.to_compile_error().into(),
2128    }
2129}