fraiseql-db 2.17.1

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

use std::{fmt::Write as _, sync::Arc};

use async_trait::async_trait;
use bytes::BufMut as _;
use fraiseql_error::{FraiseQLError, Result};
use tokio_postgres::{
    Row,
    types::{FromSql, Kind, Type},
};

use super::{
    PostgresAdapter, build_projection_select_sql, build_where_select_sql,
    build_where_select_sql_ordered, composed::build_composed_select_sql, jsonb_cell,
    numeric::PgNumericText,
};
use crate::{
    identifier::quote_postgres_identifier,
    postgres::pg_detail,
    traits::{
        ColumnRowStream, ComposedLevel, DatabaseAdapter, JsonbRowStream, ProjectionRequest, Writer,
    },
    types::{
        DatabaseType, JsonbValue, PoolMetrics, ReadRouting,
        sql_hints::{OrderByClause, SqlProjectionHint},
    },
    where_clause::WhereClause,
};

/// One row a write function returned, by column.
type RowMap = std::collections::HashMap<String, serde_json::Value>;

/// One call of a write function, ready to send: its statement, its arguments, and the
/// configuration it runs under.
struct PreparedCall<'r> {
    function_name:  &'r str,
    sql:            String,
    args:           Vec<FlexParam>,
    configuration:  Vec<(&'r str, &'r str)>,
    /// Names the outbox in an error message when the outbox is what ran. The messages are
    /// the strings the error sanitizer's corpus is reduced from, and an operator reading a
    /// failed write wants to know whether the CTE was in it.
    mechanism:      &'static str,
    derived:        Option<&'r crate::traits::DerivedCascade<'r>>,
    /// Report the rows the call changed, at most this many, in the call's own flight
    /// (#1576). Never with `derived`, whose report already says.
    report_changes: Option<i32>,
}

impl<'r> PreparedCall<'r> {
    fn new(adapter: &'r PostgresAdapter, request: &crate::traits::WriteRequest<'r>) -> Self {
        let crate::traits::WriteRequest {
            function: function_name,
            args,
            session_vars,
            changelog,
            derived_cascade,
            report_changes,
            ..
        } = *request;
        let quoted_fn = quote_postgres_identifier(function_name);

        // One statement when there is an outbox row: run the function once and INSERT
        // its outbox row in the same txn, atomically, with no extra connection acquire
        // (Change Spine). Otherwise the plain call.
        let sql = if let Some(cl) = changelog {
            build_changelog_cte_sql(&quoted_fn, args.len(), cl.pre_image)
        } else {
            let placeholders: Vec<String> = (1..=args.len()).map(|i| format!("${i}")).collect();
            format!("SELECT * FROM {quoted_fn}({})", placeholders.join(", "))
        };

        // Arguments bind as FlexParam: serde_json::Value only accepts JSON/JSONB types, and
        // Option<String> only text-family types, and a function signature can mix any of
        // them. FlexParam accepts every PostgreSQL type and sends each value in the format of
        // the server-resolved parameter type: binary for six, text for the rest (#1547).
        let mut flex_args: Vec<FlexParam> = args
            .iter()
            .map(|v| match v {
                serde_json::Value::Null => FlexParam::Null,
                value => FlexParam::Value(value.clone()),
            })
            .collect();
        if let Some(changelog) = changelog {
            // Function args first; then the threaded change-log envelope params —
            // object_type fallback ($n+1), modification_type verb ($n+2), the
            // tenant_id stamp ($n+3, bound against `::uuid`), the trace_id
            // ($n+4, plain text), the schema_version ($n+5, plain text), the
            // trace_context ($n+6, bound against `::jsonb`), the actor_type ($n+7,
            // plain text), the acting_for ($n+8, bound against `::uuid`) and the
            // transport ($n+9, plain text merged into extra_metadata — #376). Order
            // matches build_changelog_cte_sql's positional contract; appending the
            // envelope params keeps the SQL text stable for prepare_cached.
            flex_args.push(FlexParam::Text(changelog.object_type.to_string()));
            flex_args.push(FlexParam::Text(changelog.modification_type.to_string()));
            // tenant_id: bound as text and serialised by FlexParam's UUID branch
            // (the `::uuid` cast pins the param type); None → SQL NULL.
            flex_args.push(
                changelog.tenant_id.map_or(FlexParam::Null, |t| FlexParam::Text(t.to_string())),
            );
            // trace_id ($n+4): plain text, None → SQL NULL.
            flex_args.push(
                changelog.trace_id.map_or(FlexParam::Null, |t| FlexParam::Text(t.to_string())),
            );
            // schema_version ($n+5): plain text, None → SQL NULL.
            flex_args.push(
                changelog
                    .schema_version
                    .map_or(FlexParam::Null, |s| FlexParam::Text(s.to_string())),
            );
            // trace_context ($n+6): JSON text bound against `::jsonb`, None → SQL NULL.
            flex_args.push(
                changelog
                    .trace_context
                    .map_or(FlexParam::Null, |s| FlexParam::Text(s.to_string())),
            );
            // actor_type ($n+7): plain text, None → SQL NULL.
            flex_args.push(
                changelog.actor_type.map_or(FlexParam::Null, |s| FlexParam::Text(s.to_string())),
            );
            // acting_for ($n+8): bound as text + serialised by FlexParam's UUID branch
            // (the `::uuid` cast pins the param type); None → SQL NULL.
            flex_args.push(
                changelog.acting_for.map_or(FlexParam::Null, |u| FlexParam::Text(u.to_string())),
            );
            // transport ($n+9): plain text merged into extra_metadata.transport by the
            // CTE's deterministic CASE; None → SQL NULL → key omitted (#376).
            flex_args.push(
                changelog.transport.map_or(FlexParam::Null, |s| FlexParam::Text(s.to_string())),
            );
        }

        // Everything the function and the outbox read of their configuration, in one
        // statement: the session variables, the #366 marker, the timing stamp, and the
        // `started_at` the outbox needs. Later pairs win, as when each was its own statement.
        //
        // The marker makes the #366 fallback-capture trigger suppress its row: this write is
        // already logged by the outbox, and on the no-outbox path the opt-out means "no
        // change-log row", not "let the trigger write a degraded one".
        let mut configuration: Vec<(&str, &str)> = Vec::with_capacity(session_vars.len() + 3);
        configuration.extend_from_slice(session_vars);
        configuration.push((crate::changelog::CDC_MEDIATED_VAR, crate::changelog::CDC_MEDIATED_ON));
        if adapter.mutation_timing_enabled {
            configuration.push((
                adapter.timing_variable_name.as_str(),
                crate::changelog::CLOCK_TIMESTAMP_DIRECTIVE,
            ));
        }
        // The outbox INSERT reads `fraiseql.started_at` with current_setting() (no
        // missing_ok), so it must exist on this txn. The mutation runner injects it on the
        // authenticated path; stamp it on every other one (e.g. an unauthenticated mutation
        // that resolves no session vars), and never over a value already set. Only the
        // outbox reads it.
        if changelog.is_some()
            && !configuration.iter().any(|(name, _)| *name == crate::changelog::STARTED_AT_VAR)
        {
            configuration.push((
                crate::changelog::STARTED_AT_VAR,
                crate::changelog::CLOCK_TIMESTAMP_DIRECTIVE,
            ));
        }

        Self {
            function_name,
            sql,
            args: flex_args,
            configuration,
            mechanism: if changelog.is_some() {
                " (with change-log outbox)"
            } else {
                ""
            },
            derived: derived_cascade,
            report_changes: report_changes.filter(|_| derived_cascade.is_none()),
        }
    }

    fn params(&self) -> Vec<&(dyn tokio_postgres::types::ToSql + Sync)> {
        self.args
            .iter()
            .map(|v| v as &(dyn tokio_postgres::types::ToSql + Sync))
            .collect()
    }

    fn configuration_failed(&self, e: &tokio_postgres::Error) -> FraiseQLError {
        let names: Vec<&str> = self.configuration.iter().map(|(name, _)| *name).collect();
        crate::postgres::database_error(
            format!("set_config({names:?}) failed: {}", pg_detail(e)),
            e,
        )
    }

    fn call_failed(&self, e: &tokio_postgres::Error) -> FraiseQLError {
        crate::postgres::database_error(
            format!(
                "Function call {}{} failed: {}",
                self.function_name,
                self.mechanism,
                pg_detail(e)
            ),
            e,
        )
    }
}

/// The one write (ruling AA 6): run write functions inside one explicit transaction, each
/// with its change-log outbox row in the same statement when its request carries one, and
/// let the gate decide the transaction's end.
///
/// `gate` runs on each call's rows, in order, after the call and before the transaction
/// ends. An `Err` from it rolls back and is returned to the caller verbatim, so a refusal
/// that could only be decided from a written row still refuses the write — every call of a
/// batch with it (#1574). In [`WriteMode::DryRun`] everything else happens exactly as in a
/// commit — session variables, CDC marking, the timing stamp, the outbox row, the gate — and
/// the transaction then rolls back: a dry run exercises the write it stands in for, and
/// nothing persists.
///
/// `numbered`: a database error says which call of the batch raised it.
async fn run_functions_in_txn(
    adapter: &PostgresAdapter,
    requests: &[crate::traits::WriteRequest<'_>],
    gate: crate::traits::BatchRowGate<'_>,
    numbered: bool,
) -> Result<Vec<Vec<RowMap>>> {
    let Some(mode) = requests.first().map(|request| request.mode) else {
        return Ok(Vec::new());
    };
    if requests.iter().any(|request| request.mode != mode) {
        return Err(FraiseQLError::Validation {
            message: "a batch of writes commits all of its calls or none: they must share one \
                      write mode"
                .to_string(),
            path:    None,
        });
    }
    let count = requests.len();
    let at = |index: usize, error: FraiseQLError| {
        if numbered {
            error.in_batch_item(index, count)
        } else {
            error
        }
    };
    let commit = matches!(mode, crate::traits::WriteMode::Commit);
    // Arm the read-your-writes pin (entry + post-commit) — #407. A dry run writes nothing
    // for a later read to miss.
    if commit {
        adapter.mark_write();
    }
    let calls: Vec<PreparedCall<'_>> =
        requests.iter().map(|request| PreparedCall::new(adapter, request)).collect();
    let configurations: Vec<_> =
        calls.iter().map(|call| set_config_batch(&call.configuration)).collect();

    let mut client = adapter.acquire_connection_with_retry().await?;
    // Parse/plan each statement once per connection (statement cache): the call (with the
    // outbox, a complex CTE) and the configuration, whose text depends only on how many
    // pairs it sets and which carry the clock directive. A batch of one function prepares
    // each text once.
    let mut statements = Vec::with_capacity(count);
    for (index, (call, (configure_sql, _))) in calls.iter().zip(&configurations).enumerate() {
        let stmt = prepare_cached_stmt(&client, call.sql.as_str())
            .await
            .map_err(|e| at(index, e))?;
        let configure = client
            .prepare_cached(configure_sql)
            .await
            .map_err(|e| at(index, call.configuration_failed(&e)))?;
        let report = match call.report_changes {
            Some(_) => Some(
                client
                    .prepare_cached(CHANGED_ROWS_SQL)
                    .await
                    .map_err(|e| at(index, changes_report_failed(&e)))?,
            ),
            None => None,
        };
        statements.push((stmt, configure, report));
    }
    let mechanism = calls
        .iter()
        .find(|call| !call.mechanism.is_empty())
        .map_or("", |call| call.mechanism);
    let txn = client.build_transaction().start().await.map_err(|e| {
        crate::postgres::database_error(
            format!("Failed to start mutation{mechanism} transaction: {}", pg_detail(&e)),
            &e,
        )
    })?;

    // The configuration and the call in one flight (#1572): the driver sends both before
    // reading either answer, and PostgreSQL runs them in order, so the function sees the
    // configuration. Only once `BEGIN` is confirmed, so neither can run outside the txn.
    // A failed configuration aborts the txn and the call with it; its own error is the one
    // reported, not the call's "current transaction is aborted".
    //
    // A call that reports what it changed (#1576) sends the report in the same flight, after
    // it: no round trip of its own.
    let flight = |index: usize| {
        let (call, (stmt, configure, report)) = (&calls[index], &statements[index]);
        let configure_params = &configurations[index].1;
        let txn = &txn;
        async move {
            let params = call.params();
            let max_entities = call.report_changes.unwrap_or_default();
            futures::join!(
                txn.execute(configure, configure_params),
                txn.query(stmt, params.as_slice()),
                async {
                    match report {
                        Some(report) => Some(txn.query_one(report, &[&max_entities]).await),
                        None => None,
                    }
                }
            )
        }
    };
    // What a flight answered, as the call's rows: its errors, then (#1391) the rows pg_tviews
    // reports this transaction changed, read on this connection before the gate adjudicates
    // the row they are attached to.
    let settle = |index: usize,
                  (configured, called, reported): (
        std::result::Result<u64, tokio_postgres::Error>,
        std::result::Result<Vec<Row>, tokio_postgres::Error>,
        Option<std::result::Result<Row, tokio_postgres::Error>>,
    )| {
        let call = &calls[index];
        let txn = &txn;
        async move {
            configured.map_err(|e| call.configuration_failed(&e))?;
            let rows = called.map_err(|e| call.call_failed(&e))?;
            let mut results: Vec<RowMap> = rows.iter().map(row_to_map).collect();
            if let Some(reported) = reported {
                let report: serde_json::Value =
                    reported.map_err(|e| changes_report_failed(&e))?.get("report");
                if let Some(first) = results.first_mut() {
                    first.insert(crate::traits::CHANGED_ROWS_KEY.to_string(), report);
                }
            }
            if let Some(derived) = call.derived {
                if let Some(first) = results.first_mut() {
                    if first.get("succeeded").and_then(serde_json::Value::as_bool) == Some(true) {
                        let report = derived_cascade_report(txn, derived).await?;
                        first.insert(crate::traits::DERIVED_CASCADE_KEY.to_string(), report);
                    }
                }
            }
            Ok::<_, FraiseQLError>(results)
        }
    };

    // Every flight at once (#1574), unless a call reports a derived cascade: its report is
    // read after its own call and before the next, so those calls go one flight at a time.
    let answers: Vec<Option<_>> = if calls.iter().all(|call| call.derived.is_none()) {
        in_order((0..count).map(flight).collect()).await.into_iter().map(Some).collect()
    } else {
        std::iter::repeat_with(|| None).take(count).collect()
    };
    let mut results = Vec::with_capacity(count);
    for (index, answer) in answers.into_iter().enumerate() {
        let answer = match answer {
            Some(answer) => answer,
            None => flight(index).await,
        };
        let rows = settle(index, answer).await.map_err(|e| at(index, e))?;

        // The gate decides the commit. It sees the rows the function returned — the
        // only thing a per-row decision can be keyed on — while they are still
        // uncommitted, so a refusal takes the write with it rather than leaving the
        // caller refused and the side effect standing (#1353).
        if let Err(refusal) = gate(index, &rows) {
            txn.rollback().await.map_err(|e| {
                crate::postgres::database_error(
                    format!("Failed to roll back refused mutation transaction: {}", pg_detail(&e)),
                    &e,
                )
            })?;
            return Err(refusal);
        }
        results.push(rows);
    }

    if !commit {
        // The whole point of a dry run: discard every write, the outbox row included.
        txn.rollback().await.map_err(|e| {
            crate::postgres::database_error(
                format!("Failed to roll back dry-run transaction: {}", pg_detail(&e)),
                &e,
            )
        })?;
        return Ok(results);
    }

    txn.commit().await.map_err(|e| {
        crate::postgres::database_error(
            format!("Failed to commit mutation{mechanism} transaction: {}", pg_detail(&e)),
            &e,
        )
    })?;
    adapter.mark_write();

    Ok(results)
}

/// Await `futures` together, polling each for the first time in order: what one sends
/// reaches the connection before what the next sends, so PostgreSQL runs them in that order.
async fn in_order<F: std::future::Future>(futures: Vec<F>) -> Vec<F::Output> {
    let mut pending: Vec<_> =
        futures.into_iter().map(|f| Box::pin(futures::future::maybe_done(f))).collect();
    std::future::poll_fn(|cx| {
        let mut done = true;
        for future in &mut pending {
            done &= std::future::Future::poll(future.as_mut(), cx).is_ready();
        }
        if done {
            std::task::Poll::Ready(())
        } else {
            std::task::Poll::Pending
        }
    })
    .await;
    pending.iter_mut().filter_map(|future| future.as_mut().take_output()).collect()
}

/// The report of the rows a call changed (#1576): `pg_tviews`' ids only, no row read.
const CHANGED_ROWS_SQL: &str =
    "SELECT tviews.pg_tviews_flush_and_report($1, false, true) AS report";

fn changes_report_failed(e: &tokio_postgres::Error) -> FraiseQLError {
    crate::postgres::database_error(
        format!(
            "tviews.pg_tviews_flush_and_report() failed, asked for the rows this write changed \
             to evict the cached reads of exactly those (is pg_tviews installed and \
             preloaded?): {}",
            pg_detail(e)
        ),
        e,
    )
}

/// Flush `pg_tviews`' queue and report the rows this transaction changed, each reported
/// updated row read from its type's view on this connection (see
/// [`crate::traits::DerivedCascade`]).
///
/// The rows of a type are read by one prepared statement, `WHERE id = ANY($1)`, and every
/// type's read is sent in one flight (#1573): the cost does not grow with the fan-out.
async fn derived_cascade_report(
    txn: &deadpool_postgres::Transaction<'_>,
    derived: &crate::traits::DerivedCascade<'_>,
) -> Result<serde_json::Value> {
    let report_failed = |e: &tokio_postgres::Error| {
        crate::postgres::database_error(
            format!(
                "cascade_source = \"pg_tviews\": tviews.pg_tviews_flush_and_report() \
                 failed (is pg_tviews installed and preloaded?): {}",
                pg_detail(e)
            ),
            e,
        )
    };
    let flush = txn
        .prepare_cached(
            "SELECT tviews.pg_tviews_flush_and_report($1, false, true) AS report, \
             to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS at",
        )
        .await
        .map_err(|e| report_failed(&e))?;
    let row = txn
        .query_one(&flush, &[&derived.max_entities])
        .await
        .map_err(|e| report_failed(&e))?;
    let mut report: serde_json::Value = row.get("report");
    let at: String = row.get("at");
    let reported_id = |entry: &serde_json::Value| match &entry["id"] {
        serde_json::Value::String(s) => s.clone(),
        other => other.to_string(),
    };

    if let Some(updated) = report.get_mut("updated").and_then(serde_json::Value::as_array_mut) {
        // The reported ids of each type a view serves, in report order.
        let mut ids_by_view: Vec<(&str, &str, Vec<FlexParam>)> = Vec::new();
        for entry in updated.iter() {
            let typename = entry["__typename"].as_str().unwrap_or_default();
            let Some((name, view)) = derived.views.iter().find(|(name, _)| *name == typename)
            else {
                continue;
            };
            let id = FlexParam::Text(reported_id(entry));
            match ids_by_view.iter_mut().find(|(n, ..)| n == name) {
                Some((.., ids)) => ids.push(id),
                None => ids_by_view.push((name, view, vec![id])),
            }
        }
        let reads = ids_by_view.iter().map(|(typename, view, ids)| async move {
            let read_failed = |e: &tokio_postgres::Error| {
                crate::postgres::database_error(
                    format!(
                        "cascade_source = \"pg_tviews\": reading {typename} from {view} \
                         failed: {}",
                        pg_detail(e)
                    ),
                    e,
                )
            };
            // Prepared once per connection: one text per view a schema names.
            let sql = format!(
                "SELECT id::text AS id, data FROM {} WHERE id = ANY($1)",
                quote_postgres_identifier(view)
            );
            let statement = txn.prepare_cached(&sql).await.map_err(|e| read_failed(&e))?;
            let rows = txn.query(&statement, &[ids]).await.map_err(|e| read_failed(&e))?;
            let by_id: std::collections::HashMap<String, serde_json::Value> =
                rows.iter().map(|r| (r.get("id"), r.get("data"))).collect();
            Ok::<_, FraiseQLError>((*typename, by_id))
        });
        let read: Vec<(&str, std::collections::HashMap<String, serde_json::Value>)> =
            futures::future::try_join_all(reads).await?;

        // A row its view did not return (not visible to this caller), or of a type no view
        // serves, is `null`.
        for entry in updated.iter_mut() {
            let typename = entry["__typename"].as_str().unwrap_or_default();
            let entity = read
                .iter()
                .find(|(name, _)| *name == typename)
                .and_then(|(_, by_id)| by_id.get(&reported_id(entry)))
                .cloned()
                .unwrap_or(serde_json::Value::Null);
            entry["entity"] = entity;
        }
    }
    if let Some(deleted) = report.get_mut("deleted").and_then(serde_json::Value::as_array_mut) {
        for entry in deleted.iter_mut() {
            entry["deletedAt"] = serde_json::Value::String(at.clone());
        }
    }
    Ok(report)
}

/// PostgreSQL SQLSTATE 42703: undefined column.
const PG_UNDEFINED_COLUMN: &str = "42703";

/// A flexible SQL parameter that binds to any PostgreSQL type.
///
/// Solves the impedance mismatch between `serde_json::Value` (only accepts JSON/JSONB)
/// and `Option<String>` (only accepts text-family types) when binding function-call
/// arguments whose types are resolved at runtime from the function signature.
///
/// Serialisation strategy:
/// - `JSONB`: binary, a 1-byte version header (1) + UTF-8 JSON bytes
/// - `JSON`: binary, UTF-8 JSON bytes
/// - `UUID`: binary, 16-byte big-endian UUID
/// - `INT4`: binary, 4-byte big-endian i32
/// - `INT8`: binary, 8-byte big-endian i64
/// - `BOOL`: binary, 1 byte (0 or 1)
/// - Every other type: the **text** format, the value's UTF-8 bytes, which PostgreSQL parses with
///   the type's own input function (#1547). A `float8`, `numeric`, `date`, `timestamp`, `interval`,
///   an array, an enum or a domain reads its text form; the binary form of most of them is not
///   their text (a `float8` is 8 bytes, a `date` 4), so sending the text as binary failed with
///   `insufficient data left in message`.
///
/// A write function's argument is the JSON value the request carries, written for the
/// parameter's type: a `json`/`jsonb` parameter takes it as the JSON it is (a string stays a
/// string), an array parameter a JSON array in PostgreSQL's array syntax, `{"a","b"}`, each
/// item parsed by the element type's input function, and any other parameter its text (a
/// string's own characters, any other value's JSON).
///
/// Inside an array (`id = ANY($1)`) each element is written by [`ToSql::to_sql`] in the binary
/// format whatever [`ToSql::encode_format`] says, so the six binary encodings stay.
#[derive(Debug)]
enum FlexParam {
    /// SQL NULL — accepted by any PostgreSQL type.
    Null,
    /// A text-encoded value; binary-serialised according to the server-resolved type. A
    /// `json`/`jsonb` parameter takes the text as JSON text.
    Text(String),
    /// A request's JSON value, written for the server-resolved type.
    Value(serde_json::Value),
}

/// An aggregate's parameters, each written for the type the server resolves it to, as a
/// write function's arguments are (#1620): a string compared with `data->>'region'` is text,
/// a number compared with `SUM(qty)` (a `numeric`) its text in the text format. They were
/// bound as `QueryParam`, whose number is text bytes sent under the binary format, which a
/// `numeric` parameter cannot read (`insufficient data left in message`).
fn aggregate_params(params: &[serde_json::Value]) -> Vec<FlexParam> {
    params
        .iter()
        .map(|v| match v {
            serde_json::Value::Null => FlexParam::Null,
            value => FlexParam::Value(value.clone()),
        })
        .collect()
}

/// Write `text`, the text form of a value, for the parameter type `ty`: the binary form of
/// the six types `encode_format` sends in binary, the UTF-8 bytes otherwise.
fn write_text(
    text: &str,
    ty: &tokio_postgres::types::Type,
    out: &mut bytes::BytesMut,
) -> std::result::Result<(), Box<dyn std::error::Error + Sync + Send>> {
    use tokio_postgres::types::Type;
    if *ty == Type::JSONB {
        // JSONB binary wire format: 1-byte version (1) + JSON bytes
        out.put_u8(1);
        out.extend_from_slice(text.as_bytes());
    } else if *ty == Type::UUID {
        let uuid = uuid::Uuid::parse_str(text)?;
        out.extend_from_slice(uuid.as_bytes());
    } else if *ty == Type::INT4 {
        let n: i32 = text.parse()?;
        out.put_i32(n);
    } else if *ty == Type::INT8 {
        let n: i64 = text.parse()?;
        out.put_i64(n);
    } else if *ty == Type::BOOL {
        let b: bool = text.parse()?;
        out.put_u8(u8::from(b));
    } else {
        // Sent in the text format (`encode_format`): the UTF-8 bytes, parsed by the type's
        // input function. Also the binary form of `json` and of the text family.
        out.extend_from_slice(text.as_bytes());
    }
    Ok(())
}

/// Write `items` in PostgreSQL's array syntax: every item quoted (an element type's input
/// function reads `"1"` as it reads `1`), `NULL` for a JSON `null`, and a nested JSON array as
/// a sub-array, unless the elements are `json`/`jsonb`, where every item is one JSON value
/// written as its JSON text.
fn write_array_literal(items: &[serde_json::Value], json_elements: bool, out: &mut String) {
    out.push('{');
    for (i, item) in items.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        match item {
            serde_json::Value::Null => out.push_str("NULL"),
            serde_json::Value::Array(inner) if !json_elements => {
                write_array_literal(inner, json_elements, out);
            },
            serde_json::Value::String(s) if !json_elements => quote_array_item(s, out),
            other => quote_array_item(&other.to_string(), out),
        }
    }
    out.push('}');
}

fn quote_array_item(item: &str, out: &mut String) {
    out.push('"');
    for c in item.chars() {
        if c == '"' || c == '\\' {
            out.push('\\');
        }
        out.push(c);
    }
    out.push('"');
}

/// The element type of `ty`, seen through any domains over it, when it is an array type.
fn array_element(ty: &tokio_postgres::types::Type) -> Option<&tokio_postgres::types::Type> {
    use tokio_postgres::types::Kind;
    match ty.kind() {
        Kind::Array(element) => Some(element),
        Kind::Domain(base) => array_element(base),
        _ => None,
    }
}

impl tokio_postgres::types::ToSql for FlexParam {
    fn to_sql(
        &self,
        ty: &tokio_postgres::types::Type,
        out: &mut bytes::BytesMut,
    ) -> std::result::Result<tokio_postgres::types::IsNull, Box<dyn std::error::Error + Sync + Send>>
    {
        use tokio_postgres::types::{IsNull, Type};
        match self {
            Self::Null => Ok(IsNull::Yes),
            Self::Text(s) => {
                write_text(s, ty, out)?;
                Ok(IsNull::No)
            },
            Self::Value(value) => {
                if *ty == Type::JSONB {
                    out.put_u8(1);
                    serde_json::to_writer((&mut *out).writer(), value)?;
                } else if *ty == Type::JSON {
                    serde_json::to_writer((&mut *out).writer(), value)?;
                } else if let (Some(element), serde_json::Value::Array(items)) =
                    (array_element(ty), value)
                {
                    let json_elements = [Type::JSONB, Type::JSON].contains(element);
                    let mut literal = String::new();
                    write_array_literal(items, json_elements, &mut literal);
                    out.extend_from_slice(literal.as_bytes());
                } else if let serde_json::Value::String(s) = value {
                    write_text(s, ty, out)?;
                } else {
                    // Another type reads the JSON text with its own input function, which
                    // accepts it (`9.5` for a `float8`) or refuses it with its own message.
                    write_text(&value.to_string(), ty, out)?;
                }
                Ok(IsNull::No)
            },
        }
    }

    fn accepts(_ty: &tokio_postgres::types::Type) -> bool {
        // Accepts all types; per-type serialisation is handled in `to_sql`.
        true
    }

    fn encode_format(&self, ty: &tokio_postgres::types::Type) -> tokio_postgres::types::Format {
        use tokio_postgres::types::{Format, Type};
        if [
            Type::JSONB,
            Type::JSON,
            Type::UUID,
            Type::INT4,
            Type::INT8,
            Type::BOOL,
        ]
        .contains(ty)
        {
            Format::Binary
        } else {
            Format::Text
        }
    }

    fn to_sql_checked(
        &self,
        ty: &tokio_postgres::types::Type,
        out: &mut bytes::BytesMut,
    ) -> std::result::Result<tokio_postgres::types::IsNull, Box<dyn std::error::Error + Sync + Send>>
    {
        // `accepts()` returns true for all types, so the standard WrongType check is
        // unnecessary.  Delegate directly to `to_sql`.
        self.to_sql(ty, out)
    }
}

/// Enrich a `FraiseQLError::Database` error for PostgreSQL SQLSTATE 42703 (undefined column)
/// when the WHERE clause contains `NativeField` conditions.
///
/// Native columns may be inferred automatically at compile time from `ID`/`UUID`-typed
/// arguments.  If the column does not exist on the target table at runtime, the raw
/// PostgreSQL error is replaced with a diagnostic message that names the native columns
/// involved and explains how to fix the schema.
fn enrich_undefined_column_error(
    err: FraiseQLError,
    view: &str,
    where_clause: Option<&WhereClause>,
) -> FraiseQLError {
    let FraiseQLError::Database { ref sql_state, .. } = err else {
        return err;
    };
    if sql_state.as_deref() != Some(PG_UNDEFINED_COLUMN) {
        return err;
    }
    let native_cols: Vec<&str> =
        where_clause.map(|wc| wc.native_column_names()).unwrap_or_default();
    if native_cols.is_empty() {
        return err;
    }
    FraiseQLError::Database {
        message:    format!(
            "Column(s) {:?} referenced as native column(s) on `{view}` do not exist. \
             These columns were auto-inferred from ID/UUID-typed query arguments. \
             Either add the column(s) to the table/view, or set \
             `native_columns = {{}}` explicitly in your schema to disable inference.",
            native_cols,
        ),
        sql_state:  Some(PG_UNDEFINED_COLUMN.to_string()),
        constraint: None,
    }
}

/// Decodes any PostgreSQL `ENUM` value as its text label.
///
/// `String`'s `FromSql` accepts only the text family (TEXT/VARCHAR/BPCHAR/NAME), not
/// a custom enum OID, so an enum column otherwise falls through [`row_to_map`]'s
/// decode ladder to `Null`. An enum's binary wire representation *is* its label as
/// UTF-8 text, so this reads it directly (#472).
struct PgEnumLabel(String);

impl<'a> FromSql<'a> for PgEnumLabel {
    fn from_sql(
        _ty: &Type,
        raw: &'a [u8],
    ) -> std::result::Result<Self, Box<dyn std::error::Error + Sync + Send>> {
        Ok(Self(std::str::from_utf8(raw)?.to_owned()))
    }

    fn accepts(ty: &Type) -> bool {
        matches!(ty.kind(), Kind::Enum(_))
    }
}

/// Accepts every PostgreSQL type and decodes none of it.
///
/// Read as `Option<AnyCell>`, it answers one question: is this cell SQL `NULL`. Each branch
/// of [`decode_cell`]'s ladder refuses a `NULL` with `WasNull`, so without this a `NULL` of any
/// type fell through to the "not representable" warning (#1514).
struct AnyCell;

impl<'a> FromSql<'a> for AnyCell {
    fn from_sql(
        _ty: &Type,
        _raw: &'a [u8],
    ) -> std::result::Result<Self, Box<dyn std::error::Error + Sync + Send>> {
        Ok(Self)
    }

    fn accepts(_ty: &Type) -> bool {
        true
    }
}

/// Convert a single `tokio_postgres::Row` into a `HashMap<String, serde_json::Value>`.
///
/// Tries each PostgreSQL type in priority order; falls back to `Null` for
/// types that cannot be represented as JSON.
fn row_to_map(row: &Row) -> std::collections::HashMap<String, serde_json::Value> {
    let mut map = std::collections::HashMap::new();
    for (idx, column) in row.columns().iter().enumerate() {
        map.insert(column.name().to_string(), decode_cell(row, idx));
    }
    map
}

/// Decode one cell of a `tokio_postgres::Row` to JSON.
///
/// The decode ladder itself, extracted from [`row_to_map`] so the positional
/// reader the admin SQL console needs (#962) and the name-keyed map every other
/// caller wants cannot disagree about what a `numeric`, an enum or a `timestamptz`
/// becomes. A console keyed by column *name* would also collapse `SELECT 1 AS a,
/// 2 AS a` to one column and silently drop the other.
///
/// Tries each PostgreSQL type in priority order; falls back to `Null` for types
/// that cannot be represented as JSON.
pub(super) fn decode_cell(row: &Row, idx: usize) -> serde_json::Value {
    let column = &row.columns()[idx];
    if matches!(row.try_get::<_, Option<AnyCell>>(idx), Ok(None)) {
        // SQL NULL, whatever the column's type: decided once, before the ladder (#1514).
        serde_json::Value::Null
    } else if let Ok(v) = row.try_get::<_, i16>(idx) {
        // SMALLINT/int2 columns (e.g. `app.mutation_response.http_status`).
        // Without this branch a non-null int2 fell through to `Null` because
        // `FromSql for i32` rejects int2 — which dropped `MutationError`'s
        // `httpStatus` to absent. Order among i16/i32/i64 is correctness-
        // neutral (each `FromSql` accepts only its own PG int width), so this
        // sits first for readability.
        serde_json::json!(v)
    } else if let Ok(v) = row.try_get::<_, i32>(idx) {
        serde_json::json!(v)
    } else if let Ok(v) = row.try_get::<_, i64>(idx) {
        serde_json::json!(v)
    } else if let Ok(v) = row.try_get::<_, f64>(idx) {
        serde_json::json!(v)
    } else if let Ok(v) = row.try_get::<_, String>(idx) {
        serde_json::json!(v)
    } else if let Ok(v) = row.try_get::<_, bool>(idx) {
        serde_json::json!(v)
    } else if let Ok(v) = row.try_get::<_, PgNumericText>(idx) {
        // NUMERIC/DECIMAL — decoded to PostgreSQL's exact text rendering
        // (#980), then re-parsed as a JSON number so the value isn't forced
        // through f64 at construction. Without this branch a `SUM(revenue)`
        // aggregate (and every raw NUMERIC column) fell through to `Null`
        // (H35). Falls back to a JSON string for the values whose text is
        // not JSON numeric syntax: NaN, Infinity and -Infinity.
        let s = v.0;
        serde_json::from_str::<serde_json::Value>(&s).unwrap_or(serde_json::Value::String(s))
    } else if let Ok(v) = row.try_get::<_, uuid::Uuid>(idx) {
        // UUID columns (e.g. `app.mutation_response.entity_id`) render as the
        // canonical hyphenated string instead of silently nulling (H35).
        serde_json::json!(v.to_string())
    } else if let Ok(v) = row.try_get::<_, chrono::DateTime<chrono::Utc>>(idx) {
        // `timestamptz` → RFC 3339 / ISO 8601 text (H35).
        serde_json::json!(v.to_rfc3339())
    } else if let Ok(v) = row.try_get::<_, chrono::NaiveDateTime>(idx) {
        // `timestamp` (no tz) → ISO 8601 text (H35).
        serde_json::json!(v.to_string())
    } else if let Ok(v) = row.try_get::<_, chrono::NaiveDate>(idx) {
        // `date` → ISO 8601 date text (H35).
        serde_json::json!(v.to_string())
    } else if let Ok(v) = row.try_get::<_, Vec<String>>(idx) {
        // TEXT[] columns (e.g. `app.mutation_response.updated_fields`) — without
        // this branch a non-null text array falls through to Null and a parser
        // expecting a sequence fails. Must precede the jsonb branch (a jsonb
        // column never deserializes as Vec<String>, so ordering is safe).
        serde_json::json!(v)
    } else if let Ok(v) = row.try_get::<_, PgEnumLabel>(idx) {
        // ENUM columns (e.g. `app.mutation_response.error_class`, the
        // `app.mutation_error_class` enum) render as their text label. Without
        // this branch a non-null enum fell through to `Null` (`String: FromSql`
        // rejects a custom enum OID), which dropped `error_class` to absent on a
        // failed mutation — and the parser then rejected the row with
        // "succeeded=false requires error_class", so the typed error arm was
        // never reached (#472). `PgEnumLabel` accepts only `Kind::Enum`, so this
        // never shadows another branch regardless of position.
        serde_json::json!(v.0)
    } else if let Ok(v) = row.try_get::<_, serde_json::Value>(idx) {
        v
    } else {
        // A column whose PostgreSQL type none of the branches above can
        // decode. Name the column and its type so the next drift is visible
        // in logs instead of a silent null (H35).
        tracing::warn!(
            column = %column.name(),
            pg_type = %column.type_(),
            "decode_cell: column type not representable as JSON; returning null"
        );
        serde_json::Value::Null
    }
}

/// Apply transaction-local session variables on an in-progress transaction.
///
/// Every `(name, value)` pair is set with `set_config(name, value, true)`, all of them in one
/// `SELECT`, so the values are scoped to `txn` and visible to every statement run on it (fixes
/// #329), for one round trip whatever their number. The caller is responsible for committing or
/// rolling back.
pub(super) async fn apply_session_vars(
    txn: &deadpool_postgres::Transaction<'_>,
    session_vars: &[(&str, &str)],
) -> Result<()> {
    if session_vars.is_empty() {
        return Ok(());
    }
    let (sql, params) = set_config_batch(session_vars);
    // Prepared once per connection. Names and values are parameters, so the text depends only
    // on how many variables are set and which carry the clock directive: a handful of texts per
    // schema, none a client can mint, so unlike a read's it needs no cap.
    let applied = match txn.prepare_cached(&sql).await {
        Ok(statement) => txn.execute(&statement, &params).await,
        Err(e) => Err(e),
    };
    applied.map_err(|e| {
        let names: Vec<&str> = session_vars.iter().map(|(name, _)| *name).collect();
        crate::postgres::database_error(
            format!("set_config({names:?}) failed: {}", pg_detail(&e)),
            &e,
        )
    })?;
    Ok(())
}

/// One `SELECT set_config(…), set_config(…), …` setting every pair transaction-locally, and its
/// parameters. Names and values are always parameters, never SQL text.
///
/// A var carrying the clock-timestamp directive (e.g. `fraiseql.started_at`) is stamped with the
/// DB clock at apply time, on this very transaction, so the start timestamp and the
/// close-of-interval at the outbox write share one clock (no app↔DB skew).
fn set_config_batch<'a>(
    session_vars: &'a [(&'a str, &'a str)],
) -> (String, Vec<&'a (dyn tokio_postgres::types::ToSql + Sync)>) {
    let mut sql = String::from("SELECT ");
    let mut params: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
        Vec::with_capacity(session_vars.len() * 2);
    for (index, (name, value)) in session_vars.iter().enumerate() {
        if index > 0 {
            sql.push_str(", ");
        }
        params.push(name);
        let name_param = params.len();
        if *value == crate::changelog::CLOCK_TIMESTAMP_DIRECTIVE {
            let _ = write!(sql, "set_config(${name_param}, clock_timestamp()::text, true)");
        } else {
            params.push(value);
            let _ = write!(sql, "set_config(${name_param}, ${}, true)", name_param + 1);
        }
    }
    (sql, params)
}

/// Build the single statement that runs a mutation function and writes its
/// `core.tb_entity_change_log` outbox row in the same transaction (the Change
/// Spine transactional outbox).
///
/// The function call is materialised once (`WITH r AS MATERIALIZED`, so a
/// volatile mutation function executes **exactly once** even though two CTEs
/// read it), a data-modifying CTE INSERTs the change-log row for an effective
/// change (`succeeded AND state_changed`), and the primary `SELECT * FROM r`
/// returns the function's row unchanged to the caller. The changed-entity
/// columns (`object_id`, `object_data`, `updated_fields`, `cascade`) come from
/// the function's own `app.mutation_response` row; `$<n+1>` is the NOT-NULL
/// `object_type` fallback, `$<n+2>` is the `modification_type` verb,
/// `$<n+3>` is the envelope `tenant_id` (the Trinity public-facing UUID, NULL
/// for system / unauthenticated / non-UUID-tenant rows), `$<n+4>` is the
/// `trace_id` (the request's W3C trace id, plain text), `$<n+5>` is the
/// `schema_version` (the compiled schema's content hash, plain text), `$<n+6>`
/// is the `trace_context` (the full W3C trace context, cast `::jsonb`), and
/// `$<n+9>` is the ingress `transport` (#376), merged into `extra_metadata` as
/// `{"transport": …}` by a deterministic `CASE` (NULL omits the key, so the SQL
/// text never depends on the value), where `n` = `n_args` (the number of
/// function arguments). The envelope params are
/// appended **after** the function args so the SQL text stays deterministic per
/// `(function, n_args)` — `prepare_cached` keys the statement by text, so the
/// column list and placeholder positions must never depend on the param *values*.
///
/// `started_at`/`duration_ms` read `fraiseql.started_at` (set txn-locally by the
/// caller) on the DB clock — the canonical computation from
/// [`crate::changelog::duration_ms_sql`], stamped with
/// [`crate::changelog::DURATION_CALC_VERSION`]. `commit_time` is the DB clock at
/// INSERT; `seq` is omitted so the column's `SEQUENCE` default fires (so any
/// INSERTer, incl. cooperative external producers, gets a monotonic value).
pub(super) fn build_changelog_cte_sql(quoted_fn: &str, n_args: usize, pre_image: bool) -> String {
    let placeholders: Vec<String> = (1..=n_args).map(|i| format!("${i}")).collect();
    let object_type_idx = n_args + 1;
    let modification_type_idx = n_args + 2;
    let tenant_id_idx = n_args + 3;
    let trace_id_idx = n_args + 4;
    let schema_version_idx = n_args + 5;
    let trace_context_idx = n_args + 6;
    let actor_type_idx = n_args + 7;
    let acting_for_idx = n_args + 8;
    let transport_idx = n_args + 9;
    let started_var = crate::changelog::STARTED_AT_VAR;
    let duration = crate::changelog::duration_ms_sql(started_var);
    let calc_version = crate::changelog::DURATION_CALC_VERSION;
    // Pre-image (opt-in, #changelog_pre_image): also record the changed entity's
    // before-state from the function's own `entity_before` column, alongside the
    // after-image `entity`. Adds `object_data_before` to the INSERT and
    // `r.entity_before` to the SELECT ONLY when requested — `object_data` stays
    // the after-image for every consumer; an absent flag emits today's SQL
    // byte-for-byte. No new placeholder: the before-image is a column on `r`, like
    // `r.entity`. The two SQL forms differ in text, so `prepare_cached` keys them
    // as separate statements automatically (no extra cache discriminator needed).
    let after_before_cols = if pre_image {
        "object_data, object_data_before"
    } else {
        "object_data"
    };
    let after_before_vals = if pre_image {
        "r.entity, r.entity_before"
    } else {
        "r.entity"
    };
    format!(
        "WITH r AS MATERIALIZED (SELECT * FROM {quoted_fn}({args})), \
         _changelog AS ( \
           INSERT INTO core.tb_entity_change_log \
             (object_type, modification_type, object_id, {after_before_cols}, \
              updated_fields, cascade, started_at, duration_ms, extra_metadata, \
              tenant_id, trace_id, schema_version, trace_context, \
              actor_type, acting_for, commit_time) \
           SELECT \
             COALESCE(r.entity_type, ${object_type_idx}), \
             ${modification_type_idx}, \
             r.entity_id, {after_before_vals}, r.updated_fields, r.cascade, \
             current_setting('{started_var}')::timestamptz, \
             {duration}, \
             jsonb_build_object('duration_calc_version', {calc_version}::int) \
               || CASE WHEN ${transport_idx}::text IS NULL THEN '{{}}'::jsonb \
                       ELSE jsonb_build_object('transport', ${transport_idx}::text) END, \
             ${tenant_id_idx}::uuid, \
             ${trace_id_idx}, \
             ${schema_version_idx}, \
             ${trace_context_idx}::jsonb, \
             ${actor_type_idx}, \
             ${acting_for_idx}::uuid, \
             clock_timestamp() \
           FROM r \
           WHERE r.succeeded AND r.state_changed \
           RETURNING 1 \
         ) \
         SELECT * FROM r",
        args = placeholders.join(", "),
    )
}

/// Prepare `sql` on `client` using deadpool's **per-connection statement cache**.
///
/// The mutation function-call path sends the same statement (a fixed
/// `SELECT * FROM fn(...)` or the change-log CTE) on every call, so without
/// caching PostgreSQL re-parses and re-plans it for each mutation — the dominant
/// hot-path cost (the complex outbox CTE in particular). `prepare_cached` keys
/// the parsed/planned [`tokio_postgres::Statement`] by SQL text per connection
/// and reuses it across calls, so the parse/plan happens once per connection.
///
/// Returns an owned `Statement` (releasing the `&client` borrow), so it can be
/// prepared before `client.build_transaction()` and used inside that transaction.
async fn prepare_cached_stmt(
    client: &deadpool_postgres::Client,
    sql: &str,
) -> Result<tokio_postgres::Statement> {
    client.prepare_cached(sql).await.map_err(|e| {
        // Surface the underlying PostgreSQL diagnostic (SQLSTATE message, e.g.
        // `function "foo" does not exist`) rather than the opaque `db error` the
        // top-level `Display` renders (#451, generalised to every query path by #888).
        let detail = pg_detail(&e);
        let hint = changelog_prepare_hint(&detail);
        crate::postgres::database_error(format!("Failed to prepare statement: {detail}{hint}"), &e)
    })
}

/// Actionable operator guidance for the two prepare failures every freshly
/// authored stack hits (#569). The bare PostgreSQL diagnostics — `relation
/// "core.tb_entity_change_log" does not exist` and `column r.entity_type does
/// not exist` — point at neither of the actual requirements: the change-log
/// outbox table must be installed (`fraiseql setup`), and every mutation
/// function must return the 13-column v2.2 `mutation_response` row the outbox
/// CTE reads (`r.` is that CTE's alias for the function result, so a missing
/// `r.*` column means the function returns some other shape — classically
/// `RETURNS SETOF v_*`).
fn changelog_prepare_hint(detail: &str) -> &'static str {
    if detail.contains("core.tb_entity_change_log") {
        "\nhint: the mutation change-log outbox table is not installed in this database — \
         run `fraiseql setup` (or apply the fraiseql-observers change-log contract \
         migration) before executing mutations"
    } else if detail.contains("column r.") {
        "\nhint: the mutation function does not return the v2.2 mutation_response row \
         (13 columns: succeeded, state_changed, …) that the change-log outbox reads. \
         `RETURNS SETOF v_*` and bare scalar returns are not supported — build the row \
         with fraiseql.mutation_ok()/fraiseql.mutation_err() (installed by `fraiseql \
         setup`); see docs/architecture/mutation-response.md"
    } else {
        ""
    }
}

// Reason: DatabaseAdapter is defined with #[async_trait]; all implementations must match
// its transformed method signatures to satisfy the trait contract
// async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
#[async_trait]
impl DatabaseAdapter for PostgresAdapter {
    // Every `*_with_session` read is overridden to apply its variables (#1115).
    fn applies_session_variables(&self) -> bool {
        true
    }

    fn serves_reads_from_standbys(&self) -> bool {
        self.read_replicas.is_some()
    }

    async fn execute_with_projection(
        &self,
        view: &str,
        projection: Option<&SqlProjectionHint>,
        where_clause: Option<&WhereClause>,
        limit: Option<u32>,
        offset: Option<u32>,
        order_by: Option<&[OrderByClause]>,
    ) -> Result<Vec<JsonbValue>> {
        self.execute_with_projection_impl(view, projection, where_clause, limit, offset, order_by)
            .await
    }

    async fn execute_where_query(
        &self,
        view: &str,
        where_clause: Option<&WhereClause>,
        limit: Option<u32>,
        offset: Option<u32>,
        order_by: Option<&[OrderByClause]>,
    ) -> Result<Vec<JsonbValue>> {
        let (sql, typed_params) =
            build_where_select_sql_ordered(view, where_clause, limit, offset, order_by)?;

        let param_refs = crate::types::as_sql_param_refs(&typed_params);

        self.execute_raw(&sql, &param_refs, ReadRouting::Any)
            .await
            .map_err(|e| enrich_undefined_column_error(e, view, where_clause))
    }

    async fn explain_where_query(
        &self,
        view: &str,
        where_clause: Option<&WhereClause>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<serde_json::Value> {
        let (select_sql, typed_params) = build_where_select_sql(view, where_clause, limit, offset)?;
        // Defense-in-depth: compiler-generated SQL should never contain a
        // semicolon, but guard against it to prevent statement injection.
        if select_sql.contains(';') {
            return Err(FraiseQLError::Validation {
                message: "EXPLAIN SQL must be a single statement".into(),
                path:    None,
            });
        }
        let explain_sql = format!("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {select_sql}");

        let param_refs = crate::types::as_sql_param_refs(&typed_params);

        // EXPLAIN ANALYZE of a compiled SELECT: read-only, and most truthful when
        // it runs where the reads it describes run — the replica route (#407).
        let client = self.acquire_read_connection_with_retry(ReadRouting::Any).await?;
        let rows = client.query(explain_sql.as_str(), &param_refs).await.map_err(|e| {
            crate::postgres::database_error(
                format!("EXPLAIN ANALYZE failed: {}", pg_detail(&e)),
                &e,
            )
        })?;

        if let Some(row) = rows.first() {
            let plan: serde_json::Value = row.try_get(0).map_err(|e| FraiseQLError::Database {
                message:    format!("Failed to parse EXPLAIN output: {e}"),
                sql_state:  None,
                constraint: None,
            })?;
            Ok(plan)
        } else {
            Ok(serde_json::Value::Null)
        }
    }

    fn database_type(&self) -> DatabaseType {
        DatabaseType::PostgreSQL
    }

    /// `execute_composed_with_session` is implemented below.
    fn supports_composed_reads(&self) -> bool {
        true
    }

    async fn tview_profiles(&self, sources: &[String]) -> Result<Vec<crate::traits::TviewProfile>> {
        let client = self.acquire_connection_with_retry().await?;
        crate::postgres::introspector::query_tview_profiles(&client, sources).await
    }

    async fn schema_storage_bytes(&self, schema: &str) -> Result<Option<u64>> {
        let client = self.acquire_connection_with_retry().await?;
        // Tables and materialized views only: `pg_total_relation_size` already counts a
        // relation's indexes and TOAST, so listing those too would count them twice. The
        // schema is a bound parameter, never interpolated.
        let row = client
            .query_one(
                "SELECT COALESCE(sum(pg_total_relation_size(c.oid)), 0)::bigint FROM pg_class c \
                 JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 \
                 AND c.relkind IN ('r', 'm')",
                &[&schema],
            )
            .await
            .map_err(|e| {
                crate::postgres::database_error(
                    format!("measuring schema {schema:?}: {}", pg_detail(&e)),
                    &e,
                )
            })?;
        let bytes: i64 = row.get(0);
        Ok(Some(u64::try_from(bytes).unwrap_or(0)))
    }

    async fn describe_constraint(
        &self,
        violation: &fraiseql_error::ConstraintViolation,
    ) -> Result<crate::traits::ConstraintDescription> {
        // The catalog is keyed by the relation the error names; without it there is nothing
        // to read, and the violation is reported as given.
        let (Some(schema), Some(table)) = (&violation.schema, &violation.table) else {
            return Ok(crate::traits::ConstraintDescription {
                name:    violation.name.clone(),
                columns: None,
            });
        };
        let client = self.acquire_connection_with_retry().await?;
        // A not-null violation names its column, not its constraint: PostgreSQL 18
        // catalogues the not-null constraint (`contype = 'n'`), so it is found from it.
        let name = match (&violation.name, &violation.column) {
            (Some(name), _) => Some(name.clone()),
            (None, Some(column)) => client
                .query_opt(
                    "SELECT c.conname::text FROM pg_constraint c JOIN pg_attribute a ON \
                     a.attrelid = c.conrelid WHERE c.conrelid = to_regclass(format('%I.%I', \
                     $1::text, $2::text)) AND c.contype = 'n' AND a.attname = $3 AND c.conkey = \
                     ARRAY[a.attnum]",
                    &[schema, table, column],
                )
                .await
                .map_err(|e| {
                    crate::postgres::database_error(
                        format!("Failed to resolve a not-null constraint: {}", pg_detail(&e)),
                        &e,
                    )
                })?
                .map(|row| row.get(0)),
            (None, None) => None,
        };
        let Some(name) = name else {
            return Ok(crate::traits::ConstraintDescription::default());
        };
        // The key columns of the constraint, or of the unique index of that name (a partial
        // unique index has no `pg_constraint` row), in order. An expression column
        // (`attnum = 0`) makes the answer `NULL`: never guessed. `INCLUDE` columns are not
        // key columns.
        let columns: Option<Vec<String>> = client
            .query_one(
                "WITH k AS ( \
                   SELECT u.attnum, u.ord FROM pg_constraint c, \
                          unnest(c.conkey) WITH ORDINALITY u(attnum, ord) \
                    WHERE c.conrelid = to_regclass(format('%I.%I', $1::text, $2::text)) \
                      AND c.conname = $3 \
                   UNION ALL \
                   SELECT u.attnum, u.ord FROM pg_index i, \
                          unnest(i.indkey) WITH ORDINALITY u(attnum, ord) \
                    WHERE i.indexrelid = to_regclass(format('%I.%I', $1::text, $3::text)) \
                      AND i.indrelid = to_regclass(format('%I.%I', $1::text, $2::text)) \
                      AND u.ord <= i.indnkeyatts \
                      AND NOT EXISTS (SELECT 1 FROM pg_constraint c2 \
                                       WHERE c2.conrelid = i.indrelid AND c2.conname = $3)) \
                 SELECT CASE WHEN count(*) = 0 OR bool_or(k.attnum = 0) THEN NULL \
                             ELSE array_agg(a.attname::text ORDER BY k.ord) END \
                   FROM k LEFT JOIN pg_attribute a \
                     ON a.attrelid = to_regclass(format('%I.%I', $1::text, $2::text)) \
                    AND a.attnum = k.attnum",
                &[schema, table, &name],
            )
            .await
            .map_err(|e| {
                crate::postgres::database_error(
                    format!("Failed to resolve a constraint's columns: {}", pg_detail(&e)),
                    &e,
                )
            })?
            .get(0);
        Ok(crate::traits::ConstraintDescription {
            name: Some(name),
            columns,
        })
    }

    async fn health_check(&self) -> Result<()> {
        // Use retry logic for health check to avoid false negatives during pool exhaustion
        let client = self.acquire_connection_with_retry().await?;

        client.query("SELECT 1", &[]).await.map_err(|e| {
            crate::postgres::database_error(format!("Health check failed: {}", pg_detail(&e)), &e)
        })?;

        Ok(())
    }

    #[allow(clippy::cast_possible_truncation)] // Reason: value is bounded; truncation cannot occur in practice
    fn pool_metrics(&self) -> PoolMetrics {
        let status = self.pool.status();

        PoolMetrics {
            total_connections:  status.size as u32,
            idle_connections:   status.available as u32,
            active_connections: (status.size - status.available) as u32,
            waiting_requests:   status.waiting as u32,
        }
    }

    /// # Security
    ///
    /// `sql` **must** be compiler-generated. Never pass user-supplied strings
    /// directly — doing so would open SQL-injection vulnerabilities.
    async fn execute_raw_query(
        &self,
        sql: &str,
    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
        // Use retry logic for connection acquisition
        let client = self.acquire_connection_with_retry().await?;

        let rows: Vec<Row> = client.query(sql, &[]).await.map_err(|e| {
            crate::postgres::database_error(
                format!("Query execution failed: {}", pg_detail(&e)),
                &e,
            )
        })?;

        // Convert each row to HashMap<String, Value>
        let results: Vec<std::collections::HashMap<String, serde_json::Value>> =
            rows.iter().map(row_to_map).collect();

        Ok(results)
    }

    async fn execute_parameterized_aggregate(
        &self,
        sql: &str,
        params: &[serde_json::Value],
    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
        let typed = aggregate_params(params);
        let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
            typed.iter().map(|v| v as &(dyn tokio_postgres::types::ToSql + Sync)).collect();

        // Compiled aggregate SELECT: read-only, replica-eligible (#407).
        let client = self.acquire_read_connection_with_retry(ReadRouting::Any).await?;
        let rows: Vec<Row> = client.query(sql, &param_refs).await.map_err(|e| {
            crate::postgres::database_error(
                format!("Parameterized aggregate query failed: {}", pg_detail(&e)),
                &e,
            )
        })?;

        let results: Vec<std::collections::HashMap<String, serde_json::Value>> =
            rows.iter().map(row_to_map).collect();

        Ok(results)
    }

    async fn execute_parameterized_aggregate_with_session(
        &self,
        sql: &str,
        params: &[serde_json::Value],
        session_vars: &[(&str, &str)],
        routing: ReadRouting,
    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
        if session_vars.is_empty() {
            return self.execute_parameterized_aggregate(sql, params).await;
        }

        let typed = aggregate_params(params);
        let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
            typed.iter().map(|v| v as &(dyn tokio_postgres::types::ToSql + Sync)).collect();

        // Read-only aggregate with session vars; standby-safe → replica-eligible.
        let mut client = self.acquire_read_connection_with_retry(routing).await?;
        let txn = client.build_transaction().start().await.map_err(|e| {
            crate::postgres::database_error(
                format!("Failed to start session-var transaction: {}", pg_detail(&e)),
                &e,
            )
        })?;
        apply_session_vars(&txn, session_vars).await?;
        let rows: Vec<Row> = txn.query(sql, &param_refs).await.map_err(|e| {
            crate::postgres::database_error(
                format!("Parameterized aggregate query failed: {}", pg_detail(&e)),
                &e,
            )
        })?;
        txn.commit().await.map_err(|e| {
            crate::postgres::database_error(
                format!("Failed to commit session-var transaction: {}", pg_detail(&e)),
                &e,
            )
        })?;

        Ok(rows.iter().map(row_to_map).collect())
    }

    // PostgreSQL session variables are applied connection-affinely by the
    // `*_with_session` methods below: `set_config(..., true)` and the operation
    // share one transaction on one connection, so transaction-local GUCs are
    // visible to the function / view (fixes #329).

    async fn execute_where_query_arc_with_session(
        &self,
        view: &str,
        where_clause: Option<&WhereClause>,
        limit: Option<u32>,
        offset: Option<u32>,
        order_by: Option<&[OrderByClause]>,
        session_vars: &[(&str, &str)],
        routing: ReadRouting,
    ) -> Result<Arc<Vec<JsonbValue>>> {
        let (sql, typed_params) =
            build_where_select_sql_ordered(view, where_clause, limit, offset, order_by)?;
        let param_refs = crate::types::as_sql_param_refs(&typed_params);

        // No session variables => no transaction wrapper, but still this query's
        // routing. The fast path used to delegate to `execute_where_query_arc`,
        // which has no routing parameter, so every read that happened not to carry
        // session variables silently reverted to server policy — `read_routing`
        // accepted and dropped on the most common shape there is.
        if session_vars.is_empty() {
            return self
                .execute_raw(&sql, &param_refs, routing)
                .await
                .map(Arc::new)
                .map_err(|e| enrich_undefined_column_error(e, view, where_clause));
        }

        self.execute_raw_with_session(&sql, &param_refs, session_vars, routing)
            .await
            .map(Arc::new)
            .map_err(|e| enrich_undefined_column_error(e, view, where_clause))
    }

    /// `SELECT COUNT(*)`, pushed into the database rather than counted in Rust.
    ///
    /// The trait's default fetches every matching row and takes `.len()`, which
    /// is correct but materialises the whole filtered set — on an unfiltered
    /// list that is the entire table in memory to answer a single integer.
    async fn count_where_query(
        &self,
        view: &str,
        where_clause: Option<&WhereClause>,
        session_vars: &[(&str, &str)],
        routing: ReadRouting,
    ) -> Result<u64> {
        let (sql, typed_params) = super::build_count_sql(view, where_clause)?;
        let param_refs = crate::types::as_sql_param_refs(&typed_params);

        // Structurally read-only: replica-eligible, and `set_config` + SELECT are
        // both fine inside a hot-standby read-only transaction (#407).
        let row = if session_vars.is_empty() {
            let client = self.acquire_read_connection_with_retry(routing).await?;
            client.query_one(&sql, &param_refs).await.map_err(|e| {
                crate::postgres::database_error(
                    format!("Count query failed: {}", pg_detail(&e)),
                    &e,
                )
            })?
        } else {
            // Session variables must land on the *same* connection as the count,
            // or an RLS-filtered page gets an unfiltered total beside it (#329).
            let mut client = self.acquire_read_connection_with_retry(routing).await?;
            let txn = client.build_transaction().start().await.map_err(|e| {
                crate::postgres::database_error(
                    format!("Failed to start count session-var transaction: {}", pg_detail(&e)),
                    &e,
                )
            })?;
            super::database::apply_session_vars(&txn, session_vars).await?;
            let row = txn.query_one(&sql, &param_refs).await.map_err(|e| {
                crate::postgres::database_error(
                    format!("Count query failed: {}", pg_detail(&e)),
                    &e,
                )
            })?;
            txn.commit().await.map_err(|e| {
                crate::postgres::database_error(
                    format!("Failed to commit count session-var transaction: {}", pg_detail(&e)),
                    &e,
                )
            })?;
            row
        };

        let total: i64 = row.get(0);
        // COUNT(*) is never negative, so the bit pattern is the value; `cast_unsigned`
        // states that intent where `as u64` would only imply it.
        Ok(total.cast_unsigned())
    }

    async fn execute_with_projection_arc_with_session(
        &self,
        request: &ProjectionRequest<'_>,
        session_vars: &[(&str, &str)],
        routing: ReadRouting,
    ) -> Result<Arc<Vec<JsonbValue>>> {
        // #1314: a page that also counts what its filter matches, in one statement so the
        // count and the page see the same snapshot.
        if let Some(bound) = request.matched_up_to {
            let (page, params) = match request.projection {
                Some(projection) => build_projection_select_sql(
                    projection,
                    request.view,
                    request.where_clause,
                    request.limit,
                    request.offset,
                    request.order_by,
                )?,
                None => super::build_where_select_sql_ordered(
                    request.view,
                    request.where_clause,
                    request.limit,
                    request.offset,
                    request.order_by,
                )?,
            };
            let (sql, typed_params) = super::with_matched_count(
                &page,
                params,
                request.view,
                request.where_clause,
                bound,
            )?;
            let param_refs = crate::types::as_sql_param_refs(&typed_params);
            if session_vars.is_empty() {
                return self.execute_raw(&sql, &param_refs, routing).await.map(Arc::new);
            }
            return self
                .execute_raw_with_session(&sql, &param_refs, session_vars, routing)
                .await
                .map(Arc::new);
        }

        // No projection => behave like a plain WHERE query, matching
        // execute_with_projection_impl's fallback.
        let Some(projection) = request.projection else {
            return self
                .execute_where_query_arc_with_session(
                    request.view,
                    request.where_clause,
                    request.limit,
                    request.offset,
                    request.order_by,
                    session_vars,
                    routing,
                )
                .await;
        };

        let (sql, typed_params) = build_projection_select_sql(
            projection,
            request.view,
            request.where_clause,
            request.limit,
            request.offset,
            request.order_by,
        )?;
        tracing::debug!("SQL with projection = {}", sql);
        let param_refs = crate::types::as_sql_param_refs(&typed_params);

        // See `execute_where_query_arc_with_session`: the session-free path has to
        // carry the routing too.
        if session_vars.is_empty() {
            return self.execute_raw(&sql, &param_refs, routing).await.map(Arc::new);
        }

        self.execute_raw_with_session(&sql, &param_refs, session_vars, routing)
            .await
            .map(Arc::new)
    }

    /// One statement, one snapshot, one connection held for the delivery (#958).
    ///
    /// The SQL is built by the same two builders the collecting read uses, so a
    /// streamed export and a buffered read of the same query cannot select
    /// different rows — the drift that made `execute_query_direct` disagree with
    /// `count_rows` about a tenant filter (#739).
    async fn execute_composed_with_session(
        &self,
        read: &ComposedLevel,
        session_vars: &[(&str, &str)],
        routing: ReadRouting,
    ) -> Result<Arc<Vec<JsonbValue>>> {
        let (sql, typed_params) = build_composed_select_sql(read)?;
        let param_refs = crate::types::as_sql_param_refs(&typed_params);

        // See `execute_where_query_arc_with_session`: the session-free path has to
        // carry the routing too.
        if session_vars.is_empty() {
            return self.execute_raw(&sql, &param_refs, routing).await.map(Arc::new);
        }

        self.execute_raw_with_session(&sql, &param_refs, session_vars, routing)
            .await
            .map(Arc::new)
    }

    async fn stream_with_projection(
        &self,
        request: &ProjectionRequest<'_>,
        session_vars: &[(&str, &str)],
        routing: ReadRouting,
    ) -> Result<JsonbRowStream> {
        let (sql, typed_params) = match request.projection {
            Some(projection) => build_projection_select_sql(
                projection,
                request.view,
                request.where_clause,
                request.limit,
                request.offset,
                request.order_by,
            )?,
            None => build_where_select_sql_ordered(
                request.view,
                request.where_clause,
                request.limit,
                request.offset,
                request.order_by,
            )?,
        };

        super::streaming::stream_rows(self, sql, typed_params, session_vars, routing, |row, sql| {
            jsonb_cell(row, 0, sql)
        })
        .await
        .map_err(|e| enrich_undefined_column_error(e, request.view, request.where_clause))
    }

    /// The column-shaped streaming read behind gRPC server-streaming (#958).
    ///
    /// Routed to the primary like its collecting sibling: `execute_row_query`
    /// reaches `execute_raw_query`, and a surface that executes composed SQL is
    /// never sent to a replica.
    async fn stream_row_query(
        &self,
        view_name: &str,
        columns: &[crate::types::ColumnSpec],
        where_sql: Option<&str>,
        order_by: Option<&str>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<ColumnRowStream> {
        let sql = crate::traits::build_row_query_sql(view_name, where_sql, order_by, limit, offset);
        let columns = columns.to_vec();

        super::streaming::stream_rows(
            self,
            sql,
            Vec::new(),
            &[],
            ReadRouting::Primary,
            move |row, _sql| Ok(crate::traits::row_to_column_values(&row_to_map(row), &columns)),
        )
        .await
    }

    /// The session-pinned collecting row read (#1351).
    ///
    /// Same shape as [`count_where_query`](Self::count_where_query): with no session
    /// variables it is a plain read; with them it is one transaction, so `set_config`
    /// and the SELECT land on the same connection and an RLS policy backed by
    /// `current_setting()` sees them (#329).
    async fn execute_row_query_with_session(
        &self,
        view_name: &str,
        columns: &[crate::types::ColumnSpec],
        where_sql: Option<&str>,
        order_by: Option<&str>,
        limit: Option<u32>,
        offset: Option<u32>,
        session_vars: &[(&str, &str)],
    ) -> Result<Vec<Vec<crate::types::ColumnValue>>> {
        if session_vars.is_empty() {
            return self
                .execute_row_query(view_name, columns, where_sql, order_by, limit, offset)
                .await;
        }

        let sql = crate::traits::build_row_query_sql(view_name, where_sql, order_by, limit, offset);

        let mut client = self.acquire_connection_with_retry().await?;
        let txn = client.build_transaction().start().await.map_err(|e| {
            crate::postgres::database_error(
                format!("Failed to start row-read session-var transaction: {}", pg_detail(&e)),
                &e,
            )
        })?;
        apply_session_vars(&txn, session_vars).await?;
        let rows: Vec<Row> = txn.query(sql.as_str(), &[]).await.map_err(|e| {
            crate::postgres::database_error(
                format!("Row query execution failed: {}", pg_detail(&e)),
                &e,
            )
        })?;
        txn.commit().await.map_err(|e| {
            crate::postgres::database_error(
                format!("Failed to commit row-read session-var transaction: {}", pg_detail(&e)),
                &e,
            )
        })?;

        Ok(rows
            .iter()
            .map(|row| crate::traits::row_to_column_values(&row_to_map(row), columns))
            .collect())
    }

    /// The session-pinned streaming row read (#1351).
    ///
    /// `stream_rows` already pins session variables for the life of the portal —
    /// the non-session arm above passes `&[]` to the very same call.
    async fn stream_row_query_with_session(
        &self,
        view_name: &str,
        columns: &[crate::types::ColumnSpec],
        where_sql: Option<&str>,
        order_by: Option<&str>,
        limit: Option<u32>,
        offset: Option<u32>,
        session_vars: &[(&str, &str)],
    ) -> Result<ColumnRowStream> {
        let sql = crate::traits::build_row_query_sql(view_name, where_sql, order_by, limit, offset);
        let columns = columns.to_vec();

        super::streaming::stream_rows(
            self,
            sql,
            Vec::new(),
            session_vars,
            ReadRouting::Primary,
            move |row, _sql| Ok(crate::traits::row_to_column_values(&row_to_map(row), &columns)),
        )
        .await
    }

    async fn explain_query(
        &self,
        sql: &str,
        _params: &[serde_json::Value],
    ) -> Result<serde_json::Value> {
        // Defense-in-depth: reject multi-statement input even though this SQL is
        // compiler-generated. A semicolon would allow a second statement to be
        // appended to the EXPLAIN prefix.
        if sql.contains(';') {
            return Err(FraiseQLError::Validation {
                message: "EXPLAIN SQL must be a single statement".into(),
                path:    None,
            });
        }
        let explain_sql = format!("EXPLAIN (ANALYZE false, FORMAT JSON) {sql}");
        // Read-only (plan only, ANALYZE false): replica-eligible (#407).
        let client = self.acquire_read_connection_with_retry(ReadRouting::Any).await?;
        let rows: Vec<Row> = client.query(explain_sql.as_str(), &[]).await.map_err(|e| {
            crate::postgres::database_error(format!("EXPLAIN failed: {}", pg_detail(&e)), &e)
        })?;

        if let Some(row) = rows.first() {
            let plan: serde_json::Value = row.try_get(0).map_err(|e| FraiseQLError::Database {
                message:    format!("Failed to parse EXPLAIN output: {e}"),
                sql_state:  None,
                constraint: None,
            })?;
            Ok(plan)
        } else {
            Ok(serde_json::Value::Null)
        }
    }

    async fn query_stats(&self, limit: u32) -> Result<Vec<crate::types::QueryStatEntry>> {
        self.pg_query_stats(limit).await
    }

    async fn query_stats_by_id(&self, id: &str) -> Result<Option<crate::types::QueryStatEntry>> {
        self.pg_query_stats_by_id(id).await
    }

    async fn reset_query_stats(&self) -> Result<()> {
        self.pg_reset_query_stats().await
    }

    /// The operator SQL console (#962). The containment lives in the private
    /// `postgres::adapter::admin_sql` module; see [`AdminSqlRequest`] for what
    /// each bound is and how PostgreSQL — not a parse of the statement text —
    /// enforces it.
    ///
    /// [`AdminSqlRequest`]: crate::traits::AdminSqlRequest
    async fn execute_admin_sql(
        &self,
        request: &crate::traits::AdminSqlRequest,
    ) -> Result<crate::traits::AdminSqlOutcome> {
        super::admin_sql::execute_admin_sql_impl(self, request).await
    }
}

// async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
#[async_trait]
impl Writer for PostgresAdapter {
    async fn execute_write(
        &self,
        request: &crate::traits::WriteRequest<'_>,
        gate: crate::traits::MutationRowGate<'_>,
    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
        let mut rows =
            run_functions_in_txn(self, std::slice::from_ref(request), &|_, rows| gate(rows), false)
                .await?;
        Ok(rows.pop().unwrap_or_default())
    }

    async fn execute_writes(
        &self,
        requests: &[crate::traits::WriteRequest<'_>],
        gate: crate::traits::BatchRowGate<'_>,
    ) -> Result<Vec<Vec<std::collections::HashMap<String, serde_json::Value>>>> {
        run_functions_in_txn(self, requests, gate, true).await
    }
}