glacier-web 0.1.1

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
//! Typed query building.
//!
//! Columns come from the model's generated `…Columns` struct, handed to a
//! closure, so filters are checked by the compiler and complete in the IDE:
//!
//! ```no_run
//! # use glacier::prelude::*;
//! # #[derive(Model)] struct Post { id: i64, title: String, views: i64 }
//! # async fn demo() -> glacier::Result<()> {
//! let popular = Post::filter(|p| p.views.gt(100).and(p.title.like("%rust%")))
//!     .order(|p| p.views.desc())
//!     .limit(10)
//!     .await?;
//! # Ok(()) }
//! ```

use std::future::{Future, IntoFuture};
use std::marker::PhantomData;
use std::pin::Pin;

use super::assoc::Preload;
use super::sql::{Dialect, Sql};
use super::value::{FromColumn, ToValue, Value};
use super::{Connection, current};
use crate::error::{Error, Result};
use crate::model::Model;

/// A column of model `M` holding values of type `T`.
pub struct Col<M, T> {
    name: &'static str,
    _marker: PhantomData<fn() -> (M, T)>,
}

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

impl<M, T> Copy for Col<M, T> {}

impl<M, T> Col<M, T> {
    #[doc(hidden)]
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            _marker: PhantomData,
        }
    }

    pub fn name(&self) -> &'static str {
        self.name
    }

    pub fn asc(self) -> Order {
        Order {
            column: self.name,
            descending: false,
        }
    }

    pub fn desc(self) -> Order {
        Order {
            column: self.name,
            descending: true,
        }
    }
}

impl<M, T: ToValue> Col<M, T> {
    fn compare(self, op: &'static str, value: impl Into<T>) -> Expr {
        Expr::Compare {
            column: self.name,
            op,
            value: value.into().to_value(),
        }
    }

    pub fn eq(self, value: impl Into<T>) -> Expr {
        self.compare("=", value)
    }

    /// `eq` converting as a field assignment does (`"x"` for an
    /// `Option<String>` column), for `.glacier`'s `where(status: "x")`.
    #[doc(hidden)]
    pub fn eq_field(self, value: impl crate::db::IntoField<T>) -> Expr {
        Expr::Compare {
            column: self.name,
            op: "=",
            value: value.into_field().to_value(),
        }
    }

    /// `to` converting as a field assignment does, for `update_all(…)`.
    #[doc(hidden)]
    pub fn to_field(self, value: impl crate::db::IntoField<T>) -> Assign {
        Assign {
            column: self.name,
            value: value.into_field().to_value(),
        }
    }

    /// An assignment for [`Query::update_all`]: `p.published.to(false)`.
    pub fn to(self, value: impl Into<T>) -> Assign {
        Assign {
            column: self.name,
            value: value.into().to_value(),
        }
    }

    pub fn ne(self, value: impl Into<T>) -> Expr {
        self.compare("<>", value)
    }

    pub fn lt(self, value: impl Into<T>) -> Expr {
        self.compare("<", value)
    }

    pub fn le(self, value: impl Into<T>) -> Expr {
        self.compare("<=", value)
    }

    pub fn gt(self, value: impl Into<T>) -> Expr {
        self.compare(">", value)
    }

    pub fn ge(self, value: impl Into<T>) -> Expr {
        self.compare(">=", value)
    }

    /// `column IN (…)`. An empty list matches nothing.
    pub fn is_in<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Expr {
        Expr::In {
            column: self.name,
            values: values.into_iter().map(|v| v.into().to_value()).collect(),
        }
    }
}

impl<M> Col<M, String> {
    /// SQL `LIKE`: `%` matches any run of characters, `_` any one.
    pub fn like(self, pattern: impl Into<String>) -> Expr {
        self.compare("LIKE", pattern.into())
    }
}

impl<M, T> Col<M, Option<T>> {
    pub fn is_null(self) -> Expr {
        Expr::Null {
            column: self.name,
            negated: false,
        }
    }

    pub fn is_not_null(self) -> Expr {
        Expr::Null {
            column: self.name,
            negated: true,
        }
    }
}

/// A `WHERE` condition. Combine with `.and(..)`, `.or(..)` and `.not()`.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    #[doc(hidden)]
    Compare {
        column: &'static str,
        op: &'static str,
        value: Value,
    },
    #[doc(hidden)]
    In {
        column: &'static str,
        values: Vec<Value>,
    },
    #[doc(hidden)]
    Null { column: &'static str, negated: bool },
    #[doc(hidden)]
    And(Box<Expr>, Box<Expr>),
    #[doc(hidden)]
    Or(Box<Expr>, Box<Expr>),
    #[doc(hidden)]
    Not(Box<Expr>),
    #[doc(hidden)]
    Raw(Sql),
}

impl Expr {
    /// A raw SQL condition with `?` placeholders, for anything the typed
    /// columns can't express.
    pub fn raw(sql: &str, values: impl IntoIterator<Item = Value>) -> Expr {
        Expr::Raw(Sql::raw(sql, values))
    }

    pub fn and(self, other: Expr) -> Expr {
        Expr::And(Box::new(self), Box::new(other))
    }

    pub fn or(self, other: Expr) -> Expr {
        Expr::Or(Box::new(self), Box::new(other))
    }

    #[allow(clippy::should_implement_trait)]
    pub fn not(self) -> Expr {
        Expr::Not(Box::new(self))
    }

    /// Writes the condition, its columns qualified with `table` when given
    /// (`"posts"."title"`), as a query with joins needs.
    fn write_in(&self, sql: &mut Sql, table: Option<&str>) {
        let column = |sql: &mut Sql, name: &str| {
            if let Some(table) = table {
                sql.push_ident(table).push(".");
            }
            sql.push_ident(name);
        };
        match self {
            // `= NULL` is never true in SQL; mean what the code says.
            Expr::Compare {
                column: column_name,
                op,
                value: Value::Null,
            } if matches!(*op, "=" | "<>") => {
                column(sql, column_name);
                sql.push(if *op == "=" {
                    " IS NULL"
                } else {
                    " IS NOT NULL"
                });
            }
            Expr::Compare {
                column: column_name,
                op,
                value,
            } => {
                column(sql, column_name);
                sql.push(&format!(" {op} "));
                sql.push_value(value.clone());
            }
            Expr::In { values, .. } if values.is_empty() => {
                sql.push("1 = 0");
            }
            Expr::In {
                column: column_name,
                values,
            } => {
                column(sql, column_name);
                sql.push(" IN (");
                for (i, value) in values.iter().enumerate() {
                    if i > 0 {
                        sql.push(", ");
                    }
                    sql.push_value(value.clone());
                }
                sql.push(")");
            }
            Expr::Null {
                column: column_name,
                negated,
            } => {
                column(sql, column_name);
                sql.push(if *negated { " IS NOT NULL" } else { " IS NULL" });
            }
            Expr::And(a, b) | Expr::Or(a, b) => {
                let op = if matches!(self, Expr::And(..)) {
                    " AND "
                } else {
                    " OR "
                };
                sql.push("(");
                a.write_in(sql, table);
                sql.push(op);
                b.write_in(sql, table);
                sql.push(")");
            }
            Expr::Not(e) => {
                sql.push("NOT (");
                e.write_in(sql, table);
                sql.push(")");
            }
            Expr::Raw(raw) => {
                sql.push("(");
                sql.append(raw.clone());
                sql.push(")");
            }
        }
    }
}

/// An `ORDER BY` term, from `column.asc()` or `column.desc()`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Order {
    column: &'static str,
    descending: bool,
}

/// `column = value` in [`Query::update_all`]; made with `Col::to`.
#[derive(Debug, Clone)]
pub struct Assign {
    column: &'static str,
    value: Value,
}

impl Order {
    pub(crate) fn by(column: &'static str, descending: bool) -> Self {
        Self { column, descending }
    }
}

/// A query for records of `M`. Build it up, then `.await` it for a
/// `Vec<M>`, or finish with `.first()`, `.one()`, `.count()`,
/// `.exists()` or `.delete_all()`.
pub struct Query<M> {
    filter: Option<Expr>,
    order: Vec<Order>,
    limit: Option<u64>,
    offset: Option<u64>,
    conn: Option<Connection>,
    preloads: Vec<Preload<M>>,
    /// `order_raw` clauses, after the typed ones.
    raw_order: Vec<String>,
    /// `SELECT DISTINCT`.
    distinct: bool,
    /// Associated tables joined in, with conditions on their columns.
    joins: Vec<Join>,
    _model: PhantomData<fn() -> M>,
}

/// An `INNER JOIN` from `Query::join`.
#[derive(Clone)]
struct Join {
    table: &'static str,
    /// The joining columns: the query's model's, then the joined table's.
    own: &'static str,
    other: &'static str,
    condition: Option<Expr>,
}

/// A query can be reused: count it, then fetch a page of it.
impl<M> Clone for Query<M> {
    fn clone(&self) -> Self {
        Self {
            filter: self.filter.clone(),
            order: self.order.clone(),
            limit: self.limit,
            offset: self.offset,
            conn: self.conn.clone(),
            preloads: self.preloads.clone(),
            raw_order: self.raw_order.clone(),
            distinct: self.distinct,
            joins: self.joins.clone(),
            _model: PhantomData,
        }
    }
}

impl<M: Model> Default for Query<M> {
    fn default() -> Self {
        Self::new()
    }
}

impl<M: Model> Query<M> {
    /// All records, with the model's default scope (`default_scope …` in
    /// `.glacier`) applied, as every query starts.
    pub fn new() -> Self {
        M::default_scope(Self::unscoped())
    }

    /// All records, ignoring the model's default scope.
    pub fn unscoped() -> Self {
        Self {
            filter: None,
            order: Vec::new(),
            limit: None,
            offset: None,
            conn: None,
            preloads: Vec::new(),
            raw_order: Vec::new(),
            distinct: false,
            joins: Vec::new(),
            _model: PhantomData,
        }
    }

    /// Adds a condition; several `filter` calls are combined with `AND`.
    pub fn filter(mut self, condition: impl FnOnce(&M::Columns) -> Expr) -> Self {
        let expr = condition(&M::columns());
        self.filter = Some(match self.filter.take() {
            Some(existing) => existing.and(expr),
            None => expr,
        });
        self
    }

    /// Adds an ordering; earlier `order` calls take precedence.
    pub fn order(mut self, order: impl FnOnce(&M::Columns) -> Order) -> Self {
        self.order.push(order(&M::columns()));
        self
    }

    /// Orders by raw SQL, as Rails' `.order("first_name ASC, last_name
    /// ASC")`, after any typed orders. Never pass it user input: build it
    /// from fixed choices.
    pub fn order_raw(mut self, sql: impl Into<String>) -> Self {
        self.raw_order.push(sql.into());
        self
    }

    pub fn limit(mut self, limit: u64) -> Self {
        self.limit = Some(limit);
        self
    }

    pub fn offset(mut self, offset: u64) -> Self {
        self.offset = Some(offset);
        self
    }

    /// One page of the results: `Post.order(id: :desc).page(page)`.
    pub fn page(self, page: crate::pagination::Page) -> Self {
        self.limit(page.per_page)
            .offset((page.number.max(1) - 1) * page.per_page)
    }

    /// Runs on `conn` instead of the ambient connection.
    pub fn on(mut self, conn: impl Into<Connection>) -> Self {
        self.conn = Some(conn.into());
        self
    }

    /// Loads an association for every record with one extra query.
    pub fn preload<P: Into<Preload<M>>>(
        mut self,
        association: impl FnOnce(&M::Columns) -> P,
    ) -> Self {
        self.preloads.push(association(&M::columns()).into());
        self
    }

    fn connection(&self) -> Result<Connection> {
        match &self.conn {
            Some(conn) => Ok(conn.clone()),
            None => current(),
        }
    }

    fn write_where(&self, sql: &mut Sql) {
        let own = if self.joins.is_empty() {
            None
        } else {
            Some(M::TABLE)
        };
        let mut conditions = Vec::new();
        if let Some(filter) = &self.filter {
            conditions.push((filter, own));
        }
        for join in &self.joins {
            if let Some(condition) = &join.condition {
                conditions.push((condition, Some(join.table)));
            }
        }
        for (i, (condition, table)) in conditions.into_iter().enumerate() {
            sql.push(if i == 0 { " WHERE " } else { " AND " });
            condition.write_in(sql, table);
        }
    }

    /// The table, and any joined tables.
    fn write_from(&self, sql: &mut Sql) {
        sql.push_ident(M::TABLE);
        for join in &self.joins {
            sql.push(" INNER JOIN ")
                .push_ident(join.table)
                .push(" ON ")
                .push_ident(join.table)
                .push(".")
                .push_ident(join.other)
                .push(" = ")
                .push_ident(M::TABLE)
                .push(".")
                .push_ident(join.own);
        }
    }

    /// One of the model's columns as SQL: qualified when tables are joined,
    /// so a shared name (`id`) isn't ambiguous.
    fn col(&self, name: &str) -> String {
        let quoted = super::sql::quote_ident(name);
        if self.joins.is_empty() {
            quoted
        } else {
            format!("{}.{quoted}", super::sql::quote_ident(M::TABLE))
        }
    }

    /// Joins an association's table, keeping the matches with a related
    /// record that meets `condition`, as Rails' `joins(:author).where(users:
    /// {…})`: `Post::all().join(|p| p.author, |a| a.name.eq("Ada"))`. A
    /// `has_many` join gives a match per related record; add `distinct()`.
    ///
    /// # Panics
    ///
    /// For a `has_many` through a join table, which can't be joined yet.
    pub fn join<C: Model>(
        mut self,
        association: impl FnOnce(&M::Columns) -> super::Association<M, C>,
        condition: impl FnOnce(&C::Columns) -> Expr,
    ) -> Self {
        let (own, other) = association(&M::columns())
            .join
            .expect("joining through a join table isn't supported yet");
        self.joins.push(Join {
            table: C::TABLE,
            own,
            other,
            condition: Some(condition(&C::columns())),
        });
        self
    }

    /// Joins an association's table: the matches with at least one related
    /// record, as Rails' `joins(:comments)`.
    pub fn joins<C: Model>(
        mut self,
        association: impl FnOnce(&M::Columns) -> super::Association<M, C>,
    ) -> Self {
        let (own, other) = association(&M::columns())
            .join
            .expect("joining through a join table isn't supported yet");
        self.joins.push(Join {
            table: C::TABLE,
            own,
            other,
            condition: None,
        });
        self
    }

    fn select(&self, columns: &str) -> Sql {
        let mut sql = Sql::new();
        let distinct = if self.distinct { "DISTINCT " } else { "" };
        let columns = if columns == "*" && !self.joins.is_empty() {
            format!("{}.*", super::sql::quote_ident(M::TABLE))
        } else {
            columns.to_owned()
        };
        sql.push(&format!("SELECT {distinct}{columns} FROM "));
        self.write_from(&mut sql);
        self.write_where(&mut sql);
        if !self.order.is_empty() || !self.raw_order.is_empty() {
            sql.push(" ORDER BY ");
            for (i, order) in self.order.iter().enumerate() {
                if i > 0 {
                    sql.push(", ");
                }
                sql.push(&self.col(order.column)).push(if order.descending {
                    " DESC"
                } else {
                    " ASC"
                });
            }
            for (i, order) in self.raw_order.iter().enumerate() {
                if i > 0 || !self.order.is_empty() {
                    sql.push(", ");
                }
                sql.push(order);
            }
        }
        match (self.limit, self.offset) {
            (Some(limit), Some(offset)) => {
                sql.push(&format!(" LIMIT {limit} OFFSET {offset}"));
            }
            (Some(limit), None) => {
                sql.push(&format!(" LIMIT {limit}"));
            }
            // SQLite requires a LIMIT before OFFSET (-1 means none);
            // Postgres rejects a negative LIMIT.
            (None, Some(offset)) => {
                sql.push_dialect(
                    &format!(" OFFSET {offset}"),
                    &format!(" LIMIT -1 OFFSET {offset}"),
                );
            }
            (None, None) => {}
        }
        sql
    }

    /// The SQL this query would run, for debugging and tests.
    pub fn to_sql(&self, dialect: Dialect) -> (String, Vec<Value>) {
        self.select("*").render(dialect)
    }

    pub async fn all(self) -> Result<Vec<M>> {
        let conn = self.connection()?;
        let rows = conn.fetch_all(&self.select("*")).await?;
        let mut records = rows.iter().map(M::from_row).collect::<Result<Vec<M>>>()?;
        for preload in &self.preloads {
            preload.run(&mut records, conn.clone()).await?;
        }
        Ok(records)
    }

    /// The first match (by primary key unless ordered otherwise).
    pub async fn first(mut self) -> Result<Option<M>> {
        if self.order.is_empty() {
            self.order.push(Order {
                column: M::PRIMARY_KEY,
                descending: false,
            });
        }
        Ok(self.limit(1).all().await?.into_iter().next())
    }

    /// The last match: the ordering reversed, or the highest primary key.
    pub async fn last(mut self) -> Result<Option<M>> {
        if self.order.is_empty() {
            self.order.push(Order {
                column: M::PRIMARY_KEY,
                descending: true,
            });
        } else {
            for order in &mut self.order {
                order.descending = !order.descending;
            }
        }
        Ok(self.limit(1).all().await?.into_iter().next())
    }

    /// The first `n` matches.
    pub async fn take(self, n: u64) -> Result<Vec<M>> {
        self.limit(n).all().await
    }

    /// One column of every match, without loading records:
    /// `Post::all().pluck(|p| p.title).await?` → `Vec<String>`.
    pub async fn pluck<T: FromColumn>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
    ) -> Result<Vec<T>> {
        let name = column(&M::columns()).name();
        let conn = self.connection()?;
        let selected = format!("{} AS {}", self.col(name), super::sql::quote_ident(name));
        let rows = conn.fetch_all(&self.select(&selected)).await?;
        rows.iter().map(|row| row.get(name)).collect()
    }

    /// The primary keys of every match.
    pub async fn ids(self) -> Result<Vec<i64>> {
        let conn = self.connection()?;
        let selected = format!(
            "{} AS {}",
            self.col(M::PRIMARY_KEY),
            super::sql::quote_ident(M::PRIMARY_KEY)
        );
        let rows = conn.fetch_all(&self.select(&selected)).await?;
        // `bigint` keys, or Rails' `integer` ones.
        rows.iter()
            .map(|row| {
                row.get::<i64>(M::PRIMARY_KEY)
                    .or_else(|_| row.get::<i32>(M::PRIMARY_KEY).map(i64::from))
            })
            .collect()
    }

    /// Sets columns on every match in one statement, returning how many
    /// changed. Like Rails' `update_all`, it skips validations and
    /// callbacks: `Post::filter(…).update_all(|p| [p.published.to(false)])`.
    pub async fn update_all<I>(self, assignments: impl FnOnce(&M::Columns) -> I) -> Result<u64>
    where
        I: IntoIterator<Item = Assign>,
    {
        self.refuse_joins("update_all")?;
        let conn = self.connection()?;
        let mut sql = Sql::new();
        sql.push("UPDATE ").push_ident(M::TABLE).push(" SET ");
        let mut any = false;
        for (i, assign) in assignments(&M::columns()).into_iter().enumerate() {
            if i > 0 {
                sql.push(", ");
            }
            sql.push_ident(assign.column).push(" = ");
            sql.push_value(assign.value);
            any = true;
        }
        if !any {
            return Ok(0);
        }
        self.write_where(&mut sql);
        Ok(conn.execute(&sql).await?)
    }

    /// Only distinct rows, as Rails' `distinct`: with `pluck`, each value
    /// once (`Post::all().distinct().pluck(|p| p.status)`).
    pub fn distinct(mut self) -> Self {
        self.distinct = true;
        self
    }

    /// The sum of a numeric column over the matches, 0 when there are none,
    /// as Rails' `sum`: `Post::all().sum(|p| p.views)`. Integer columns sum
    /// to an `i64`.
    pub fn sum<T: Summable>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
    ) -> impl Future<Output = Result<T::Sum>> + Send {
        let expression = T::sum(&self.col(column(&M::columns()).name()));
        async move {
            let value = self.aggregate::<Option<T::Sum>>(&expression).await?;
            Ok(value.unwrap_or_default())
        }
    }

    /// The mean of a numeric column, `None` without matches. A float,
    /// whatever the column (Rails returns a `BigDecimal`).
    pub fn average<T: Summable>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
    ) -> impl Future<Output = Result<Option<f64>>> + Send {
        let expression = average_sql(&self.col(column(&M::columns()).name()));
        async move { self.aggregate(&expression).await }
    }

    /// The smallest value of a column, `None` without matches.
    pub fn minimum<T: Aggregable>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
    ) -> impl Future<Output = Result<Option<T::Value>>> + Send {
        let expression = format!("MIN({})", self.col(column(&M::columns()).name()));
        async move { self.aggregate(&expression).await }
    }

    /// The largest value of a column, `None` without matches.
    pub fn maximum<T: Aggregable>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
    ) -> impl Future<Output = Result<Option<T::Value>>> + Send {
        let expression = format!("MAX({})", self.col(column(&M::columns()).name()));
        async move { self.aggregate(&expression).await }
    }

    /// Groups the matches by a column, to count or total each group:
    /// `Post::all().group(|p| p.status).count()` → `[("draft", 3), …]`,
    /// in the order of the column's values.
    pub fn group<K: FromColumn>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, K>,
    ) -> Grouped<M, K> {
        Grouped {
            query: self,
            key: column(&M::columns()).name(),
            _key: PhantomData,
        }
    }

    /// One aggregate (`SUM("views")`) over the matches, ignoring any order
    /// or limit.
    async fn aggregate<T: FromColumn>(&self, expression: &str) -> Result<T> {
        let conn = self.connection()?;
        let mut sql = Sql::new();
        sql.push(&format!("SELECT {expression} AS value FROM "));
        self.write_from(&mut sql);
        self.write_where(&mut sql);
        let rows = conn.fetch_all(&sql).await?;
        rows[0].get("value")
    }

    /// A joined query's writes would need its joins: refused, rather than
    /// touch records the joins were meant to rule out.
    fn refuse_joins(&self, method: &str) -> Result<()> {
        if self.joins.is_empty() {
            Ok(())
        } else {
            Err(Error::internal(format!(
                "{method} can't run on a query with joins; filter by ids instead"
            )))
        }
    }

    /// Like `first`, but a missing record is a `404 Not Found`.
    pub async fn one(self) -> Result<M> {
        self.first().await?.ok_or_else(Error::not_found)
    }

    pub async fn count(self) -> Result<i64> {
        let conn = self.connection()?;
        let mut sql = Sql::new();
        if self.distinct && !self.joins.is_empty() {
            sql.push(&format!(
                "SELECT COUNT(DISTINCT {}) AS count FROM ",
                self.col(M::PRIMARY_KEY)
            ));
        } else {
            // DISTINCT rows of one table are its rows: the count is the same.
            sql.push("SELECT COUNT(*) AS count FROM ");
        }
        self.write_from(&mut sql);
        self.write_where(&mut sql);
        let rows = conn.fetch_all(&sql).await?;
        rows[0].get("count")
    }

    pub async fn exists(self) -> Result<bool> {
        Ok(self.count().await? > 0)
    }

    /// Destroys every matching record one by one, running each one's
    /// destroy callbacks (and `dependent` children), as Rails'
    /// `destroy_all`; returns how many. `delete_all` is one `DELETE`.
    pub async fn destroy_all(self) -> Result<u64> {
        let records = self.all().await?;
        let count = records.len() as u64;
        for record in records {
            record.destroy().await?;
        }
        Ok(count)
    }

    /// Deletes every matching record, returning how many there were.
    pub async fn delete_all(self) -> Result<u64> {
        self.refuse_joins("delete_all")?;
        let conn = self.connection()?;
        let mut sql = Sql::new();
        sql.push("DELETE FROM ").push_ident(M::TABLE);
        self.write_where(&mut sql);
        Ok(conn.execute(&sql).await?)
    }
}

impl<M: Model> IntoFuture for Query<M> {
    type Output = Result<Vec<M>>;
    type IntoFuture = Pin<Box<dyn Future<Output = Result<Vec<M>>> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.all())
    }
}

/// A query grouped by a column (`Query::group`), to aggregate per group.
/// Each result is `(key, value)`, ordered by key.
pub struct Grouped<M, K> {
    query: Query<M>,
    key: &'static str,
    _key: PhantomData<fn() -> K>,
}

impl<M: Model, K: FromColumn> Grouped<M, K> {
    /// How many matches each group has, as Rails' `group(:x).count`.
    pub async fn count(self) -> Result<Vec<(K, i64)>> {
        self.aggregate("COUNT(*)").await
    }

    /// Each group's sum of a column.
    pub async fn sum<T: Summable>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
    ) -> Result<Vec<(K, T::Sum)>> {
        let name = column(&M::columns()).name();
        let column = self.query.col(name);
        let rows: Vec<(K, Option<T::Sum>)> = self.aggregate(&T::sum(&column)).await?;
        Ok(rows
            .into_iter()
            .map(|(key, sum)| (key, sum.unwrap_or_default()))
            .collect())
    }

    /// Each group's mean of a column.
    pub async fn average<T: Summable>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
    ) -> Result<Vec<(K, Option<f64>)>> {
        let name = column(&M::columns()).name();
        let column = self.query.col(name);
        self.aggregate(&average_sql(&column)).await
    }

    /// Each group's smallest value of a column.
    pub async fn minimum<T: Aggregable>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
    ) -> Result<Vec<(K, Option<T::Value>)>> {
        let name = column(&M::columns()).name();
        let column = self.query.col(name);
        self.aggregate(&format!("MIN({column})")).await
    }

    /// Each group's largest value of a column.
    pub async fn maximum<T: Aggregable>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
    ) -> Result<Vec<(K, Option<T::Value>)>> {
        let name = column(&M::columns()).name();
        let column = self.query.col(name);
        self.aggregate(&format!("MAX({column})")).await
    }

    async fn aggregate<V: FromColumn>(self, expression: &str) -> Result<Vec<(K, V)>> {
        let conn = self.query.connection()?;
        let key = self.query.col(self.key);
        let mut sql = Sql::new();
        sql.push(&format!("SELECT {key} AS key, {expression} AS value FROM "));
        self.query.write_from(&mut sql);
        self.query.write_where(&mut sql);
        sql.push(&format!(" GROUP BY {key} ORDER BY {key}"));
        let rows = conn.fetch_all(&sql).await?;
        rows.iter()
            .map(|row| Ok((row.get("key")?, row.get("value")?)))
            .collect()
    }
}

/// `column` is SQL: a quoted, perhaps qualified, column.
fn average_sql(column: &str) -> String {
    format!("CAST(AVG({column}) AS DOUBLE PRECISION)")
}

/// A column type that `minimum` and `maximum` work on; nullable columns
/// aggregate their values.
pub trait Aggregable {
    type Value: FromColumn;
}

/// A numeric column type `sum` and `average` work on: integers sum to an
/// `i64`, floats to an `f64`, decimals to a `Decimal`.
pub trait Summable {
    type Sum: FromColumn + Default;
    /// `SUM` of `column`, which is SQL (quoted, perhaps qualified).
    #[doc(hidden)]
    fn sum(column: &str) -> String;
}

macro_rules! aggregable {
    ($($t:ty),*) => {$(
        impl Aggregable for $t {
            type Value = $t;
        }
    )*};
}

aggregable!(
    i16,
    i32,
    i64,
    f32,
    f64,
    bool,
    String,
    super::Decimal,
    super::Date,
    super::NaiveTimestamp,
    super::Timestamp
);

impl<T: Aggregable> Aggregable for Option<T> {
    type Value = T::Value;
}

macro_rules! summable_integer {
    ($($t:ty),*) => {$(
        impl Summable for $t {
            type Sum = i64;
            fn sum(column: &str) -> String {
                format!("CAST(SUM({column}) AS BIGINT)")
            }
        }
    )*};
}

summable_integer!(i16, i32, i64);

impl Summable for f64 {
    type Sum = f64;
    fn sum(column: &str) -> String {
        format!("CAST(SUM({column}) AS DOUBLE PRECISION)")
    }
}

impl Summable for super::Decimal {
    type Sum = super::Decimal;
    fn sum(column: &str) -> String {
        format!("SUM({column})")
    }
}

impl<T: Summable> Summable for Option<T> {
    type Sum = T::Sum;
    fn sum(column: &str) -> String {
        T::sum(column)
    }
}