Skip to main content

navree_orm/
model.rs

1//! [`Model`]: what `#[derive(Model)]` implements, the metadata it writes
2//! ([`ModelMeta`], [`ColumnMeta`]), keys ([`PrimaryKey`], [`KeyKind`]) and
3//! timestamps ([`Timestamp`]).
4
5use std::borrow::Cow;
6use std::fmt;
7use std::future::Future;
8use std::sync::Arc;
9
10use chrono::{DateTime, FixedOffset, NaiveDateTime, Utc};
11use navree_kernel::BoxFuture;
12use serde::Serialize;
13use uuid::Uuid;
14
15use crate::attributes::{Accessor, CastContext};
16use crate::collection::Collection;
17use crate::column::{Assignment, Filter};
18use crate::error::Result;
19use crate::exec::Executor;
20use crate::factory::RelationshipInfo;
21use crate::hooks::ModelHook;
22use crate::query::Builder;
23use crate::record::Record;
24use crate::relations::{DynRelation, RelationMeta};
25use crate::row::Row;
26use crate::scope::GlobalScope;
27use crate::ulid::Ulid;
28use crate::value::{Field, FieldKind, Value};
29
30/// How a model's key gets its value.
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32#[non_exhaustive]
33pub enum KeyKind {
34    /// The database assigns it (auto-increment, identity, serial): a record
35    /// whose key is `0` inserts without it and reads the new key back.
36    Increments,
37    /// A UUID version 7 (time-ordered), generated when the key is nil.
38    UuidV7,
39    /// A random UUID (version 4), generated when the key is nil.
40    UuidV4,
41    /// A [`Ulid`], generated when the key is nil.
42    Ulid,
43    /// A MongoDB ObjectId (12 bytes: a timestamp in seconds, a random
44    /// value and a counter, so new ids sort by creation time), generated
45    /// when the key is all zeros. The key type is the MongoDB driver
46    /// crate's `ObjectId`.
47    ObjectId,
48    /// Set by the application; never generated.
49    Manual,
50}
51
52/// The Rust type of a model's key.
53///
54/// Implemented for `i16`, `i32`, `i64`, `u32`, `u64`, `Uuid`, [`Ulid`] and
55/// `String`.
56#[diagnostic::on_unimplemented(
57    message = "`{Self}` cannot be a model key",
58    note = "use an integer, `Uuid`, `Ulid` or `String` field as the primary key"
59)]
60pub trait PrimaryKey: Field + Clone + PartialEq + fmt::Debug {
61    /// Whether the key is unset (`0`, the nil UUID or ULID, an empty
62    /// string): a new record with such a key gets a generated one.
63    fn is_empty(&self) -> bool;
64
65    /// A new key of `kind`, when this type can hold one.
66    fn generate(kind: KeyKind) -> Option<Self>;
67
68    /// The unset key (for [`Record::replicate`]).
69    fn empty() -> Self;
70
71    /// The key as text (change events, error messages).
72    fn to_key_string(&self) -> String;
73}
74
75macro_rules! integer_key {
76    ($($ty:ty),*) => {$(
77        impl PrimaryKey for $ty {
78            fn is_empty(&self) -> bool {
79                *self == 0
80            }
81
82            fn generate(_kind: KeyKind) -> Option<Self> {
83                None
84            }
85
86            fn empty() -> Self {
87                0
88            }
89
90            fn to_key_string(&self) -> String {
91                self.to_string()
92            }
93        }
94    )*};
95}
96
97integer_key!(i16, i32, i64, u32, u64);
98
99impl PrimaryKey for Uuid {
100    fn is_empty(&self) -> bool {
101        self.is_nil()
102    }
103
104    fn generate(kind: KeyKind) -> Option<Self> {
105        match kind {
106            KeyKind::UuidV7 => Some(Uuid::now_v7()),
107            KeyKind::UuidV4 => Some(Uuid::new_v4()),
108            KeyKind::Ulid => Some(Ulid::new().to_uuid()),
109            KeyKind::Increments | KeyKind::ObjectId | KeyKind::Manual => None,
110        }
111    }
112
113    fn empty() -> Self {
114        Uuid::nil()
115    }
116
117    fn to_key_string(&self) -> String {
118        self.to_string()
119    }
120}
121
122impl PrimaryKey for Ulid {
123    fn is_empty(&self) -> bool {
124        self.is_nil()
125    }
126
127    fn generate(kind: KeyKind) -> Option<Self> {
128        match kind {
129            KeyKind::Ulid | KeyKind::UuidV7 | KeyKind::UuidV4 => Some(Ulid::new()),
130            KeyKind::Increments | KeyKind::ObjectId | KeyKind::Manual => None,
131        }
132    }
133
134    fn empty() -> Self {
135        Ulid::nil()
136    }
137
138    fn to_key_string(&self) -> String {
139        self.to_string()
140    }
141}
142
143impl PrimaryKey for String {
144    fn is_empty(&self) -> bool {
145        str::is_empty(self)
146    }
147
148    fn generate(kind: KeyKind) -> Option<Self> {
149        match kind {
150            KeyKind::UuidV7 => Some(Uuid::now_v7().to_string()),
151            KeyKind::UuidV4 => Some(Uuid::new_v4().to_string()),
152            KeyKind::Ulid => Some(Ulid::new().to_string()),
153            KeyKind::Increments | KeyKind::ObjectId | KeyKind::Manual => None,
154        }
155    }
156
157    fn empty() -> Self {
158        String::new()
159    }
160
161    fn to_key_string(&self) -> String {
162        self.clone()
163    }
164}
165
166/// The Rust type of a timestamp column (`created_at`, `updated_at`,
167/// `deleted_at`).
168///
169/// Implemented for `DateTime<Utc>`, `DateTime<FixedOffset>`,
170/// `NaiveDateTime` (UTC), `i64` (Unix seconds) and `Option` of each. A
171/// timestamp is "empty" when it is `None` or the type's zero value (the
172/// Unix epoch): a new record's empty timestamps are set when it is saved.
173#[diagnostic::on_unimplemented(
174    message = "`{Self}` cannot be a timestamp column",
175    note = "use `DateTime<Utc>`, `DateTime<FixedOffset>`, `NaiveDateTime`, `i64` or an `Option` of one"
176)]
177pub trait Timestamp: Field {
178    /// The timestamp for `now`.
179    fn from_now(now: DateTime<Utc>) -> Self;
180
181    /// Whether the timestamp is unset.
182    fn is_empty(&self) -> bool;
183
184    /// The unset timestamp.
185    fn empty() -> Self;
186}
187
188impl Timestamp for DateTime<Utc> {
189    fn from_now(now: DateTime<Utc>) -> Self {
190        now
191    }
192
193    fn is_empty(&self) -> bool {
194        *self == DateTime::<Utc>::UNIX_EPOCH
195    }
196
197    fn empty() -> Self {
198        DateTime::<Utc>::UNIX_EPOCH
199    }
200}
201
202impl Timestamp for DateTime<FixedOffset> {
203    fn from_now(now: DateTime<Utc>) -> Self {
204        now.fixed_offset()
205    }
206
207    fn is_empty(&self) -> bool {
208        *self == DateTime::<Utc>::UNIX_EPOCH
209    }
210
211    fn empty() -> Self {
212        DateTime::<Utc>::UNIX_EPOCH.fixed_offset()
213    }
214}
215
216impl Timestamp for NaiveDateTime {
217    fn from_now(now: DateTime<Utc>) -> Self {
218        now.naive_utc()
219    }
220
221    fn is_empty(&self) -> bool {
222        *self == DateTime::<Utc>::UNIX_EPOCH.naive_utc()
223    }
224
225    fn empty() -> Self {
226        DateTime::<Utc>::UNIX_EPOCH.naive_utc()
227    }
228}
229
230impl Timestamp for i64 {
231    fn from_now(now: DateTime<Utc>) -> Self {
232        now.timestamp()
233    }
234
235    fn is_empty(&self) -> bool {
236        *self == 0
237    }
238
239    fn empty() -> Self {
240        0
241    }
242}
243
244impl<T: Timestamp> Timestamp for Option<T> {
245    fn from_now(now: DateTime<Utc>) -> Self {
246        Some(T::from_now(now))
247    }
248
249    fn is_empty(&self) -> bool {
250        self.as_ref().is_none_or(T::is_empty)
251    }
252
253    fn empty() -> Self {
254        None
255    }
256}
257
258/// The OpenAPI schema of a column or appended value
259/// (`#[model(schema = Type)]` gives `Type`'s `ToSchema::schema`).
260pub type PartialSchemaFn = fn() -> navree_openapi::Schema;
261
262/// One column of a model, as `#[derive(Model)]` describes it.
263#[derive(Clone, Copy, Debug)]
264pub struct ColumnMeta {
265    name: &'static str,
266    field: &'static str,
267    rust_type: &'static str,
268    nullable: bool,
269    cast: Option<&'static str>,
270    serialized: Option<&'static str>,
271    kind: FieldKind,
272    serde_custom: bool,
273    serde_optional: bool,
274    mutator: bool,
275    schema: Option<PartialSchemaFn>,
276}
277
278impl ColumnMeta {
279    /// Column `name`, stored from struct field `field` of Rust type
280    /// `rust_type`, serialized under the field's name.
281    pub const fn new(name: &'static str, field: &'static str, rust_type: &'static str) -> Self {
282        ColumnMeta {
283            name,
284            field,
285            rust_type,
286            nullable: false,
287            cast: None,
288            serialized: Some(field),
289            kind: FieldKind::Any,
290            serde_custom: false,
291            serde_optional: false,
292            mutator: false,
293            schema: None,
294        }
295    }
296
297    /// The column holds NULLs (the field is an `Option`).
298    pub const fn nullable(self) -> Self {
299        ColumnMeta {
300            nullable: true,
301            ..self
302        }
303    }
304
305    /// The column is converted by cast `cast`.
306    pub const fn cast(self, cast: &'static str) -> Self {
307        ColumnMeta {
308            cast: Some(cast),
309            ..self
310        }
311    }
312
313    /// The key the field has in serialized records (serde's name for it);
314    /// `None` when serde never writes it.
315    pub const fn serialized_as(self, key: Option<&'static str>) -> Self {
316        ColumnMeta {
317            serialized: key,
318            ..self
319        }
320    }
321
322    /// What the field's values are in serialized records (from the field
323    /// type's [`Field::KIND`] or its cast's
324    /// [`Cast::KIND`](crate::cast::Cast::KIND)).
325    pub const fn kind(self, kind: FieldKind) -> Self {
326        ColumnMeta { kind, ..self }
327    }
328
329    /// Serde writes the field its own way (`serialize_with`, `with`,
330    /// `flatten`): serialized records keep what serde writes.
331    pub const fn serde_custom(self) -> Self {
332        ColumnMeta {
333            serde_custom: true,
334            ..self
335        }
336    }
337
338    /// Serde may leave the field out (`skip_serializing_if`).
339    pub const fn serde_optional(self) -> Self {
340        ColumnMeta {
341            serde_optional: true,
342            ..self
343        }
344    }
345
346    /// The field has a mutator (`#[model(set_with = ..)]`).
347    pub const fn mutator(self) -> Self {
348        ColumnMeta {
349            mutator: true,
350            ..self
351        }
352    }
353
354    /// The column's OpenAPI schema (`#[model(schema = Type)]`).
355    pub const fn schema(self, schema: PartialSchemaFn) -> Self {
356        ColumnMeta {
357            schema: Some(schema),
358            ..self
359        }
360    }
361
362    /// The column's name.
363    pub const fn name(&self) -> &'static str {
364        self.name
365    }
366
367    /// The struct field's name.
368    pub const fn field(&self) -> &'static str {
369        self.field
370    }
371
372    /// The field's Rust type, as written.
373    pub const fn rust_type(&self) -> &'static str {
374        self.rust_type
375    }
376
377    /// Whether the column holds NULLs.
378    pub const fn is_nullable(&self) -> bool {
379        self.nullable
380    }
381
382    /// The cast converting the column, if any.
383    pub const fn cast_name(&self) -> Option<&'static str> {
384        self.cast
385    }
386
387    /// The key the field has in serialized records; `None` when serde
388    /// never writes it (`#[serde(skip)]`).
389    pub const fn serialized_name(&self) -> Option<&'static str> {
390        self.serialized
391    }
392
393    /// What the field's values are in serialized records.
394    pub const fn field_kind(&self) -> FieldKind {
395        self.kind
396    }
397
398    /// Whether the field is a date-time that serialized records write in
399    /// the model's date format (no serde customization).
400    pub const fn is_date_time(&self) -> bool {
401        matches!(self.kind, FieldKind::DateTime) && !self.serde_custom
402    }
403
404    /// Whether the column holds JSON (a `serde_json::Value` field or a JSON
405    /// cast): fill keys may reach into it (`"meta->status"`).
406    pub const fn is_json(&self) -> bool {
407        matches!(self.kind, FieldKind::Json)
408    }
409
410    /// Whether serde writes the field its own way.
411    pub const fn has_custom_serde(&self) -> bool {
412        self.serde_custom
413    }
414
415    /// Whether serde may leave the field out of serialized records.
416    pub const fn is_serde_optional(&self) -> bool {
417        self.serde_optional
418    }
419
420    /// Whether the field has a mutator (`#[model(set_with = ..)]`).
421    pub const fn has_mutator(&self) -> bool {
422        self.mutator
423    }
424
425    /// The column's OpenAPI schema override, if any.
426    pub const fn schema_override(&self) -> Option<PartialSchemaFn> {
427        self.schema
428    }
429}
430
431impl PartialEq for ColumnMeta {
432    fn eq(&self, other: &Self) -> bool {
433        let same_schema = match (self.schema, other.schema) {
434            (Some(a), Some(b)) => std::ptr::fn_addr_eq(a, b),
435            (None, None) => true,
436            _ => false,
437        };
438        self.name == other.name
439            && self.field == other.field
440            && self.rust_type == other.rust_type
441            && self.nullable == other.nullable
442            && self.cast == other.cast
443            && self.serialized == other.serialized
444            && self.kind == other.kind
445            && self.serde_custom == other.serde_custom
446            && self.serde_optional == other.serde_optional
447            && self.mutator == other.mutator
448            && same_schema
449    }
450}
451
452impl Eq for ColumnMeta {}
453
454/// What `#[derive(Model)]` knows about a model: its name, table, key,
455/// columns, timestamps, soft-delete column, connection and page size.
456///
457/// Built with `const` methods, so the derive writes it as a `static`.
458///
459/// ```
460/// use navree_orm::{ColumnMeta, KeyKind, ModelMeta};
461///
462/// static COLUMNS: [ColumnMeta; 2] = [
463///     ColumnMeta::new("id", "id", "i64"),
464///     ColumnMeta::new("title", "title", "String"),
465/// ];
466/// static META: ModelMeta = ModelMeta::new("Deal", "deals")
467///     .primary_key("id", KeyKind::Increments)
468///     .columns(&COLUMNS)
469///     .per_page(25);
470/// assert_eq!(META.table(), "deals");
471/// assert_eq!(META.column("title").unwrap().rust_type(), "String");
472/// assert!(!META.uses_timestamps());
473/// ```
474#[derive(Debug)]
475pub struct ModelMeta {
476    name: &'static str,
477    table: &'static str,
478    key: &'static str,
479    key_kind: KeyKind,
480    columns: &'static [ColumnMeta],
481    created_at: Option<&'static str>,
482    updated_at: Option<&'static str>,
483    deleted_at: Option<&'static str>,
484    connection: Option<&'static str>,
485    driver: Option<&'static str>,
486    per_page: u64,
487    pruning: Option<crate::prune::Pruning>,
488    morph_name: Option<&'static str>,
489    foreign_key: Option<&'static str>,
490    touches: &'static [&'static str],
491    with: &'static [&'static str],
492    with_count: &'static [&'static str],
493    pivot_keys: Option<(&'static str, &'static str)>,
494    fillable: &'static [&'static str],
495    guarded: Option<&'static [&'static str]>,
496    unguarded: bool,
497    hidden: &'static [&'static str],
498    visible: &'static [&'static str],
499    appends: &'static [&'static str],
500    encrypter: Option<&'static str>,
501    cast_context: bool,
502    date_serializer: Option<DateSerializer>,
503    route_key: Option<&'static str>,
504    workspace: Option<&'static str>,
505    factory: Option<&'static str>,
506    relationships: Option<fn() -> Vec<RelationshipInfo>>,
507    subject: Option<&'static str>,
508    policy: Option<&'static str>,
509}
510
511/// How a model writes its date-times in serialized records
512/// (`#[model(serialize_dates_with = path)]`): the instant, with the offset
513/// the field had (UTC for `DateTime<Utc>` and `NaiveDateTime` fields), to
514/// any JSON value.
515pub type DateSerializer = fn(&DateTime<FixedOffset>) -> serde_json::Value;
516
517impl ModelMeta {
518    /// Model `name` stored in `table`, keyed by an auto-incrementing `id`,
519    /// 15 records per page, totally guarded (no column is fillable), with
520    /// nothing hidden and nothing appended.
521    pub const fn new(name: &'static str, table: &'static str) -> Self {
522        ModelMeta {
523            name,
524            table,
525            key: "id",
526            key_kind: KeyKind::Increments,
527            columns: &[],
528            created_at: None,
529            updated_at: None,
530            deleted_at: None,
531            connection: None,
532            driver: None,
533            per_page: 15,
534            pruning: None,
535            morph_name: None,
536            foreign_key: None,
537            touches: &[],
538            with: &[],
539            with_count: &[],
540            pivot_keys: None,
541            fillable: &[],
542            guarded: None,
543            unguarded: false,
544            hidden: &[],
545            visible: &[],
546            appends: &[],
547            encrypter: None,
548            cast_context: false,
549            date_serializer: None,
550            route_key: None,
551            workspace: None,
552            factory: None,
553            relationships: None,
554            subject: None,
555            policy: None,
556        }
557    }
558
559    /// The columns `fill` may set (`#[model(fillable(..))]`); JSON paths
560    /// into a JSON column are written `"meta->status"`.
561    pub const fn fillable(self, columns: &'static [&'static str]) -> Self {
562        ModelMeta {
563            fillable: columns,
564            ..self
565        }
566    }
567
568    /// The columns `fill` may not set (`#[model(guarded(..))]`); every other
569    /// column becomes fillable. An empty list guards nothing.
570    pub const fn guarded(self, columns: &'static [&'static str]) -> Self {
571        ModelMeta {
572            guarded: Some(columns),
573            ..self
574        }
575    }
576
577    /// Mass assignment is never guarded for this model
578    /// (`#[model(unguarded)]`).
579    pub const fn unguarded(self) -> Self {
580        ModelMeta {
581            unguarded: true,
582            ..self
583        }
584    }
585
586    /// The names left out of serialized records (`#[model(hidden(..))]` and
587    /// fields marked `#[model(hidden)]`).
588    pub const fn hidden(self, names: &'static [&'static str]) -> Self {
589        ModelMeta {
590            hidden: names,
591            ..self
592        }
593    }
594
595    /// The only names serialized records keep (`#[model(visible(..))]`);
596    /// empty keeps every name.
597    pub const fn visible(self, names: &'static [&'static str]) -> Self {
598        ModelMeta {
599            visible: names,
600            ..self
601        }
602    }
603
604    /// The accessors appended to serialized records
605    /// (`#[model(appends(..))]`).
606    pub const fn appends(self, names: &'static [&'static str]) -> Self {
607        ModelMeta {
608            appends: names,
609            ..self
610        }
611    }
612
613    /// The named `Encrypter` the model's encrypted casts use
614    /// (`#[model(encrypter = "...")]`).
615    pub const fn encrypter(self, name: &'static str) -> Self {
616        ModelMeta {
617            encrypter: Some(name),
618            ..self
619        }
620    }
621
622    /// The model's factory, as written in `#[model(factory = ...)]`, and
623    /// the relationships it declares (`model:show` lists both).
624    pub const fn factory(
625        self,
626        name: &'static str,
627        relationships: fn() -> Vec<RelationshipInfo>,
628    ) -> Self {
629        ModelMeta {
630            factory: Some(name),
631            relationships: Some(relationships),
632            ..self
633        }
634    }
635
636    /// The navree-access subject the model's records are
637    /// (`#[model(subject)]`).
638    pub const fn subject(self, subject: &'static str) -> Self {
639        ModelMeta {
640            subject: Some(subject),
641            ..self
642        }
643    }
644
645    /// The policy attached to the model, as written in
646    /// `#[model(policy = ...)]`.
647    pub const fn policy(self, policy: &'static str) -> Self {
648        ModelMeta {
649            policy: Some(policy),
650            ..self
651        }
652    }
653
654    /// The model's factory, as written in `#[model(factory = ...)]`.
655    pub const fn factory_name(&self) -> Option<&'static str> {
656        self.factory
657    }
658
659    /// The relationships the model's factory declares
660    /// ([`ModelFactory::relationships`](crate::factory::ModelFactory::relationships)),
661    /// in declaration order; none without a factory.
662    pub fn factory_relationships(&self) -> Vec<RelationshipInfo> {
663        self.relationships.map(|f| f()).unwrap_or_default()
664    }
665
666    /// The navree-access subject of the model's records, if it is one.
667    pub const fn subject_name(&self) -> Option<&'static str> {
668        self.subject
669    }
670
671    /// The policy attached to the model, as written.
672    pub const fn policy_name(&self) -> Option<&'static str> {
673        self.policy
674    }
675
676    /// The column route model binding looks records up by, when it is not
677    /// the key (`#[model(route_key = "slug")]`).
678    pub const fn route_key(self, column: &'static str) -> Self {
679        ModelMeta {
680            route_key: Some(column),
681            ..self
682        }
683    }
684
685    /// The column holding a workspace-scoped model's workspace
686    /// (`#[model(workspace)]`): queries see the current workspace's records
687    /// only, and new records get it.
688    pub const fn workspace(self, column: &'static str) -> Self {
689        ModelMeta {
690            workspace: Some(column),
691            ..self
692        }
693    }
694
695    /// Whether a cast of the model needs a
696    /// [`CastContext`](crate::attributes::CastContext) (resolved from the
697    /// app before records are read or written).
698    pub const fn cast_context(self, needed: bool) -> Self {
699        ModelMeta {
700            cast_context: needed,
701            ..self
702        }
703    }
704
705    /// How serialized records write the model's date-times
706    /// (`#[model(serialize_dates_with = path)]`).
707    pub const fn serialize_dates_with(self, serializer: DateSerializer) -> Self {
708        ModelMeta {
709            date_serializer: Some(serializer),
710            ..self
711        }
712    }
713
714    /// The name polymorphic type columns store for the model
715    /// (`#[model(morph_name = "...")]`; the derive writes the snake_case
716    /// type name when none is given).
717    pub const fn morph_name(self, name: &'static str) -> Self {
718        ModelMeta {
719            morph_name: Some(name),
720            ..self
721        }
722    }
723
724    /// The column other models' foreign keys to this model are named by
725    /// default (`company_id`).
726    pub const fn foreign_key(self, column: &'static str) -> Self {
727        ModelMeta {
728            foreign_key: Some(column),
729            ..self
730        }
731    }
732
733    /// The relations whose records are touched (their update timestamp
734    /// set to now) when a record of this model is saved or deleted
735    /// (`#[model(touches = ["company"])]`).
736    pub const fn touches(self, relations: &'static [&'static str]) -> Self {
737        ModelMeta {
738            touches: relations,
739            ..self
740        }
741    }
742
743    /// The relations every query of the model eager loads
744    /// (`#[model(with = ["company"])]`).
745    pub const fn with(self, relations: &'static [&'static str]) -> Self {
746        ModelMeta {
747            with: relations,
748            ..self
749        }
750    }
751
752    /// The relations every query of the model counts
753    /// (`#[model(with_count = ["notes"])]`).
754    pub const fn with_count(self, relations: &'static [&'static str]) -> Self {
755        ModelMeta {
756            with_count: relations,
757            ..self
758        }
759    }
760
761    /// For a pivot model without an `id` column: the pivot columns
762    /// pointing at the two related records. Its rows are identified by
763    /// both (`#[model(pivot(foreign_key = "deal_id", related_key =
764    /// "tag_id"))]`).
765    pub const fn pivot_keys(self, foreign_key: &'static str, related_key: &'static str) -> Self {
766        ModelMeta {
767            pivot_keys: Some((foreign_key, related_key)),
768            ..self
769        }
770    }
771
772    /// How `model:prune` prunes the model (`#[model(prunable)]`,
773    /// `#[model(mass_prunable)]`).
774    pub const fn pruned(self, pruning: crate::prune::Pruning) -> Self {
775        ModelMeta {
776            pruning: Some(pruning),
777            ..self
778        }
779    }
780
781    /// How the model is pruned, when it is prunable.
782    pub const fn pruning(&self) -> Option<&crate::prune::Pruning> {
783        self.pruning.as_ref()
784    }
785
786    /// The key column and how it gets its value.
787    pub const fn primary_key(self, column: &'static str, kind: KeyKind) -> Self {
788        ModelMeta {
789            key: column,
790            key_kind: kind,
791            ..self
792        }
793    }
794
795    /// The columns, in field order.
796    pub const fn columns(self, columns: &'static [ColumnMeta]) -> Self {
797        ModelMeta { columns, ..self }
798    }
799
800    /// The creation and update timestamp columns (either may be `None`).
801    pub const fn timestamps(
802        self,
803        created_at: Option<&'static str>,
804        updated_at: Option<&'static str>,
805    ) -> Self {
806        ModelMeta {
807            created_at,
808            updated_at,
809            ..self
810        }
811    }
812
813    /// The soft-delete column: deleting sets it, queries skip rows where it
814    /// is set.
815    pub const fn soft_deletes(self, column: &'static str) -> Self {
816        ModelMeta {
817            deleted_at: Some(column),
818            ..self
819        }
820    }
821
822    /// The named connection the model lives on.
823    pub const fn connection(self, name: &'static str) -> Self {
824        ModelMeta {
825            connection: Some(name),
826            ..self
827        }
828    }
829
830    /// The document driver the model is stored with (`mongodb`), declared
831    /// with `#[model(driver = "...")]`; SQL models declare none.
832    pub const fn driver(self, name: &'static str) -> Self {
833        ModelMeta {
834            driver: Some(name),
835            ..self
836        }
837    }
838
839    /// The default page size.
840    pub const fn per_page(self, per_page: u64) -> Self {
841        ModelMeta { per_page, ..self }
842    }
843
844    /// The model's name, e.g. `Deal`.
845    pub const fn name(&self) -> &'static str {
846        self.name
847    }
848
849    /// The table.
850    pub const fn table(&self) -> &'static str {
851        self.table
852    }
853
854    /// The key column.
855    pub const fn key_column(&self) -> &'static str {
856        self.key
857    }
858
859    /// How the key gets its value.
860    pub const fn key_kind(&self) -> KeyKind {
861        self.key_kind
862    }
863
864    /// Every column, in field order.
865    pub const fn all_columns(&self) -> &'static [ColumnMeta] {
866        self.columns
867    }
868
869    /// The column `name`, if the model has it.
870    pub fn column(&self, name: &str) -> Option<&'static ColumnMeta> {
871        self.columns.iter().find(|column| column.name == name)
872    }
873
874    /// Whether the model has column `name`.
875    pub fn has_column(&self, name: &str) -> bool {
876        self.column(name).is_some()
877    }
878
879    /// The creation timestamp column.
880    pub const fn created_at(&self) -> Option<&'static str> {
881        self.created_at
882    }
883
884    /// The update timestamp column.
885    pub const fn updated_at(&self) -> Option<&'static str> {
886        self.updated_at
887    }
888
889    /// Whether the model keeps either timestamp.
890    pub const fn uses_timestamps(&self) -> bool {
891        self.created_at.is_some() || self.updated_at.is_some()
892    }
893
894    /// The soft-delete column.
895    pub const fn deleted_at(&self) -> Option<&'static str> {
896        self.deleted_at
897    }
898
899    /// Whether the model soft-deletes.
900    pub const fn soft_deletes_enabled(&self) -> bool {
901        self.deleted_at.is_some()
902    }
903
904    /// The named connection, if the model declares one.
905    pub const fn connection_name(&self) -> Option<&'static str> {
906        self.connection
907    }
908
909    /// The document driver the model declares (`#[model(driver =
910    /// "mongodb")]`); `None` for SQL models.
911    pub const fn driver_name(&self) -> Option<&'static str> {
912        self.driver
913    }
914
915    /// The default page size.
916    pub const fn default_per_page(&self) -> u64 {
917        self.per_page
918    }
919
920    /// The name polymorphic type columns store for the model: the declared
921    /// one, else the snake_case model name (`DealStage` → `deal_stage`).
922    pub fn morph_type(&self) -> Cow<'static, str> {
923        match self.morph_name {
924            Some(name) => Cow::Borrowed(name),
925            None => Cow::Owned(snake_case(self.name)),
926        }
927    }
928
929    /// The default name of foreign keys to the model: the declared one,
930    /// else the snake_case model name, `_`, and the key column
931    /// (`Company` keyed by `id` → `company_id`).
932    pub fn foreign_key_name(&self) -> Cow<'static, str> {
933        match self.foreign_key {
934            Some(column) => Cow::Borrowed(column),
935            None => Cow::Owned(format!("{}_{}", snake_case(self.name), self.key)),
936        }
937    }
938
939    /// The relations touched when a record is saved or deleted.
940    pub const fn touched_relations(&self) -> &'static [&'static str] {
941        self.touches
942    }
943
944    /// The relations every query eager loads.
945    pub const fn default_with(&self) -> &'static [&'static str] {
946        self.with
947    }
948
949    /// The relations every query counts.
950    pub const fn default_with_count(&self) -> &'static [&'static str] {
951        self.with_count
952    }
953
954    /// The two pivot columns of a pivot model (`#[model(pivot(..))]`):
955    /// `(foreign_key, related_key)`. A pivot model without an `id` column
956    /// is keyed by `related_key`, and its rows are identified by both.
957    pub const fn pivot_key_columns(&self) -> Option<(&'static str, &'static str)> {
958        self.pivot_keys
959    }
960
961    /// The fillable columns, as declared.
962    pub const fn fillable_columns(&self) -> &'static [&'static str] {
963        self.fillable
964    }
965
966    /// The guarded columns, as declared: `None` when the model declares no
967    /// guarded list (then every column is guarded unless it is fillable).
968    pub const fn guarded_columns(&self) -> Option<&'static [&'static str]> {
969        self.guarded
970    }
971
972    /// Whether the model is never guarded (`#[model(unguarded)]`).
973    pub const fn is_unguarded(&self) -> bool {
974        self.unguarded
975    }
976
977    /// The names hidden in serialized records.
978    pub const fn hidden_names(&self) -> &'static [&'static str] {
979        self.hidden
980    }
981
982    /// The only names serialized records keep; empty keeps every name.
983    pub const fn visible_names(&self) -> &'static [&'static str] {
984        self.visible
985    }
986
987    /// The accessors appended to serialized records.
988    pub const fn appended_names(&self) -> &'static [&'static str] {
989        self.appends
990    }
991
992    /// The named `Encrypter` the model's encrypted casts use, if it names
993    /// one.
994    pub const fn encrypter_name(&self) -> Option<&'static str> {
995        self.encrypter
996    }
997
998    /// Whether a cast of the model needs a cast context.
999    pub const fn uses_cast_context(&self) -> bool {
1000        self.cast_context
1001    }
1002
1003    /// How serialized records write the model's date-times, when the model
1004    /// overrides the default (RFC 3339, UTC, microseconds).
1005    pub const fn date_serializer(&self) -> Option<DateSerializer> {
1006        self.date_serializer
1007    }
1008
1009    /// The column whose field is `field` (its first column, for a field
1010    /// stored across several columns).
1011    pub fn column_of_field(&self, field: &str) -> Option<&'static ColumnMeta> {
1012        self.columns.iter().find(|column| column.field == field)
1013    }
1014
1015    /// The column called `name`, or the column of the field called `name`.
1016    pub fn column_named(&self, name: &str) -> Option<&'static ColumnMeta> {
1017        self.column(name).or_else(|| self.column_of_field(name))
1018    }
1019
1020    /// The column route model binding looks records up by: the declared
1021    /// route key, else the key column.
1022    pub const fn route_key_column(&self) -> &'static str {
1023        match self.route_key {
1024            Some(column) => column,
1025            None => self.key,
1026        }
1027    }
1028
1029    /// The workspace column of a workspace-scoped model.
1030    pub const fn workspace_column(&self) -> Option<&'static str> {
1031        self.workspace
1032    }
1033
1034    /// Whether the model is scoped to workspaces.
1035    pub const fn is_workspace_scoped(&self) -> bool {
1036        self.workspace.is_some()
1037    }
1038}
1039
1040/// `DealStage` → `deal_stage`, `HTTPRequest` → `http_request`.
1041pub(crate) fn snake_case(name: &str) -> String {
1042    let chars: Vec<char> = name.chars().collect();
1043    let mut out = String::with_capacity(name.len() + 4);
1044    for (i, &c) in chars.iter().enumerate() {
1045        if c.is_uppercase() {
1046            let previous = i.checked_sub(1).map(|j| chars[j]);
1047            let next = chars.get(i + 1).copied();
1048            let boundary = match previous {
1049                Some(p) if p.is_lowercase() || p.is_ascii_digit() => true,
1050                Some(p) if p.is_uppercase() => next.is_some_and(char::is_lowercase),
1051                _ => false,
1052            };
1053            if boundary && !out.ends_with('_') {
1054                out.push('_');
1055            }
1056            out.extend(c.to_lowercase());
1057        } else {
1058            out.push(c);
1059        }
1060    }
1061    out
1062}
1063
1064/// An ORM model: a plain struct with `#[derive(Model)]`.
1065///
1066/// The derive implements the required methods; the provided ones are the
1067/// model API, all taking the executor first:
1068///
1069/// ```no_run
1070/// # use navree_orm::__doc_models::*;
1071/// # async fn demo(db: Db, uow: Uow) -> Result<()> {
1072/// let deal = Deal::create(&uow, Deal { title: "Renewal".into(), ..Default::default() }).await?;
1073/// let found = Deal::find(&db, deal.id).await?;
1074/// let open = Deal::query().where_(Deal::CLOSED_AT.is_null()).latest().get(&db).await?;
1075/// let removed = Deal::destroy(&uow, [deal.id]).await?;
1076/// # Ok(()) }
1077/// ```
1078///
1079/// Records come back as [`Record<Self>`](Record), which dereferences to
1080/// the model and tracks what changed.
1081pub trait Model: Clone + Send + Sync + Serialize + 'static {
1082    /// The key's Rust type.
1083    type Key: PrimaryKey;
1084
1085    /// What the derive knows about the model.
1086    fn meta() -> &'static ModelMeta;
1087
1088    /// The key.
1089    fn key(&self) -> Self::Key;
1090
1091    /// Sets the key.
1092    fn set_key(&mut self, key: Self::Key);
1093
1094    /// Reads a model from a row.
1095    fn from_row(row: &Row) -> Result<Self>;
1096
1097    /// Every column and its stored value, in field order.
1098    fn values(&self) -> Result<Vec<(&'static str, Value)>>;
1099
1100    /// The stored value of `column`; `None` when the model has no such
1101    /// column.
1102    fn value(&self, column: &str) -> Result<Option<Value>>;
1103
1104    /// Sets `column` from a stored value.
1105    fn set_value(&mut self, column: &str, value: Value) -> Result<()>;
1106
1107    /// Sets timestamp column `column` to `now`.
1108    fn touch_timestamp(&mut self, column: &str, now: DateTime<Utc>) -> Result<()>;
1109
1110    /// Whether timestamp column `column` is unset.
1111    fn timestamp_is_empty(&self, column: &str) -> bool;
1112
1113    /// Unsets timestamp column `column`.
1114    fn clear_timestamp(&mut self, column: &str);
1115
1116    /// The stored value of timestamp column `column` at `now`.
1117    fn timestamp_value(column: &str, now: DateTime<Utc>) -> Option<Value>;
1118
1119    /// The global scopes applied to every query of the model
1120    /// (`#[model(global_scopes(..))]`).
1121    fn global_scopes() -> Vec<Arc<dyn GlobalScope<Self>>> {
1122        Vec::new()
1123    }
1124
1125    /// The model's own lifecycle hooks, run before the app's (see
1126    /// [`hooks`](crate::hooks)).
1127    fn hooks() -> Vec<Arc<dyn ModelHook<Self>>> {
1128        Vec::new()
1129    }
1130
1131    // ---------------------------------------------------------------------
1132    // Attributes (the derive writes these from the field types, casts and
1133    // `#[model(..)]` attributes)
1134    // ---------------------------------------------------------------------
1135
1136    /// Sets `column` from untyped input, the way mass assignment does: the
1137    /// value is converted to the field's type (through its cast's
1138    /// [`from_json`](crate::cast::Cast::from_json)), then assigned through
1139    /// the field's mutator (`#[model(set_with = ..)]`) when it has one.
1140    /// Unknown columns are errors.
1141    ///
1142    /// Unlike [`set_value`](Model::set_value), which takes the *stored*
1143    /// form (what the database holds: a ciphertext, an enum's name), this
1144    /// takes the *plain* form a user sends (the secret, the enum's name).
1145    fn set_attribute(&mut self, column: &str, input: serde_json::Value) -> Result<()> {
1146        self.set_value(column, crate::value::json_to_value(input))
1147    }
1148
1149    /// Sets several columns of field `field` (a field stored across several
1150    /// columns) from untyped input at once, so the field is checked whole
1151    /// rather than one column at a time.
1152    #[doc(hidden)]
1153    fn set_attribute_parts(
1154        &mut self,
1155        field: &str,
1156        inputs: Vec<(String, serde_json::Value)>,
1157    ) -> Result<()> {
1158        let _ = field;
1159        for (column, input) in inputs {
1160            self.set_attribute(&column, input)?;
1161        }
1162        Ok(())
1163    }
1164
1165    /// The columns whose values differ between `self` and `original`
1166    /// (dirty tracking), compared as stored: floats within a small
1167    /// tolerance, decimals numerically, date-times by instant, JSON
1168    /// structurally, cast fields by their cast's
1169    /// [`same`](crate::cast::Cast::same).
1170    fn changed_columns(&self, original: &Self) -> Result<Vec<&'static str>> {
1171        let now = self.values()?;
1172        let then = original.values()?;
1173        Ok(now
1174            .into_iter()
1175            .zip(then)
1176            .filter(|((_, a), (_, b))| !crate::value::same_value(a, b))
1177            .map(|((column, _), _)| column)
1178            .collect())
1179    }
1180
1181    /// The JSON value of JSON column `column` (a `serde_json::Value` field
1182    /// or a JSON cast), for edits by path; `None` when the model has no
1183    /// such JSON column.
1184    fn json_attribute(&self, column: &str) -> Result<Option<serde_json::Value>> {
1185        let _ = column;
1186        Ok(None)
1187    }
1188
1189    /// The accessors of the model (`#[accessor]` methods in an
1190    /// `#[accessors]` impl block), which serialized records can append.
1191    fn accessors() -> &'static [Accessor<Self>] {
1192        &[]
1193    }
1194
1195    /// The columns `fill` may set, as declared (`#[model(fillable(..))]`).
1196    fn fillable() -> &'static [&'static str] {
1197        Self::meta().fillable_columns()
1198    }
1199
1200    /// The columns `fill` may not set, as declared (`#[model(guarded(..))]`);
1201    /// `None` when the model declares none (every column not fillable is
1202    /// guarded).
1203    fn guarded() -> Option<&'static [&'static str]> {
1204        Self::meta().guarded_columns()
1205    }
1206
1207    /// Whether `fill` may set `column` (or the JSON path `column->path`).
1208    fn is_fillable(column: &str) -> bool {
1209        crate::attributes::fill::is_fillable(Self::meta(), column, false)
1210    }
1211
1212    /// Whether `column` is guarded against mass assignment.
1213    fn is_guarded(column: &str) -> bool {
1214        crate::attributes::fill::is_guarded(Self::meta(), column, false)
1215    }
1216
1217    /// Whether the model declares neither fillable nor guarded columns, so
1218    /// every `fill` is refused (`force_fill` still works).
1219    fn totally_guarded() -> bool {
1220        crate::attributes::fill::totally_guarded(Self::meta(), false)
1221    }
1222
1223    /// Runs the casts' asynchronous preparation before the record is
1224    /// written (the hashed cast hashes plain values here).
1225    #[doc(hidden)]
1226    fn prepare_for_write<'a>(&'a mut self, context: &'a CastContext) -> BoxFuture<'a, Result<()>> {
1227        let _ = context;
1228        Box::pin(std::future::ready(Ok(())))
1229    }
1230
1231    /// The values casts write into serialized records themselves
1232    /// ([`Cast::serialize`](crate::cast::Cast::serialize)), by serialized
1233    /// key.
1234    #[doc(hidden)]
1235    fn serialized_overrides(&self) -> Result<Vec<(&'static str, serde_json::Value)>> {
1236        Ok(Vec::new())
1237    }
1238
1239    /// The cast columns of `row` whose stored values should be rewritten
1240    /// ([`Cast::is_stale`](crate::cast::Cast::is_stale)).
1241    #[doc(hidden)]
1242    fn stale_columns(row: &Row) -> Vec<&'static str> {
1243        let _ = row;
1244        Vec::new()
1245    }
1246
1247    /// Adds (or subtracts) `amount`, given in the stored form, to cast
1248    /// column `column` in memory, through the cast's
1249    /// [`increment`](crate::cast::Cast::increment) and
1250    /// [`decrement`](crate::cast::Cast::decrement).
1251    #[doc(hidden)]
1252    fn increment_cast(&mut self, column: &str, amount: Value, decrement: bool) -> Result<()> {
1253        let _ = (amount, decrement);
1254        Err(derive_support::not_a_cast_column::<Self>(column))
1255    }
1256
1257    /// The relation named `name`, for relation paths (`"company.owner"` in
1258    /// `with`, `has`, `load`, ...): the ones a `#[relations]` impl block
1259    /// declares, then the ones other modules define with
1260    /// [`RelationRegistry`](crate::relations::RelationRegistry).
1261    /// `#[derive(Model)]` writes this method.
1262    fn relation(name: &str) -> Option<DynRelation<Self>> {
1263        crate::relations::registry::defined::<Self>(name)
1264    }
1265
1266    /// The names of the model's relations (declared, then registered).
1267    fn relation_names() -> Vec<Cow<'static, str>> {
1268        crate::relations::registry::defined_names::<Self>()
1269    }
1270
1271    /// What relation `name` is: its kind, related model, tables and keys
1272    /// (for tooling such as `model:show` and API documentation).
1273    ///
1274    /// ```
1275    /// # use navree_orm::__doc_models::*;
1276    /// use navree_orm::relations::RelationKind;
1277    ///
1278    /// let company = Deal::relation_meta("company").unwrap();
1279    /// assert_eq!(company.kind, RelationKind::BelongsTo);
1280    /// assert_eq!(company.related, Some("Company"));
1281    /// assert_eq!(company.foreign_key.as_deref(), Some("company_id"));
1282    /// assert!(Deal::relation_meta("nope").is_none());
1283    /// ```
1284    fn relation_meta(name: &str) -> Option<RelationMeta> {
1285        Self::relation(name).map(|relation| relation.meta())
1286    }
1287
1288    /// The name polymorphic type columns store for the model
1289    /// (`#[model(morph_name = "...")]`, else the snake_case type name).
1290    fn morph_name() -> Cow<'static, str> {
1291        Self::meta().morph_type()
1292    }
1293
1294    /// The default name of foreign keys to the model (`company_id`): the
1295    /// snake_case type name, `_`, the key column.
1296    fn foreign_key_name() -> Cow<'static, str> {
1297        Self::meta().foreign_key_name()
1298    }
1299
1300    /// The relations touched when a record is saved or deleted
1301    /// (`#[model(touches = [..])]`).
1302    fn touched_relations() -> &'static [&'static str] {
1303        Self::meta().touched_relations()
1304    }
1305
1306    /// The model's table.
1307    ///
1308    /// ```
1309    /// # use navree_orm::__doc_models::*;
1310    /// assert_eq!(Company::table_name(), "companies");
1311    /// ```
1312    fn table_name() -> &'static str {
1313        Self::meta().table()
1314    }
1315
1316    /// The column route model binding looks records up by: the model's
1317    /// `#[model(route_key = "...")]`, else its key column.
1318    ///
1319    /// ```
1320    /// # use navree_orm::__doc_models::*;
1321    /// assert_eq!(Deal::route_key_name(), "id");
1322    /// ```
1323    fn route_key_name() -> &'static str {
1324        Self::meta().route_key_column()
1325    }
1326
1327    /// A query of the model, with the model's default eager loads and
1328    /// relation counts (`#[model(with = [..], with_count = [..])]`).
1329    fn query() -> Builder<Self> {
1330        Builder::new().with_model_defaults()
1331    }
1332
1333    /// A query of the model with one condition (and the model's default
1334    /// eager loads and relation counts, as [`query`](Model::query)).
1335    fn where_(filter: impl Into<Filter>) -> Builder<Self> {
1336        Self::query().where_(filter)
1337    }
1338
1339    /// The connection the model lives on (`#[model(connection = "..")]`);
1340    /// `None` runs it on the executor's. Given the default `Db`, the
1341    /// model's queries and records go to this connection.
1342    fn connection_name() -> Option<&'static str> {
1343        Self::meta().connection_name()
1344    }
1345
1346    /// A query of the model on connection `name`, whatever the model's
1347    /// (see [`Builder::on_connection`]).
1348    fn on_connection(name: impl Into<std::borrow::Cow<'static, str>>) -> Builder<Self> {
1349        Builder::new().on_connection(name)
1350    }
1351
1352    /// A query of the model reading from the writer, even where read
1353    /// replicas exist (see [`Builder::use_write`]).
1354    ///
1355    /// ```no_run
1356    /// # use navree_orm::__doc_models::*;
1357    /// # async fn demo(db: Db, id: Uuid) -> Result<()> {
1358    /// let current = Deal::on_write_connection().find(&db, id).await?;
1359    /// # Ok(()) }
1360    /// ```
1361    fn on_write_connection() -> Builder<Self> {
1362        Builder::new().use_write()
1363    }
1364
1365    /// Every record.
1366    fn all<E: Executor + ?Sized>(
1367        exec: &E,
1368    ) -> impl Future<Output = Result<Collection<Self>>> + Send {
1369        Self::query().get(exec)
1370    }
1371
1372    /// The record with key `key`.
1373    fn find<E: Executor + ?Sized>(
1374        exec: &E,
1375        key: impl Into<Self::Key>,
1376    ) -> impl Future<Output = Result<Option<Record<Self>>>> + Send {
1377        let key: Self::Key = key.into();
1378        Self::query().find(exec, key)
1379    }
1380
1381    /// The record with key `key`, or [`OrmError::ModelNotFound`](crate::OrmError::ModelNotFound) (a 404 over
1382    /// HTTP).
1383    fn find_or_fail<E: Executor + ?Sized>(
1384        exec: &E,
1385        key: impl Into<Self::Key>,
1386    ) -> impl Future<Output = Result<Record<Self>>> + Send {
1387        let key: Self::Key = key.into();
1388        Self::query().find_or_fail(exec, key)
1389    }
1390
1391    /// The records with these keys (missing ones are left out).
1392    fn find_many<E: Executor + ?Sized>(
1393        exec: &E,
1394        keys: impl IntoIterator<Item = impl Into<Self::Key>>,
1395    ) -> impl Future<Output = Result<Collection<Self>>> + Send {
1396        let keys: Vec<Self::Key> = keys.into_iter().map(Into::into).collect();
1397        Self::query().find_many(exec, keys)
1398    }
1399
1400    /// Inserts `model` and returns its record (with any generated key and
1401    /// timestamps).
1402    fn create<E: Executor + ?Sized>(
1403        exec: &E,
1404        model: Self,
1405    ) -> impl Future<Output = Result<Record<Self>>> + Send {
1406        async move {
1407            let mut record = Record::new(model);
1408            record.save(exec).await?;
1409            Ok(record)
1410        }
1411    }
1412
1413    /// Inserts a record built from the model's defaults and filled with
1414    /// untyped `attributes` (guarded: only fillable columns are set; see
1415    /// [`Record::fill`]).
1416    ///
1417    /// ```no_run
1418    /// # use navree_orm::__doc_models::*;
1419    /// # async fn demo(uow: Uow, body: navree_orm::attributes::Attributes) -> Result<()> {
1420    /// let tag = Tag::create_from(&uow, body).await?;
1421    /// # Ok(()) }
1422    /// ```
1423    fn create_from<E: Executor + ?Sized>(
1424        exec: &E,
1425        attributes: impl Into<crate::attributes::Attributes>,
1426    ) -> impl Future<Output = Result<Record<Self>>> + Send
1427    where
1428        Self: Default,
1429    {
1430        let attributes = attributes.into();
1431        Self::query().create_from(exec, attributes)
1432    }
1433
1434    /// Inserts a record built from the model's defaults with every key of
1435    /// `attributes` set, ignoring the model's guards (see
1436    /// [`Record::force_fill`]).
1437    fn force_create<E: Executor + ?Sized>(
1438        exec: &E,
1439        attributes: impl Into<crate::attributes::Attributes>,
1440    ) -> impl Future<Output = Result<Record<Self>>> + Send
1441    where
1442        Self: Default,
1443    {
1444        let attributes = attributes.into();
1445        Self::query().force_create(exec, attributes)
1446    }
1447
1448    /// Inserts `models` as they are, in one statement without hooks or
1449    /// change events (see [`Builder::insert`]); returns how many rows were
1450    /// inserted.
1451    fn insert<E: Executor + ?Sized>(
1452        exec: &E,
1453        models: impl IntoIterator<Item = Self>,
1454    ) -> impl Future<Output = Result<u64>> + Send {
1455        let models: Vec<Self> = models.into_iter().collect();
1456        Self::query().insert(exec, models)
1457    }
1458
1459    /// Inserts `models` as they are, skipping the ones that conflict with a
1460    /// unique index (see [`Builder::insert_or_ignore`]).
1461    fn insert_or_ignore<E: Executor + ?Sized>(
1462        exec: &E,
1463        models: impl IntoIterator<Item = Self>,
1464    ) -> impl Future<Output = Result<u64>> + Send {
1465        let models: Vec<Self> = models.into_iter().collect();
1466        Self::query().insert_or_ignore(exec, models)
1467    }
1468
1469    /// Inserts `models` with generated keys and timestamps, in one
1470    /// statement without hooks (see [`Builder::fill_and_insert`]).
1471    fn fill_and_insert<E: Executor + ?Sized>(
1472        exec: &E,
1473        models: impl IntoIterator<Item = Self>,
1474    ) -> impl Future<Output = Result<u64>> + Send {
1475        let models: Vec<Self> = models.into_iter().collect();
1476        Self::query().fill_and_insert(exec, models)
1477    }
1478
1479    /// Inserts `models`, updating the stored rows they conflict with on
1480    /// `unique_by` (see [`Builder::upsert`]).
1481    fn upsert<E, U>(
1482        exec: &E,
1483        models: impl IntoIterator<Item = Self>,
1484        unique_by: impl IntoIterator<Item = impl crate::column::ColumnName>,
1485        update: impl IntoIterator<Item = U>,
1486    ) -> impl Future<Output = Result<u64>> + Send
1487    where
1488        E: Executor + ?Sized,
1489        U: Into<crate::query::ConflictUpdate>,
1490    {
1491        let models: Vec<Self> = models.into_iter().collect();
1492        let unique_by: Vec<String> = unique_by
1493            .into_iter()
1494            .map(|column| column.column_name().into_owned())
1495            .collect();
1496        let update: Vec<crate::query::ConflictUpdate> =
1497            update.into_iter().map(Into::into).collect();
1498        Self::query().upsert(exec, models, unique_by, update)
1499    }
1500
1501    /// Deletes the records with these keys one by one (so each one's
1502    /// lifecycle runs); returns how many were deleted.
1503    fn destroy<E: Executor + ?Sized>(
1504        exec: &E,
1505        keys: impl IntoIterator<Item = impl Into<Self::Key>>,
1506    ) -> impl Future<Output = Result<u64>> + Send {
1507        let keys: Vec<Self::Key> = keys.into_iter().map(Into::into).collect();
1508        async move {
1509            if keys.is_empty() {
1510                return Ok(0);
1511            }
1512            let records = Self::query().where_key_in(keys).get(exec).await?;
1513            let mut deleted = 0;
1514            for mut record in records {
1515                if record.delete(exec).await? {
1516                    deleted += 1;
1517                }
1518            }
1519            Ok(deleted)
1520        }
1521    }
1522
1523    /// The first record matching `attributes`, or a new one with them
1524    /// (and whatever `fill` sets) inserted. A concurrent insert of the same
1525    /// record (a unique violation) returns the record that won.
1526    fn first_or_create<E: Executor + ?Sized>(
1527        exec: &E,
1528        attributes: impl IntoIterator<Item = Assignment>,
1529        fill: impl FnOnce(&mut Self) + Send,
1530    ) -> impl Future<Output = Result<Record<Self>>> + Send
1531    where
1532        Self: Default,
1533    {
1534        let attributes: Vec<Assignment> = attributes.into_iter().collect();
1535        Self::query().first_or_create(exec, attributes, fill)
1536    }
1537
1538    /// The first record matching `attributes`, or a new, unsaved one with
1539    /// them (and whatever `fill` sets).
1540    fn first_or_new<E: Executor + ?Sized>(
1541        exec: &E,
1542        attributes: impl IntoIterator<Item = Assignment>,
1543        fill: impl FnOnce(&mut Self) + Send,
1544    ) -> impl Future<Output = Result<Record<Self>>> + Send
1545    where
1546        Self: Default,
1547    {
1548        let attributes: Vec<Assignment> = attributes.into_iter().collect();
1549        Self::query().first_or_new(exec, attributes, fill)
1550    }
1551
1552    /// Inserts a record with `attributes` (and whatever `fill` sets), or,
1553    /// when that violates a unique constraint, returns the record matching
1554    /// `attributes`.
1555    fn create_or_first<E: Executor + ?Sized>(
1556        exec: &E,
1557        attributes: impl IntoIterator<Item = Assignment>,
1558        fill: impl FnOnce(&mut Self) + Send,
1559    ) -> impl Future<Output = Result<Record<Self>>> + Send
1560    where
1561        Self: Default,
1562    {
1563        let attributes: Vec<Assignment> = attributes.into_iter().collect();
1564        Self::query().create_or_first(exec, attributes, fill)
1565    }
1566
1567    /// Updates the first record matching `attributes` with `fill`, or
1568    /// creates one with both.
1569    fn update_or_create<E: Executor + ?Sized>(
1570        exec: &E,
1571        attributes: impl IntoIterator<Item = Assignment>,
1572        fill: impl Fn(&mut Self) + Send + Sync,
1573    ) -> impl Future<Output = Result<Record<Self>>> + Send
1574    where
1575        Self: Default,
1576    {
1577        let attributes: Vec<Assignment> = attributes.into_iter().collect();
1578        Self::query().update_or_create(exec, attributes, fill)
1579    }
1580}
1581
1582/// Functions `#[derive(Model)]` expands to. Not part of the API.
1583#[doc(hidden)]
1584pub mod derive_support {
1585    use std::borrow::Cow;
1586
1587    use serde::Serialize;
1588
1589    use crate::attributes::CastContext;
1590    use crate::cast::{Cast, CastError, MultiColumnCast, StoredColumns};
1591    use crate::error::OrmError;
1592    use crate::model::Model;
1593    use crate::row::{Row, decode_error};
1594    use crate::value::{Field, FieldError, Value, same_value};
1595
1596    fn cast_error<M: Model>(column: &str, message: impl Into<String>) -> OrmError {
1597        OrmError::Cast {
1598            model: Cow::Borrowed(M::meta().name()),
1599            column: column.to_owned(),
1600            message: message.into(),
1601        }
1602    }
1603
1604    /// Reads field column `column` of model `M`; `default` is the field's
1605    /// default when its type has one (for a column a partial select left
1606    /// out, in lenient mode).
1607    pub fn read<M: Model, T: Field>(
1608        row: &Row,
1609        column: &str,
1610        default: Option<fn() -> T>,
1611    ) -> Result<T, OrmError> {
1612        match row.field::<T>(column) {
1613            Ok(value) => Ok(value),
1614            Err(FieldError::Missing) => missing::<M, T>(row, column, T::type_name(), default),
1615            Err(error) => Err(decode_error(
1616                M::meta().name(),
1617                column,
1618                T::type_name(),
1619                &error,
1620            )),
1621        }
1622    }
1623
1624    /// A field whose column the row lacks: an error in strict mode (unless
1625    /// a handler tolerates it) and when the field has no default; else the
1626    /// default.
1627    fn missing<M: Model, T>(
1628        row: &Row,
1629        column: &str,
1630        expected: Cow<'static, str>,
1631        default: Option<fn() -> T>,
1632    ) -> Result<T, OrmError> {
1633        let error = |expected| OrmError::MissingAttribute {
1634            model: Cow::Borrowed(M::meta().name()),
1635            column: column.to_owned(),
1636            expected,
1637            selected: row.columns(),
1638        };
1639        let Some(default) = default else {
1640            return Err(error(expected));
1641        };
1642        crate::strict::current().check_with(
1643            crate::strict::Violation::MissingAttribute {
1644                model: M::meta().name(),
1645                column: column.to_owned(),
1646            },
1647            |_| error(expected),
1648        )?;
1649        Ok(default())
1650    }
1651
1652    /// The default of a field's type, when it has one: `(&DefaultOf::<T>::new()).default_fn()`
1653    /// is `Some(T::default)` for a `T: Default` and `None` otherwise (the
1654    /// derive names concrete types, so the method resolves to one of
1655    /// [`ViaDefault`] and [`WithoutDefault`]).
1656    pub struct DefaultOf<T>(std::marker::PhantomData<fn() -> T>);
1657
1658    impl<T> DefaultOf<T> {
1659        /// The probe for `T`.
1660        pub const fn new() -> Self {
1661            DefaultOf(std::marker::PhantomData)
1662        }
1663    }
1664
1665    impl<T> Default for DefaultOf<T> {
1666        fn default() -> Self {
1667            DefaultOf::new()
1668        }
1669    }
1670
1671    /// The default of a type that has one.
1672    pub trait ViaDefault {
1673        /// The field type.
1674        type Field;
1675        /// `Some(Field::default)`.
1676        fn default_fn(&self) -> Option<fn() -> Self::Field>;
1677    }
1678
1679    impl<T: Default> ViaDefault for DefaultOf<T> {
1680        type Field = T;
1681        fn default_fn(&self) -> Option<fn() -> T> {
1682            Some(T::default)
1683        }
1684    }
1685
1686    /// No default for a type that has none.
1687    pub trait WithoutDefault {
1688        /// The field type.
1689        type Field;
1690        /// `None`.
1691        fn default_fn(&self) -> Option<fn() -> Self::Field>;
1692    }
1693
1694    impl<T> WithoutDefault for &DefaultOf<T> {
1695        type Field = T;
1696        fn default_fn(&self) -> Option<fn() -> T> {
1697            None
1698        }
1699    }
1700
1701    /// Reads field column `column`, or the field's default when the row
1702    /// does not have it (`#[model(default)]`).
1703    pub fn read_or_default<M: Model, T: Field + Default>(
1704        row: &Row,
1705        column: &str,
1706    ) -> Result<T, OrmError> {
1707        match row.field::<T>(column) {
1708            Ok(value) => Ok(value),
1709            Err(FieldError::Missing) => Ok(T::default()),
1710            Err(error) => Err(decode_error(
1711                M::meta().name(),
1712                column,
1713                T::type_name(),
1714                &error,
1715            )),
1716        }
1717    }
1718
1719    /// Reads cast column `column` through cast `C`; `default` as for
1720    /// [`read`].
1721    pub fn read_cast<M: Model, C: Cast<T>, T>(
1722        row: &Row,
1723        column: &str,
1724        default: Option<fn() -> T>,
1725    ) -> Result<T, OrmError> {
1726        match row.field::<C::Stored>(column) {
1727            Ok(stored) => get::<M, C, T>(column, stored),
1728            Err(FieldError::Missing) => {
1729                missing::<M, T>(row, column, C::Stored::type_name(), default)
1730            }
1731            Err(error) => Err(decode_error(
1732                M::meta().name(),
1733                column,
1734                C::Stored::type_name(),
1735                &error,
1736            )),
1737        }
1738    }
1739
1740    /// `C::get_with` with the current cast context.
1741    fn get<M: Model, C: Cast<T>, T>(column: &str, stored: C::Stored) -> Result<T, OrmError> {
1742        CastContext::with_current(|context| C::get_with(stored, context))
1743            .map_err(|error| cast_error::<M>(column, error.to_string()))
1744    }
1745
1746    /// `C::set_with` with the current cast context.
1747    fn set<M: Model, C: Cast<T>, T>(column: &str, value: &T) -> Result<C::Stored, OrmError> {
1748        CastContext::with_current(|context| C::set_with(value, context))
1749            .map_err(|error| cast_error::<M>(column, error.to_string()))
1750    }
1751
1752    /// Reads nullable cast column `column` through cast `C`; `default` as
1753    /// for [`read`].
1754    pub fn read_cast_option<M: Model, C: Cast<T>, T>(
1755        row: &Row,
1756        column: &str,
1757        default: Option<fn() -> Option<T>>,
1758    ) -> Result<Option<T>, OrmError> {
1759        match row.field::<Option<C::Stored>>(column) {
1760            Ok(Some(stored)) => get::<M, C, T>(column, stored).map(Some),
1761            Ok(None) => Ok(None),
1762            Err(FieldError::Missing) => {
1763                missing::<M, Option<T>>(row, column, <Option<C::Stored>>::type_name(), default)
1764            }
1765            Err(error) => Err(decode_error(
1766                M::meta().name(),
1767                column,
1768                <Option<C::Stored>>::type_name(),
1769                &error,
1770            )),
1771        }
1772    }
1773
1774    /// Reads cast column `column`, or the default when the row lacks it.
1775    pub fn read_cast_or_default<M: Model, C: Cast<T>, T: Default>(
1776        row: &Row,
1777        column: &str,
1778    ) -> Result<T, OrmError> {
1779        if row.has_column(column) {
1780            read_cast::<M, C, T>(row, column, Some(T::default))
1781        } else {
1782            Ok(T::default())
1783        }
1784    }
1785
1786    /// Reads nullable cast column `column`, or `None` when the row lacks it.
1787    pub fn read_cast_option_or_default<M: Model, C: Cast<T>, T>(
1788        row: &Row,
1789        column: &str,
1790    ) -> Result<Option<T>, OrmError> {
1791        if row.has_column(column) {
1792            read_cast_option::<M, C, T>(row, column, Some(|| None))
1793        } else {
1794            Ok(None)
1795        }
1796    }
1797
1798    /// The stored value of a cast field.
1799    pub fn write_cast<M: Model, C: Cast<T>, T>(column: &str, value: &T) -> Result<Value, OrmError> {
1800        set::<M, C, T>(column, value).map(|stored| stored.to_value())
1801    }
1802
1803    /// The stored value of a nullable cast field.
1804    pub fn write_cast_option<M: Model, C: Cast<T>, T>(
1805        column: &str,
1806        value: &Option<T>,
1807    ) -> Result<Value, OrmError> {
1808        match value {
1809            Some(value) => write_cast::<M, C, T>(column, value),
1810            None => Ok(CastContext::with_current(C::null_with)),
1811        }
1812    }
1813
1814    /// Converts a stored value into a field.
1815    pub fn convert<M: Model, T: Field>(column: &str, value: Value) -> Result<T, OrmError> {
1816        T::from_value(value)
1817            .map_err(|error| decode_error(M::meta().name(), column, T::type_name(), &error))
1818    }
1819
1820    /// Converts a stored value into a cast field.
1821    pub fn convert_cast<M: Model, C: Cast<T>, T>(
1822        column: &str,
1823        value: Value,
1824    ) -> Result<T, OrmError> {
1825        let stored = convert::<M, C::Stored>(column, value)?;
1826        get::<M, C, T>(column, stored)
1827    }
1828
1829    /// Converts a stored value into a nullable cast field.
1830    pub fn convert_cast_option<M: Model, C: Cast<T>, T>(
1831        column: &str,
1832        value: Value,
1833    ) -> Result<Option<T>, OrmError> {
1834        match convert::<M, Option<C::Stored>>(column, value)? {
1835            Some(stored) => get::<M, C, T>(column, stored).map(Some),
1836            None => Ok(None),
1837        }
1838    }
1839
1840    // ---------------------------------------------------------------------
1841    // Untyped input (mass assignment)
1842    // ---------------------------------------------------------------------
1843
1844    fn input_error<M: Model>(
1845        column: &str,
1846        expected: Cow<'static, str>,
1847        message: String,
1848    ) -> OrmError {
1849        OrmError::Decode {
1850            model: Cow::Borrowed(M::meta().name()),
1851            column: column.to_owned(),
1852            expected,
1853            message,
1854        }
1855    }
1856
1857    /// Converts untyped input into a field.
1858    pub fn input<M: Model, T: Field>(
1859        column: &str,
1860        input: serde_json::Value,
1861    ) -> Result<T, OrmError> {
1862        T::from_json(input).map_err(|error| {
1863            input_error::<M>(
1864                column,
1865                T::type_name(),
1866                match error {
1867                    FieldError::Null => "the input is null (make the field an Option)".to_owned(),
1868                    other => other.to_string(),
1869                },
1870            )
1871        })
1872    }
1873
1874    /// Converts untyped input into a cast field.
1875    pub fn input_cast<M: Model, C: Cast<T>, T>(
1876        column: &str,
1877        input: serde_json::Value,
1878    ) -> Result<T, OrmError> {
1879        if input.is_null() {
1880            return Err(input_error::<M>(
1881                column,
1882                Cow::Borrowed(short_type_name::<T>()),
1883                "the input is null (make the field an Option)".to_owned(),
1884            ));
1885        }
1886        CastContext::with_current(|context| C::from_json(input, context))
1887            .map_err(|error| cast_error::<M>(column, error.to_string()))
1888    }
1889
1890    /// Converts untyped input into a nullable cast field (`null` is `None`).
1891    pub fn input_cast_option<M: Model, C: Cast<T>, T>(
1892        column: &str,
1893        input: serde_json::Value,
1894    ) -> Result<Option<T>, OrmError> {
1895        if input.is_null() {
1896            return Ok(None);
1897        }
1898        input_cast::<M, C, T>(column, input).map(Some)
1899    }
1900
1901    /// `T`'s name without its module path, for messages.
1902    fn short_type_name<T>() -> &'static str {
1903        let full = std::any::type_name::<T>();
1904        let base = full.split('<').next().unwrap_or(full);
1905        base.rsplit("::").next().unwrap_or(base)
1906    }
1907
1908    // ---------------------------------------------------------------------
1909    // Dirty tracking
1910    // ---------------------------------------------------------------------
1911
1912    /// Whether two field values are stored as the same thing.
1913    pub fn same_field<T: Field>(a: &T, b: &T) -> bool {
1914        same_value(&a.to_value(), &b.to_value())
1915    }
1916
1917    /// Whether two cast field values are stored as the same thing.
1918    pub fn same_cast<C: Cast<T>, T>(a: &T, b: &T) -> bool {
1919        CastContext::with_current(|context| C::same(a, b, context))
1920    }
1921
1922    /// Whether two nullable cast field values are stored as the same thing.
1923    pub fn same_cast_option<C: Cast<T>, T>(a: &Option<T>, b: &Option<T>) -> bool {
1924        match (a, b) {
1925            (Some(a), Some(b)) => same_cast::<C, T>(a, b),
1926            (None, None) => true,
1927            _ => false,
1928        }
1929    }
1930
1931    /// Whether cast column `column` of `row` holds a value to rewrite.
1932    pub fn stale_cast<C: Cast<T>, T>(row: &Row, column: &str) -> bool {
1933        CastContext::with_current(|context| C::is_stale(row, column, context))
1934    }
1935
1936    // ---------------------------------------------------------------------
1937    // Preparation, serialization, increments
1938    // ---------------------------------------------------------------------
1939
1940    /// Runs cast `C`'s preparation of a field before a write.
1941    pub async fn prepare_cast<M: Model, C: Cast<T>, T>(
1942        column: &str,
1943        value: &mut T,
1944        context: &CastContext,
1945    ) -> Result<(), OrmError> {
1946        C::prepare(value, context)
1947            .await
1948            .map_err(|error| cast_error::<M>(column, error.to_string()))
1949    }
1950
1951    /// Runs cast `C`'s preparation of a nullable field before a write.
1952    pub async fn prepare_cast_option<M: Model, C: Cast<T>, T>(
1953        column: &str,
1954        value: &mut Option<T>,
1955        context: &CastContext,
1956    ) -> Result<(), OrmError> {
1957        match value {
1958            Some(value) => prepare_cast::<M, C, T>(column, value, context).await,
1959            None => Ok(()),
1960        }
1961    }
1962
1963    /// What cast `C` writes for a field in serialized records, if it
1964    /// decides it.
1965    pub fn serialize_cast<M: Model, C: Cast<T>, T>(
1966        column: &str,
1967        value: &T,
1968    ) -> Result<Option<serde_json::Value>, OrmError> {
1969        C::serialize(value)
1970            .transpose()
1971            .map_err(|error| serialize_error::<M>(column, error.to_string()))
1972    }
1973
1974    /// What cast `C` writes for a nullable field in serialized records, if
1975    /// it decides it (`None` stays `null`).
1976    pub fn serialize_cast_option<M: Model, C: Cast<T>, T>(
1977        column: &str,
1978        value: &Option<T>,
1979    ) -> Result<Option<serde_json::Value>, OrmError> {
1980        match value {
1981            Some(value) => serialize_cast::<M, C, T>(column, value),
1982            None => Ok(None),
1983        }
1984    }
1985
1986    fn serialize_error<M: Model>(column: &str, message: String) -> OrmError {
1987        OrmError::Serialize {
1988            model: Cow::Borrowed(M::meta().name()),
1989            column: Some(column.to_owned()),
1990            message,
1991        }
1992    }
1993
1994    /// A field as JSON (JSON columns edited by path).
1995    pub fn json_of<M: Model, T: Serialize>(
1996        column: &str,
1997        value: &T,
1998    ) -> Result<serde_json::Value, OrmError> {
1999        serde_json::to_value(value).map_err(|error| serialize_error::<M>(column, error.to_string()))
2000    }
2001
2002    /// Adds or subtracts `amount` (stored form) to a cast field through
2003    /// `C::increment` / `C::decrement`.
2004    pub fn increment_cast<M: Model, C: Cast<T>, T>(
2005        column: &str,
2006        value: &mut T,
2007        amount: Value,
2008        decrement: bool,
2009    ) -> Result<(), OrmError> {
2010        let amount = convert_cast::<M, C, T>(column, amount)?;
2011        let next = if decrement {
2012            C::decrement(value, &amount)
2013        } else {
2014            C::increment(value, &amount)
2015        };
2016        *value = next.map_err(|error| cast_error::<M>(column, error.to_string()))?;
2017        Ok(())
2018    }
2019
2020    /// Like [`increment_cast`] for a nullable field: a `None` stays `None`
2021    /// (the database's `NULL + amount` is `NULL` too).
2022    pub fn increment_cast_option<M: Model, C: Cast<T>, T>(
2023        column: &str,
2024        value: &mut Option<T>,
2025        amount: Value,
2026        decrement: bool,
2027    ) -> Result<(), OrmError> {
2028        match value {
2029            Some(value) => increment_cast::<M, C, T>(column, value, amount, decrement),
2030            None => Ok(()),
2031        }
2032    }
2033
2034    /// The error for a column that has no cast to increment through.
2035    pub fn not_a_cast_column<M: Model>(column: &str) -> OrmError {
2036        OrmError::InvalidQuery(format!(
2037            "`{column}` of {} is not a cast column: increment it with Record::increment",
2038            M::meta().name()
2039        ))
2040    }
2041
2042    // ---------------------------------------------------------------------
2043    // Fields stored across several columns
2044    // ---------------------------------------------------------------------
2045
2046    /// Builds a field from its stored columns through cast `C`.
2047    pub fn read_multi<M: Model, C: MultiColumnCast<T>, T>(
2048        field: &str,
2049        stored: C::Stored,
2050    ) -> Result<T, OrmError> {
2051        CastContext::with_current(|context| C::get_with(stored, context))
2052            .map_err(|error| cast_error::<M>(field, error.to_string()))
2053    }
2054
2055    /// The stored columns of a field through cast `C`.
2056    pub fn write_multi<M: Model, C: MultiColumnCast<T>, T>(
2057        field: &str,
2058        value: &T,
2059    ) -> Result<C::Stored, OrmError> {
2060        CastContext::with_current(|context| C::set_with(value, context))
2061            .map_err(|error| cast_error::<M>(field, error.to_string()))
2062    }
2063
2064    /// The stored columns of a nullable field (`None` is NULL in each).
2065    pub fn write_multi_option<M: Model, C: MultiColumnCast<T>, T>(
2066        field: &str,
2067        value: &Option<T>,
2068    ) -> Result<Vec<Value>, OrmError> {
2069        match value {
2070            Some(value) => write_multi::<M, C, T>(field, value).map(|stored| stored.to_values()),
2071            None => Ok(C::Stored::nulls()),
2072        }
2073    }
2074
2075    /// The stored columns of a field as values.
2076    pub fn multi_values<M: Model, C: MultiColumnCast<T>, T>(
2077        field: &str,
2078        value: &T,
2079    ) -> Result<Vec<Value>, OrmError> {
2080        write_multi::<M, C, T>(field, value).map(|stored| stored.to_values())
2081    }
2082
2083    fn multi_error<M: Model, C: MultiColumnCast<T>, T>(
2084        row: &Row,
2085        columns: &[&str],
2086        (index, error): (usize, FieldError),
2087    ) -> OrmError {
2088        let column = columns.get(index).copied().unwrap_or("?");
2089        let expected = C::Stored::type_name(index);
2090        match error {
2091            // The columns of a multi-column field have no default to read
2092            // instead.
2093            FieldError::Missing => OrmError::MissingAttribute {
2094                model: Cow::Borrowed(M::meta().name()),
2095                column: column.to_owned(),
2096                expected,
2097                selected: row.columns(),
2098            },
2099            other => decode_error(M::meta().name(), column, expected, &other),
2100        }
2101    }
2102
2103    /// Reads a field stored across `columns` of `row`.
2104    pub fn read_multi_row<M: Model, C: MultiColumnCast<T>, T>(
2105        row: &Row,
2106        field: &str,
2107        columns: &[&str],
2108    ) -> Result<T, OrmError> {
2109        let stored = C::Stored::from_row(row, columns)
2110            .map_err(|error| multi_error::<M, C, T>(row, columns, error))?;
2111        read_multi::<M, C, T>(field, stored)
2112    }
2113
2114    /// Reads a nullable field stored across `columns` of `row`: `None` when
2115    /// every column is NULL.
2116    pub fn read_multi_row_option<M: Model, C: MultiColumnCast<T>, T>(
2117        row: &Row,
2118        field: &str,
2119        columns: &[&str],
2120    ) -> Result<Option<T>, OrmError> {
2121        match C::Stored::from_row_option(row, columns)
2122            .map_err(|error| multi_error::<M, C, T>(row, columns, error))?
2123        {
2124            Some(stored) => read_multi::<M, C, T>(field, stored).map(Some),
2125            None => Ok(None),
2126        }
2127    }
2128
2129    /// The field after replacing stored column `index` with `value`.
2130    pub fn replace_multi<M: Model, C: MultiColumnCast<T>, T>(
2131        field: &str,
2132        current: &T,
2133        column: &str,
2134        index: usize,
2135        value: Value,
2136    ) -> Result<T, OrmError> {
2137        let mut values = write_multi::<M, C, T>(field, current)?.to_values();
2138        values[index] = value;
2139        let stored = C::Stored::from_values(values).map_err(|(index, error)| {
2140            decode_error(
2141                M::meta().name(),
2142                column,
2143                C::Stored::type_name(index),
2144                &error,
2145            )
2146        })?;
2147        read_multi::<M, C, T>(field, stored)
2148    }
2149
2150    /// A nullable field after replacing stored column `index` with
2151    /// `value`: a `None` field takes NULLs in its other columns, and
2152    /// becomes `None` again when every column is NULL.
2153    pub fn replace_multi_option<M: Model, C: MultiColumnCast<T>, T>(
2154        field: &str,
2155        current: &Option<T>,
2156        column: &str,
2157        index: usize,
2158        value: Value,
2159    ) -> Result<Option<T>, OrmError> {
2160        let mut values = write_multi_option::<M, C, T>(field, current)?;
2161        values[index] = value;
2162        if values.iter().all(crate::value::is_null) {
2163            return Ok(None);
2164        }
2165        let stored = C::Stored::from_values(values).map_err(|(index, error)| {
2166            decode_error(
2167                M::meta().name(),
2168                column,
2169                C::Stored::type_name(index),
2170                &error,
2171            )
2172        })?;
2173        read_multi::<M, C, T>(field, stored).map(Some)
2174    }
2175
2176    /// A multi-column field from its stored column values.
2177    pub fn multi_from_values<M: Model, C: MultiColumnCast<T>, T>(
2178        field: &str,
2179        columns: &[&str],
2180        values: Vec<Value>,
2181    ) -> Result<T, OrmError> {
2182        let stored = C::Stored::from_values(values).map_err(|(index, error)| {
2183            let column = columns.get(index).copied().unwrap_or(field);
2184            decode_error(
2185                M::meta().name(),
2186                column,
2187                C::Stored::type_name(index),
2188                &error,
2189            )
2190        })?;
2191        read_multi::<M, C, T>(field, stored)
2192    }
2193
2194    /// A nullable multi-column field from its stored column values: `None`
2195    /// when every one is NULL.
2196    pub fn multi_from_values_option<M: Model, C: MultiColumnCast<T>, T>(
2197        field: &str,
2198        columns: &[&str],
2199        values: Vec<Value>,
2200    ) -> Result<Option<T>, OrmError> {
2201        if values.iter().all(crate::value::is_null) {
2202            return Ok(None);
2203        }
2204        multi_from_values::<M, C, T>(field, columns, values).map(Some)
2205    }
2206
2207    /// The stored columns of a multi-column field that differ between `a`
2208    /// and `b` (by index); every column when either cannot be encoded.
2209    pub fn changed_multi<M: Model, C: MultiColumnCast<T>, T>(
2210        field: &str,
2211        a: &T,
2212        b: &T,
2213    ) -> Vec<usize> {
2214        match (
2215            multi_values::<M, C, T>(field, a),
2216            multi_values::<M, C, T>(field, b),
2217        ) {
2218            (Ok(a), Ok(b)) => (0..a.len())
2219                .filter(|&i| !same_value(&a[i], &b[i]))
2220                .collect(),
2221            _ => (0..C::Stored::COUNT).collect(),
2222        }
2223    }
2224
2225    /// Like [`changed_multi`] for a nullable field.
2226    pub fn changed_multi_option<M: Model, C: MultiColumnCast<T>, T>(
2227        field: &str,
2228        a: &Option<T>,
2229        b: &Option<T>,
2230    ) -> Vec<usize> {
2231        match (
2232            write_multi_option::<M, C, T>(field, a),
2233            write_multi_option::<M, C, T>(field, b),
2234        ) {
2235            (Ok(a), Ok(b)) => (0..a.len())
2236                .filter(|&i| !same_value(&a[i], &b[i]))
2237                .collect(),
2238            _ => (0..C::Stored::COUNT).collect(),
2239        }
2240    }
2241
2242    /// The relationships factory `F` declares, for [`ModelMeta::factory`]
2243    /// (`#[model(factory = F)]`).
2244    ///
2245    /// [`ModelMeta::factory`]: crate::ModelMeta::factory
2246    pub fn factory_relationships<F: crate::factory::ModelFactory>()
2247    -> Vec<crate::factory::RelationshipInfo> {
2248        crate::factory::Relationships::<F::Model>::of::<F>().infos()
2249    }
2250
2251    /// The error for a column the model does not have.
2252    pub fn unknown_column<M: Model>(column: &str) -> OrmError {
2253        OrmError::InvalidQuery(format!("{} has no column `{column}`", M::meta().name()))
2254    }
2255
2256    /// The error for a column that is not one of the model's timestamps.
2257    pub fn not_a_timestamp<M: Model>(column: &str) -> OrmError {
2258        OrmError::InvalidQuery(format!(
2259            "`{column}` is not a timestamp column of {}",
2260            M::meta().name()
2261        ))
2262    }
2263
2264    /// An accessor's value as JSON.
2265    pub fn accessor_json<T: Serialize>(value: &T) -> Result<serde_json::Value, CastError> {
2266        serde_json::to_value(value).map_err(|error| CastError::new(error.to_string()))
2267    }
2268
2269    /// The JSON inside a stored value, if it is JSON.
2270    pub fn stored_json(value: Value) -> Option<serde_json::Value> {
2271        match value {
2272            Value::Json(json) => Some(json),
2273            _ => None,
2274        }
2275    }
2276
2277    /// A field's value, probed for being JSON (`json_attribute`): fields of
2278    /// type `serde_json::Value` (or an `Option` of it) answer with their
2279    /// JSON through [`JsonProbeJson`], every other field with `None`
2280    /// through [`JsonProbeAny`] (the derive calls
2281    /// `(&JsonProbe::<T>(&field)).json_attribute()`, which picks the first
2282    /// when it applies).
2283    pub struct JsonProbe<'a, T>(pub &'a T);
2284
2285    /// [`JsonProbe`] of a JSON field.
2286    pub trait JsonProbeJson {
2287        /// The field's JSON.
2288        fn json_attribute(&self) -> Result<Option<serde_json::Value>, OrmError>;
2289    }
2290
2291    impl JsonProbeJson for JsonProbe<'_, serde_json::Value> {
2292        fn json_attribute(&self) -> Result<Option<serde_json::Value>, OrmError> {
2293            Ok(Some(self.0.clone()))
2294        }
2295    }
2296
2297    impl JsonProbeJson for JsonProbe<'_, Option<serde_json::Value>> {
2298        fn json_attribute(&self) -> Result<Option<serde_json::Value>, OrmError> {
2299            Ok(Some(self.0.clone().unwrap_or(serde_json::Value::Null)))
2300        }
2301    }
2302
2303    /// [`JsonProbe`] of any other field.
2304    pub trait JsonProbeAny {
2305        /// `None`: the field is not JSON.
2306        fn json_attribute(&self) -> Result<Option<serde_json::Value>, OrmError>;
2307    }
2308
2309    impl<T> JsonProbeAny for &JsonProbe<'_, T> {
2310        fn json_attribute(&self) -> Result<Option<serde_json::Value>, OrmError> {
2311            Ok(None)
2312        }
2313    }
2314}