1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32#[non_exhaustive]
33pub enum KeyKind {
34 Increments,
37 UuidV7,
39 UuidV4,
41 Ulid,
43 ObjectId,
48 Manual,
50}
51
52#[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 fn is_empty(&self) -> bool;
64
65 fn generate(kind: KeyKind) -> Option<Self>;
67
68 fn empty() -> Self;
70
71 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#[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 fn from_now(now: DateTime<Utc>) -> Self;
180
181 fn is_empty(&self) -> bool;
183
184 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
258pub type PartialSchemaFn = fn() -> navree_openapi::Schema;
261
262#[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 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 pub const fn nullable(self) -> Self {
299 ColumnMeta {
300 nullable: true,
301 ..self
302 }
303 }
304
305 pub const fn cast(self, cast: &'static str) -> Self {
307 ColumnMeta {
308 cast: Some(cast),
309 ..self
310 }
311 }
312
313 pub const fn serialized_as(self, key: Option<&'static str>) -> Self {
316 ColumnMeta {
317 serialized: key,
318 ..self
319 }
320 }
321
322 pub const fn kind(self, kind: FieldKind) -> Self {
326 ColumnMeta { kind, ..self }
327 }
328
329 pub const fn serde_custom(self) -> Self {
332 ColumnMeta {
333 serde_custom: true,
334 ..self
335 }
336 }
337
338 pub const fn serde_optional(self) -> Self {
340 ColumnMeta {
341 serde_optional: true,
342 ..self
343 }
344 }
345
346 pub const fn mutator(self) -> Self {
348 ColumnMeta {
349 mutator: true,
350 ..self
351 }
352 }
353
354 pub const fn schema(self, schema: PartialSchemaFn) -> Self {
356 ColumnMeta {
357 schema: Some(schema),
358 ..self
359 }
360 }
361
362 pub const fn name(&self) -> &'static str {
364 self.name
365 }
366
367 pub const fn field(&self) -> &'static str {
369 self.field
370 }
371
372 pub const fn rust_type(&self) -> &'static str {
374 self.rust_type
375 }
376
377 pub const fn is_nullable(&self) -> bool {
379 self.nullable
380 }
381
382 pub const fn cast_name(&self) -> Option<&'static str> {
384 self.cast
385 }
386
387 pub const fn serialized_name(&self) -> Option<&'static str> {
390 self.serialized
391 }
392
393 pub const fn field_kind(&self) -> FieldKind {
395 self.kind
396 }
397
398 pub const fn is_date_time(&self) -> bool {
401 matches!(self.kind, FieldKind::DateTime) && !self.serde_custom
402 }
403
404 pub const fn is_json(&self) -> bool {
407 matches!(self.kind, FieldKind::Json)
408 }
409
410 pub const fn has_custom_serde(&self) -> bool {
412 self.serde_custom
413 }
414
415 pub const fn is_serde_optional(&self) -> bool {
417 self.serde_optional
418 }
419
420 pub const fn has_mutator(&self) -> bool {
422 self.mutator
423 }
424
425 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#[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
511pub type DateSerializer = fn(&DateTime<FixedOffset>) -> serde_json::Value;
516
517impl ModelMeta {
518 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 pub const fn fillable(self, columns: &'static [&'static str]) -> Self {
562 ModelMeta {
563 fillable: columns,
564 ..self
565 }
566 }
567
568 pub const fn guarded(self, columns: &'static [&'static str]) -> Self {
571 ModelMeta {
572 guarded: Some(columns),
573 ..self
574 }
575 }
576
577 pub const fn unguarded(self) -> Self {
580 ModelMeta {
581 unguarded: true,
582 ..self
583 }
584 }
585
586 pub const fn hidden(self, names: &'static [&'static str]) -> Self {
589 ModelMeta {
590 hidden: names,
591 ..self
592 }
593 }
594
595 pub const fn visible(self, names: &'static [&'static str]) -> Self {
598 ModelMeta {
599 visible: names,
600 ..self
601 }
602 }
603
604 pub const fn appends(self, names: &'static [&'static str]) -> Self {
607 ModelMeta {
608 appends: names,
609 ..self
610 }
611 }
612
613 pub const fn encrypter(self, name: &'static str) -> Self {
616 ModelMeta {
617 encrypter: Some(name),
618 ..self
619 }
620 }
621
622 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 pub const fn subject(self, subject: &'static str) -> Self {
639 ModelMeta {
640 subject: Some(subject),
641 ..self
642 }
643 }
644
645 pub const fn policy(self, policy: &'static str) -> Self {
648 ModelMeta {
649 policy: Some(policy),
650 ..self
651 }
652 }
653
654 pub const fn factory_name(&self) -> Option<&'static str> {
656 self.factory
657 }
658
659 pub fn factory_relationships(&self) -> Vec<RelationshipInfo> {
663 self.relationships.map(|f| f()).unwrap_or_default()
664 }
665
666 pub const fn subject_name(&self) -> Option<&'static str> {
668 self.subject
669 }
670
671 pub const fn policy_name(&self) -> Option<&'static str> {
673 self.policy
674 }
675
676 pub const fn route_key(self, column: &'static str) -> Self {
679 ModelMeta {
680 route_key: Some(column),
681 ..self
682 }
683 }
684
685 pub const fn workspace(self, column: &'static str) -> Self {
689 ModelMeta {
690 workspace: Some(column),
691 ..self
692 }
693 }
694
695 pub const fn cast_context(self, needed: bool) -> Self {
699 ModelMeta {
700 cast_context: needed,
701 ..self
702 }
703 }
704
705 pub const fn serialize_dates_with(self, serializer: DateSerializer) -> Self {
708 ModelMeta {
709 date_serializer: Some(serializer),
710 ..self
711 }
712 }
713
714 pub const fn morph_name(self, name: &'static str) -> Self {
718 ModelMeta {
719 morph_name: Some(name),
720 ..self
721 }
722 }
723
724 pub const fn foreign_key(self, column: &'static str) -> Self {
727 ModelMeta {
728 foreign_key: Some(column),
729 ..self
730 }
731 }
732
733 pub const fn touches(self, relations: &'static [&'static str]) -> Self {
737 ModelMeta {
738 touches: relations,
739 ..self
740 }
741 }
742
743 pub const fn with(self, relations: &'static [&'static str]) -> Self {
746 ModelMeta {
747 with: relations,
748 ..self
749 }
750 }
751
752 pub const fn with_count(self, relations: &'static [&'static str]) -> Self {
755 ModelMeta {
756 with_count: relations,
757 ..self
758 }
759 }
760
761 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 pub const fn pruned(self, pruning: crate::prune::Pruning) -> Self {
775 ModelMeta {
776 pruning: Some(pruning),
777 ..self
778 }
779 }
780
781 pub const fn pruning(&self) -> Option<&crate::prune::Pruning> {
783 self.pruning.as_ref()
784 }
785
786 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 pub const fn columns(self, columns: &'static [ColumnMeta]) -> Self {
797 ModelMeta { columns, ..self }
798 }
799
800 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 pub const fn soft_deletes(self, column: &'static str) -> Self {
816 ModelMeta {
817 deleted_at: Some(column),
818 ..self
819 }
820 }
821
822 pub const fn connection(self, name: &'static str) -> Self {
824 ModelMeta {
825 connection: Some(name),
826 ..self
827 }
828 }
829
830 pub const fn driver(self, name: &'static str) -> Self {
833 ModelMeta {
834 driver: Some(name),
835 ..self
836 }
837 }
838
839 pub const fn per_page(self, per_page: u64) -> Self {
841 ModelMeta { per_page, ..self }
842 }
843
844 pub const fn name(&self) -> &'static str {
846 self.name
847 }
848
849 pub const fn table(&self) -> &'static str {
851 self.table
852 }
853
854 pub const fn key_column(&self) -> &'static str {
856 self.key
857 }
858
859 pub const fn key_kind(&self) -> KeyKind {
861 self.key_kind
862 }
863
864 pub const fn all_columns(&self) -> &'static [ColumnMeta] {
866 self.columns
867 }
868
869 pub fn column(&self, name: &str) -> Option<&'static ColumnMeta> {
871 self.columns.iter().find(|column| column.name == name)
872 }
873
874 pub fn has_column(&self, name: &str) -> bool {
876 self.column(name).is_some()
877 }
878
879 pub const fn created_at(&self) -> Option<&'static str> {
881 self.created_at
882 }
883
884 pub const fn updated_at(&self) -> Option<&'static str> {
886 self.updated_at
887 }
888
889 pub const fn uses_timestamps(&self) -> bool {
891 self.created_at.is_some() || self.updated_at.is_some()
892 }
893
894 pub const fn deleted_at(&self) -> Option<&'static str> {
896 self.deleted_at
897 }
898
899 pub const fn soft_deletes_enabled(&self) -> bool {
901 self.deleted_at.is_some()
902 }
903
904 pub const fn connection_name(&self) -> Option<&'static str> {
906 self.connection
907 }
908
909 pub const fn driver_name(&self) -> Option<&'static str> {
912 self.driver
913 }
914
915 pub const fn default_per_page(&self) -> u64 {
917 self.per_page
918 }
919
920 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 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 pub const fn touched_relations(&self) -> &'static [&'static str] {
941 self.touches
942 }
943
944 pub const fn default_with(&self) -> &'static [&'static str] {
946 self.with
947 }
948
949 pub const fn default_with_count(&self) -> &'static [&'static str] {
951 self.with_count
952 }
953
954 pub const fn pivot_key_columns(&self) -> Option<(&'static str, &'static str)> {
958 self.pivot_keys
959 }
960
961 pub const fn fillable_columns(&self) -> &'static [&'static str] {
963 self.fillable
964 }
965
966 pub const fn guarded_columns(&self) -> Option<&'static [&'static str]> {
969 self.guarded
970 }
971
972 pub const fn is_unguarded(&self) -> bool {
974 self.unguarded
975 }
976
977 pub const fn hidden_names(&self) -> &'static [&'static str] {
979 self.hidden
980 }
981
982 pub const fn visible_names(&self) -> &'static [&'static str] {
984 self.visible
985 }
986
987 pub const fn appended_names(&self) -> &'static [&'static str] {
989 self.appends
990 }
991
992 pub const fn encrypter_name(&self) -> Option<&'static str> {
995 self.encrypter
996 }
997
998 pub const fn uses_cast_context(&self) -> bool {
1000 self.cast_context
1001 }
1002
1003 pub const fn date_serializer(&self) -> Option<DateSerializer> {
1006 self.date_serializer
1007 }
1008
1009 pub fn column_of_field(&self, field: &str) -> Option<&'static ColumnMeta> {
1012 self.columns.iter().find(|column| column.field == field)
1013 }
1014
1015 pub fn column_named(&self, name: &str) -> Option<&'static ColumnMeta> {
1017 self.column(name).or_else(|| self.column_of_field(name))
1018 }
1019
1020 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 pub const fn workspace_column(&self) -> Option<&'static str> {
1031 self.workspace
1032 }
1033
1034 pub const fn is_workspace_scoped(&self) -> bool {
1036 self.workspace.is_some()
1037 }
1038}
1039
1040pub(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
1064pub trait Model: Clone + Send + Sync + Serialize + 'static {
1082 type Key: PrimaryKey;
1084
1085 fn meta() -> &'static ModelMeta;
1087
1088 fn key(&self) -> Self::Key;
1090
1091 fn set_key(&mut self, key: Self::Key);
1093
1094 fn from_row(row: &Row) -> Result<Self>;
1096
1097 fn values(&self) -> Result<Vec<(&'static str, Value)>>;
1099
1100 fn value(&self, column: &str) -> Result<Option<Value>>;
1103
1104 fn set_value(&mut self, column: &str, value: Value) -> Result<()>;
1106
1107 fn touch_timestamp(&mut self, column: &str, now: DateTime<Utc>) -> Result<()>;
1109
1110 fn timestamp_is_empty(&self, column: &str) -> bool;
1112
1113 fn clear_timestamp(&mut self, column: &str);
1115
1116 fn timestamp_value(column: &str, now: DateTime<Utc>) -> Option<Value>;
1118
1119 fn global_scopes() -> Vec<Arc<dyn GlobalScope<Self>>> {
1122 Vec::new()
1123 }
1124
1125 fn hooks() -> Vec<Arc<dyn ModelHook<Self>>> {
1128 Vec::new()
1129 }
1130
1131 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 #[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 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 fn json_attribute(&self, column: &str) -> Result<Option<serde_json::Value>> {
1185 let _ = column;
1186 Ok(None)
1187 }
1188
1189 fn accessors() -> &'static [Accessor<Self>] {
1192 &[]
1193 }
1194
1195 fn fillable() -> &'static [&'static str] {
1197 Self::meta().fillable_columns()
1198 }
1199
1200 fn guarded() -> Option<&'static [&'static str]> {
1204 Self::meta().guarded_columns()
1205 }
1206
1207 fn is_fillable(column: &str) -> bool {
1209 crate::attributes::fill::is_fillable(Self::meta(), column, false)
1210 }
1211
1212 fn is_guarded(column: &str) -> bool {
1214 crate::attributes::fill::is_guarded(Self::meta(), column, false)
1215 }
1216
1217 fn totally_guarded() -> bool {
1220 crate::attributes::fill::totally_guarded(Self::meta(), false)
1221 }
1222
1223 #[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 #[doc(hidden)]
1235 fn serialized_overrides(&self) -> Result<Vec<(&'static str, serde_json::Value)>> {
1236 Ok(Vec::new())
1237 }
1238
1239 #[doc(hidden)]
1242 fn stale_columns(row: &Row) -> Vec<&'static str> {
1243 let _ = row;
1244 Vec::new()
1245 }
1246
1247 #[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 fn relation(name: &str) -> Option<DynRelation<Self>> {
1263 crate::relations::registry::defined::<Self>(name)
1264 }
1265
1266 fn relation_names() -> Vec<Cow<'static, str>> {
1268 crate::relations::registry::defined_names::<Self>()
1269 }
1270
1271 fn relation_meta(name: &str) -> Option<RelationMeta> {
1285 Self::relation(name).map(|relation| relation.meta())
1286 }
1287
1288 fn morph_name() -> Cow<'static, str> {
1291 Self::meta().morph_type()
1292 }
1293
1294 fn foreign_key_name() -> Cow<'static, str> {
1297 Self::meta().foreign_key_name()
1298 }
1299
1300 fn touched_relations() -> &'static [&'static str] {
1303 Self::meta().touched_relations()
1304 }
1305
1306 fn table_name() -> &'static str {
1313 Self::meta().table()
1314 }
1315
1316 fn route_key_name() -> &'static str {
1324 Self::meta().route_key_column()
1325 }
1326
1327 fn query() -> Builder<Self> {
1330 Builder::new().with_model_defaults()
1331 }
1332
1333 fn where_(filter: impl Into<Filter>) -> Builder<Self> {
1336 Self::query().where_(filter)
1337 }
1338
1339 fn connection_name() -> Option<&'static str> {
1343 Self::meta().connection_name()
1344 }
1345
1346 fn on_connection(name: impl Into<std::borrow::Cow<'static, str>>) -> Builder<Self> {
1349 Builder::new().on_connection(name)
1350 }
1351
1352 fn on_write_connection() -> Builder<Self> {
1362 Builder::new().use_write()
1363 }
1364
1365 fn all<E: Executor + ?Sized>(
1367 exec: &E,
1368 ) -> impl Future<Output = Result<Collection<Self>>> + Send {
1369 Self::query().get(exec)
1370 }
1371
1372 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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#[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 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 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 pub struct DefaultOf<T>(std::marker::PhantomData<fn() -> T>);
1657
1658 impl<T> DefaultOf<T> {
1659 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 pub trait ViaDefault {
1673 type Field;
1675 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 pub trait WithoutDefault {
1688 type Field;
1690 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn same_field<T: Field>(a: &T, b: &T) -> bool {
1914 same_value(&a.to_value(), &b.to_value())
1915 }
1916
1917 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn unknown_column<M: Model>(column: &str) -> OrmError {
2253 OrmError::InvalidQuery(format!("{} has no column `{column}`", M::meta().name()))
2254 }
2255
2256 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 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 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 pub struct JsonProbe<'a, T>(pub &'a T);
2284
2285 pub trait JsonProbeJson {
2287 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 pub trait JsonProbeAny {
2305 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}