glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
//! Associations: `belongs_to` and `has_many`, loaded with `preload`.
//!
//! ```no_run
//! use glacier::db::{BelongsTo, HasMany};
//! use glacier::prelude::*;
//!
//! #[derive(Clone, Model)]
//! struct User { id: i64, name: String }
//!
//! #[derive(Clone, Model)]
//! struct Comment { id: i64, post_id: i64, body: String }
//!
//! #[derive(Model)]
//! struct Post {
//!     id: i64,
//!     author_id: i64,
//!     #[glacier(belongs_to)]          // uses `author_id`
//!     author: BelongsTo<User>,
//!     #[glacier(has_many)]            // uses `comments.post_id`
//!     comments: HasMany<Comment>,
//! }
//!
//! # async fn demo() -> glacier::Result<()> {
//! let posts = Post::all()
//!     .preload(|p| p.author)
//!     .preload(|p| p.comments)
//!     .await?;                        // 3 queries, however many posts
//! for post in &posts {
//!     println!("{} ({} comments)", post.author.name, post.comments.len());
//! }
//! # Ok(()) }
//! ```
//!
//! Associations are never loaded lazily: touching one that wasn't preloaded
//! panics with a message naming the fix. That turns an accidental N+1 query
//! into a bug you see the first time the code runs.

use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::sync::Arc;

use serde::{Serialize, Serializer};

use super::query::Expr;
use super::value::{ToValue, Value};
use super::{Connection, Query};
use crate::error::Result;
use crate::model::Model;

/// The parent record of a `belongs_to` association.
pub struct BelongsTo<M>(State<Option<M>>);

/// The child records of a `has_many` association.
pub struct HasMany<M>(State<Vec<M>>);

/// The one child record of a `has_one` association (the first, or with
/// `order`, the first in that order: `has_one :latest_order, Order,
/// latest: :inserted_at`), if there is one. Boxed, so a child that
/// `belongs_to` its parent can be one (`User` has one `Post`, a `Post`
/// belongs to a `User`).
pub struct HasOne<M>(State<Option<Box<M>>>);

enum State<T> {
    NotLoaded,
    Loaded(T),
    /// Only how many there are (`with_count`): a `has_many`'s.
    Counted(usize),
}

fn not_loaded<M>() -> ! {
    panic!(
        "association to `{}` was not preloaded; add `.preload(..)` to the query that \
         loaded this record",
        std::any::type_name::<M>()
    )
}

impl<M> BelongsTo<M> {
    pub fn loaded(record: Option<M>) -> Self {
        Self(State::Loaded(record))
    }

    pub fn is_loaded(&self) -> bool {
        matches!(self.0, State::Loaded(_))
    }

    /// The parent, or `None` if it wasn't loaded or doesn't exist.
    pub fn get(&self) -> Option<&M> {
        match &self.0 {
            State::Loaded(record) => record.as_ref(),
            State::NotLoaded | State::Counted(_) => None,
        }
    }
}

/// `post.author.name` reads through to the loaded record.
///
/// # Panics
///
/// If the association wasn't preloaded, or the parent doesn't exist (for a
/// nullable foreign key; use `get` there).
impl<M> Deref for BelongsTo<M> {
    type Target = M;

    fn deref(&self) -> &M {
        match &self.0 {
            State::Loaded(Some(record)) => record,
            State::Loaded(None) => panic!(
                "association to `{}` is empty (the foreign key is NULL or dangling); \
                 use `.get()` for optional associations",
                std::any::type_name::<M>()
            ),
            State::NotLoaded | State::Counted(_) => not_loaded::<M>(),
        }
    }
}

/// A `belongs_to` key's type (`i64`, `Option<i64>`, `Uuid`…): whether a new
/// record left it unset, and the key from a `default:`'s value.
#[doc(hidden)]
pub trait ForeignKey: Sized {
    fn is_unset(&self) -> bool;
    fn from_value(value: Value) -> Option<Self>;
}

impl ForeignKey for i64 {
    fn is_unset(&self) -> bool {
        *self == 0
    }
    fn from_value(value: Value) -> Option<Self> {
        match value {
            Value::Int(key) => Some(key),
            _ => None,
        }
    }
}

impl ForeignKey for i32 {
    fn is_unset(&self) -> bool {
        *self == 0
    }
    fn from_value(value: Value) -> Option<Self> {
        match value {
            Value::Int(key) => key.try_into().ok(),
            _ => None,
        }
    }
}

impl ForeignKey for String {
    fn is_unset(&self) -> bool {
        self.is_empty()
    }
    fn from_value(value: Value) -> Option<Self> {
        match value {
            Value::Text(key) => Some(key),
            _ => None,
        }
    }
}

impl ForeignKey for uuid::Uuid {
    fn is_unset(&self) -> bool {
        self.is_nil()
    }
    fn from_value(value: Value) -> Option<Self> {
        match value {
            Value::Uuid(key) => Some(key),
            _ => None,
        }
    }
}

impl<T: ForeignKey> ForeignKey for Option<T> {
    fn is_unset(&self) -> bool {
        self.is_none()
    }
    fn from_value(value: Value) -> Option<Self> {
        T::from_value(value).map(Some)
    }
}

/// What a `belongs_to`'s `default:` gives: the parent record, its key, or
/// an `Option` of either (`None` leaves the key unset).
#[doc(hidden)]
pub trait ParentKey {
    fn parent_key(self) -> Value;
}

impl<M: crate::Model> ParentKey for M {
    fn parent_key(self) -> Value {
        self.id_value()
    }
}

impl<T: ParentKey> ParentKey for Option<T> {
    fn parent_key(self) -> Value {
        self.map_or(Value::Null, ParentKey::parent_key)
    }
}

macro_rules! key_parent {
    ($($ty:ty),*) => {$(
        impl ParentKey for $ty {
            fn parent_key(self) -> Value {
                self.to_value()
            }
        }
    )*};
}
key_parent!(i64, i32, String, &str, uuid::Uuid);

impl<M> HasOne<M> {
    pub fn loaded(record: Option<M>) -> Self {
        Self(State::Loaded(record.map(Box::new)))
    }

    pub fn is_loaded(&self) -> bool {
        matches!(self.0, State::Loaded(_))
    }

    /// The child, or `None` if it wasn't loaded or there isn't one.
    pub fn get(&self) -> Option<&M> {
        match &self.0 {
            State::Loaded(record) => record.as_deref(),
            State::NotLoaded | State::Counted(_) => None,
        }
    }
}

/// `user.profile.bio` reads through to the loaded record.
///
/// # Panics
///
/// If the association wasn't preloaded, or there's no such child (use
/// `get` when there may be none).
impl<M> Deref for HasOne<M> {
    type Target = M;

    fn deref(&self) -> &M {
        match &self.0 {
            State::Loaded(Some(record)) => record,
            State::Loaded(None) => panic!(
                "there's no `{}` for this record; use `.get()` when there may be none",
                std::any::type_name::<M>()
            ),
            State::NotLoaded | State::Counted(_) => not_loaded::<M>(),
        }
    }
}

impl<M> HasMany<M> {
    pub fn loaded(records: Vec<M>) -> Self {
        Self(State::Loaded(records))
    }

    pub fn is_loaded(&self) -> bool {
        matches!(self.0, State::Loaded(_))
    }

    /// The children, or `None` if they weren't loaded.
    pub fn get(&self) -> Option<&[M]> {
        match &self.0 {
            State::Loaded(records) => Some(records),
            State::NotLoaded | State::Counted(_) => None,
        }
    }

    /// Only how many there are, as `with_count` loads it.
    pub fn counted(count: usize) -> Self {
        Self(State::Counted(count))
    }

    /// How many there are: `Author.with_count(:books)` loads only this,
    /// `preload(:books)` the records too.
    ///
    /// # Panics
    ///
    /// If neither loaded them.
    pub fn count(&self) -> usize {
        match &self.0 {
            State::Loaded(records) => records.len(),
            State::Counted(count) => *count,
            State::NotLoaded => panic!(
                "association to `{}` was neither counted nor preloaded; add \
                 `.with_count(..)` or `.preload(..)` to the query that loaded this record",
                std::any::type_name::<M>()
            ),
        }
    }
}

/// `post.comments.len()`, `for c in &post.comments`.
///
/// # Panics
///
/// If the association wasn't preloaded.
impl<M> Deref for HasMany<M> {
    type Target = [M];

    fn deref(&self) -> &[M] {
        self.get().unwrap_or_else(|| not_loaded::<M>())
    }
}

/// `for c in post.comments.iter_mut()`: loaded records change in memory.
impl<M> DerefMut for HasMany<M> {
    fn deref_mut(&mut self) -> &mut [M] {
        match &mut self.0 {
            State::Loaded(records) => records,
            State::NotLoaded | State::Counted(_) => not_loaded::<M>(),
        }
    }
}

impl<'a, M> IntoIterator for &'a HasMany<M> {
    type Item = &'a M;
    type IntoIter = std::slice::Iter<'a, M>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

macro_rules! assoc_impls {
    ($($ty:ident),*) => {$(
        impl<M> Default for $ty<M> {
            fn default() -> Self {
                Self(State::NotLoaded)
            }
        }

        impl<M: Clone> Clone for $ty<M> {
            fn clone(&self) -> Self {
                Self(match &self.0 {
                    State::NotLoaded => State::NotLoaded,
                    State::Loaded(v) => State::Loaded(v.clone()),
                    State::Counted(n) => State::Counted(*n),
                })
            }
        }

        impl<M: fmt::Debug> fmt::Debug for $ty<M> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                match &self.0 {
                    State::NotLoaded => f.write_str("NotLoaded"),
                    State::Loaded(v) => v.fmt(f),
                    State::Counted(n) => write!(f, "Counted({n})"),
                }
            }
        }

        /// Serializes the loaded value; not-loaded serializes as `null`.
        impl<M: Serialize> Serialize for $ty<M> {
            fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
                match &self.0 {
                    State::NotLoaded | State::Counted(_) => s.serialize_none(),
                    State::Loaded(v) => v.serialize(s),
                }
            }
        }
    )*};
}

assoc_impls!(BelongsTo, HasMany, HasOne);

type PreloadFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;

type LoadAll<M> = dyn for<'a> Fn(&'a mut [M], Connection) -> PreloadFuture<'a> + Send + Sync;

type LoadFn<M, C> = for<'a> fn(&'a mut [M], Connection, Loading<C>) -> PreloadFuture<'a>;

type CountFn<M> = for<'a> fn(&'a mut [M], Connection) -> PreloadFuture<'a>;

/// An association to load alongside a query; from `.preload(|p|
/// p.author)`, with its own associations: `.preload(|p|
/// p.comments.with(|c| c.author))`, or only the records a query
/// matches: `.preload(|p| p.books.only(Book::published()))`.
pub struct Preload<M> {
    load: Arc<LoadAll<M>>,
}

impl<M> Clone for Preload<M> {
    fn clone(&self) -> Self {
        Self {
            load: Arc::clone(&self.load),
        }
    }
}

impl<M> Preload<M> {
    pub(crate) fn run<'a>(&self, records: &'a mut [M], conn: Connection) -> PreloadFuture<'a> {
        (self.load)(records, conn)
    }
}

/// A model's association to `C`, as its `Columns` list it: preload it with
/// `.preload(|p| p.comments)`, and its own associations with `.with(…)`.
pub struct Association<M, C> {
    load: LoadFn<M, C>,
    /// Counting a `has_many`'s records per record, for `with_count`.
    count: Option<CountFn<M>>,
    /// `has_many … through:` a join table: the table, its column naming
    /// this record, and its column naming the other.
    pub(crate) through: Option<(&'static str, &'static str, &'static str)>,
    /// The joining columns, `(this model's, the other's)`, for
    /// `Query::join`; `None` through a join table.
    pub(crate) join: Option<(&'static str, &'static str)>,
    /// `has_many :comments, as: :commentable`: the other's column naming
    /// this model, and the name it holds (`commentable_type`, `"Post"`).
    pub(crate) kind: Option<(&'static str, &'static str)>,
}

impl<M, C> Clone for Association<M, C> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<M, C> Copy for Association<M, C> {}

impl<M, C> Association<M, C> {
    #[doc(hidden)]
    pub const fn new(load: LoadFn<M, C>) -> Self {
        Self {
            load,
            count: None,
            through: None,
            join: None,
            kind: None,
        }
    }

    /// For a polymorphic `has_many … as:`: only the other's records whose
    /// `column` names this model as `name`.
    #[doc(hidden)]
    pub const fn of_kind(mut self, column: &'static str, name: &'static str) -> Self {
        self.kind = Some((column, name));
        self
    }

    /// The join table of a `has_many … through:`, for `attach`, `detach`
    /// and `sync`.
    #[doc(hidden)]
    pub const fn through_table(
        mut self,
        table: &'static str,
        owner_key: &'static str,
        target_key: &'static str,
    ) -> Self {
        self.through = Some((table, owner_key, target_key));
        self
    }

    /// How a `has_many` counts its records, for `with_count`.
    #[doc(hidden)]
    pub const fn counted_by(mut self, count: CountFn<M>) -> Self {
        self.count = Some(count);
        self
    }

    /// The association's count, for [`Query::with_count`].
    pub(crate) fn counting(self) -> Option<Preload<M>>
    where
        M: 'static,
    {
        let count = self.count?;
        Some(Preload {
            load: Arc::new(move |records, conn| count(records, conn)),
        })
    }

    /// The columns joining the two tables: this model's, then the other's.
    #[doc(hidden)]
    pub const fn joined_on(mut self, own: &'static str, other: &'static str) -> Self {
        self.join = Some((own, other));
        self
    }

    /// Also preloads the associated records' own association:
    /// `p.comments.with(|c| c.author)`.
    pub fn with<P: Into<Preload<C>>>(
        self,
        association: impl FnOnce(&C::Columns) -> P,
    ) -> Nested<M, C>
    where
        C: Model,
    {
        Nested {
            load: self.load,
            loading: Loading::default(),
        }
        .with(association)
    }

    /// Loads only the associated records `query` matches, in its order:
    /// `p.books.only(Book::all().filter(…))`, as Ecto's preload queries
    /// and Laravel's constrained eager loads. The query may preload too;
    /// it can't take a `limit` or `offset`.
    pub fn only(self, query: Query<C>) -> Nested<M, C> {
        Nested {
            load: self.load,
            loading: Loading::default(),
        }
        .only(query)
    }
}

/// What an association's loader is given besides the records: the
/// loaded records' own preloads, and the query they must match.
#[doc(hidden)]
pub struct Loading<C> {
    nested: Vec<Preload<C>>,
    query: Option<Query<C>>,
}

impl<C> Default for Loading<C> {
    fn default() -> Self {
        Self {
            nested: Vec::new(),
            query: None,
        }
    }
}

impl<C> Clone for Loading<C> {
    fn clone(&self) -> Self {
        Self {
            nested: self.nested.clone(),
            query: self.query.clone(),
        }
    }
}

impl<C: Model> Loading<C> {
    /// The query to start from: `only`'s, or every record.
    fn query(&self) -> Result<Query<C>> {
        match &self.query {
            Some(query) => query.clone().for_association(),
            None => Ok(Query::new().via_association()),
        }
    }

    fn is_ordered(&self) -> bool {
        self.query.as_ref().is_some_and(Query::is_ordered)
    }
}

/// An association with preloads of its own, or a query, from
/// [`Association::with`] and [`Association::only`].
pub struct Nested<M, C> {
    load: LoadFn<M, C>,
    loading: Loading<C>,
}

impl<M, C> Nested<M, C> {
    /// Loads only the associated records `query` matches.
    pub fn only(mut self, query: Query<C>) -> Self {
        self.loading.query = Some(query);
        self
    }

    /// Preloads another of the associated records' associations.
    pub fn with<P: Into<Preload<C>>>(mut self, association: impl FnOnce(&C::Columns) -> P) -> Self
    where
        C: Model,
    {
        self.loading.nested.push(association(&C::columns()).into());
        self
    }
}

impl<M: 'static, C: 'static> From<Association<M, C>> for Preload<M> {
    fn from(association: Association<M, C>) -> Self {
        Nested {
            load: association.load,
            loading: Loading::default(),
        }
        .into()
    }
}

impl<M: 'static, C: 'static> From<Nested<M, C>> for Preload<M> {
    fn from(nested: Nested<M, C>) -> Self {
        let Nested { load, loading } = nested;
        let loading = Arc::new(loading);
        Preload {
            load: Arc::new(move |records, conn| load(records, conn, (*loading).clone())),
        }
    }
}

/// Runs `nested` preloads on records just loaded for an association.
async fn run_nested<C>(records: &mut [C], conn: &Connection, nested: &[Preload<C>]) -> Result<()> {
    for preload in nested {
        preload.run(records, conn.clone()).await?;
    }
    Ok(())
}

/// A hashable stand-in for a key value.
fn key(value: &Value) -> Option<String> {
    match value {
        Value::Null => None,
        other => Some(format!("{other:?}")),
    }
}

/// What [`PolymorphicTarget::load`] gives: each record with its id.
pub type LoadedTargets<T> =
    std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<(String, T)>>> + Send>>;

/// The models a polymorphic `belongs_to` may point at, as one enum:
/// `belongs_to :commentable, polymorphic: [Book, Author]` generates
/// `Commentable` and this for it.
pub trait PolymorphicTarget: Sized + Clone + Send + 'static {
    /// The records of the model named `type_name` (`"Book"`) with these
    /// ids, each with its id as text; nothing for a model not listed.
    fn load(type_name: String, ids: Vec<Value>, conn: Connection) -> LoadedTargets<Self>;
}

/// A polymorphic `belongs_to`'s parents: one query per model named, as
/// Rails' `includes(:commentable)`.
#[doc(hidden)]
pub async fn load_polymorphic<P, C>(
    parents: &mut [P],
    conn: Connection,
    target: impl Fn(&P) -> (Value, Value),
    assign: impl Fn(&mut P, Option<C>),
) -> Result<()>
where
    P: Model,
    C: PolymorphicTarget,
{
    // The ids wanted of each model, in the order first seen.
    let mut wanted: Vec<(String, Vec<Value>)> = Vec::new();
    for parent in parents.iter() {
        let (kind, id) = target(parent);
        let (Some(kind), Some(_)) = (type_name(&kind), key(&id)) else {
            continue;
        };
        match wanted.iter_mut().find(|(k, _)| *k == kind) {
            Some((_, ids)) if !ids.contains(&id) => ids.push(id),
            Some(_) => {}
            None => wanted.push((kind, vec![id])),
        }
    }
    let mut found: HashMap<(String, String), C> = HashMap::new();
    for (kind, ids) in wanted {
        for (id, record) in C::load(kind.clone(), ids, conn.clone()).await? {
            found.insert((kind.clone(), id), record);
        }
    }
    for parent in parents.iter_mut() {
        let (kind, id) = target(parent);
        let record = type_name(&kind)
            .zip(key(&id))
            .and_then(|k| found.get(&k).cloned());
        assign(parent, record);
    }
    Ok(())
}

/// A polymorphic type column's model name (`"Book"`).
fn type_name(value: &Value) -> Option<String> {
    match value {
        Value::Text(name) if !name.is_empty() => Some(name.clone()),
        _ => None,
    }
}

/// The records of `C` with these ids, each with its id as text: for a
/// generated [`PolymorphicTarget`].
#[doc(hidden)]
pub async fn load_by_ids<C: Model>(ids: Vec<Value>, conn: Connection) -> Result<Vec<(String, C)>> {
    let records = Query::<C>::new()
        .via_association()
        .filter(|_| Expr::In {
            column: C::PRIMARY_KEY,
            values: ids,
        })
        .on(conn)
        .all()
        .await?;
    Ok(records
        .into_iter()
        .filter_map(|record| Some((key(&record.id_value())?, record)))
        .collect())
}

#[doc(hidden)]
pub async fn load_belongs_to<P, C>(
    parents: &mut [P],
    conn: Connection,
    loading: Loading<C>,
    foreign_key: impl Fn(&P) -> Value,
    assign: impl Fn(&mut P, Option<C>),
) -> Result<()>
where
    P: Model,
    C: Model + Clone,
{
    let mut ids: Vec<Value> = Vec::new();
    for parent in parents.iter() {
        let id = foreign_key(parent);
        if key(&id).is_some() && !ids.contains(&id) {
            ids.push(id);
        }
    }
    let found: HashMap<String, C> = if ids.is_empty() {
        HashMap::new()
    } else {
        let mut records = loading
            .query()?
            .filter(|_| Expr::In {
                column: C::PRIMARY_KEY,
                values: ids,
            })
            .on(conn.clone())
            .all()
            .await?;
        run_nested(&mut records, &conn, &loading.nested).await?;
        records
            .into_iter()
            .filter_map(|c| Some((key(&c.id_value())?, c)))
            .collect()
    };
    for parent in parents.iter_mut() {
        let record = key(&foreign_key(parent)).and_then(|k| found.get(&k).cloned());
        assign(parent, record);
    }
    Ok(())
}

#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub async fn load_has_many<P, C>(
    parents: &mut [P],
    conn: Connection,
    loading: Loading<C>,
    foreign_key_column: &'static str,
    order: Option<(&'static str, bool)>,
    kind: Option<(&'static str, &'static str)>,
    foreign_key: impl Fn(&C) -> Value,
    assign: impl Fn(&mut P, Vec<C>),
) -> Result<()>
where
    P: Model,
    C: Model,
{
    let ids: Vec<Value> = parents.iter().map(Model::id_value).collect();
    let mut grouped: HashMap<String, Vec<C>> = HashMap::new();
    if !ids.is_empty() {
        let mut query = loading.query()?.filter(|_| Expr::In {
            column: foreign_key_column,
            values: ids,
        });
        if let Some(kind) = kind {
            query = query.filter(|_| of_kind(kind));
        }
        if let Some((column, descending)) = order {
            query = query.order(|_| super::query::Order::by(column, descending));
        }
        let mut children = query
            .order(|_| super::query::Order::by(C::PRIMARY_KEY, false))
            .on(conn.clone())
            .all()
            .await?;
        run_nested(&mut children, &conn, &loading.nested).await?;
        for child in children {
            if let Some(k) = key(&foreign_key(&child)) {
                grouped.entry(k).or_default().push(child);
            }
        }
    }
    for parent in parents.iter_mut() {
        let children = key(&parent.id_value())
            .and_then(|k| grouped.remove(&k))
            .unwrap_or_default();
        assign(parent, children);
    }
    Ok(())
}

/// `commentable_type = 'Post'`: a polymorphic child's type column.
pub(crate) fn of_kind((column, name): (&'static str, &'static str)) -> Expr {
    Expr::Compare {
        column,
        op: "=",
        value: Value::Text(name.to_owned()),
    }
}

/// `with_count(:books)`: how many of each parent's children there are,
/// in one grouped query (the children's default scope applies).
#[doc(hidden)]
pub async fn count_has_many<P, C>(
    parents: &mut [P],
    conn: Connection,
    foreign_key_column: &'static str,
    kind: Option<(&'static str, &'static str)>,
    assign: impl Fn(&mut P, usize),
) -> Result<()>
where
    P: Model,
    C: Model,
{
    let ids: Vec<Value> = parents.iter().map(Model::id_value).collect();
    let counts: HashMap<String, i64> = if ids.is_empty() {
        HashMap::new()
    } else {
        let mut query = Query::<C>::new().via_association().filter(|_| Expr::In {
            column: foreign_key_column,
            values: ids,
        });
        if let Some(kind) = kind {
            query = query.filter(|_| of_kind(kind));
        }
        query
            .on(conn)
            .count_by(foreign_key_column)
            .await?
            .into_iter()
            .collect()
    };
    for parent in parents.iter_mut() {
        let count = counts
            .get(&parent.id_value().to_text())
            .copied()
            .unwrap_or(0);
        assign(parent, usize::try_from(count).unwrap_or(0));
    }
    Ok(())
}

/// `has_many :x, through: join_table`: the join rows linking each parent
/// to its children, then the children, in two queries.
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub async fn load_has_many_through<P, C>(
    parents: &mut [P],
    conn: Connection,
    loading: Loading<C>,
    join_table: &'static str,
    owner_key: &'static str,
    target_key: &'static str,
    order: Option<(&'static str, bool)>,
    assign: impl Fn(&mut P, Vec<C>),
) -> Result<()>
where
    P: Model,
    C: Model + Clone,
{
    let ids: Vec<Value> = parents
        .iter()
        .map(Model::id_value)
        .filter(|id| key(id).is_some())
        .collect();
    let ordered = loading.is_ordered();
    let mut targets: HashMap<String, Vec<String>> = HashMap::new();
    let mut found: HashMap<String, C> = HashMap::new();
    // Each child's place in the ordered query, for an `order` option.
    let mut rank: HashMap<String, usize> = HashMap::new();
    if !ids.is_empty() {
        let mut sql = super::Sql::new();
        sql.push(&format!(
            "SELECT CAST({owner_key} AS BIGINT) AS owner, CAST({target_key} AS BIGINT) AS target \
             FROM {join_table} WHERE {owner_key}"
        ));
        sql.push_in(ids);
        let rows = conn.read_all(&sql).await?;
        let mut target_ids: Vec<Value> = Vec::new();
        for row in rows.iter() {
            let (Some(owner), Some(target)) = (
                row.get::<Option<i64>>("owner")?,
                row.get::<Option<i64>>("target")?,
            ) else {
                continue;
            };
            let target = Value::Int(target);
            if !target_ids.contains(&target) {
                target_ids.push(target.clone());
            }
            targets
                .entry(key(&Value::Int(owner)).unwrap_or_default())
                .or_default()
                .extend(key(&target));
        }
        if !target_ids.is_empty() {
            let mut query = loading.query()?.filter(|_| Expr::In {
                column: C::PRIMARY_KEY,
                values: target_ids,
            });
            if let Some((column, descending)) = order {
                query = query.order(|_| super::query::Order::by(column, descending));
            }
            let mut children = query.on(conn.clone()).all().await?;
            run_nested(&mut children, &conn, &loading.nested).await?;
            for (i, child) in children.into_iter().enumerate() {
                if let Some(k) = key(&child.id_value()) {
                    rank.insert(k.clone(), i);
                    found.insert(k, child);
                }
            }
        }
    }
    for parent in parents.iter_mut() {
        let mut keys: Vec<&String> = key(&parent.id_value())
            .and_then(|k| targets.get(&k))
            .into_iter()
            .flatten()
            .collect();
        if order.is_some() || ordered {
            keys.sort_by_key(|k| rank.get(*k).copied().unwrap_or(usize::MAX));
        }
        let children: Vec<C> = keys
            .into_iter()
            .filter_map(|k| found.get(k).cloned())
            .collect();
        assign(parent, children);
    }
    Ok(())
}

/// `has_many :leaves, through: :books`, where `books` is another of the
/// parent's `has_many`s: each parent's children by way of its middle
/// records, in two queries, as Rails' `has_many … through:`.
///
/// Which way the middle model points is read from the columns: when it
/// has the source key (`accesses.book_id`, for `has_many :books,
/// through: :accesses`), it's a join model, loaded as a join table is;
/// otherwise the children point at it (`leaves.book_id`).
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub async fn load_has_many_via<P, Mid, C>(
    parents: &mut [P],
    conn: Connection,
    loading: Loading<C>,
    owner_key: &'static str,
    source_key: &'static str,
    child_key: &'static str,
    order: Option<(&'static str, bool)>,
    assign: impl Fn(&mut P, Vec<C>),
) -> Result<()>
where
    P: Model,
    Mid: Model,
    C: Model + Clone,
{
    if Mid::COLUMNS.contains(&source_key) {
        return load_has_many_through(
            parents,
            conn,
            loading,
            Mid::TABLE,
            owner_key,
            source_key,
            order,
            assign,
        )
        .await;
    }
    let ids: Vec<Value> = parents
        .iter()
        .map(Model::id_value)
        .filter(|id| key(id).is_some())
        .collect();
    // Each middle record's parent.
    let mut owner_of: HashMap<String, String> = HashMap::new();
    let mut grouped: HashMap<String, Vec<C>> = HashMap::new();
    if !ids.is_empty() {
        let mut sql = super::Sql::new();
        sql.push(&format!(
            "SELECT CAST({} AS BIGINT) AS middle, CAST({owner_key} AS BIGINT) AS owner FROM {} \
             WHERE {owner_key}",
            Mid::PRIMARY_KEY,
            Mid::TABLE
        ));
        sql.push_in(ids);
        let mut middle_ids: Vec<Value> = Vec::new();
        for row in conn.read_all(&sql).await?.iter() {
            let (Some(middle), Some(owner)) = (
                row.get::<Option<i64>>("middle")?,
                row.get::<Option<i64>>("owner")?,
            ) else {
                continue;
            };
            let middle = Value::Int(middle);
            if let (Some(m), Some(o)) = (key(&middle), key(&Value::Int(owner))) {
                owner_of.insert(m, o);
            }
            middle_ids.push(middle);
        }
        if !middle_ids.is_empty() {
            let mut query = loading.query()?.filter(|_| Expr::In {
                column: child_key,
                values: middle_ids,
            });
            if let Some((column, descending)) = order {
                query = query.order(|_| super::query::Order::by(column, descending));
            }
            let mut children = query
                .order(|_| super::query::Order::by(C::PRIMARY_KEY, false))
                .on(conn.clone())
                .all()
                .await?;
            run_nested(&mut children, &conn, &loading.nested).await?;
            for child in children {
                let middle = child
                    .values()
                    .into_iter()
                    .find(|(column, _)| *column == child_key)
                    .map(|(_, value)| value);
                let owner = middle.as_ref().and_then(key).and_then(|m| owner_of.get(&m));
                if let Some(owner) = owner {
                    grouped.entry(owner.clone()).or_default().push(child);
                }
            }
        }
    }
    for parent in parents.iter_mut() {
        let children = key(&parent.id_value())
            .and_then(|k| grouped.remove(&k))
            .unwrap_or_default();
        assign(parent, children);
    }
    Ok(())
}

/// `has_many :x, through: join_table`'s `set_x_ids`, as Rails'
/// `x_ids=`: links `owner` to exactly `ids`, deleting the join rows for
/// ids not listed and adding the missing ones in order, so links kept
/// keep their rows.
#[doc(hidden)]
pub async fn set_through_ids(
    owner: Value,
    join_table: &'static str,
    owner_key: &'static str,
    target_key: &'static str,
    ids: Vec<i64>,
) -> Result<()> {
    write_through_ids(
        owner,
        join_table,
        owner_key,
        target_key,
        ids,
        Links::Exactly,
    )
    .await
}

/// What `write_through_ids` does with the ids it's given.
#[derive(Clone, Copy, PartialEq)]
#[doc(hidden)]
pub enum Links {
    /// Links these too (`attach`).
    Add,
    /// Unlinks these (`detach`).
    Remove,
    /// Links exactly these (`sync`).
    Exactly,
}

pub(crate) async fn write_through_ids(
    owner: Value,
    join_table: &'static str,
    owner_key: &'static str,
    target_key: &'static str,
    ids: Vec<i64>,
    links: Links,
) -> Result<()> {
    let conn = super::current()?;
    let mut sql = super::Sql::new();
    sql.push(&format!(
        "SELECT CAST({target_key} AS BIGINT) AS target FROM {join_table} WHERE {owner_key} = "
    ));
    sql.push_value(owner.clone());
    let mut existing = Vec::new();
    for row in conn.fetch_all(&sql).await? {
        if let Some(id) = row.get::<Option<i64>>("target")? {
            existing.push(id);
        }
    }
    let gone: Vec<Value> = match links {
        Links::Add => Vec::new(),
        Links::Remove => existing
            .iter()
            .filter(|id| ids.contains(id))
            .map(|id| Value::Int(*id))
            .collect(),
        Links::Exactly => existing
            .iter()
            .filter(|id| !ids.contains(id))
            .map(|id| Value::Int(*id))
            .collect(),
    };
    if !gone.is_empty() {
        let mut sql = super::Sql::new();
        sql.push(&format!("DELETE FROM {join_table} WHERE {owner_key} = "));
        sql.push_value(owner.clone());
        sql.push(&format!(" AND {target_key}"));
        sql.push_in(gone);
        conn.execute(&sql).await?;
    }
    let mut added = Vec::new();
    for id in ids {
        if links == Links::Remove || existing.contains(&id) || added.contains(&id) {
            continue;
        }
        let mut sql = super::Sql::new();
        sql.push(&format!(
            "INSERT INTO {join_table} ({owner_key}, {target_key}) VALUES ("
        ));
        sql.push_value(owner.clone());
        sql.push(", ");
        sql.push_value(Value::Int(id));
        sql.push(")");
        conn.execute(&sql).await?;
        added.push(id);
    }
    Ok(())
}

/// Used by generated code to turn a field into a `Value`.
#[doc(hidden)]
pub fn value_of<T: ToValue>(value: &T) -> Value {
    value.to_value()
}

/// Sets a parent's `updated_at` to now, for `belongs_to … touch`. Nothing
/// happens without a parent (a null key) or an `updated_at` column.
#[doc(hidden)]
pub async fn touch_parent<P: crate::model::Model>(id: Value) -> Result<()> {
    let Some(column) = P::UPDATED_AT else {
        return Ok(());
    };
    if id.is_null() {
        return Ok(());
    }
    let mut sql = crate::db::Sql::new();
    sql.push("UPDATE ")
        .push_ident(P::TABLE)
        .push(" SET ")
        .push_ident(column)
        .push(" = ");
    sql.push_value(Value::Timestamp(crate::time::now()));
    sql.push(" WHERE ").push_ident(P::PRIMARY_KEY).push(" = ");
    sql.push_value(id);
    crate::db::current_in(P::DATABASE)?.execute(&sql).await?;
    Ok(())
}

const NESTED_INVALID: &str = "glacier: a nested record is invalid";

/// The error that rolls back a save whose nested records are invalid.
#[doc(hidden)]
pub fn nested_invalid() -> crate::Error {
    crate::Error::unprocessable(NESTED_INVALID)
}

#[doc(hidden)]
pub fn is_nested_invalid(err: &crate::Error) -> bool {
    err.message() == NESTED_INVALID
}

/// One entry of `has_many … nested` attributes, as Rails applies it: an
/// `id` updates that child (one of the parent's, else `404`), `_destroy`
/// destroys it (when allowed), and no `id` creates one. Returns the
/// child's errors, if it's invalid.
#[doc(hidden)]
pub async fn save_nested_child<C>(
    parent_id: Value,
    foreign_key: &'static str,
    entry: &crate::Params,
    allow_destroy: bool,
) -> Result<Vec<String>>
where
    C: crate::model::Model + Default + Clone,
{
    let id = entry.get("id").map(str::trim).filter(|id| !id.is_empty());
    let Some(id) = id else {
        let mut params = entry.clone().without("_destroy");
        params.insert(foreign_key, parent_id.to_text());
        let mut child = C::default();
        return Ok(if child.update(params).await? {
            Vec::new()
        } else {
            child.messages()
        });
    };
    let id = id.parse::<i64>().map_err(|_| crate::Error::not_found())?;
    let child = Query::<C>::new()
        .via_association()
        .filter(|_| Expr::Compare {
            column: C::PRIMARY_KEY,
            op: "=",
            value: Value::Int(id),
        })
        .filter(|_| Expr::Compare {
            column: foreign_key,
            op: "=",
            value: parent_id,
        })
        .first()
        .await?;
    let Some(mut child) = child else {
        return Err(crate::Error::not_found());
    };
    let destroy = entry
        .get("_destroy")
        .is_some_and(|d| matches!(d.trim(), "1" | "true" | "on" | "yes"));
    if destroy && allow_destroy {
        child.destroy().await?;
        return Ok(Vec::new());
    }
    // Only the parent sets its key: an entry can't move the child to
    // another parent.
    let params = entry
        .clone()
        .without("id")
        .without("_destroy")
        .without(foreign_key);
    Ok(if child.update(params).await? {
        Vec::new()
    } else {
        child.messages()
    })
}