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
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
//! 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_in};
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(values.clone());
}
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 Assign {
/// `column = value`, by the column's name.
pub(crate) fn new(column: &'static str, value: Value) -> Self {
Assign { column, 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>,
/// The owner columns and values from `Model::for(access)`, which
/// records built from the query get.
owners: Vec<(&'static str, Value)>,
/// Through `Model::for(access)`, or an association from a record that
/// was: what the unscoped-read check looks for.
scoped: bool,
/// For a `soft_deletes` model: which rows, by `deleted_at`.
trashed: Trashed,
_model: PhantomData<fn() -> M>,
}
/// Soft-deleted rows in a query: left out (the default), with the rest,
/// or only them.
#[derive(Clone, Copy, PartialEq)]
enum Trashed {
Without,
With,
Only,
}
/// An `INNER JOIN` from `Query::join`.
#[derive(Clone)]
struct Join {
table: &'static str,
/// The table it joins to: the query's model's, or for a join table's
/// far side, the join table.
from: &'static str,
/// The joining columns: `from`'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(),
owners: self.owners.clone(),
scoped: self.scoped,
trashed: self.trashed,
_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(),
owners: Vec::new(),
scoped: false,
trashed: Trashed::Without,
_model: PhantomData,
}
}
/// Soft-deleted records too (`soft_deletes`).
pub fn with_trashed(mut self) -> Self {
self.trashed = Trashed::With;
self
}
/// Only soft-deleted records.
pub fn only_trashed(mut self) -> Self {
self.trashed = Trashed::Only;
self
}
/// Only the rows `access` owns: each of the model's owner columns
/// equal to the access's value for it. When the access has no value
/// for one (a user's access, for an org's rows), nothing matches.
pub fn owned_by(mut self, access: &dyn crate::access::Access) -> Self {
self.scoped = true;
for &(column, key) in M::OWNER {
match access.owns(key) {
Some(value) => {
self.owners.push((column, value.clone()));
let own = Expr::Compare {
column,
op: "=",
value,
};
// `global: true`: the tenant's rows and the shared ones.
self = if M::GLOBAL_ROWS {
self.filter(|_| {
own.or(Expr::Null {
column,
negated: false,
})
})
} else {
self.filter(|_| own)
};
}
None => self = self.filter(|_| Expr::raw("1 = 0", [])),
}
}
self
}
/// For a write under a tenant's access, the tenant's rows only: shared
/// rows (`global: true`) change only `unscoped`.
fn without_shared(self) -> Self {
if !M::GLOBAL_ROWS || !self.scoped || crate::access::may_change_shared() {
return self;
}
let mut query = self;
for &(column, _) in M::OWNER {
query = query.filter(|_| Expr::Null {
column,
negated: true,
});
}
query
}
/// The record with this primary key among the query's, or `404 Not
/// Found`: `Post.for(access).find(params[:id])!` finds another org's
/// post no more than a missing one.
pub async fn find(self, id: impl crate::db::ToValue) -> Result<M> {
let id = match id.to_value() {
Value::Text(text) if M::INTEGER_KEY => match text.trim().parse::<i64>() {
Ok(id) => Value::Int(id),
Err(_) => return Err(Error::not_found()),
},
value => value,
};
self.filter(|_| Expr::Compare {
column: M::PRIMARY_KEY,
op: "=",
value: id,
})
.one()
.await
}
/// A new record with `change` setting its fields, and the query's owner
/// columns set: `Note.for(access).build(title: "…")` in `.glacier`.
pub fn build_with(&self, change: impl FnOnce(&mut M)) -> M
where
M: Default,
{
let mut record = M::default();
change(&mut record);
for (column, value) in &self.owners {
record.set_owner(column, &value_text(value));
}
record
}
/// A new record from params, with the query's owner columns set (the
/// org's id), as Rails' `current_org.posts.build(params)`.
pub fn build(&self, params: impl Into<crate::Params>) -> M
where
M: Default,
{
let mut record = M::build(params);
for (column, value) in &self.owners {
record.set_owner(column, &value_text(value));
}
record
}
/// Adds a condition; several `filter` calls are combined with `AND`.
pub fn filter(mut self, condition: impl FnOnce(&M::Columns) -> Expr) -> Self {
// Values for `encrypted(deterministic)` columns, as they're stored.
let expr = crate::encryption::query_condition::<M>(condition(&M::columns()));
self.filter = Some(match self.filter.take() {
Some(existing) => existing.and(expr),
None => expr,
});
self
}
/// Adds a condition in SQL, `?` for each of `values`, as Rails'
/// `where("…", …)`: `Post.where_sql("NOT EXISTS (SELECT 1 FROM comments
/// WHERE comments.post_id = posts.id)", [])`.
pub fn where_sql(self, sql: &str, values: impl IntoIterator<Item = Value>) -> Self {
let expr = Expr::raw(sql, values);
self.filter(|_| expr)
}
/// 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 the request's `sort` param, as JSON:API has it:
/// `?sort=-inserted_at,title` sorts by `inserted_at` descending, then
/// `title`. Only the columns in `allowed` can be named; anything else is
/// a `400 Bad Request`. Given, it replaces the query's own order;
/// absent or empty, the query keeps it:
///
/// ```ignore
/// let books = Book::order(|b| b.title.asc())
/// .sort(¶ms, ["title", "inserted_at"])?
/// .await?;
/// ```
///
/// # Errors
///
/// `400 Bad Request` naming the column that can't be sorted by.
///
/// # Panics
///
/// If `allowed` names a column the model doesn't have.
pub fn sort(
mut self,
params: &crate::context::Params,
allowed: impl AsRef<[&'static str]>,
) -> Result<Self> {
let allowed = allowed.as_ref();
for column in allowed {
assert!(
M::COLUMNS.contains(column),
"sort: `{}` has no column `{column}`",
M::TABLE
);
}
let Some(text) = params.get("sort").map(str::trim).filter(|t| !t.is_empty()) else {
return Ok(self);
};
let mut order = Vec::new();
for field in text.split(',').map(str::trim) {
let (name, descending) = match field.strip_prefix('-') {
Some(name) => (name, true),
None => (field, false),
};
let column = allowed.iter().find(|c| **c == name).ok_or_else(|| {
Error::bad_request(format!(
"can't sort by `{name}`; sort by {}",
allowed
.iter()
.map(|c| format!("`{c}`"))
.collect::<Vec<_>>()
.join(", ")
))
})?;
order.push(Order { column, descending });
}
self.order = order;
self.raw_order.clear();
Ok(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
}
/// Counts a `has_many` association for each record loaded, without
/// loading its records: `Author.with_count(:books)`, then
/// `author.books.count()`, in one grouped query.
///
/// # Panics
///
/// For an association that isn't a `has_many` (without `through`).
pub fn with_count<C>(
mut self,
association: impl FnOnce(&M::Columns) -> super::Association<M, C>,
) -> Self
where
M: 'static,
{
let preload = association(&M::columns())
.counting()
.expect("with_count counts a `has_many` association (not one `through` a join table)");
self.preloads.push(preload);
self
}
/// How many matches each value of `column` has, the values as text:
/// an association counted per parent.
pub(crate) async fn count_by(self, column: &'static str) -> Result<Vec<(String, i64)>> {
let conn = self.connection()?;
let col = self.col(column);
let mut sql = Sql::new();
sql.push(&format!(
"SELECT CAST({col} AS TEXT) AS key, COUNT(*) AS value FROM "
));
self.write_from(&mut sql);
self.write_where(&mut sql);
sql.push(&format!(" GROUP BY {col}"));
let rows = conn.read_all(&sql).await?;
rows.iter()
.map(|row| Ok((row.get("key")?, row.get("value")?)))
.collect()
}
/// A loaded record's own query (deleting or reloading it): the record
/// was read already, so this isn't another read.
pub(crate) fn of_record(mut self) -> Self {
self.scoped = true;
self
}
/// Loading an association: scoped by the record it's loaded from.
pub(crate) fn via_association(mut self) -> Self {
self.scoped = true;
self
}
/// A constrained preload's query (`preload(books: Book.where(…))`),
/// to which the association adds its own conditions. A limit or
/// offset would count across every record's children together, so
/// they're refused.
pub(crate) fn for_association(self) -> Result<Self> {
if self.limit.is_some() || self.offset.is_some() {
return Err(Error::internal(format!(
"a preload's query can't take `limit` or `offset` (they'd count every {}'s \
children together); filter or order it instead",
std::any::type_name::<M>()
)));
}
Ok(self.via_association())
}
/// Whether the query has an order of its own.
pub(crate) fn is_ordered(&self) -> bool {
!self.order.is_empty() || !self.raw_order.is_empty()
}
fn connection(&self) -> Result<Connection> {
if !M::OWNER.is_empty() && !self.scoped {
crate::access::check_unscoped(M::TABLE)?;
}
match &self.conn {
Some(conn) => Ok(conn.clone()),
None => current_in(M::DATABASE),
}
}
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));
}
// `soft_deletes`: the rows still here, unless asked otherwise.
let trashed = M::SOFT_DELETE.and_then(|column| match self.trashed {
Trashed::Without => Some(Expr::Null {
column,
negated: false,
}),
Trashed::Only => Some(Expr::Null {
column,
negated: true,
}),
Trashed::With => None,
});
if let Some(trashed) = &trashed {
conditions.push((trashed, 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(join.from)
.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))
}
}
/// One page of the matches by cursor (keyset) pagination, in the
/// query's order with the primary key as the tie-breaker:
/// `Post::order(|p| p.inserted_at.desc()).cursor(page).await?`. Fast at
/// any depth, and no row is skipped or repeated when rows change between
/// pages. Order by columns that are never NULL; `order_raw` can't be
/// paged this way.
pub async fn cursor(
mut self,
page: crate::pagination::CursorPage,
) -> Result<crate::pagination::Cursored<M>> {
use crate::pagination::{Cursor, Cursored};
if !self.raw_order.is_empty() {
return Err(Error::internal(
"cursor pagination needs typed order columns: use order(), not order_raw()",
));
}
if let Some(first) = self.order.first()
&& first.column != M::PRIMARY_KEY
{
crate::db::warn_unindexed(&self.connection()?, M::TABLE, first.column).await;
}
// The keys: the query's order, then the primary key.
let mut keys = self.order.clone();
if !keys.iter().any(|o| o.column == M::PRIMARY_KEY) {
let descending = keys.last().is_some_and(|o| o.descending);
keys.push(Order {
column: M::PRIMARY_KEY,
descending,
});
}
let backwards = page.cursor.as_ref().is_some_and(|c| c.backwards);
// Going back, read the other way and turn the rows round after.
let order: Vec<Order> = keys
.iter()
.map(|o| Order {
column: o.column,
descending: o.descending != backwards,
})
.collect();
if let Some(cursor) = &page.cursor {
if cursor.keys.len() != order.len() {
return Err(Error::unprocessable("invalid cursor"));
}
let after = self.keyset_after(&order, &cursor.keys);
self = self.filter(|_| after);
}
self.order = order;
self.limit = Some(page.per_page + 1);
self.offset = None;
let mut records = self.all().await?;
let more = records.len() as u64 > page.per_page;
records.truncate(page.per_page as usize);
if backwards {
records.reverse();
}
let key_values = |record: &M| -> Vec<Value> {
let values = record.values();
keys.iter()
.map(|o| {
if o.column == M::PRIMARY_KEY {
record.id_value()
} else {
values
.iter()
.find(|(column, _)| *column == o.column)
.map_or(Value::Null, |(_, v)| v.clone())
}
})
.collect()
};
let cursor = |record: &M, backwards: bool| {
Cursor {
keys: key_values(record),
backwards,
}
.encode()
};
let (next, prev) = if backwards {
// Come back from a later page: there's always a next one.
(
records.last().map(|r| cursor(r, false)),
records.first().filter(|_| more).map(|r| cursor(r, true)),
)
} else {
(
records.last().filter(|_| more).map(|r| cursor(r, false)),
records
.first()
.filter(|_| page.cursor.is_some())
.map(|r| cursor(r, true)),
)
};
Ok(Cursored {
records,
next,
prev,
per_page: page.per_page,
})
}
/// The matches in batches of `size`, by the same keyset paging as
/// `cursor` (so rows changing meanwhile are neither skipped nor
/// repeated), as Rails' `in_batches`/`find_each`:
///
/// ```ignore
/// let mut batches = Post::all().batches(1000);
/// while let Some(posts) = batches.next().await? { … }
/// ```
pub fn batches(self, size: u64) -> Batches<M> {
Batches {
query: Some(self),
page: crate::pagination::CursorPage::first(size),
}
}
/// How many rows match, cheaply: for a whole Postgres table, the
/// planner's estimate (from its statistics, so approximate); otherwise
/// an exact count.
pub async fn estimated_count(self) -> Result<i64> {
let conn = self.connection()?;
if conn.dialect() == Dialect::Postgres && self.filter.is_none() && self.joins.is_empty() {
let mut sql = Sql::new();
sql.push("SELECT reltuples::bigint AS estimate FROM pg_class WHERE relname = ");
sql.push_value(Value::Text(M::TABLE.to_owned()));
let rows = conn.read_all(&sql).await?;
// -1 (or none) until the table has been analyzed.
if let Some(estimate) = rows.first().and_then(|r| r.get::<i64>("estimate").ok())
&& estimate >= 0
{
return Ok(estimate);
}
}
self.count().await
}
/// The rows after `keys` in `order`: `(a > ?) OR (a = ? AND b > ?) OR …`,
/// each column compared the way it's sorted.
fn keyset_after(&self, order: &[Order], keys: &[Value]) -> Expr {
let mut terms = Vec::new();
let mut values = Vec::new();
for i in 0..order.len() {
let mut parts = Vec::new();
for j in 0..i {
parts.push(format!("{} = ?", self.col(order[j].column)));
values.push(keys[j].clone());
}
let op = if order[i].descending { "<" } else { ">" };
parts.push(format!("{} {op} ?", self.col(order[i].column)));
values.push(keys[i].clone());
terms.push(format!("({})", parts.join(" AND ")));
}
Expr::raw(&terms.join(" OR "), values)
}
/// 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()`.
///
/// Through a join table (`has_many :tags, through: :book_tags`), it
/// joins that table, then the other model's.
pub fn join<C: Model>(
mut self,
association: impl FnOnce(&M::Columns) -> super::Association<M, C>,
condition: impl FnOnce(&C::Columns) -> Expr,
) -> Self {
let association = association(&M::columns());
let condition = condition(&C::columns());
let condition = match association.kind {
Some(kind) => condition.and(super::assoc::of_kind(kind)),
None => condition,
};
self.push_join(&association, Some(condition));
self
}
/// The joins for an association: its table, or a join table and then
/// the other model's.
fn push_join<C: Model>(
&mut self,
association: &super::Association<M, C>,
condition: Option<Expr>,
) {
match (association.join, association.through) {
(Some((own, other)), _) => self.joins.push(Join {
table: C::TABLE,
from: M::TABLE,
own,
other,
condition,
}),
(None, Some((table, mine, theirs))) => {
self.joins.push(Join {
table,
from: M::TABLE,
own: M::PRIMARY_KEY,
other: mine,
condition: None,
});
self.joins.push(Join {
table: C::TABLE,
from: table,
own: theirs,
other: C::PRIMARY_KEY,
condition,
});
}
(None, None) => unreachable!("an association joins directly or through a table"),
}
}
/// The records with at least one associated record matching `inner`,
/// as Laravel's `whereHas`: `Author.where_has(:books, published:
/// true)` in `.glacier`. One `EXISTS` subquery, so each record comes
/// once, and the associated model's default scope (and soft deletes)
/// apply.
pub fn where_has<C: Model>(
self,
association: impl FnOnce(&M::Columns) -> super::Association<M, C>,
inner: impl FnOnce(Query<C>) -> Query<C>,
) -> Self {
let exists = self.exists_in(association(&M::columns()), inner(Query::new()));
self.filter(|_| exists)
}
/// The records with no associated record at all, as Laravel's
/// `doesntHave`: `Author.without(:books)`.
pub fn without<C: Model>(
self,
association: impl FnOnce(&M::Columns) -> super::Association<M, C>,
) -> Self {
let exists = self.exists_in(association(&M::columns()), Query::new());
self.filter(|_| exists.not())
}
/// `EXISTS (SELECT 1 FROM child WHERE child.key = parent.key AND …)`.
fn exists_in<C: Model>(&self, association: super::Association<M, C>, inner: Query<C>) -> Expr {
let quote = super::sql::quote_ident;
let correlated = match (association.join, association.through) {
(Some((own, other)), _) => format!(
"{}.{} = {}.{}",
quote(C::TABLE),
quote(other),
quote(M::TABLE),
quote(own)
),
// Through a join table: the other's id among this record's rows.
(None, Some((table, mine, theirs))) => format!(
"{}.{} IN (SELECT {}.{} FROM {} WHERE {}.{} = {}.{})",
quote(C::TABLE),
quote(C::PRIMARY_KEY),
quote(table),
quote(theirs),
quote(table),
quote(table),
quote(mine),
quote(M::TABLE),
quote(M::PRIMARY_KEY)
),
(None, None) => unreachable!("an association joins directly or through a table"),
};
let mut inner = inner.filter(|_| Expr::raw(&correlated, []));
if let Some(kind) = association.kind {
inner = inner.filter(|_| super::assoc::of_kind(kind));
}
let mut sql = Sql::new();
sql.push("EXISTS (");
sql.append(inner.select("1"));
sql.push(")");
Expr::Raw(sql)
}
/// 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 association = association(&M::columns());
let condition = association.kind.map(super::assoc::of_kind);
self.push_join(&association, condition);
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.read_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.read_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.read_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 query = self.without_shared();
let conn = query.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(crate::encryption::stored::<M>(assign.column, assign.value)?);
any = true;
}
if !any {
return Ok(0);
}
query.write_target(&mut sql);
Ok(conn.execute(&sql).await?)
}
/// The rows an `update_all` or `delete_all` changes: those matching,
/// or with a `limit` or `offset`, only the rows the query would load
/// (`WHERE id IN (SELECT id … ORDER BY … LIMIT 1)`), as Rails does.
fn write_target(&self, sql: &mut Sql) {
if self.limit.is_none() && self.offset.is_none() {
self.write_where(sql);
return;
}
sql.push(" WHERE ").push_ident(M::PRIMARY_KEY).push(" IN (");
sql.append(self.select(&super::sql::quote_ident(M::PRIMARY_KEY)));
sql.push(")");
}
/// 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 column = self.col(column(&M::columns()).name());
let expression = T::sum(&column);
async move {
// SQLite adds decimals as floats (29.990000000000002): add
// them here, exactly.
if T::EXACT_ON_SQLITE && self.connection()?.dialect() == super::Dialect::Sqlite {
let conn = self.connection()?;
let mut sql = Sql::new();
sql.push(&format!("SELECT {column} AS value FROM "));
self.write_from(&mut sql);
self.write_where(&mut sql);
let mut total = T::Sum::default();
for row in conn.read_all(&sql).await?.iter() {
if let Some(value) = row.get::<Option<T::Sum>>("value")? {
total = T::add(total, value);
}
}
return Ok(total);
}
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.read_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"
)))
}
}
/// The first match that also meets `condition`, or `None`: a scope's
/// `find_by`, as `User.active().find_by(email_address: …)`.
pub async fn find_by(self, condition: impl FnOnce(&M::Columns) -> Expr) -> Result<Option<M>> {
self.filter(condition).first().await
}
/// 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.read_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. For
/// a `soft_deletes` model it sets their `deleted_at` instead;
/// `force_delete_all` deletes them.
pub async fn delete_all(self) -> Result<u64> {
if let Some(column) = M::SOFT_DELETE {
let now = crate::time::now();
return self
.update_all(|_| [Assign::new(column, Value::Timestamp(now))])
.await;
}
self.force_delete_all().await
}
/// Deletes every matching record for good, even a `soft_deletes`
/// model's.
pub async fn force_delete_all(self) -> Result<u64> {
self.refuse_joins("delete_all")?;
let query = self.without_shared();
let conn = query.connection()?;
let mut sql = Sql::new();
sql.push("DELETE FROM ").push_ident(M::TABLE);
query.write_target(&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);
if T::EXACT_ON_SQLITE && self.query.connection()?.dialect() == super::Dialect::Sqlite {
return self.exact_sums::<T>(&column).await;
}
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 sum added here, exactly (SQLite's `SUM` adds decimals
/// as floats): the rows in key order, grouped by the key's text.
async fn exact_sums<T: Summable>(self, column: &str) -> Result<Vec<(K, T::Sum)>> {
let conn = self.query.connection()?;
let key = self.query.col(self.key);
let mut sql = Sql::new();
sql.push(&format!(
"SELECT {key} AS key, CAST({key} AS TEXT) AS key_text, {column} AS value FROM "
));
self.query.write_from(&mut sql);
self.query.write_where(&mut sql);
sql.push(&format!(" ORDER BY {key}"));
let mut sums: Vec<(Option<String>, K, T::Sum)> = Vec::new();
for row in conn.read_all(&sql).await?.iter() {
let text: Option<String> = row.get("key_text")?;
let value: Option<T::Sum> = row.get("value")?;
match sums.last_mut() {
Some((last, _, total)) if *last == text => {
if let Some(value) = value {
*total = T::add(std::mem::take(total), value);
}
}
_ => sums.push((text, row.get("key")?, value.unwrap_or_default())),
}
}
Ok(sums
.into_iter()
.map(|(_, key, total)| (key, total))
.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.read_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;
/// Whether SQLite's `SUM` would round it (it adds decimals as
/// floats), so the values are added here instead.
#[doc(hidden)]
const EXACT_ON_SQLITE: bool = false;
#[doc(hidden)]
fn add(a: Self::Sum, _b: Self::Sum) -> Self::Sum {
a
}
}
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})")
}
const EXACT_ON_SQLITE: bool = true;
fn add(a: Self::Sum, b: Self::Sum) -> Self::Sum {
a + b
}
}
impl<T: Summable> Summable for Option<T> {
type Sum = T::Sum;
fn sum(column: &str) -> String {
T::sum(column)
}
const EXACT_ON_SQLITE: bool = T::EXACT_ON_SQLITE;
fn add(a: Self::Sum, b: Self::Sum) -> Self::Sum {
T::add(a, b)
}
}
/// A query read in batches (`Query::batches`).
pub struct Batches<M> {
query: Option<Query<M>>,
page: crate::pagination::CursorPage,
}
impl<M: Model> Batches<M> {
/// The next batch, or `None` when they're all read.
pub async fn next(&mut self) -> Result<Option<Vec<M>>> {
let Some(query) = self.query.take() else {
return Ok(None);
};
let page = query.clone().cursor(self.page.clone()).await?;
if page.records.is_empty() {
return Ok(None);
}
if let Some(next) = page.next {
self.page = crate::pagination::CursorPage::after(self.page.per_page, &next);
self.query = Some(query);
}
Ok(Some(page.records))
}
}
/// An owner column's value as text, for `Model::set_owner`.
fn value_text(value: &Value) -> String {
match value {
Value::Int(v) => v.to_string(),
Value::Text(v) => v.clone(),
Value::Uuid(v) => v.to_string(),
other => format!("{other:?}"),
}
}