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
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
//! Query builders.
use std::borrow::Cow;
use std::marker::PhantomData;
use std::sync::Arc;
use crate::Error;
use crate::aggregate::{AggregateEntry, AggregateSet, GroupBy};
use crate::col::{Column, Projection};
use crate::compile::{
CompiledSql, SetExpr, delete, dialect_for_pool, insert, insert_many, join_select_with_columns,
select, update_with_sets, upsert,
};
use crate::executor::Executor;
use crate::filter::{Cte, CteQuery, Filter, FilterNode};
use crate::include::IncludeSet;
use crate::join::{Join2, JoinKind, JoinOn, JoinSpec, LeftJoin2, Maybe};
use crate::json::JsonSet;
use crate::m2m::{AnyM2mWrite, M2mWrite};
use crate::model::{Model, RowDecode};
use crate::order::OrderBy;
use crate::page::Page;
use crate::pool::Pool;
use crate::query_manifest;
use crate::rel::{AnyRelDelete, AnyRelWrite, DeleteAction, DeleteCascade, RelAction, RelWrite};
use crate::value::{Encodable, Ordered, Value};
/// A typed `SELECT` query.
///
/// Not `Debug`: the executor behind it is a trait object, and requiring
/// `Debug` on `Executor` would exclude perfectly good executors for no gain.
/// Use [`to_sql`](SelectQuery::to_sql) to inspect a query instead — that is the
/// representation anyone debugging actually wants.
#[derive(Clone)]
#[allow(dead_code)]
pub struct SelectQuery<'db, M: Model, Out = M, I = ()> {
exec: &'db dyn Executor,
filter: Filter<M>,
projection: Vec<&'static str>,
order: Vec<OrderBy<M>>,
limit: Option<u64>,
offset: Option<u64>,
distinct: bool,
ctes: Vec<Cte>,
includes: I,
join: Option<JoinSpec>,
with_deleted: bool,
only_deleted: bool,
_out: PhantomData<fn() -> Out>,
}
/// A prepared `SELECT` statement.
///
/// The SQL is compiled once; bind values can be swapped and the statement can
/// be re-executed without rebuilding the query string. Bind positions are
/// positional and match the placeholders in the compiled SQL.
#[allow(dead_code)]
pub struct PreparedSelect<'db, M: Model, Out = M> {
exec: &'db dyn Executor,
sql: Cow<'static, str>,
binds: Vec<Value>,
_marker: PhantomData<fn() -> (M, Out)>,
}
impl<'db, M: Model, Out> Clone for PreparedSelect<'db, M, Out> {
fn clone(&self) -> Self {
Self {
exec: self.exec,
sql: self.sql.clone(),
binds: self.binds.clone(),
_marker: PhantomData,
}
}
}
impl<'db, M> SelectQuery<'db, M, M, ()>
where
M: Model,
{
/// Creates a new query.
///
/// Accepts anything that can execute SQL, so the same query runs against a
/// pool or inside a transaction. `&Pool` and `&Tx` both coerce here.
#[must_use]
pub fn new(exec: &'db dyn Executor) -> Self {
Self {
exec,
filter: Filter::new(FilterNode::And(Vec::new())),
projection: Vec::new(),
order: Vec::new(),
limit: None,
offset: None,
distinct: false,
ctes: Vec::new(),
includes: (),
join: None,
with_deleted: false,
only_deleted: false,
_out: PhantomData,
}
}
}
impl<'db, M, Out, I> SelectQuery<'db, M, Out, I>
where
M: Model,
{
/// Adds a filter (`AND`).
pub fn filter(self, f: Filter<M>) -> Self {
Self {
filter: self.filter.and(f),
..self
}
}
/// Adds a filter (`OR`).
pub fn or_filter(self, f: Filter<M>) -> Self {
Self {
filter: self.filter.or(f),
..self
}
}
/// Adds a filter (`AND`) only if `f` is `Some`.
pub fn filter_if(self, f: Option<Filter<M>>) -> Self {
match f {
Some(f) => self.filter(f),
None => self,
}
}
/// Adds a filter (`OR`) only if `f` is `Some`.
pub fn or_filter_if(self, f: Option<Filter<M>>) -> Self {
match f {
Some(f) => self.or_filter(f),
None => self,
}
}
/// Filters rows by discriminator column value for Single Table Inheritance (STI) and polymorphic models.
pub fn filter_type<V: Encodable>(self, col: Column<M, V>, value: impl Into<V>) -> Self {
self.filter(col.eq(value))
}
/// Adds an ordering.
pub fn order_by(self, o: OrderBy<M>) -> Self {
let mut order = self.order;
order.push(o);
Self { order, ..self }
}
/// Adds an ordering only if `o` is `Some`.
pub fn order_by_if(self, o: Option<OrderBy<M>>) -> Self {
match o {
Some(o) => self.order_by(o),
None => self,
}
}
/// Sets the limit.
pub fn limit(self, n: u64) -> Self {
Self {
limit: Some(n),
..self
}
}
/// Sets the limit only if `n` is `Some`.
pub fn limit_if(self, n: Option<u64>) -> Self {
match n {
Some(n) => self.limit(n),
None => self,
}
}
/// Sets the offset.
pub fn offset(self, n: u64) -> Self {
Self {
offset: Some(n),
..self
}
}
/// Sets the offset only if `n` is `Some`.
pub fn offset_if(self, n: Option<u64>) -> Self {
match n {
Some(n) => self.offset(n),
None => self,
}
}
/// Returns the first `n` rows after a cursor value (exclusive).
pub fn after<V: Ordered>(self, col: Column<M, V>, value: impl Into<V>, n: u64) -> Self {
self.filter(col.gt(value)).order_by(col.asc()).limit(n)
}
/// Returns the first `n` rows before a cursor value (exclusive).
pub fn before<V: Ordered>(self, col: Column<M, V>, value: impl Into<V>, n: u64) -> Self {
self.filter(col.lt(value)).order_by(col.desc()).limit(n)
}
/// Makes the query `SELECT DISTINCT`.
pub fn distinct(self) -> Self {
Self {
distinct: true,
..self
}
}
/// **Does nothing.** The argument is discarded and the query is not cached.
///
/// Query execution never reads or writes a [`QueryCache`](crate::QueryCache).
/// To cache results, call [`InMemoryCache`](crate::InMemoryCache) (or your own
/// `QueryCache`) around the query yourself. This method will be implemented or
/// removed in `2.0`.
#[must_use]
#[deprecated(
since = "1.5.2",
note = "has no effect: the query cache is not wired to execution; use InMemoryCache directly"
)]
pub fn cache(self, _ttl: std::time::Duration) -> Self {
self
}
/// **Does nothing.** See [`SelectQuery::cache`].
#[must_use]
#[deprecated(
since = "1.5.2",
note = "has no effect: the query cache is not wired to execution; use InMemoryCache directly"
)]
pub fn cache_key(self, _key: impl Into<String>) -> Self {
self
}
/// **Does nothing.** See [`SelectQuery::cache`].
#[must_use]
#[deprecated(
since = "1.5.2",
note = "has no effect: the query cache is not wired to execution; use InMemoryCache directly"
)]
pub fn cache_tag(self, _tag: impl Into<String>) -> Self {
self
}
/// **Does nothing.** The query runs on whatever executor it was built with.
///
/// For a read that must see the primary, build the query on
/// [`RoutedPool::primary()`](crate::RoutedPool::primary) instead. This method
/// will be implemented or removed in `2.0`.
#[must_use]
#[deprecated(
since = "1.5.2",
note = "has no effect: build the query on RoutedPool::primary() instead"
)]
pub fn use_primary(self) -> Self {
self
}
/// **Does nothing.** The query runs on whatever executor it was built with.
///
/// To read from a replica, build the query on a
/// [`RoutedPool`](crate::RoutedPool) (reads are routed to replicas) or on
/// [`RoutedPool::select_replica()`](crate::RoutedPool::select_replica).
#[must_use]
#[deprecated(
since = "1.5.2",
note = "has no effect: build the query on a RoutedPool or RoutedPool::select_replica()"
)]
pub fn use_replica(self) -> Self {
self
}
/// Adds a non-recursive common table expression (CTE).
///
/// `query` can be any [`SelectQuery`]; it is compiled and emitted as
/// `WITH <name> AS (...)`.
#[must_use]
pub fn with<Q: Into<CteQuery>>(mut self, name: &'static str, query: Q) -> Self {
self.ctes.push(Cte::new(name, query.into().compiled));
self
}
/// Adds a recursive common table expression (CTE).
///
/// The body is `(anchor) UNION ALL (recursive)`, with placeholders
/// renumbered across the union. The CTE is emitted as
/// `WITH RECURSIVE <name> AS (...)`.
#[must_use]
pub fn with_recursive<A: Into<CteQuery>, R: Into<CteQuery>>(
mut self,
name: &'static str,
anchor: A,
recursive: R,
) -> Self {
let anchor = anchor.into().compiled;
let recursive = recursive.into().compiled.renumbered(anchor.binds.len());
let mut binds = anchor.binds.clone();
binds.extend(recursive.binds.clone());
let sql = format!(
"({}) UNION ALL ({})",
anchor.sql.as_ref(),
recursive.sql.as_ref()
);
self.ctes.push(Cte {
name,
compiled: CompiledSql {
sql: Cow::Owned(sql),
binds,
},
recursive: true,
});
self
}
/// Adds an inner join to another model.
pub fn inner_join<J: Model>(
self,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<M, J>, I> {
self.join_with::<J, Join2<M, J>>(JoinKind::Inner, None, on)
}
/// Adds a left join to another model.
pub fn left_join<J: Model>(
self,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, LeftJoin2<M, J>, I> {
self.join_with::<J, LeftJoin2<M, J>>(JoinKind::Left, None, on)
}
/// Adds a right join to another model.
pub fn right_join<J: Model>(
self,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<Maybe<M>, J>, I> {
self.join_with::<J, Join2<Maybe<M>, J>>(JoinKind::Right, None, on)
}
/// Adds a full join to another model.
pub fn full_join<J: Model>(
self,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<Maybe<M>, Maybe<J>>, I> {
self.join_with::<J, Join2<Maybe<M>, Maybe<J>>>(JoinKind::Full, None, on)
}
/// Adds an aliased inner join to another model.
///
/// Use `Column::aliased` in the `ON` condition so the right-hand side is
/// qualified by the alias. This is the fully-typed way to write self-joins:
///
/// ```ignore
/// User::query().inner_join_aliased::<User>("u2", User::id.on(User::manager_id.aliased("u2")))
/// ```
pub fn inner_join_aliased<J: Model>(
self,
alias: &'static str,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<M, J>, I> {
self.join_with::<J, Join2<M, J>>(JoinKind::Inner, Some(alias), on)
}
/// Adds an aliased left join to another model.
pub fn left_join_aliased<J: Model>(
self,
alias: &'static str,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, LeftJoin2<M, J>, I> {
self.join_with::<J, LeftJoin2<M, J>>(JoinKind::Left, Some(alias), on)
}
/// Adds an aliased right join to another model.
pub fn right_join_aliased<J: Model>(
self,
alias: &'static str,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<Maybe<M>, J>, I> {
self.join_with::<J, Join2<Maybe<M>, J>>(JoinKind::Right, Some(alias), on)
}
/// Adds an aliased full join to another model.
pub fn full_join_aliased<J: Model>(
self,
alias: &'static str,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<Maybe<M>, Maybe<J>>, I> {
self.join_with::<J, Join2<Maybe<M>, Maybe<J>>>(JoinKind::Full, Some(alias), on)
}
/// Includes soft-deleted rows in the query results (disables default `WHERE deleted_at IS NULL`).
pub fn with_deleted(mut self) -> Self {
self.with_deleted = true;
self.only_deleted = false;
self
}
/// Queries *only* soft-deleted rows (`WHERE deleted_at IS NOT NULL`).
pub fn only_deleted(mut self) -> Self {
self.with_deleted = false;
self.only_deleted = true;
self
}
fn join_with<J: Model, O>(
self,
kind: JoinKind,
right_alias: Option<&'static str>,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, O, I> {
SelectQuery {
exec: self.exec,
filter: self.filter,
projection: Vec::new(),
order: self.order,
limit: self.limit,
offset: self.offset,
distinct: self.distinct,
ctes: self.ctes,
includes: self.includes,
join: Some(JoinSpec {
kind,
right_table: J::TABLE,
right_columns: J::COLUMNS,
right_alias,
on: on.into(),
right_deleted_at: J::DELETED_AT_COLUMN,
}),
with_deleted: self.with_deleted,
only_deleted: self.only_deleted,
_out: PhantomData,
}
}
/// Switches the query to return aggregate results rather than rows.
///
/// The output type is a tuple, e.g. `(Option<i64>, i64)` for
/// `aggregate((User::age.sum(), User::id.count()))`.
#[must_use]
pub fn aggregate<R, A>(self, set: A) -> AggregateQuery<'db, M, R>
where
R: RowDecode,
A: AggregateSet<M, R>,
{
let mut entries = Vec::new();
set.push_entries(&mut entries);
AggregateQuery {
exec: self.exec,
filter: self.effective_filter(),
aggregates: entries,
group_by: Vec::new(),
having: Filter::new(FilterNode::And(Vec::new())),
order: self.order,
limit: self.limit,
offset: self.offset,
ctes: self.ctes,
_out: PhantomData,
}
}
/// Groups the query by one or more columns.
///
/// Returns a [`GroupedQuery`] that supports `having` and `aggregate`.
#[must_use]
pub fn group_by<G: GroupBy<M>>(self, g: G) -> GroupedQuery<'db, M, Out, I> {
GroupedQuery {
inner: self,
group_by: g.columns(),
having: Filter::new(FilterNode::And(Vec::new())),
_marker: PhantomData,
}
}
/// Includes a related model, loaded in a second batched query.
pub fn include<J: IncludeSet<M>>(self, include: J) -> SelectQuery<'db, M, Out, J> {
SelectQuery {
exec: self.exec,
filter: self.filter,
projection: self.projection,
order: self.order,
limit: self.limit,
offset: self.offset,
distinct: self.distinct,
ctes: self.ctes,
includes: include,
join: self.join,
with_deleted: self.with_deleted,
only_deleted: self.only_deleted,
_out: PhantomData,
}
}
/// Restricts the selected columns and changes the output type.
pub fn columns<P: Projection<M>>(self, p: P) -> SelectQuery<'db, M, P::Output> {
SelectQuery {
exec: self.exec,
filter: self.filter,
projection: p.projection(),
order: self.order,
limit: self.limit,
offset: self.offset,
distinct: self.distinct,
ctes: self.ctes,
includes: (),
join: None,
with_deleted: self.with_deleted,
only_deleted: self.only_deleted,
_out: PhantomData,
}
}
/// Returns `true` when this query is known to load every row of the model's
/// table with no filter, limit, offset or distinct.
pub(crate) fn is_full_table(&self) -> bool {
self.ctes.is_empty()
&& self.limit.is_none()
&& self.offset.is_none()
&& !self.distinct
&& matches!(
self.filter.node,
crate::filter::FilterNode::And(ref v) if v.is_empty()
)
}
/// Returns an error if the query's join is not supported by the dialect.
fn check_join_support(&self) -> Result<(), Error> {
let dialect = self.exec.dialect();
if let Some(ref join) = self.join {
match join.kind {
JoinKind::Right if !dialect.supports_right_join() => {
return Err(Error::Message(format!(
"RIGHT JOIN is not supported by {}",
dialect.name()
)));
}
JoinKind::Full if !dialect.supports_full_join() => {
return Err(Error::Message(format!(
"FULL OUTER JOIN is not supported by {}",
dialect.name()
)));
}
_ => {}
}
}
Ok(())
}
/// Returns the effective filter incorporating soft-delete filters if configured on the model.
pub(crate) fn effective_filter(&self) -> Filter<M> {
let mut filter = self.filter.clone();
if let Some(col) = M::DELETED_AT_COLUMN {
if !self.with_deleted {
if self.only_deleted {
filter = filter.and(Filter::new(FilterNode::Null {
table: M::TABLE,
column: col,
negated: true,
}));
} else {
filter = filter.and(Filter::new(FilterNode::Null {
table: M::TABLE,
column: col,
negated: false,
}));
}
}
}
filter
}
/// Compiles the main query (without the CTE `WITH` prefix) to SQL and binds.
///
/// # Errors
///
/// Returns [`Error::Message`] if the query uses a `RIGHT JOIN` or
/// `FULL OUTER JOIN` that the target dialect does not support.
pub(crate) fn to_sql_without_cte(&self) -> Result<CompiledSql, Error> {
self.check_join_support()?;
let dialect = self.exec.dialect();
let eff_filter = self.effective_filter();
if let Some(ref join) = self.join {
// `with_deleted()` opts both sides out. `only_deleted()` selects the
// left model's recycle bin but still joins live right-hand rows.
let on = match join.right_deleted_at {
Some(column) if !self.with_deleted => FilterNode::And(vec![
join.on.node.clone(),
FilterNode::Null {
table: join.right_alias.unwrap_or(join.right_table),
column,
negated: false,
},
]),
_ => join.on.node.clone(),
};
Ok(join_select_with_columns::<M>(
dialect,
M::TABLE,
M::COLUMNS,
join.right_table,
join.right_columns,
join.right_alias,
join.kind,
&on,
&eff_filter.node,
&self.order,
self.limit,
self.offset,
self.distinct,
))
} else {
Ok(select::<M>(
dialect,
M::TABLE,
&self.projection,
&eff_filter.node,
&self.order,
self.limit,
self.offset,
self.distinct,
))
}
}
/// Compiles the query to SQL and binds.
///
/// # Errors
///
/// Returns [`Error::Message`] if the query uses a `RIGHT JOIN` or
/// `FULL OUTER JOIN` that the target dialect does not support.
pub fn to_sql(&self) -> Result<CompiledSql, Error> {
let dialect = self.exec.dialect();
let main = self.to_sql_without_cte()?;
let compiled = crate::compile::with_cte_prefix(dialect, &self.ctes, main);
query_manifest::record(
compiled.sql.clone().into_owned(),
Some(file!()),
Some(line!()),
dialect.name(),
);
Ok(compiled)
}
/// Combines this query with another using `UNION`.
///
/// The output shape of both sides must match exactly; this is enforced at
/// compile time by the shared `Out` type parameter.
pub fn union<M2, I2>(self, other: SelectQuery<'db, M2, Out, I2>) -> SetOpQuery<'db, Out>
where
M2: Model,
{
SetOpQuery::new(self.exec, SetOp::Union, self, other)
}
/// Combines this query with another using `UNION ALL`.
pub fn union_all<M2, I2>(self, other: SelectQuery<'db, M2, Out, I2>) -> SetOpQuery<'db, Out>
where
M2: Model,
{
SetOpQuery::new(self.exec, SetOp::UnionAll, self, other)
}
/// Combines this query with another using `INTERSECT`.
pub fn intersect<M2, I2>(self, other: SelectQuery<'db, M2, Out, I2>) -> SetOpQuery<'db, Out>
where
M2: Model,
{
SetOpQuery::new(self.exec, SetOp::Intersect, self, other)
}
/// Combines this query with another using `EXCEPT`.
pub fn except<M2, I2>(self, other: SelectQuery<'db, M2, Out, I2>) -> SetOpQuery<'db, Out>
where
M2: Model,
{
SetOpQuery::new(self.exec, SetOp::Except, self, other)
}
/// Returns the number of rows the query would return.
///
/// `ORDER BY`, `LIMIT` and `OFFSET` are ignored for the count: counting the
/// matching rows is independent of ordering or pagination.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn count(self) -> Result<i64, Error> {
self.check_join_support()?;
let dialect = self.exec.dialect();
let eff_filter = self.effective_filter();
let compiled = crate::compile::count::<M>(dialect, M::TABLE, &eff_filter.node);
let compiled = crate::compile::with_cte_prefix(dialect, &self.ctes, compiled);
#[cfg(feature = "sqlite-rusqlite")]
let mut counts: Vec<(i64,)> = if let Some(pool) = self.exec.as_rusqlite() {
self.exec.on_query();
pool.fetch_all_sync_decoded::<(i64,)>(compiled.sql, compiled.binds)
.await?
} else {
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)?
};
#[cfg(not(feature = "sqlite-rusqlite"))]
let mut counts: Vec<(i64,)> = {
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)?
};
let (count,) = counts
.pop()
.ok_or_else(|| Error::Message("COUNT(*) returned no row".into()))?;
Ok(count)
}
/// Whether any row matches.
///
/// Compiles to `SELECT 1 ... LIMIT 1` rather than counting: the database
/// can stop at the first match, which on a large table is the difference
/// between an index probe and a full scan.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn exists(self) -> Result<bool, Error> {
self.check_join_support()?;
let dialect = self.exec.dialect();
let eff_filter = self.effective_filter();
let compiled = crate::compile::exists::<M>(dialect, M::TABLE, &eff_filter.node);
let compiled = crate::compile::with_cte_prefix(dialect, &self.ctes, compiled);
#[cfg(feature = "sqlite-rusqlite")]
{
if let Some(pool) = self.exec.as_rusqlite() {
self.exec.on_query();
let rows = pool
.fetch_all_sync_decoded::<(i64,)>(compiled.sql, compiled.binds)
.await?;
return Ok(!rows.is_empty());
}
}
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
Ok(!batch.is_empty())
}
}
/// A stream of decoded rows, returned by [`SelectQuery::stream`].
pub struct RowStream<'db, Out> {
inner: crate::executor::BoxRowStream<'db>,
_out: PhantomData<fn() -> Out>,
}
impl<Out> futures_core::Stream for RowStream<'_, Out>
where
Out: Unpin + RowDecode,
{
type Item = Result<Out, Error>;
fn poll_next(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
// Both fields are `Unpin`, so no `unsafe` projection is needed.
let this = self.get_mut();
std::pin::Pin::new(&mut this.inner).poll_next(cx).map(|o| {
o.map(|r| {
r.and_then(|raw| match raw {
crate::executor::RawRow::Any(r) => Out::from_row(&r).map_err(Error::Sqlx),
crate::executor::RawRow::Postgres(r) => Out::from_row(&r).map_err(Error::Sqlx),
crate::executor::RawRow::Sqlite(r) => Out::from_row(&r).map_err(Error::Sqlx),
crate::executor::RawRow::Mysql(r) => Out::from_row(&r).map_err(Error::Sqlx),
#[cfg(feature = "sqlite-rusqlite")]
crate::executor::RawRow::Rusqlite(r) => Out::from_owned_row(&r),
#[cfg(feature = "postgres-tokio-postgres")]
crate::executor::RawRow::PostgresNative(r) => Out::from_tokio_postgres_row(&r),
crate::executor::RawRow::Edge(_) => Err(Error::Message(
"RawRow::Edge cannot be streamed into sqlx FromRow; use custom edge decoder".into(),
)),
})
})
})
}
}
impl<'db, M, Out> SelectQuery<'db, M, Out, ()>
where
M: Model,
{
/// Prepares a reusable compiled statement.
///
/// The SQL is compiled once; bind values can be swapped with
/// [`PreparedSelect::bind`] and the statement can be executed repeatedly
/// without rebuilding the query string.
pub fn prepare(self) -> Result<PreparedSelect<'db, M, Out>, Error> {
let compiled = self.to_sql()?;
Ok(PreparedSelect {
exec: self.exec,
sql: compiled.sql,
binds: compiled.binds,
_marker: PhantomData,
})
}
/// Executes the query and returns all matching rows.
///
/// Only available when the query has no `.include(...)`: fetching all rows
/// without loading declared includes would silently return the wrong data.
/// Use [`exec`](SelectQuery::exec) for include-aware execution.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn fetch_all(self) -> Result<Vec<Out>, Error>
where
Out: Send + Unpin + RowDecode,
{
let compiled = self.to_sql()?;
#[cfg(feature = "sqlite-rusqlite")]
if let Some(pool) = self.exec.as_rusqlite() {
self.exec.on_query();
return pool
.fetch_all_sync_decoded::<Out>(compiled.sql, compiled.binds)
.await;
}
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)
}
/// Alias for [`fetch_all`](SelectQuery::fetch_all).
pub async fn all(self) -> Result<Vec<Out>, Error>
where
Out: Send + Unpin + RowDecode,
{
self.fetch_all().await
}
/// Streams matching rows instead of collecting them.
///
/// Only available when the query has no `.include(...)`: a stream without
/// loaded includes would silently return the wrong data. Use
/// [`exec`](SelectQuery::exec) for include-aware execution.
///
/// Rows are decoded one at a time as the stream is polled. The underlying
/// fetch is currently buffered by both executors (see
/// [`Executor::stream_raw`]), so this bounds decode cost rather than peak
/// memory; the buffering lives behind the executor so it can be replaced
/// with a true cursor without touching this API.
pub fn stream(self) -> Result<RowStream<'db, Out>, Error>
where
Out: Send + Unpin + RowDecode,
{
let compiled = self.to_sql()?;
Ok(RowStream {
inner: self.exec.stream_raw(compiled.sql, compiled.binds),
_out: PhantomData,
})
}
/// Streams matching rows without buffering the whole result set.
///
/// Only available when the query has no `.include(...)`: a stream without
/// loaded includes would silently return the wrong data. Use
/// [`exec`](SelectQuery::exec) for include-aware execution.
///
/// For `sqlx` backends the rows are produced incrementally by the driver,
/// which keeps peak memory proportional to the number of in-flight rows
/// rather than the total result size. The `postgres-tokio-postgres` backend
/// uses an unbuffered server-side portal.
pub fn stream_unbuffered(self) -> Result<RowStream<'db, Out>, Error>
where
Out: Send + Unpin + RowDecode,
{
let compiled = self.to_sql()?;
Ok(RowStream {
inner: self
.exec
.stream_unbuffered_raw(compiled.sql, compiled.binds),
_out: PhantomData,
})
}
/// Fetches one page, reporting whether another page follows.
///
/// Fetches `size + 1` rows and discards the extra, so `has_next` is exact
/// rather than inferred from a full page. The model's primary key is
/// appended to `ORDER BY` so the total order is deterministic — without a
/// unique tiebreaker, rows sharing an ordering value can repeat across
/// pages or be skipped entirely.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn page(self, size: u64) -> Result<Page<Out>, Error>
where
Out: Send + Unpin + RowDecode,
{
let pk: Column<M, i64> = Column::new(M::TABLE, M::PRIMARY_KEY);
let q = self.order_by(pk.asc()).limit(size.saturating_add(1));
let mut items: Vec<Out> = q.fetch_all().await?;
let has_next = items.len() as u64 > size;
if has_next {
items.truncate(size as usize);
}
Ok(Page::new(items, has_next, None))
}
/// Executes the query and returns the first row, if any.
///
/// Only available when the query has no `.include(...)`: fetching a single
/// row without loading declared includes would silently return the wrong
/// data. Use [`exec_optional`](SelectQuery::exec_optional) for include-aware
/// execution.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn fetch_optional(mut self) -> Result<Option<Out>, Error>
where
Out: Send + Unpin + RowDecode,
{
// `fetch_optional` only needs one row. Forcing `LIMIT 1` prevents the
// database from materialising and ruprizzle from decoding a larger
// result set when the caller set a higher limit.
self.limit = Some(1);
let compiled = self.to_sql()?;
#[cfg(feature = "sqlite-rusqlite")]
let v: Vec<Out> = if let Some(pool) = self.exec.as_rusqlite() {
self.exec.on_query();
pool.fetch_all_sync_decoded::<Out>(compiled.sql, compiled.binds)
.await?
} else {
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)?
};
#[cfg(not(feature = "sqlite-rusqlite"))]
let v: Vec<Out> = {
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)?
};
Ok(v.into_iter().next())
}
/// Executes the query and returns exactly one row.
///
/// Only available when the query has no `.include(...)`. Use
/// [`exec_one`](SelectQuery::exec_one) when includes are requested.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors, including the case where no
/// row matches.
pub async fn fetch_one(self) -> Result<Out, Error>
where
Out: Send + Unpin + RowDecode,
{
self.fetch_optional()
.await?
.ok_or_else(|| Error::Message("no row found for query".into()))
}
}
/// A SQL set operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetOp {
/// `UNION` (deduplicating).
Union,
/// `UNION ALL` (preserves duplicates).
UnionAll,
/// `INTERSECT`.
Intersect,
/// `EXCEPT`.
Except,
}
impl SetOp {
/// Returns the SQL keyword for this operation.
pub(crate) fn sql(self) -> &'static str {
match self {
SetOp::Union => "UNION",
SetOp::UnionAll => "UNION ALL",
SetOp::Intersect => "INTERSECT",
SetOp::Except => "EXCEPT",
}
}
}
/// A query built from two `SELECT`s combined by a set operation.
#[derive(Clone)]
#[allow(dead_code)]
pub struct SetOpQuery<'db, Out> {
exec: &'db dyn Executor,
op: SetOp,
left: CompiledSql,
right: CompiledSql,
ctes: Vec<Cte>,
limit: Option<u64>,
offset: Option<u64>,
compile_error: Option<String>,
_out: PhantomData<fn() -> Out>,
}
impl<'db, Out> SetOpQuery<'db, Out> {
pub(crate) fn new<M, M2, I, I2>(
exec: &'db dyn Executor,
op: SetOp,
left: SelectQuery<'db, M, Out, I>,
right: SelectQuery<'db, M2, Out, I2>,
) -> Self
where
M: Model,
M2: Model,
{
let mut compile_error = None;
let left_sql = match left.to_sql_without_cte() {
Ok(c) => c,
Err(e) => {
compile_error = Some(e.to_string());
CompiledSql {
sql: Cow::Borrowed(""),
binds: Vec::new(),
}
}
};
let right_sql = match right.to_sql_without_cte() {
Ok(c) => c,
Err(e) => {
if compile_error.is_none() {
compile_error = Some(e.to_string());
}
CompiledSql {
sql: Cow::Borrowed(""),
binds: Vec::new(),
}
}
};
let mut ctes = left.ctes;
ctes.extend(right.ctes);
Self {
exec,
op,
left: left_sql,
right: right_sql,
ctes,
limit: None,
offset: None,
compile_error,
_out: PhantomData,
}
}
/// Sets the limit on the combined result.
pub fn limit(mut self, n: u64) -> Self {
self.limit = Some(n);
self
}
/// Sets the limit on the combined result only if `n` is `Some`.
pub fn limit_if(mut self, n: Option<u64>) -> Self {
if let Some(n) = n {
self.limit = Some(n);
}
self
}
/// Sets the offset on the combined result.
pub fn offset(mut self, n: u64) -> Self {
self.offset = Some(n);
self
}
/// Sets the offset on the combined result only if `n` is `Some`.
pub fn offset_if(mut self, n: Option<u64>) -> Self {
if let Some(n) = n {
self.offset = Some(n);
}
self
}
/// Compiles the query to SQL and binds.
///
/// # Errors
///
/// Returns [`Error::Message`] if either side could not be compiled, or if
/// the target dialect does not support the set operation (`INTERSECT` or
/// `EXCEPT` on MySQL).
pub fn to_sql(&self) -> Result<CompiledSql, Error> {
if let Some(ref e) = self.compile_error {
return Err(Error::Message(e.clone()));
}
let dialect = self.exec.dialect();
match self.op {
SetOp::Intersect if !dialect.supports_intersect() => {
return Err(Error::Message(format!(
"INTERSECT is not supported by {}",
dialect.name()
)));
}
SetOp::Except if !dialect.supports_except() => {
return Err(Error::Message(format!(
"EXCEPT is not supported by {}",
dialect.name()
)));
}
_ => {}
}
let mut compiled = crate::compile::set_op(
dialect,
self.op,
&self.ctes,
self.left.clone(),
self.right.clone(),
);
if let Some(n) = self.limit {
compiled.sql = Cow::Owned(format!("{} LIMIT {}", compiled.sql, n));
}
if let Some(n) = self.offset {
compiled.sql = Cow::Owned(format!("{} OFFSET {}", compiled.sql, n));
}
query_manifest::record(
compiled.sql.clone().into_owned(),
Some(file!()),
Some(line!()),
dialect.name(),
);
Ok(compiled)
}
}
impl<'db, Out> SetOpQuery<'db, Out>
where
Out: RowDecode,
{
/// Executes the query and returns all matching rows.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn fetch_all(self) -> Result<Vec<Out>, Error>
where
Out: Send + Unpin,
{
let compiled = self.to_sql()?;
#[cfg(feature = "sqlite-rusqlite")]
if let Some(pool) = self.exec.as_rusqlite() {
self.exec.on_query();
return pool
.fetch_all_sync_decoded::<Out>(compiled.sql, compiled.binds)
.await;
}
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)
}
/// Streams matching rows instead of collecting them.
pub fn stream(self) -> Result<RowStream<'db, Out>, Error>
where
Out: Send + Unpin,
{
let compiled = self.to_sql()?;
Ok(RowStream {
inner: self.exec.stream_raw(compiled.sql, compiled.binds),
_out: PhantomData,
})
}
/// Streams matching rows without buffering the whole result set.
pub fn stream_unbuffered(self) -> Result<RowStream<'db, Out>, Error>
where
Out: Send + Unpin,
{
let compiled = self.to_sql()?;
Ok(RowStream {
inner: self
.exec
.stream_unbuffered_raw(compiled.sql, compiled.binds),
_out: PhantomData,
})
}
/// Executes the query and returns the first row, if any.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn fetch_optional(self) -> Result<Option<Out>, Error>
where
Out: Send + Unpin,
{
self.limit(1)
.fetch_all()
.await
.map(|rows| rows.into_iter().next())
}
/// Executes the query and returns exactly one row.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors, including the case where no
/// row matches.
pub async fn fetch_one(self) -> Result<Out, Error>
where
Out: Send + Unpin,
{
self.fetch_optional()
.await?
.ok_or_else(|| Error::Message("no row found for query".into()))
}
}
impl<'db, M, Out> PreparedSelect<'db, M, Out>
where
M: Model,
{
/// Returns the compiled SQL.
pub fn sql(&self) -> &str {
&self.sql
}
/// Returns the current bind values.
pub fn binds(&self) -> &[Value] {
&self.binds
}
/// Sets the bind value at the given position.
pub fn bind(&mut self, index: usize, value: impl Encodable) -> &mut Self {
if index < self.binds.len() {
self.binds[index] = value.to_value();
}
self
}
/// Replaces all bind values.
///
/// The length must match the number of placeholders in the compiled SQL;
/// extra values are ignored and missing values leave the existing binds.
pub fn bind_many(&mut self, binds: Vec<Value>) -> &mut Self {
let n = self.binds.len().min(binds.len());
self.binds[..n].clone_from_slice(&binds[..n]);
if binds.len() > self.binds.len() {
self.binds.extend_from_slice(&binds[self.binds.len()..]);
}
self
}
/// Executes the prepared statement and returns all matching rows.
pub async fn fetch_all(&self) -> Result<Vec<Out>, Error>
where
Out: Send + Unpin + RowDecode,
{
#[cfg(feature = "sqlite-rusqlite")]
if let Some(pool) = self.exec.as_rusqlite() {
self.exec.on_query();
return pool
.fetch_all_sync_decoded::<Out>(self.sql.clone(), self.binds.clone())
.await;
}
let batch = self
.exec
.fetch_all_raw(self.sql.clone(), self.binds.clone())
.await?;
crate::executor::decode_rows(batch)
}
/// Executes the prepared statement and streams matching rows.
pub fn stream(&self) -> RowStream<'db, Out>
where
Out: Send + Unpin + RowDecode,
{
RowStream {
inner: self.exec.stream_raw(self.sql.clone(), self.binds.clone()),
_out: PhantomData,
}
}
/// Executes the prepared statement and streams rows without buffering.
pub fn stream_unbuffered(&self) -> RowStream<'db, Out>
where
Out: Send + Unpin + RowDecode,
{
RowStream {
inner: self
.exec
.stream_unbuffered_raw(self.sql.clone(), self.binds.clone()),
_out: PhantomData,
}
}
/// Executes the prepared statement and returns the first row, if any.
pub async fn fetch_optional(&self) -> Result<Option<Out>, Error>
where
Out: Send + Unpin + RowDecode,
{
let rows = self.fetch_all().await?;
Ok(rows.into_iter().next())
}
/// Executes the prepared statement and returns exactly one row.
pub async fn fetch_one(&self) -> Result<Out, Error>
where
Out: Send + Unpin + RowDecode,
{
self.fetch_optional()
.await?
.ok_or_else(|| Error::Message("no row found for query".into()))
}
}
impl<'db, M, I> SelectQuery<'db, M, M, I>
where
M: Model,
I: IncludeSet<M>,
{
/// Executes the query, then loads any requested includes.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn exec(self) -> Result<Vec<M>, Error> {
let compiled = self.to_sql()?;
#[cfg(feature = "sqlite-rusqlite")]
let mut rows: Vec<M> = if let Some(pool) = self.exec.as_rusqlite() {
self.exec.on_query();
pool.fetch_all_sync_decoded::<M>(compiled.sql, compiled.binds)
.await?
} else {
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)?
};
#[cfg(not(feature = "sqlite-rusqlite"))]
let mut rows: Vec<M> = {
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)?
};
self.includes
.load(self.exec, &mut rows, self.is_full_table())
.await?;
Ok(rows)
}
/// Executes the query, loads any requested includes, and returns the first
/// row if one matches.
///
/// A single-row fetch is never a full-table scan, so the full-table include
/// fast path is disabled for this call.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn exec_optional(mut self) -> Result<Option<M>, Error> {
self.limit = Some(1);
let compiled = self.to_sql()?;
#[cfg(feature = "sqlite-rusqlite")]
let mut rows: Vec<M> = if let Some(pool) = self.exec.as_rusqlite() {
self.exec.on_query();
pool.fetch_all_sync_decoded::<M>(compiled.sql, compiled.binds)
.await?
} else {
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)?
};
#[cfg(not(feature = "sqlite-rusqlite"))]
let mut rows: Vec<M> = {
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)?
};
self.includes.load(self.exec, &mut rows, false).await?;
Ok(rows.into_iter().next())
}
/// Executes the query, loads any requested includes, and returns exactly one
/// row.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors, including the case where no
/// row matches.
pub async fn exec_one(self) -> Result<M, Error> {
self.exec_optional()
.await?
.ok_or_else(|| Error::Message("no row found for query".into()))
}
}
async fn fetch_inserted_row<M: Model>(
exec: &dyn Executor,
dialect: &dyn ruprizzle_dialect::DbDialect,
values: &[(&'static str, Value)],
) -> Result<M, Error> {
let projection = if M::COLUMNS.is_empty() {
"*".to_owned()
} else {
M::COLUMNS
.iter()
.map(|col| dialect.quote_ident(col))
.collect::<Vec<_>>()
.join(", ")
};
let table = dialect.quote_ident(M::TABLE);
let key = dialect.quote_ident(M::PRIMARY_KEY);
let (predicate, binds) =
if let Some((_, value)) = values.iter().find(|(column, _)| *column == M::PRIMARY_KEY) {
(
format!("{key} = {}", dialect.placeholder(0)),
vec![value.clone()],
)
} else if dialect.name() == "mysql" {
(format!("{key} = LAST_INSERT_ID()"), Vec::new())
} else {
return Err(Error::Message(
"inserted row cannot be fetched: primary key was not supplied".into(),
));
};
let sql = format!("SELECT {projection} FROM {table} WHERE {predicate}");
let batch = exec.fetch_all_raw(sql.into(), binds).await?;
crate::executor::decode_rows(batch)?
.into_iter()
.next()
.ok_or_else(|| Error::Message("inserted row was not found after INSERT".into()))
}
/// A typed `INSERT` query.
#[allow(dead_code)]
pub struct InsertQuery<'db, M: Model> {
pool: &'db Pool,
values: Vec<(&'static str, Value)>,
on_conflict: Option<Vec<&'static str>>,
do_update: Option<Vec<&'static str>>,
nested: Option<NestedInsert<'db, M>>,
m2m: Option<Box<dyn AnyM2mWrite<M> + 'db>>,
nested_writes: Vec<Arc<dyn crate::nested::AnyNestedWrite<M>>>,
_marker: PhantomData<fn() -> M>,
}
impl<'db, M: Model> std::fmt::Debug for InsertQuery<'db, M> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InsertQuery")
.field("values", &self.values)
.field("on_conflict", &self.on_conflict)
.field("do_update", &self.do_update)
.field("nested", &self.nested.is_some())
.field("m2m", &self.m2m.is_some())
.field("nested_writes", &self.nested_writes.len())
.finish()
}
}
impl<'db, M: Model> InsertQuery<'db, M> {
/// Returns the underlying pool.
pub fn pool(&self) -> &'db Pool {
self.pool
}
/// Creates a new query.
#[must_use]
pub const fn new(pool: &'db Pool) -> Self {
Self {
pool,
values: Vec::new(),
on_conflict: None,
do_update: None,
nested: None,
m2m: None,
nested_writes: Vec::new(),
_marker: PhantomData,
}
}
/// Sets a column to a value.
pub fn set<V: Encodable>(mut self, col: Column<M, V>, value: impl Into<V>) -> Self {
self.values.push((col.column, value.into().to_value()));
self
}
/// Sets a column only if `value` is `Some`.
pub fn set_optional<V: Encodable>(
self,
col: Column<M, V>,
value: Option<impl Into<V>>,
) -> Self {
match value {
Some(v) => self.set(col, v),
None => self,
}
}
/// Alias for [`set_optional`](InsertQuery::set_optional).
pub fn set_if<V: Encodable>(self, col: Column<M, V>, value: Option<impl Into<V>>) -> Self {
self.set_optional(col, value)
}
/// Sets the conflict target for an upsert.
pub fn on_conflict(mut self, cols: impl IntoIterator<Item = &'static str>) -> Self {
self.on_conflict = Some(cols.into_iter().collect());
self
}
/// Sets which columns to update on conflict (enables `DO UPDATE`).
pub fn do_update(mut self, cols: impl IntoIterator<Item = &'static str>) -> Self {
self.do_update = Some(cols.into_iter().collect());
self
}
/// Attaches a one-level nested create to this insert.
///
/// `get_parent_pk` extracts the parent primary key from the inserted row;
/// `child_fk_col` is the child's foreign-key column; `children` is the set
/// of child rows to insert; and `setter` attaches the returned child rows
/// to the parent model.
pub fn with_related<C: Model>(
mut self,
get_parent_pk: fn(&M) -> Value,
child_fk_col: &'static str,
children: InsertManyQuery<'db, C>,
setter: impl NestedSetter<M> + 'static,
) -> Self {
self.nested = Some(NestedInsert {
get_parent_pk,
child_table: C::TABLE,
child_fk_col,
child_rows: children.rows,
setter: Box::new(setter),
_marker: PhantomData,
});
self
}
/// Attaches a many-to-many nested write to this insert.
///
/// The write runs in the same transaction as the parent insert. The parent
/// is returned with the relation loaded.
pub fn with_m2m<C: Model + Unpin, J: Model>(mut self, m2m: M2mWrite<'db, M, C, J>) -> Self {
self.m2m = Some(Box::new(m2m) as Box<dyn AnyM2mWrite<M> + 'db>);
self
}
/// Attaches an atomic nested relation write (e.g. nested create, connect, set) to this insert.
pub fn with_nested_write<W: crate::nested::AnyNestedWrite<M> + 'static>(
mut self,
write: W,
) -> Self {
self.nested_writes.push(Arc::new(write));
self
}
/// Alias for [`exec`](InsertQuery::exec) to provide an ergonomic builder `.save()` endpoint.
pub async fn save(self) -> Result<M, Error> {
self.exec().await
}
/// Compiles the query to SQL and binds.
pub fn to_sql(&self) -> CompiledSql {
let dialect = dialect_for_pool(self.pool);
let compiled = if let Some(ref conflict) = self.on_conflict {
let do_update = self.do_update.as_deref().unwrap_or(&[]);
upsert::<M>(dialect, M::TABLE, &self.values, conflict, do_update, &[])
} else {
insert::<M>(dialect, M::TABLE, &self.values, &[])
};
query_manifest::record(
compiled.sql.clone().into_owned(),
Some(file!()),
Some(line!()),
dialect.name(),
);
compiled
}
/// Executes the insert and returns the inserted row.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn exec(mut self) -> Result<M, Error> {
let nested = self.nested.take();
let m2m = self.m2m.take();
let nested_writes = std::mem::take(&mut self.nested_writes);
if !nested_writes.is_empty() {
let tx = crate::tx::Tx::begin(self.pool).await?;
let mut parent = self.insert_parent(&tx).await?;
for nw in &nested_writes {
let pk = nw.parent_pk(&parent);
nw.execute(&tx, pk).await?;
}
if let Some(nested) = nested {
let pk_value = (nested.get_parent_pk)(&parent);
Self::insert_nested_child_batch(self.pool, &tx, &mut parent, nested, pk_value)
.await?;
}
if let Some(m2m) = m2m {
m2m.execute_insert(&tx, &mut parent).await?;
}
tx.commit().await?;
return Ok(parent);
}
match (nested, m2m) {
(None, None) => self.exec_single().await,
(Some(nested), None) => self.exec_nested(nested, None).await,
(None, Some(m2m)) => self.exec_m2m(m2m).await,
(Some(nested), Some(m2m)) => self.exec_nested(nested, Some(m2m)).await,
}
}
async fn insert_parent(&self, exec: &dyn Executor) -> Result<M, Error> {
let dialect = exec.dialect();
let returning: &[&str] = if M::COLUMNS.is_empty() {
&["*"]
} else {
M::COLUMNS
};
let compiled = if let Some(ref conflict) = self.on_conflict {
let do_update = self.do_update.as_deref().unwrap_or(&[]);
upsert::<M>(
dialect,
M::TABLE,
&self.values,
conflict,
do_update,
returning,
)
} else {
insert::<M>(dialect, M::TABLE, &self.values, returning)
};
if dialect.returning_supported() {
let batch = exec.fetch_all_raw(compiled.sql, compiled.binds).await?;
let mut rows = crate::executor::decode_rows::<M>(batch)?;
rows.pop()
.ok_or_else(|| Error::Message("INSERT RETURNING returned no row".into()))
} else {
exec.execute_raw(compiled.sql, compiled.binds).await?;
fetch_inserted_row(exec, dialect, &self.values).await
}
}
async fn exec_single(self) -> Result<M, Error> {
self.insert_parent(self.pool).await
}
async fn exec_m2m(self, m2m: Box<dyn AnyM2mWrite<M> + 'db>) -> Result<M, Error> {
let tx = crate::tx::Tx::begin(self.pool).await?;
let mut parent = self.insert_parent(&tx).await?;
m2m.execute_insert(&tx, &mut parent).await?;
tx.commit().await?;
Ok(parent)
}
async fn exec_nested(
self,
nested: NestedInsert<'db, M>,
m2m: Option<Box<dyn AnyM2mWrite<M> + 'db>>,
) -> Result<M, Error> {
let tx = crate::tx::Tx::begin(self.pool).await?;
let mut parent = self.insert_parent(&tx).await?;
let pk_value = (nested.get_parent_pk)(&parent);
Self::insert_nested_child_batch(self.pool, &tx, &mut parent, nested, pk_value).await?;
if let Some(m2m) = m2m {
m2m.execute_insert(&tx, &mut parent).await?;
}
tx.commit().await?;
Ok(parent)
}
async fn insert_nested_child_batch(
pool: &'db Pool,
tx: &crate::tx::Tx,
parent: &mut M,
nested: NestedInsert<'db, M>,
pk_value: Value,
) -> Result<(), Error> {
let dialect = dialect_for_pool(pool);
if !nested.child_rows.is_empty() {
let rows: Vec<Vec<(&'static str, Value)>> = nested.child_rows;
if rows.iter().any(|r| r.is_empty()) {
return Err(Error::Message("insert row has no columns".into()));
}
validate_row_shape(&rows)?;
let mut rows = rows;
for row in &mut rows {
row.push((nested.child_fk_col, pk_value.clone()));
}
let max = dialect.capabilities().max_query_params;
let cols_per_row = rows.first().map(|r| r.len()).unwrap_or(0) as u32;
let chunk_size = (max / cols_per_row.max(1)).max(1) as usize;
let mut child_rows: Option<crate::executor::RowBatch> = None;
for chunk in rows.chunks(chunk_size) {
let returning: &[&str] = if M::COLUMNS.is_empty() {
&["*"]
} else {
M::COLUMNS
};
let compiled = insert_many::<M>(dialect, nested.child_table, chunk, returning);
if dialect.returning_supported() {
let chunk = tx.fetch_all_raw(compiled.sql, compiled.binds).await?;
match child_rows.as_mut() {
Some(acc) => acc.merge(chunk)?,
None => child_rows = Some(chunk),
}
} else {
tx.execute_raw(compiled.sql, compiled.binds).await?;
}
}
if !dialect.returning_supported() {
let sql = format!(
"SELECT * FROM {} WHERE {} = {}",
dialect.quote_ident(nested.child_table),
dialect.quote_ident(nested.child_fk_col),
dialect.placeholder(0)
);
child_rows = Some(tx.fetch_all_raw(sql.into(), vec![pk_value.clone()]).await?);
}
nested.setter.set(
parent,
child_rows.unwrap_or(crate::executor::RowBatch::Any(Vec::new())),
);
} else {
nested
.setter
.set(parent, crate::executor::RowBatch::Any(Vec::new()));
}
Ok(())
}
}
/// Trait for attaching nested child rows to a freshly inserted parent.
///
/// Generated code provides one implementation per relation.
pub trait NestedSetter<M: Model> {
/// Attaches the loaded child rows to the parent model.
fn set(&self, parent: &mut M, batch: crate::executor::RowBatch);
}
/// Specification for a one-level nested create.
struct NestedInsert<'db, M: Model> {
get_parent_pk: fn(&M) -> Value,
child_table: &'static str,
child_fk_col: &'static str,
child_rows: Vec<Vec<(&'static str, Value)>>,
setter: Box<dyn NestedSetter<M>>,
_marker: PhantomData<&'db ()>,
}
impl<'db, M: Model> std::fmt::Debug for NestedInsert<'db, M> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NestedInsert")
.field("child_table", &self.child_table)
.field("child_fk_col", &self.child_fk_col)
.field("child_rows", &self.child_rows)
.finish()
}
}
/// A typed multi-row `INSERT` query.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct InsertManyQuery<'db, M: Model> {
pool: &'db Pool,
pub(crate) rows: Vec<Vec<(&'static str, Value)>>,
_marker: PhantomData<fn() -> M>,
}
impl<'db, M: Model> InsertManyQuery<'db, M> {
/// Creates a new query.
#[must_use]
pub const fn new(pool: &'db Pool) -> Self {
Self {
pool,
rows: Vec::new(),
_marker: PhantomData,
}
}
/// Adds a row to insert.
pub fn row(mut self, columns: impl IntoIterator<Item = (&'static str, Value)>) -> Self {
self.rows.push(columns.into_iter().collect());
self
}
/// Adds multiple rows to insert.
pub fn rows(
mut self,
rows: impl IntoIterator<Item = impl IntoIterator<Item = (&'static str, Value)>>,
) -> Self {
for r in rows {
self.rows.push(r.into_iter().collect());
}
self
}
/// Executes the insert, returning all inserted rows.
///
/// The rows are chunked to stay under the database's parameter limit.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn exec(self) -> Result<Vec<M>, Error> {
if self.rows.is_empty() {
return Ok(Vec::new());
}
if self.rows.iter().any(|r| r.is_empty()) {
return Err(Error::Message("insert row has no columns".into()));
}
validate_row_shape(&self.rows)?;
let dialect = dialect_for_pool(self.pool);
let max = dialect.capabilities().max_query_params;
let cols_per_row = self.rows.first().map(|r| r.len()).unwrap_or(0) as u32;
let chunk_size = (max / cols_per_row.max(1)).max(1) as usize;
let returning: &[&str] = if M::COLUMNS.is_empty() {
&["*"]
} else {
M::COLUMNS
};
if !dialect.returning_supported() {
return self
.exec_without_returning(dialect, chunk_size, returning)
.await;
}
let mut out = Vec::new();
for chunk in self.rows.chunks(chunk_size) {
let compiled = insert_many::<M>(dialect, M::TABLE, chunk, returning);
let batch = self
.pool
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
let mut rows = crate::executor::decode_rows::<M>(batch)?;
out.append(&mut rows);
}
Ok(out)
}
/// `exec` for dialects without `RETURNING` (MySQL): insert, then read the
/// rows back in the same transaction.
///
/// Rows are selected by the supplied primary keys, or, when the key is
/// generated, by the `LAST_INSERT_ID()` block of the statement. InnoDB
/// assigns consecutive ids to a single multi-row insert with a known row
/// count in every `innodb_autoinc_lock_mode`. Both lookups need the same
/// connection as the insert, hence the transaction. Rows are returned in
/// primary-key order within each chunk.
///
/// A generated key that is not `AUTO_INCREMENT` (e.g. a `UUID()` default)
/// leaves `LAST_INSERT_ID()` stale; the row-count check turns that into an
/// error instead of returning unrelated rows.
async fn exec_without_returning(
self,
dialect: &dyn ruprizzle_dialect::DbDialect,
chunk_size: usize,
returning: &[&str],
) -> Result<Vec<M>, Error> {
let projection = returning
.iter()
.map(|col| {
if *col == "*" {
"*".to_owned()
} else {
dialect.quote_ident(col)
}
})
.collect::<Vec<_>>()
.join(", ");
let table = dialect.quote_ident(M::TABLE);
let key = dialect.quote_ident(M::PRIMARY_KEY);
let tx = crate::tx::Tx::begin(self.pool).await?;
let mut out = Vec::new();
for chunk in self.rows.chunks(chunk_size) {
let compiled = insert_many::<M>(dialect, M::TABLE, chunk, returning);
tx.execute_raw(compiled.sql, compiled.binds).await?;
let keys: Option<Vec<Value>> = chunk
.iter()
.map(|row| {
row.iter()
.find(|(column, _)| *column == M::PRIMARY_KEY)
.map(|(_, value)| value.clone())
})
.collect();
let (sql, binds) = if let Some(keys) = keys {
let placeholders = (0..keys.len())
.map(|i| dialect.placeholder(i))
.collect::<Vec<_>>()
.join(", ");
(
format!(
"SELECT {projection} FROM {table} WHERE {key} IN ({placeholders}) ORDER BY {key}"
),
keys,
)
} else if dialect.name() == "mysql" {
(
format!(
"SELECT {projection} FROM {table} WHERE {key} BETWEEN LAST_INSERT_ID() AND LAST_INSERT_ID() + {} ORDER BY {key}",
chunk.len() - 1
),
Vec::new(),
)
} else {
return Err(Error::Message(
"inserted rows cannot be fetched: primary key was not supplied".into(),
));
};
let batch = tx.fetch_all_raw(sql.into(), binds).await?;
let mut rows = crate::executor::decode_rows::<M>(batch)?;
if rows.len() != chunk.len() {
return Err(Error::Message(format!(
"inserted {} rows but read back {}; supply primary keys for tables whose key is not AUTO_INCREMENT",
chunk.len(),
rows.len()
)));
}
out.append(&mut rows);
}
tx.commit().await?;
Ok(out)
}
}
fn validate_row_shape(rows: &[Vec<(&'static str, Value)>]) -> Result<(), Error> {
let Some(first) = rows.first() else {
return Ok(());
};
if rows.len() < 2 {
return Ok(());
}
for (idx, row) in rows.iter().enumerate().skip(1) {
if row.len() != first.len() {
return Err(Error::Message(format!(
"insert row {idx} has {} columns, expected {} from row 0",
row.len(),
first.len()
)));
}
for (col_idx, (a, b)) in first.iter().zip(row.iter()).enumerate() {
if a.0 != b.0 {
return Err(Error::Message(format!(
"insert row {idx} column {col_idx} differs from row 0: expected '{}', found '{}'",
a.0, b.0
)));
}
}
}
Ok(())
}
/// A typed `UPDATE` query.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct UpdateQuery<'db, M: Model> {
pool: &'db Pool,
sets: Vec<SetExpr>,
filter: Filter<M>,
all_rows: bool,
m2m: Option<Arc<dyn AnyM2mWrite<M> + 'db>>,
rel: Vec<Arc<dyn AnyRelWrite<M>>>,
nested_writes: Vec<Arc<dyn crate::nested::AnyNestedWrite<M>>>,
_marker: PhantomData<fn() -> M>,
}
impl<'db, M: Model> UpdateQuery<'db, M> {
/// Creates a new query.
#[must_use]
pub const fn new(pool: &'db Pool) -> Self {
Self {
pool,
sets: Vec::new(),
filter: Filter::new(FilterNode::And(Vec::new())),
all_rows: false,
m2m: None,
rel: Vec::new(),
nested_writes: Vec::new(),
_marker: PhantomData,
}
}
/// Adds a filter.
pub fn filter(self, f: Filter<M>) -> Self {
Self {
filter: self.filter.and(f),
..self
}
}
/// Adds a filter only if `f` is `Some`.
///
/// If `f` is `None` the query is marked as `.all_rows()` so it can still be
/// executed. This is the conditional-building equivalent of "filter, or
/// update every row".
pub fn filter_if(mut self, f: Option<Filter<M>>) -> Self {
match f {
Some(f) => self.filter(f),
None => {
self.all_rows = true;
self
}
}
}
/// Sets an explicit value.
pub fn set<V: Encodable>(mut self, col: Column<M, V>, value: impl Into<V>) -> Self {
self.sets.push(SetExpr::Column {
column: col.column,
value: value.into().to_value(),
});
self
}
/// Sets a column to `NULL`.
pub fn set_null<V: Encodable>(mut self, col: Column<M, V>) -> Self {
self.sets.push(SetExpr::Column {
column: col.column,
value: Value::Null,
});
self
}
/// Applies a JSON set expression.
pub fn json_set(mut self, set: JsonSet) -> Self {
self.sets.push(SetExpr::JsonSet {
column: set.column,
path: set.path,
value: set.value,
});
self
}
/// Convenience: set a single key inside a JSON column.
pub fn jsonb_set(
self,
col: Column<M, serde_json::Value>,
key: &'static str,
value: serde_json::Value,
) -> Self {
self.json_set(col.json_set(key, value))
}
/// Sets a column only if `value` is `Some`.
pub fn set_if<V: Encodable>(self, col: Column<M, V>, value: Option<impl Into<V>>) -> Self {
match value {
Some(value) => self.set(col, value),
None => self,
}
}
/// Applies a JSON set expression only if `set` is `Some`.
pub fn json_set_if(self, set: Option<JsonSet>) -> Self {
match set {
Some(set) => self.json_set(set),
None => self,
}
}
/// Convenience: set a single key inside a JSON column only if `value` is `Some`.
pub fn jsonb_set_if(
self,
col: Column<M, serde_json::Value>,
key: &'static str,
value: Option<serde_json::Value>,
) -> Self {
match value {
Some(value) => self.jsonb_set(col, key, value),
None => self,
}
}
/// Allows updating all rows. Without this, `exec` returns an error if no
/// filter was supplied.
pub fn all_rows(mut self) -> Self {
self.all_rows = true;
self
}
/// Sets the model's soft-delete column (`@deletedAt`) to the current UTC time.
///
/// The time is taken from the application's clock (`Utc::now()`), not the
/// database's, and is bound as a timestamp, the same way as any other
/// `DateTime` field.
///
/// # Errors
/// Returns an error if the model does not have a `@deletedAt` column configured.
pub fn soft_delete(self) -> Result<Self, Error> {
let col = M::DELETED_AT_COLUMN.ok_or_else(|| {
Error::Message(format!(
"Model '{}' does not have a @deletedAt column configured",
M::TABLE
))
})?;
// Bound as `Value::DateTime`, not as RFC 3339 text: Postgres types a text
// parameter as `text` and refuses to assign it to a `timestamptz` column.
Ok(self.set(
Column::<M, chrono::DateTime<chrono::Utc>>::new(M::TABLE, col),
chrono::Utc::now(),
))
}
/// Attaches a many-to-many nested write to this update.
///
/// The write runs in the same transaction as the parent update.
pub fn with_m2m<C: Model + Unpin, J: Model>(mut self, m2m: M2mWrite<'db, M, C, J>) -> Self {
self.m2m = Some(Arc::new(m2m) as Arc<dyn AnyM2mWrite<M> + 'db>);
self
}
/// Attaches a one-to-many nested write to this update.
///
/// This is the low-level building block; use [`connect`](UpdateQuery::connect),
/// [`disconnect`](UpdateQuery::disconnect), or [`set_related`](UpdateQuery::set_related) for
/// the common cases.
pub fn with_related<C: Model>(mut self, write: RelWrite<M, C>) -> Self {
self.rel.push(Arc::new(write) as Arc<dyn AnyRelWrite<M>>);
self
}
/// Connects existing child rows to the parent updated by this query.
///
/// `get_parent_pk` extracts the parent primary key from the updated row;
/// `child_fk_col` is the child's foreign-key column; `child_pk_col` is the
/// child's primary-key column; and `pks` are the primary keys of the child
/// rows to connect. The query must match exactly one parent row.
pub fn connect<C: Model, P: IntoIterator<Item = V>, V: Encodable>(
self,
get_parent_pk: fn(&M) -> Value,
child_fk_col: &'static str,
child_pk_col: &'static str,
pks: P,
) -> Self {
let pks = pks.into_iter().map(|v| v.to_value()).collect();
self.with_related(RelWrite::<M, C>::new(
RelAction::Connect,
child_fk_col,
child_pk_col,
pks,
get_parent_pk,
))
}
/// Disconnects the given child rows from the parent updated by this query.
pub fn disconnect<C: Model, P: IntoIterator<Item = V>, V: Encodable>(
self,
get_parent_pk: fn(&M) -> Value,
child_fk_col: &'static str,
child_pk_col: &'static str,
pks: P,
) -> Self {
let pks = pks.into_iter().map(|v| v.to_value()).collect();
self.with_related(RelWrite::<M, C>::new(
RelAction::Disconnect,
child_fk_col,
child_pk_col,
pks,
get_parent_pk,
))
}
/// Replaces the parent's connected child rows with the given set.
pub fn set_related<C: Model, P: IntoIterator<Item = V>, V: Encodable>(
self,
get_parent_pk: fn(&M) -> Value,
child_fk_col: &'static str,
child_pk_col: &'static str,
pks: P,
) -> Self {
let pks = pks.into_iter().map(|v| v.to_value()).collect();
self.with_related(RelWrite::<M, C>::new(
RelAction::Set,
child_fk_col,
child_pk_col,
pks,
get_parent_pk,
))
}
/// Attaches an atomic nested relation write to this update.
pub fn with_nested_write<W: crate::nested::AnyNestedWrite<M> + 'static>(
mut self,
write: W,
) -> Self {
self.nested_writes.push(Arc::new(write));
self
}
/// Sets the filter condition using `.where(...)`.
pub fn r#where(self, f: Filter<M>) -> Self {
self.filter(f)
}
/// Alias for [`where`](UpdateQuery::where).
pub fn where_clause(self, f: Filter<M>) -> Self {
self.filter(f)
}
/// Alias for [`exec`](UpdateQuery::exec) to provide an ergonomic builder `.save()` endpoint.
pub async fn save(self) -> Result<u64, Error> {
self.exec().await
}
/// Compiles the query to SQL and binds.
pub fn to_sql(&self) -> Result<CompiledSql, Error> {
if !self.all_rows && matches!(self.filter.node, FilterNode::And(ref v) if v.is_empty()) {
return Err(Error::Message(
"update has no filter; call .all_rows() to update every row".into(),
));
}
if self.sets.is_empty() {
return Err(Error::Message("update has no columns to set".into()));
}
let dialect = dialect_for_pool(self.pool);
let compiled = update_with_sets(dialect, M::TABLE, &self.sets, &self.filter.node, &[]);
query_manifest::record(
compiled.sql.clone().into_owned(),
Some(file!()),
Some(line!()),
dialect.name(),
);
Ok(compiled)
}
/// Executes the update and returns the number of rows affected.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn exec(self) -> Result<u64, Error> {
let has_nested =
self.m2m.is_some() || !self.rel.is_empty() || !self.nested_writes.is_empty();
if !has_nested {
let compiled = self.to_sql()?;
return self.pool.execute_raw(compiled.sql, compiled.binds).await;
}
if !self.all_rows && matches!(self.filter.node, FilterNode::And(ref v) if v.is_empty()) {
return Err(Error::Message(
"nested update has no filter; call .all_rows() to target every row".into(),
));
}
let tx = crate::tx::Tx::begin(self.pool).await?;
let mut total = 0u64;
if !self.sets.is_empty() {
let compiled = self.to_sql()?;
total += tx.execute_raw(compiled.sql, compiled.binds).await?;
}
let parents = self.fetch_parents(&tx).await?;
if (!self.rel.is_empty() || !self.nested_writes.is_empty()) && parents.len() != 1 {
return Err(Error::Message(
"nested writes require exactly one parent row".into(),
));
}
if let Some(first_parent) = parents.first() {
for rel in &self.rel {
let parent_pk = rel.parent_pk(first_parent);
total += rel.execute_update(&tx, parent_pk).await?;
}
for nw in &self.nested_writes {
let parent_pk = nw.parent_pk(first_parent);
nw.execute(&tx, parent_pk).await?;
total += 1;
}
}
if let Some(ref m2m) = self.m2m {
for parent in &parents {
let pk = m2m.parent_pk(parent);
total += m2m.execute_update(&tx, pk).await?;
}
}
tx.commit().await?;
Ok(total)
}
async fn fetch_parents(&self, exec: &dyn Executor) -> Result<Vec<M>, Error> {
let dialect = exec.dialect();
let compiled = select::<M>(
dialect,
M::TABLE,
M::COLUMNS,
&self.filter.node,
&[],
None,
None,
false,
);
let batch = exec.fetch_all_raw(compiled.sql, compiled.binds).await?;
crate::executor::decode_rows::<M>(batch)
}
}
/// Marker for a `DeleteQuery` that has not yet received a filter or
/// `.all_rows()` call.
pub struct UnfilteredDelete;
/// Marker for a `DeleteQuery` that is safe to execute.
pub struct FilteredDelete;
/// A typed `DELETE` query.
///
/// `exec` is only available when `S = FilteredDelete`, which is reached by
/// calling `.filter(...)` or `.all_rows()`.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct DeleteQuery<'db, M: Model, S = UnfilteredDelete> {
pool: &'db Pool,
filter: Filter<M>,
all_rows: bool,
cascade: Vec<Arc<dyn AnyRelDelete<M>>>,
_state: PhantomData<fn() -> S>,
_marker: PhantomData<fn() -> M>,
}
impl<'db, M: Model> DeleteQuery<'db, M, UnfilteredDelete> {
/// Creates a new unfiltered delete query.
#[must_use]
pub const fn new(pool: &'db Pool) -> Self {
Self {
pool,
filter: Filter::new(FilterNode::And(Vec::new())),
all_rows: false,
cascade: Vec::new(),
_state: PhantomData,
_marker: PhantomData,
}
}
/// Adds a filter.
pub fn filter(self, f: Filter<M>) -> DeleteQuery<'db, M, FilteredDelete> {
DeleteQuery {
pool: self.pool,
filter: self.filter.and(f),
all_rows: false,
cascade: self.cascade,
_state: PhantomData,
_marker: PhantomData,
}
}
/// Adds a filter only if `f` is `Some`, otherwise deletes all rows.
pub fn filter_if(self, f: Option<Filter<M>>) -> DeleteQuery<'db, M, FilteredDelete> {
match f {
Some(f) => self.filter(f),
None => self.all_rows(),
}
}
/// Allows deleting all rows.
pub fn all_rows(self) -> DeleteQuery<'db, M, FilteredDelete> {
DeleteQuery {
pool: self.pool,
filter: self.filter,
all_rows: true,
cascade: self.cascade,
_state: PhantomData,
_marker: PhantomData,
}
}
/// Cascades this delete to child rows according to the given referential
/// action.
///
/// `child_fk_col` is the child's foreign-key column that references this
/// model's primary key. This must match the `onDelete` declared in the
/// schema for the relation.
pub fn cascade<C: Model>(mut self, child_fk_col: &'static str, action: DeleteAction) -> Self {
self.cascade
.push(Arc::new(DeleteCascade::<C>::new(child_fk_col, action)));
self
}
}
impl<'db, M: Model> DeleteQuery<'db, M, FilteredDelete> {
/// Adds an additional filter.
pub fn filter(self, f: Filter<M>) -> Self {
Self {
filter: self.filter.and(f),
..self
}
}
/// Adds an additional filter only if `f` is `Some`.
pub fn filter_if(self, f: Option<Filter<M>>) -> Self {
match f {
Some(f) => self.filter(f),
None => self,
}
}
/// Cascades this delete to child rows according to the given referential
/// action.
pub fn cascade<C: Model>(mut self, child_fk_col: &'static str, action: DeleteAction) -> Self {
self.cascade
.push(Arc::new(DeleteCascade::<C>::new(child_fk_col, action)));
self
}
/// Compiles the query to SQL and binds.
pub fn to_sql(&self) -> Result<CompiledSql, Error> {
if !self.all_rows && matches!(self.filter.node, FilterNode::And(ref v) if v.is_empty()) {
return Err(Error::Message(
"delete has no filter; call .all_rows() to delete every row".into(),
));
}
let dialect = dialect_for_pool(self.pool);
let compiled = delete::<M>(dialect, M::TABLE, &self.filter.node, &[]);
query_manifest::record(
compiled.sql.clone().into_owned(),
Some(file!()),
Some(line!()),
dialect.name(),
);
Ok(compiled)
}
/// Executes the delete and returns the number of rows removed.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn exec(self) -> Result<u64, Error> {
let compiled = self.to_sql()?;
if self.cascade.is_empty() {
return self.pool.execute_raw(compiled.sql, compiled.binds).await;
}
let tx = crate::tx::Tx::begin(self.pool).await?;
let parent_subquery = self.parent_subquery()?;
let mut total = 0u64;
for cascade in &self.cascade {
total += cascade.execute_delete(&tx, parent_subquery.clone()).await?;
}
total += tx.execute_raw(compiled.sql, compiled.binds).await?;
tx.commit().await?;
Ok(total)
}
fn parent_subquery(&self) -> Result<CompiledSql, Error> {
let pk_col = Column::<M, Value>::new(M::TABLE, M::PRIMARY_KEY);
SelectQuery::<M>::new(self.pool)
.filter(self.filter.clone())
.columns(pk_col)
.to_sql()
}
}
/// A grouped `SELECT` query, created by [`SelectQuery::group_by`].
///
/// Add `HAVING` filters with [`having`](GroupedQuery::having), then call
/// [`aggregate`](GroupedQuery::aggregate) to produce the final result set.
#[derive(Clone)]
#[allow(dead_code)]
pub struct GroupedQuery<'db, M: Model, Out = M, I = ()> {
inner: SelectQuery<'db, M, Out, I>,
group_by: Vec<&'static str>,
having: Filter<M>,
_marker: PhantomData<fn() -> M>,
}
impl<'db, M, Out, I> GroupedQuery<'db, M, Out, I>
where
M: Model,
{
/// Adds a `HAVING` filter (`AND`).
///
/// `HAVING` is applied after grouping; the filter is the same `Filter<M>`
/// used for `WHERE`, so group columns can be referenced directly.
pub fn having(self, f: Filter<M>) -> Self {
Self {
having: self.having.and(f),
..self
}
}
/// Adds an additional `HAVING` filter (`OR`).
pub fn or_having(self, f: Filter<M>) -> Self {
Self {
having: self.having.or(f),
..self
}
}
/// Adds a `HAVING` filter (`AND`) only if `f` is `Some`.
pub fn having_if(self, f: Option<Filter<M>>) -> Self {
match f {
Some(f) => self.having(f),
None => self,
}
}
/// Adds a `HAVING` filter (`OR`) only if `f` is `Some`.
pub fn or_having_if(self, f: Option<Filter<M>>) -> Self {
match f {
Some(f) => self.or_having(f),
None => self,
}
}
/// Switches the grouped query to return aggregate results.
#[must_use]
pub fn aggregate<R, A>(self, set: A) -> AggregateQuery<'db, M, R>
where
R: RowDecode,
A: AggregateSet<M, R>,
{
let mut entries = Vec::new();
set.push_entries(&mut entries);
AggregateQuery {
exec: self.inner.exec,
filter: self.inner.filter,
aggregates: entries,
group_by: self.group_by,
having: self.having,
order: self.inner.order,
limit: self.inner.limit,
offset: self.inner.offset,
ctes: self.inner.ctes,
_out: PhantomData,
}
}
}
/// A `SELECT` query whose projection is a set of aggregate expressions.
///
/// The output type `R` is a Rust tuple such as `(Option<i64>, i64)`, one element
/// per aggregate expression. Generated per-model structs for named fields are
/// added in Step 4.
#[derive(Clone)]
#[allow(dead_code)]
pub struct AggregateQuery<'db, M: Model, R: RowDecode> {
exec: &'db dyn Executor,
filter: Filter<M>,
aggregates: Vec<AggregateEntry>,
group_by: Vec<&'static str>,
having: Filter<M>,
order: Vec<OrderBy<M>>,
limit: Option<u64>,
offset: Option<u64>,
ctes: Vec<Cte>,
_out: PhantomData<fn() -> R>,
}
impl<'db, M, R> AggregateQuery<'db, M, R>
where
M: Model,
R: RowDecode,
{
/// Adds a `WHERE` filter (`AND`).
pub fn filter(self, f: Filter<M>) -> Self {
Self {
filter: self.filter.and(f),
..self
}
}
/// Adds a `WHERE` filter (`OR`).
pub fn or_filter(self, f: Filter<M>) -> Self {
Self {
filter: self.filter.or(f),
..self
}
}
/// Adds a `WHERE` filter (`AND`) only if `f` is `Some`.
pub fn filter_if(self, f: Option<Filter<M>>) -> Self {
match f {
Some(f) => self.filter(f),
None => self,
}
}
/// Adds a `WHERE` filter (`OR`) only if `f` is `Some`.
pub fn or_filter_if(self, f: Option<Filter<M>>) -> Self {
match f {
Some(f) => self.or_filter(f),
None => self,
}
}
/// Adds a `HAVING` filter (`AND`).
pub fn having(self, f: Filter<M>) -> Self {
Self {
having: self.having.and(f),
..self
}
}
/// Adds a `HAVING` filter (`OR`).
pub fn or_having(self, f: Filter<M>) -> Self {
Self {
having: self.having.or(f),
..self
}
}
/// Adds a `HAVING` filter (`AND`) only if `f` is `Some`.
pub fn having_if(self, f: Option<Filter<M>>) -> Self {
match f {
Some(f) => self.having(f),
None => self,
}
}
/// Adds a `HAVING` filter (`OR`) only if `f` is `Some`.
pub fn or_having_if(self, f: Option<Filter<M>>) -> Self {
match f {
Some(f) => self.or_having(f),
None => self,
}
}
/// Adds an ordering.
pub fn order_by(self, o: OrderBy<M>) -> Self {
let mut order = self.order;
order.push(o);
Self { order, ..self }
}
/// Adds an ordering only if `o` is `Some`.
pub fn order_by_if(self, o: Option<OrderBy<M>>) -> Self {
match o {
Some(o) => self.order_by(o),
None => self,
}
}
/// Sets the limit.
pub fn limit(self, n: u64) -> Self {
Self {
limit: Some(n),
..self
}
}
/// Sets the limit only if `n` is `Some`.
pub fn limit_if(self, n: Option<u64>) -> Self {
match n {
Some(n) => self.limit(n),
None => self,
}
}
/// Sets the offset.
pub fn offset(self, n: u64) -> Self {
Self {
offset: Some(n),
..self
}
}
/// Sets the offset only if `n` is `Some`.
pub fn offset_if(self, n: Option<u64>) -> Self {
match n {
Some(n) => self.offset(n),
None => self,
}
}
/// Compiles the query to SQL and binds.
pub fn to_sql(&self) -> CompiledSql {
let dialect = self.exec.dialect();
let main = crate::compile::aggregate_select::<M>(
dialect,
M::TABLE,
&self.aggregates,
&self.filter.node,
&self.group_by,
&self.having.node,
&self.order,
self.limit,
self.offset,
);
let compiled = crate::compile::with_cte_prefix(dialect, &self.ctes, main);
query_manifest::record(
compiled.sql.clone().into_owned(),
Some(file!()),
Some(line!()),
dialect.name(),
);
compiled
}
/// Executes the query and returns all matching aggregate rows.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn fetch_all(self) -> Result<Vec<R>, Error>
where
R: Send + Unpin,
{
let compiled = self.to_sql();
#[cfg(feature = "sqlite-rusqlite")]
if let Some(pool) = self.exec.as_rusqlite() {
self.exec.on_query();
return pool
.fetch_all_sync_decoded::<R>(compiled.sql, compiled.binds)
.await;
}
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)
}
/// Executes the query and returns the first aggregate row, if any.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors.
pub async fn fetch_optional(mut self) -> Result<Option<R>, Error>
where
R: Send + Unpin,
{
self.limit = Some(1);
let compiled = self.to_sql();
#[cfg(feature = "sqlite-rusqlite")]
let v: Vec<R> = if let Some(pool) = self.exec.as_rusqlite() {
self.exec.on_query();
pool.fetch_all_sync_decoded::<R>(compiled.sql, compiled.binds)
.await?
} else {
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)?
};
#[cfg(not(feature = "sqlite-rusqlite"))]
let v: Vec<R> = {
let batch = self
.exec
.fetch_all_raw(compiled.sql, compiled.binds)
.await?;
crate::executor::decode_rows(batch)?
};
Ok(v.into_iter().next())
}
/// Executes the query and returns exactly one aggregate row.
///
/// # Errors
///
/// Returns [`Error::Sqlx`] for database errors, including the case where no
/// row matches.
pub async fn fetch_one(self) -> Result<R, Error>
where
R: Send + Unpin,
{
self.fetch_optional()
.await?
.ok_or_else(|| Error::Message("no row found for aggregate query".into()))
}
}