giong-postgres 1.5.2

A PostgreSQL client and connection pool for the giong thread-per-core runtime
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
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
//! A connection: requests are queued, written by one task and answered in
//! order by another, so that any number of tasks can use one connection at
//! once and their statements share round trips.

use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
use std::future::{poll_fn, Future};
use std::net::Shutdown;
use std::ops::Deref;
use std::pin::Pin;
use std::rc::{Rc, Weak};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll, Waker};

use crate::config::Config;
use crate::connect::{self, ReadBuf, Startup, Stream};
use crate::error::{DbError, Error, ErrorKind};
use crate::protocol::{self, parse_backend, Backend, MAX_PARAMS};
use crate::row::{Column, ResultSet, Row, RowsBuilder};
use crate::types::{ToSql, Type};

/// A connection to a PostgreSQL server.
///
/// Every method takes `&self`, so tasks can share a client (through an `Rc`)
/// and run statements at the same time: their messages go out together and
/// the server answers them in order, one round trip for all of them
/// (pipelining). A [`Transaction`] needs `&mut self`, so that no other task
/// can slip a statement into it.
///
/// Statements are prepared on the server the first time the connection runs
/// them and kept (see
/// [`Config::statement_cache_capacity`](crate::Config::statement_cache_capacity)),
/// so a statement that ran before takes a single round trip.
///
/// A client lives on the worker thread that opened it. Dropping it closes the
/// connection once the statements already sent have been written.
pub struct Client {
    conn: Rc<Conn>,
}

/// A prepared statement on one connection.
pub(crate) struct Statement {
    sql: Rc<str>,
    name: Box<str>,
    params: Vec<Type>,
    columns: Rc<[Column]>,
    /// Set for a statement that is not cached: the connection, so that the
    /// statement can be closed if it was never run.
    conn: Option<Weak<Conn>>,
    closed: Cell<bool>,
    /// It failed in a batch because it writes (`25006`): it is sent on its
    /// own from then on.
    writes: Cell<bool>,
}

impl Drop for Statement {
    fn drop(&mut self) {
        let Some(conn) = self.conn.as_ref().and_then(Weak::upgrade) else {
            return;
        };
        if !self.closed.get() {
            // No Sync: the close travels with the next request.
            if let Ok(mut st) = conn.state.try_borrow_mut() {
                if st.broken.is_none() {
                    let _ = protocol::close_statement(&mut st.out, &self.name);
                    // A batch must end `out` to take more statements.
                    st.batch = None;
                }
            }
        }
    }
}

/// The error for a statement sent in a transaction that can no longer be
/// committed.
#[cold]
#[inline(never)]
fn abandoned() -> Error {
    Error::new(
        ErrorKind::Db,
        "a statement of this transaction was given up before its answer came (its future was \
         dropped, by a timeout say), and it may have run, so the transaction cannot be \
         committed; this statement was not sent. Drop the transaction (which rolls it back) and \
         run it again from the start",
    )
}

/// Why a shared connection was closed under its statements.
const LEFT_OPEN: &str = "a statement sent through the pool's shared methods (Pool::batch_execute) \
     left a transaction open on a connection other tasks share, so the connection was closed and \
     the transaction rolled back, with every statement sent on it since BEGIN, this one included. \
     Run transactions on a connection of the task's own: pool.get().await?.transaction()";

/// What a pool sends when a connection taken with `get()` comes back, so
/// that the next task finds a clean session: `DISCARD ALL` without
/// `DEALLOCATE ALL` (which would also drop the statement cache) and without
/// `DISCARD PLANS` (plans are not session state). `RESET ALL` returns the
/// settings sent when connecting (`statement_timeout`, `Config::param`) to
/// those values, not to the server's defaults.
const RESET: &str = "SET SESSION AUTHORIZATION DEFAULT; RESET ALL; CLOSE ALL; UNLISTEN *; \
     SELECT pg_advisory_unlock_all(); DISCARD TEMP; DISCARD SEQUENCES";

/// The prefix of the names of the statements this crate prepares, chosen to
/// stay clear of names an application would give its own.
const NAME_PREFIX: &str = "__giong_";

/// The state shared by a client and its two tasks.
struct Conn {
    weak: Weak<Conn>,
    stream: Stream,
    state: RefCell<State>,
    /// When the oldest unanswered request became the oldest; `None` with
    /// nothing in flight.
    head_since: Cell<Option<giong::time::Instant>>,
    config: Config,
    key: Option<(i32, i32)>,
    /// Several tasks send statements on this connection at once (it is among
    /// a pool's shared connections): none of them may leave a transaction
    /// open, which would take in the statements of the others.
    shared: Cell<bool>,
    /// Woken when nothing is in flight any more, or the connection fails.
    idle_wakers: RefCell<Vec<Waker>>,
    /// Requests sent since the connection opened: a pool compares the count
    /// before and after lending it, to know whether it was used.
    requests: Cell<u64>,
    /// While a pool lends the connection to one task: the flag its cancel
    /// tokens check, cleared when the connection goes back.
    lease: RefCell<Option<Arc<Lease>>>,
    /// The server refused a write because it is a standby (it was a primary
    /// once, or DNS still points at it): a pool closes the connection rather
    /// than keep sending writes there.
    retire: Cell<bool>,
    /// A statement ran SQL-level `PREPARE`, whose prepared statement outlives
    /// the task that made it.
    user_prepared: Cell<bool>,
    /// The state of the [`Transaction`] open on this connection.
    tx: Cell<Tx>,
}

/// Where a [`Transaction`] stands, as the client sees it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Tx {
    /// No `Transaction` is open.
    None,
    Open,
    /// A statement in it was given up before its answer came (its future
    /// was dropped): it may have run, so committing would commit work the
    /// application believes undone. Nothing more is sent until it ends.
    Abandoned,
}

struct State {
    /// Messages waiting to be written.
    out: Vec<u8>,
    writer: Option<Waker>,
    /// One entry per `Sync` or simple query sent, answered in order.
    queue: VecDeque<Rc<Slot>>,
    /// Why the connection stopped working, once it has.
    broken: Option<Error>,
    /// The client was dropped: write what is queued, then `Terminate`.
    closing: bool,
    /// The transaction status from the last `ReadyForQuery`.
    status: u8,
    cache: HashMap<Rc<str>, Entry>,
    clock: u64,
    next_name: u64,
    server_params: Vec<(String, String)>,
    /// The last request in `out`, while it may still grow into a batch, or
    /// the batch it grew into.
    batch: Option<OpenBatch>,
    /// How many slots of `queue` are a batch's guard or end, not requests.
    extra: usize,
    /// [`READ_ONLY`] is prepared (or its Parse is queued).
    read_only_prepared: bool,
    /// The statements of the batch being answered that have their answer:
    /// they complete with the batch's `ReadyForQuery`, once it is known
    /// whether its transaction committed.
    held: Vec<Rc<Slot>>,
    /// The batch being answered had an error: its transaction rolled back.
    batch_failed: bool,
}

/// Statements in `out` that end with one `Sync` (see [`Config::batch_reads`]).
struct OpenBatch {
    /// Where the first statement's messages start in `out`.
    start: usize,
    /// How many statements it holds.
    members: usize,
}

/// The most statements in one batch.
const BATCH_MAX: usize = 16;
/// The length of a `Sync` message.
const SYNC_LEN: usize = 5;
/// Makes the transaction of a batch read-only, until its `Sync`: a
/// statement that writes then fails instead of writing what the batch's
/// rollback would undo.
///
/// It also caps how long a statement of the batch waits for a lock, at 50 ms
/// (a constant: computed from the session's `lock_timeout`, the guard cost
/// the batch 10% of its speed): a batch holds the locks its statements took
/// until it ends, so a statement that waits behind another transaction while
/// earlier ones hold their locks could close a cycle that the statements one
/// by one never would (a migration that locks two tables, say), and the
/// server would roll back one side after its `deadlock_timeout`. Given up within 50 ms instead, the wait fails the
/// batch, whose statements run again on their own and wait as they would
/// without batches.
const READ_ONLY: &str =
    "SELECT set_config('transaction_read_only', 'on', true), set_config('lock_timeout', '50ms', true)";

/// The name [`READ_ONLY`] is prepared under, once per connection.
const READ_ONLY_NAME: &str = "__giong_read_only";

/// Bind and Execute of [`READ_ONLY`], after its Parse unless `prepared`.
fn read_only_guard(out: &mut Vec<u8>, prepared: bool) {
    let parsed = if prepared {
        Ok(())
    } else {
        protocol::parse(out, READ_ONLY_NAME, READ_ONLY)
    };
    let encoded = parsed
        .and_then(|()| {
            protocol::bind(
                out,
                READ_ONLY_NAME,
                0,
                |_, _| unreachable!("no parameters"),
                [].into_iter(),
            )
        })
        .and_then(|()| protocol::execute(out));
    debug_assert!(encoded.is_ok(), "a constant statement encodes");
}

enum Entry {
    Ready { stmt: Rc<Statement>, used: u64 },
    Preparing(Rc<Slot>),
}

/// A request in flight and what has arrived for it.
struct Slot {
    kind: Kind,
    /// Sent while the connection was shared.
    shared: bool,
    /// The pool's session reset: if it fails, the session is in an unknown
    /// state, so the connection is closed rather than reused.
    close_on_error: bool,
    /// A statement of an open transaction: giving it up before its answer
    /// marks the transaction [`Tx::Abandoned`].
    in_tx: Option<Weak<Conn>>,
    /// Its part in a batch: it ends with its own `CommandComplete` or
    /// error, or (the batch's end) with the `ReadyForQuery`.
    batch: Cell<Role>,
    inner: RefCell<SlotInner>,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Role {
    /// A request of its own, ended by its `ReadyForQuery`.
    Alone,
    /// One of the batch's statements.
    Member,
    /// The statement that makes the batch's transaction read-only.
    Guard,
    /// The batch's `Sync`.
    End,
}

enum Kind {
    Prepare {
        sql: Rc<str>,
        name: Box<str>,
        cached: bool,
    },
    Execute {
        stmt: Rc<Statement>,
    },
    Simple,
}

/// The tasks waiting for a request's answer: almost always one, which is
/// kept without an allocation.
#[derive(Default)]
struct Wakers {
    first: Option<Waker>,
    more: Vec<Waker>,
}

impl Wakers {
    /// Adds `waker` unless it would wake a task already here.
    fn register(&mut self, waker: &Waker) {
        match &self.first {
            None => self.first = Some(waker.clone()),
            Some(w) if w.will_wake(waker) => {}
            Some(_) => {
                if !self.more.iter().any(|w| w.will_wake(waker)) {
                    self.more.push(waker.clone());
                }
            }
        }
    }

    fn wake_all(&mut self) {
        if let Some(w) = self.first.take() {
            w.wake();
        }
        for w in self.more.drain(..) {
            w.wake();
        }
    }
}

#[derive(Default)]
struct SlotInner {
    wakers: Wakers,
    /// Nobody is waiting for the result any more: rows are not kept.
    abandoned: bool,
    /// The outcome was handed to the caller.
    delivered: bool,
    error: Option<Error>,
    params: Option<Vec<Type>>,
    columns: Option<Vec<Column>>,
    rows: RowsBuilder,
    tag: Option<Tag>,
    /// The server confirmed the Bind: the statement started running.
    bound: bool,
    /// The transaction status in the `ReadyForQuery` that ended the request.
    status: u8,
    /// The request failed on a stale cached statement before running, outside
    /// a transaction: running it again is safe.
    retry: bool,
    /// A statement of a batch that did not run (the server skipped it after
    /// another failed), or that failed because it writes: it is sent again on
    /// its own.
    alone: bool,
    outcome: Option<Result<Response, Error>>,
}

enum Response {
    Statement(Rc<Statement>),
    Rows(ResultSet, Option<Tag>),
    Done(Option<Tag>),
}

impl Slot {
    fn new(kind: Kind, shared: bool, close_on_error: bool, in_tx: Option<Weak<Conn>>) -> Rc<Self> {
        Rc::new(Slot {
            kind,
            shared,
            close_on_error,
            in_tx,
            batch: Cell::new(Role::Alone),
            inner: RefCell::default(),
        })
    }
}

/// Waits for a slot's outcome. Dropping it lets the reader throw the rows
/// away; the statement still runs.
struct Wait {
    slot: Rc<Slot>,
}

impl Future for Wait {
    type Output = Result<Response, Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut inner = self.slot.inner.borrow_mut();
        let shared = matches!(self.slot.kind, Kind::Prepare { .. });
        match &inner.outcome {
            Some(Ok(Response::Statement(stmt))) if shared => {
                return Poll::Ready(Ok(Response::Statement(stmt.clone())))
            }
            Some(Err(e)) if shared => return Poll::Ready(Err(e.clone())),
            Some(_) => {
                inner.delivered = true;
                return Poll::Ready(inner.outcome.take().expect("checked"));
            }
            None => {}
        }
        inner.wakers.register(cx.waker());
        Poll::Pending
    }
}

impl Drop for Wait {
    fn drop(&mut self) {
        if matches!(self.slot.kind, Kind::Prepare { .. }) {
            return;
        }
        // Its answer arrived (handed over or not): its outcome is known.
        let known = {
            let mut inner = self.slot.inner.borrow_mut();
            inner.abandoned = true;
            inner.rows = RowsBuilder::default();
            inner.delivered || inner.outcome.is_some()
        };
        // The application gave up on a statement of its transaction, which
        // may run all the same: the transaction must not commit it unseen.
        if !known && self.slot.in_tx.is_some() {
            abandon_tx(&self.slot);
        }
    }
}

/// Marks the transaction `slot` was sent in as abandoned (see [`Tx::Abandoned`]).
#[cold]
#[inline(never)]
fn abandon_tx(slot: &Slot) {
    if let Some(conn) = slot.in_tx.as_ref().and_then(Weak::upgrade) {
        if conn.tx.get() == Tx::Open {
            conn.tx.set(Tx::Abandoned);
        }
    }
}

/// Whether the server's error says a prepared statement no longer fits: the
/// schema changed under its cached plan (`0A000` from
/// `RevalidateCachedQuery`; the message is matched too, for servers that send
/// no routine, but it is translated when `lc_messages` is not English), or it
/// does not exist any more (`26000`, after `DEALLOCATE` or `DISCARD ALL`).
fn is_stale(db: &DbError) -> bool {
    match db.code() {
        "26000" => true,
        "0A000" => {
            db.routine() == Some("RevalidateCachedQuery")
                || db.message().contains("cached plan must not change")
        }
        _ => false,
    }
}

/// What this crate uses of a command tag (`INSERT 0 5`, `ROLLBACK`), read
/// as it arrives so that the tag itself need not be kept.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Tag {
    /// The rows it reports: `INSERT 0 5`, `UPDATE 3`, `SELECT 7`; 0 for a
    /// tag without a count.
    rows: u64,
    /// `COMMIT` ended a failed transaction with a rollback.
    rollback: bool,
}

impl Tag {
    fn of(tag: &str) -> Self {
        Self {
            rows: tag
                .rsplit(' ')
                .next()
                .and_then(|n| n.parse().ok())
                .unwrap_or(0),
            rollback: tag == "ROLLBACK",
        }
    }
}

impl Client {
    /// Opens a connection and logs in.
    ///
    /// Fails with [`ErrorKind::Connect`] when the server cannot be reached
    /// within [`Config::connect_timeout`](crate::Config::connect_timeout),
    /// [`ErrorKind::Auth`] when it refuses the credentials, and
    /// [`ErrorKind::Config`] when the configuration is incomplete.
    ///
    /// # Panics
    ///
    /// Panics when called outside of a giong runtime.
    ///
    /// Cancel safe: if the future is dropped, the connection being opened is
    /// closed.
    pub async fn connect(config: &Config) -> Result<Client, Error> {
        let startup = connect::connect(config).await?;
        Ok(Self::start(startup, config.clone()))
    }

    pub(crate) fn start(startup: Startup, config: Config) -> Client {
        let Startup {
            stream,
            buf,
            params,
            key,
            status,
        } = startup;
        let conn = Rc::new_cyclic(|weak| Conn {
            weak: weak.clone(),
            head_since: Cell::new(None),
            stream,
            config,
            key,
            shared: Cell::new(false),
            idle_wakers: RefCell::new(Vec::new()),
            requests: Cell::new(0),
            lease: RefCell::new(None),
            retire: Cell::new(false),
            user_prepared: Cell::new(false),
            tx: Cell::new(Tx::None),
            state: RefCell::new(State {
                out: Vec::new(),
                writer: None,
                queue: VecDeque::new(),
                extra: 0,
                read_only_prepared: false,
                held: Vec::new(),
                batch_failed: false,
                broken: None,
                closing: false,
                status,
                cache: HashMap::new(),
                clock: 0,
                next_name: 0,
                server_params: params,
                batch: None,
            }),
        });
        giong::spawn(read_loop(conn.clone(), buf));
        giong::spawn(write_loop(conn.clone()));
        Client { conn }
    }

    /// Runs a statement and returns its rows.
    ///
    /// Parameters are written `$1`, `$2`... in the SQL and passed in order:
    ///
    /// ```no_run
    /// # async fn f(client: &giong_postgres::Client) -> Result<(), giong_postgres::Error> {
    /// let rows = client
    ///     .query("SELECT id, email FROM users WHERE created_at > now() - $1::interval", &[&"7 days"])
    ///     .await?;
    /// for row in &rows {
    ///     let id: i64 = row.get("id")?;
    ///     let email: &str = row.get("email")?;
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// The server decides each parameter's type from the SQL; see the
    /// [`types`](crate::types) module for which Rust types fit which.
    ///
    /// Not cancel safe: if the future is dropped, the statement may still run
    /// on the server, and what it changes stays; the connection stays usable.
    /// Inside a [`Transaction`], a later [`commit`](Transaction::commit)
    /// commits it.
    pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
        let (set, _) = self.run(sql, params, false).await?;
        Ok(set.into_rows())
    }

    /// [`query`](Self::query) for the pool's shared connections: `batch`
    /// lets the statement join a batch ([`Config::batch_reads`]).
    pub(crate) async fn query_shared(
        &self,
        sql: &str,
        params: &[&dyn ToSql],
        batch: bool,
    ) -> Result<Vec<Row>, Error> {
        let (set, _) = self.run(sql, params, batch).await?;
        Ok(set.into_rows())
    }

    /// Runs a statement that must return exactly one row, and returns it.
    ///
    /// No row or several rows fail with [`ErrorKind::RowCount`].
    ///
    /// Not cancel safe, like [`query`](Self::query).
    pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
        one_row(self.query(sql, params).await?)
    }

    /// Runs a statement that returns at most one row.
    ///
    /// Several rows fail with [`ErrorKind::RowCount`].
    ///
    /// Not cancel safe, like [`query`](Self::query).
    pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
        at_most_one_row(self.query(sql, params).await?)
    }
}

/// The one row of a result, or [`ErrorKind::RowCount`].
pub(crate) fn one_row(mut rows: Vec<Row>) -> Result<Row, Error> {
    match rows.len() {
        1 => Ok(rows.pop().expect("one row")),
        n => Err(Error::new(
            ErrorKind::RowCount,
            format!(
                "the statement returned {n} rows where exactly one was expected; use \
                     query_opt for zero or one, or query for any number"
            ),
        )),
    }
}

/// The row of a result of at most one, or [`ErrorKind::RowCount`].
pub(crate) fn at_most_one_row(mut rows: Vec<Row>) -> Result<Option<Row>, Error> {
    match rows.len() {
        0 | 1 => Ok(rows.pop()),
        n => Err(Error::new(
            ErrorKind::RowCount,
            format!(
                "the statement returned {n} rows where at most one was expected; add a \
                     LIMIT, or use query"
            ),
        )),
    }
}

impl Client {
    /// Runs a statement and returns the number of rows it inserted, updated
    /// or deleted (or returned, for a `SELECT`).
    ///
    /// Not cancel safe, like [`query`](Self::query).
    pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
        let (_, tag) = self.run(sql, params, false).await?;
        Ok(tag.map_or(0, |t| t.rows))
    }

    /// Runs SQL that may hold several statements separated by `;`, with no
    /// parameters, such as a schema migration. Rows they return are thrown
    /// away.
    ///
    /// The statements run in one implicit transaction unless the SQL has its
    /// own `BEGIN` and `COMMIT`: if one fails, the earlier ones are rolled
    /// back.
    ///
    /// Not cancel safe: if the future is dropped, the statements may still run
    /// on the server, and what they change stays.
    pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
        let _wait = giong::observe::wait(giong::observe::Wait::Query, "postgres");
        let slot = self
            .conn
            .enqueue(Kind::Simple, |out| protocol::query(out, sql))?;
        Wait { slot }.await.map(|_| ())
    }

    /// Starts a transaction.
    ///
    /// It is committed by [`Transaction::commit`]; dropping it without a
    /// commit rolls it back. While it is open, it holds the client mutably,
    /// so no other statement can run on the connection outside it.
    ///
    /// ```no_run
    /// # async fn f(client: &mut giong_postgres::Client) -> Result<(), giong_postgres::Error> {
    /// let tx = client.transaction().await?;
    /// tx.execute("UPDATE accounts SET balance = balance - $1 WHERE id = $2", &[&100i64, &1i64]).await?;
    /// tx.execute("UPDATE accounts SET balance = balance + $1 WHERE id = $2", &[&100i64, &2i64]).await?;
    /// tx.commit().await?;
    /// # Ok(()) }
    /// ```
    ///
    /// Cancel safe: if the future is dropped, a transaction it began is rolled
    /// back.
    pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
        // The guard exists before BEGIN is sent: if this future is dropped
        // while waiting, the guard's drop rolls the transaction back.
        let tx = Transaction {
            client: self,
            done: false,
        };
        tx.client.conn.tx.set(Tx::Open);
        tx.client.batch_execute("BEGIN").await?;
        Ok(tx)
    }

    /// A handle that asks the server to cancel whatever this connection is
    /// running, from any thread.
    ///
    /// A token taken from a [`PooledClient`](crate::PooledClient) stops
    /// working when the connection goes back to the pool, so that it cannot
    /// cancel the statements of the tasks that use the connection next; and
    /// a connection that goes back while a request from such a token is on
    /// its way is closed rather than lent to another task.
    pub fn cancel_token(&self) -> CancelToken {
        CancelToken {
            config: self.conn.config.without_password(),
            key: self.conn.key,
            lease: self.conn.lease.borrow().clone(),
        }
    }

    /// A setting the server reported, such as `server_version`, `TimeZone`
    /// or `integer_datetimes`.
    pub fn parameter(&self, name: &str) -> Option<String> {
        let st = self.conn.state.borrow();
        st.server_params
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, v)| v.clone())
    }

    /// Whether the connection has stopped working. A closed client fails
    /// every statement with [`ErrorKind::Closed`].
    pub fn is_closed(&self) -> bool {
        self.conn.state.borrow().broken.is_some()
    }

    /// How many requests have been sent and not answered yet.
    pub fn in_flight(&self) -> usize {
        let st = self.conn.state.borrow();
        st.queue.len() - st.extra + st.held.len()
    }

    /// How long the oldest unanswered request has been waiting for its
    /// answer; zero with nothing in flight.
    pub(crate) fn waiting_for(&self, now: giong::time::Instant) -> std::time::Duration {
        self.conn
            .head_since
            .get()
            .map_or(std::time::Duration::ZERO, |t| {
                now.saturating_duration_since(t)
            })
    }

    /// Whether the last answer from the server said a transaction was open.
    pub(crate) fn in_transaction(&self) -> bool {
        self.conn.state.borrow().status != b'I'
    }

    /// Marks the connection as shared between tasks, or as one task's own.
    /// Statements sent while it is shared must not leave a transaction open:
    /// if one does, the connection is closed, which rolls the transaction
    /// back, rather than let the statements of other tasks run inside it.
    pub(crate) fn set_shared(&self, shared: bool) {
        self.conn.shared.set(shared);
    }

    /// Wakes `waker` once nothing is in flight, or the connection fails.
    pub(crate) fn wake_when_idle(&self, waker: &Waker) {
        let mut wakers = self.conn.idle_wakers.borrow_mut();
        if !wakers.iter().any(|w| w.will_wake(waker)) {
            wakers.push(waker.clone());
        }
    }

    /// How many requests have been sent on the connection since it opened.
    pub(crate) fn requests(&self) -> u64 {
        self.conn.requests.get()
    }

    /// Starts lending the connection to one task: cancel tokens taken from
    /// now on work until [`end_lease`](Self::end_lease).
    pub(crate) fn begin_lease(&self) {
        *self.conn.lease.borrow_mut() = Some(Arc::new(Lease::default()));
    }

    /// Ends the lease: the cancel tokens taken during it stop working.
    /// Returns whether a cancel request taken during it may still be on its
    /// way to the server, in which case the connection must not be lent to
    /// another task: the request would stop that task's statement.
    pub(crate) fn end_lease(&self) -> bool {
        self.conn
            .lease
            .borrow_mut()
            .take()
            .is_some_and(|lease| lease.end())
    }

    /// Whether the connection should not be used any more although it works:
    /// the server refused a write because it is a standby.
    pub(crate) fn should_retire(&self) -> bool {
        self.conn.retire.get()
    }

    /// Queues the pool's session reset ([`RESET`]), and `DEALLOCATE ALL` if a
    /// statement ran SQL-level `PREPARE` (the statement cache is emptied with
    /// it). Nobody waits for the result; if it fails, the connection is
    /// closed.
    pub(crate) fn reset_session(&self) {
        let deallocate = self.conn.user_prepared.replace(false);
        let sql = if deallocate {
            let mut st = self.conn.state.borrow_mut();
            st.cache.clear();
            st.read_only_prepared = false;
            format!("{RESET}; DEALLOCATE ALL")
        } else {
            RESET.to_owned()
        };
        if let Ok(slot) = self
            .conn
            .enqueue_with(Kind::Simple, true, |out| protocol::query(out, &sql))
        {
            slot.inner.borrow_mut().abandoned = true;
        }
    }

    /// Queues a statement whose result nobody waits for.
    pub(crate) fn send_and_forget(&self, sql: &str) {
        if let Ok(slot) = self
            .conn
            .enqueue(Kind::Simple, |out| protocol::query(out, sql))
        {
            slot.inner.borrow_mut().abandoned = true;
        }
    }

    async fn run(
        &self,
        sql: &str,
        params: &[&dyn ToSql],
        batch: bool,
    ) -> Result<(ResultSet, Option<Tag>), Error> {
        let _wait = giong::observe::wait(giong::observe::Wait::Query, "postgres");
        if params.len() > MAX_PARAMS {
            return Err(Error::conversion(format!(
                "{} parameters were given; a statement can have at most {MAX_PARAMS}",
                params.len()
            )));
        }
        // A cached statement the schema changed under fails before running
        // and is dropped from the cache: it is prepared again and run once
        // more, unless that happened inside a transaction, which the error
        // aborted.
        let mut retried = false;
        // A statement a batch skipped, or that writes, is sent again alone.
        let mut alone = !batch;
        loop {
            let slot = self.send(sql, params, !alone).await?;
            let result = Wait { slot: slot.clone() }.await;
            if result.is_err() {
                let (skipped, stale) = {
                    let inner = slot.inner.borrow();
                    (inner.alone, inner.retry)
                };
                if skipped && !alone {
                    alone = true;
                    continue;
                }
                if stale && !retried {
                    retried = true;
                    continue;
                }
            }
            return match result? {
                Response::Rows(set, tag) => Ok((set, tag)),
                _ => unreachable!("an execute slot ends with rows"),
            };
        }
    }

    /// Prepares the statement if needed and sends a Bind and Execute for it.
    async fn send(&self, sql: &str, params: &[&dyn ToSql], batch: bool) -> Result<Rc<Slot>, Error> {
        let stmt = self.conn.statement(sql).await?;
        if stmt.params.len() != params.len() {
            return Err(Error::conversion(format!(
                "the statement has {} parameters but {} values were given",
                stmt.params.len(),
                params.len()
            )));
        }
        let cached = stmt.conn.is_none();
        let encode = |out: &mut Vec<u8>| {
            protocol::bind(
                out,
                &stmt.name,
                params.len(),
                |i, out| {
                    params[i].to_sql(stmt.params[i], out).map_err(|e| {
                        e.context(&format!("parameter ${} ({})", i + 1, stmt.params[i]))
                    })
                },
                stmt.columns.iter().map(|c| c.ty().binary_result()),
            )?;
            protocol::execute(out)
        };
        let kind = Kind::Execute { stmt: stmt.clone() };
        let slot = if batch
            && cached
            && !stmt.writes.get()
            && self.conn.shared.get()
            && self.conn.tx.get() == Tx::None
        {
            self.conn.enqueue_batched(kind, encode)?
        } else {
            self.conn.enqueue(kind, |out| {
                encode(out)?;
                protocol::sync(out);
                Ok(())
            })?
        };
        if !cached {
            // In a request of its own: after an error the server skips the
            // rest of a request, and the statement must go either way.
            let close = self.conn.enqueue(Kind::Simple, |out| {
                protocol::close_statement(out, &stmt.name)?;
                protocol::sync(out);
                Ok(())
            });
            if let Ok(close) = close {
                close.inner.borrow_mut().abandoned = true;
                stmt.closed.set(true);
            }
        }
        Ok(slot)
    }
}

impl Drop for Client {
    fn drop(&mut self) {
        let mut st = self.conn.state.borrow_mut();
        st.closing = true;
        if st.broken.is_none() {
            protocol::terminate(&mut st.out);
            st.batch = None;
        }
        if let Some(w) = st.writer.take() {
            w.wake();
        }
    }
}

impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("server", &self.conn.config.target())
            .field("in_flight", &self.in_flight())
            .field("closed", &self.is_closed())
            .finish()
    }
}

impl Conn {
    /// Appends a request's messages and queues its slot, or fails without
    /// sending anything.
    fn enqueue(
        &self,
        kind: Kind,
        encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
    ) -> Result<Rc<Slot>, Error> {
        self.enqueue_with(kind, false, encode)
    }

    /// The link a request sent in the open transaction keeps, or the error
    /// if the transaction can no longer be committed.
    #[cold]
    #[inline(never)]
    fn in_tx(&self) -> Result<Weak<Conn>, Error> {
        match self.tx.get() {
            Tx::Abandoned => Err(abandoned()),
            _ => Ok(self.weak.clone()),
        }
    }

    fn enqueue_with(
        &self,
        kind: Kind,
        close_on_error: bool,
        encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
    ) -> Result<Rc<Slot>, Error> {
        let mut st = self.state.borrow_mut();
        if let Some(e) = &st.broken {
            return Err(e.clone());
        }
        let in_tx = if self.tx.get() == Tx::None {
            None
        } else {
            Some(self.in_tx()?)
        };
        // Anything else written after a batch ends it.
        st.batch = None;
        let start = st.out.len();
        if let Err(e) = encode(&mut st.out) {
            st.out.truncate(start);
            return Err(e);
        }
        let slot = Slot::new(kind, self.shared.get(), close_on_error, in_tx);
        self.requests.set(self.requests.get() + 1);
        if st.queue.is_empty() {
            self.head_since.set(Some(giong::time::Instant::now()));
        }
        st.queue.push_back(slot.clone());
        if let Some(w) = st.writer.take() {
            w.wake();
        }
        Ok(slot)
    }

    /// Appends a statement's Bind and Execute (`encode`) and a `Sync`, and
    /// queues its slot: the statement joins the batch that ends `out` when
    /// there is one with room, or may start one; its `Sync` is then taken
    /// off and the statement's messages go before it (see
    /// [`Config::batch_reads`]). On a shared connection outside a
    /// transaction only.
    #[inline(never)]
    fn enqueue_batched(
        &self,
        kind: Kind,
        encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
    ) -> Result<Rc<Slot>, Error> {
        let mut st = self.state.borrow_mut();
        if let Some(e) = &st.broken {
            return Err(e.clone());
        }
        let joins = st.batch.as_ref().is_some_and(|b| b.members < BATCH_MAX);
        if !joins {
            let start = st.out.len();
            if let Err(e) = encode(&mut st.out) {
                st.out.truncate(start);
                return Err(e);
            }
            protocol::sync(&mut st.out);
            st.batch = Some(OpenBatch { start, members: 1 });
            return Ok(self.queue_slot(&mut st, Slot::new(kind, true, false, None)));
        }
        // Encoded apart first: a value that cannot be encoded leaves the
        // batch as it was.
        let mut messages = Vec::new();
        encode(&mut messages)?;
        let sync_at = st.out.len() - SYNC_LEN;
        st.out.truncate(sync_at);
        let b = st.batch.as_mut().expect("joins");
        if b.members == 1 {
            // The request alone so far becomes the batch's first statement,
            // behind the one that makes the transaction read-only.
            let start = b.start;
            let mut guard = Vec::new();
            read_only_guard(&mut guard, st.read_only_prepared);
            st.read_only_prepared = true;
            st.out.splice(start..start, guard);
            let first = st.queue.pop_back().expect("the batch's first statement");
            first.batch.set(Role::Member);
            let guard = Slot::new(Kind::Simple, true, false, None);
            guard.batch.set(Role::Guard);
            st.extra += 2; // The guard, and the end queued below.
            guard.inner.borrow_mut().abandoned = true;
            st.queue.push_back(guard);
            st.queue.push_back(first);
        } else {
            let end = st.queue.pop_back().expect("the batch's end");
            debug_assert_eq!(end.batch.get(), Role::End);
        }
        st.batch.as_mut().expect("joins").members += 1;
        st.out.extend_from_slice(&messages);
        protocol::sync(&mut st.out);
        let slot = Slot::new(kind, true, false, None);
        slot.batch.set(Role::Member);
        st.queue.push_back(slot.clone());
        let end = Slot::new(Kind::Simple, true, false, None);
        end.batch.set(Role::End);
        end.inner.borrow_mut().abandoned = true;
        self.queue_slot(&mut st, end);
        Ok(slot)
    }

    /// Queues `slot` behind the requests in flight and wakes the writer.
    fn queue_slot(&self, st: &mut State, slot: Rc<Slot>) -> Rc<Slot> {
        self.requests.set(self.requests.get() + 1);
        if st.queue.is_empty() {
            self.head_since.set(Some(giong::time::Instant::now()));
        }
        st.queue.push_back(slot.clone());
        if let Some(w) = st.writer.take() {
            w.wake();
        }
        slot
    }

    /// A statement of a batch is done: its `CommandComplete` or its error
    /// arrived, or the batch ended without running it.
    /// Its result is held until the batch's end, when it is known whether
    /// the batch's transaction committed.
    fn finish_member(&self, slot: &Rc<Slot>) {
        // The batch's transaction ends with its `Sync`: the outcome is as
        // outside a transaction.
        slot.inner.borrow_mut().status = b'I';
        let mut st = self.state.borrow_mut();
        st.queue.pop_front();
        if slot.batch.get() == Role::Guard {
            st.extra -= 1;
        } else {
            st.held.push(slot.clone());
        }
        self.head_since
            .set((!st.queue.is_empty()).then(giong::time::Instant::now));
    }

    /// The prepared statement for `sql`: from the cache, from a prepare
    /// already in flight, or prepared now.
    async fn statement(&self, sql: &str) -> Result<Rc<Statement>, Error> {
        let mut again = true;
        loop {
            let pending = {
                let mut st = self.state.borrow_mut();
                st.clock += 1;
                let now = st.clock;
                match st.cache.get_mut(sql) {
                    Some(Entry::Ready { stmt, used }) => {
                        *used = now;
                        return Ok(stmt.clone());
                    }
                    Some(Entry::Preparing(slot)) => Some(slot.clone()),
                    None => None,
                }
            };
            let Some(slot) = pending else {
                return self.prepare(sql).await;
            };
            match (Wait { slot }).await {
                Ok(Response::Statement(stmt)) => return Ok(stmt),
                Ok(_) => unreachable!("a prepare slot ends with a statement"),
                // The task that sent this prepare tries another name (see
                // `prepare`); look in the cache again.
                Err(e) if again && e.server_code() == Some("42P05") => again = false,
                Err(e) => return Err(e),
            }
        }
    }

    async fn prepare(&self, sql: &str) -> Result<Rc<Statement>, Error> {
        match self.prepare_once(sql).await {
            // A statement of that name exists already: prepared by the
            // application with SQL-level PREPARE, or by another client behind
            // a connection pooler. The next name will do.
            Err(e) if e.server_code() == Some("42P05") => self.prepare_once(sql).await,
            result => result,
        }
    }

    async fn prepare_once(&self, sql: &str) -> Result<Rc<Statement>, Error> {
        let cached = self.config.statement_cache > 0;
        let (name, key) = {
            let mut st = self.state.borrow_mut();
            st.next_name += 1;
            (
                format!("{NAME_PREFIX}{}", st.next_name),
                Rc::<str>::from(sql),
            )
        };
        let slot = self.enqueue(
            Kind::Prepare {
                sql: key.clone(),
                name: name.as_str().into(),
                cached,
            },
            |out| {
                protocol::parse(out, &name, sql)?;
                protocol::describe_statement(out, &name)?;
                protocol::sync(out);
                Ok(())
            },
        )?;
        if cached {
            self.state
                .borrow_mut()
                .cache
                .insert(key, Entry::Preparing(slot.clone()));
        }
        match (Wait { slot }).await? {
            Response::Statement(stmt) => Ok(stmt),
            _ => unreachable!("a prepare slot ends with a statement"),
        }
    }

    /// Stops the connection: every request waiting gets `err` (or the
    /// server's own error for it), and both tasks finish.
    fn fail(&self, err: Error) {
        let slots = {
            let mut st = self.state.borrow_mut();
            if st.broken.is_none() {
                st.broken = Some(err.clone());
            }
            st.cache.clear();
            st.out.clear();
            self.head_since.set(None);
            if let Some(w) = st.writer.take() {
                w.wake();
            }
            st.extra = 0;
            st.read_only_prepared = false;
            st.batch_failed = false;
            let mut slots = std::mem::take(&mut st.held);
            slots.extend(std::mem::take(&mut st.queue));
            slots
        };
        for slot in slots {
            let mut inner = slot.inner.borrow_mut();
            let e = inner.error.take().unwrap_or_else(|| err.clone());
            inner.outcome = Some(Err(e));
            inner.wakers.wake_all();
        }
        self.wake_idle();
        self.stream.shutdown(Shutdown::Both);
    }

    fn wake_idle(&self) {
        let wakers = std::mem::take(&mut *self.idle_wakers.borrow_mut());
        for w in wakers {
            w.wake();
        }
    }

    /// Takes apart and handles every whole message in `buf`.
    fn process(&self, buf: &mut ReadBuf) -> Result<(), Error> {
        let limit = self.config.max_result_size.max(1 << 20);
        while let Some((tag, len)) = buf.peek()? {
            if len > limit {
                match tag {
                    // One row larger than the limit: skip it as it arrives,
                    // and fail the statement once it completes.
                    b'D' => self.front()?.inner.borrow_mut().rows.set_overflow(),
                    // A notice or a notification (nobody reads them), or
                    // COPY TO STDOUT output (thrown away, and the statement
                    // fails anyway).
                    b'N' | b'A' | b'd' => {}
                    // The statement's error: it fails with this one instead,
                    // and the connection stays usable.
                    b'E' => {
                        let slot = self.front()?;
                        let mut inner = slot.inner.borrow_mut();
                        if inner.error.is_none() {
                            inner.error = Some(Error::new(
                                ErrorKind::TooLarge,
                                format!(
                                    "the server's error for this statement was a {len}-byte \
                                     message, more than max_result_size allows, so it was \
                                     thrown away; raise Config::max_result_size to read it"
                                ),
                            ));
                        }
                    }
                    _ => {
                        return Err(Error::new(
                            ErrorKind::Protocol,
                            format!(
                                "the server sent a {:?} message of {len} bytes, more than \
                                 max_result_size allows, so the connection was closed; raise \
                                 Config::max_result_size if the server's messages are this large",
                                tag as char
                            ),
                        ))
                    }
                }
                buf.skip(len);
                continue;
            }
            let Some(body) = buf.body(len) else {
                return Ok(());
            };
            self.handle(tag, buf.bytes(body))?;
            buf.consume(len);
        }
        Ok(())
    }

    fn front(&self) -> Result<Rc<Slot>, Error> {
        self.state.borrow().queue.front().cloned().ok_or_else(|| {
            Error::protocol("the server sent a reply to a request that was never made")
        })
    }

    fn handle(&self, tag: u8, body: &[u8]) -> Result<(), Error> {
        let msg = parse_backend(tag, body)?;
        match msg {
            Backend::NoticeResponse | Backend::NotificationResponse => return Ok(()),
            Backend::ParameterStatus { name, value } => {
                if name == "client_encoding" && !value.eq_ignore_ascii_case("UTF8") {
                    return Err(Error::closed(format!(
                        "the session's client_encoding was changed to {value}; giong-postgres \
                         reads and writes UTF-8 only, so the connection was closed"
                    )));
                }
                let mut st = self.state.borrow_mut();
                match st.server_params.iter_mut().find(|(n, _)| n == name) {
                    Some(entry) => entry.1 = value.to_owned(),
                    None => st.server_params.push((name.to_owned(), value.to_owned())),
                }
                return Ok(());
            }
            Backend::ErrorResponse(fields) if self.state.borrow().queue.is_empty() => {
                // A FATAL error outside any request: the server is closing
                // the connection (an administrator's command, a shutdown).
                let db = DbError::parse(fields)?;
                return Err(Error::with_db(
                    ErrorKind::Closed,
                    "the server closed the connection",
                    db,
                ));
            }
            _ => {}
        }
        let slot = loop {
            let slot = self.front()?;
            if slot.batch.get() != Role::Alone
                && matches!(
                    msg,
                    Backend::CommandComplete(_)
                        | Backend::ErrorResponse(_)
                        | Backend::ReadyForQuery(_)
                )
            {
                if self.handle_batched(slot, &msg)? {
                    // A skipped statement's slot is done; the message is
                    // the next slot's.
                    continue;
                }
                return Ok(());
            }
            break slot;
        };
        let mut inner = slot.inner.borrow_mut();
        match msg {
            Backend::BindComplete => inner.bound = true,
            Backend::ParseComplete
            | Backend::CloseComplete
            | Backend::NoData
            | Backend::PortalSuspended
            | Backend::EmptyQueryResponse => {}
            Backend::ParameterDescription(types) => inner.params = Some(types),
            Backend::RowDescription(fields) => {
                if matches!(slot.kind, Kind::Prepare { .. }) {
                    inner.columns = Some(
                        fields
                            .iter()
                            .map(|f| Column::new(f.name, Type::from_oid(f.type_oid)))
                            .collect(),
                    );
                }
            }
            Backend::DataRow(body) => match &slot.kind {
                Kind::Execute { stmt } if !inner.abandoned && inner.error.is_none() => {
                    let limit = self.config.max_result_size;
                    inner.rows.push(body, stmt.columns.len(), limit)?;
                }
                _ => {}
            },
            Backend::CommandComplete(tag) => {
                if tag == "PREPARE" {
                    self.user_prepared.set(true);
                }
                inner.tag = Some(Tag::of(tag));
            }
            Backend::ErrorResponse(fields) => {
                if inner.error.is_none() {
                    inner.error = Some(self.db_error(fields, true)?);
                }
            }
            Backend::CopyOutResponse | Backend::CopyData | Backend::CopyDone => {
                if inner.error.is_none() {
                    inner.error = Some(Error::conversion(
                        "COPY ... TO STDOUT is not supported by giong-postgres yet; the output \
                         was thrown away",
                    ));
                }
            }
            Backend::CopyInResponse | Backend::CopyBothResponse => {
                return Err(Error::closed(
                    "the statement started COPY FROM STDIN or replication, which giong-postgres \
                     does not support yet; the connection was closed",
                ));
            }
            Backend::ReadyForQuery(status) => {
                // A statement sent on a shared connection opened a
                // transaction (or left a failed one): the statements other
                // tasks send next would run inside it, and be lost with it.
                let left_open = slot.shared && status != b'I';
                if left_open {
                    inner.error = Some(Error::closed(LEFT_OPEN));
                }
                let reset_failed = match &inner.error {
                    Some(e) if slot.close_on_error => Some(Error::closed(format!(
                        "resetting the session of a connection that went back to the pool \
                         failed, so it was closed rather than reused: {e}"
                    ))),
                    _ => None,
                };
                inner.status = status;
                drop(inner);
                let idle = {
                    let mut st = self.state.borrow_mut();
                    st.status = status;
                    st.queue.pop_front();
                    self.head_since
                        .set((!st.queue.is_empty()).then(giong::time::Instant::now));
                    st.queue.is_empty()
                };
                self.complete(&slot);
                if left_open {
                    // Closing the connection makes the server roll back.
                    return Err(Error::closed(LEFT_OPEN));
                }
                if let Some(e) = reset_failed {
                    return Err(e);
                }
                if idle {
                    self.wake_idle();
                }
            }
            other => {
                return Err(Error::protocol(format!(
                    "the server sent an unexpected {:?} message ({other:?})",
                    tag as char
                )))
            }
        }
        Ok(())
    }

    /// The request's error from an `ErrorResponse`.
    fn db_error(&self, fields: &[u8], may_retire: bool) -> Result<Error, Error> {
        let db = DbError::parse(fields)?;
        if may_retire && db.code() == "25006" && self.on_standby() {
            self.retire.set(true);
        }
        // Only a note: the message is translated on servers whose
        // lc_messages is not English, and then there is none.
        let note = (db.code() == "57014" && db.message().contains("statement timeout")).then(
            || match self.config.statement_timeout {
                Some(limit) => format!(
                    "the statement ran longer than the statement timeout ({limit:?}; \
                     Config::statement_timeout)"
                ),
                None => "the statement ran longer than the server's statement_timeout".to_owned(),
            },
        );
        Ok(Error::from_db(db, note))
    }

    /// The `CommandComplete`, `ErrorResponse` or `ReadyForQuery` of a slot
    /// of a batch ([`Config::batch_reads`]). Apart from [`handle`](Self::handle),
    /// which every request goes through, so that it stays as small as it was.
    #[cold]
    #[inline(never)]
    ///
    /// Returns whether the message is still to be handled, by the next slot.
    fn handle_batched(&self, slot: Rc<Slot>, msg: &Backend<'_>) -> Result<bool, Error> {
        let mut inner = slot.inner.borrow_mut();
        match *msg {
            Backend::CommandComplete(command) => {
                inner.tag = Some(Tag::of(command));
            }
            Backend::ErrorResponse(fields) => {
                // Not a sign of a standby: the batch is read-only on purpose.
                let error = self.db_error(fields, false)?;
                self.state.borrow_mut().batch_failed = true;
                match slot.batch.get() {
                    // At the `Sync`: the commit failed (a deferred
                    // constraint, say). The `ReadyForQuery` follows.
                    Role::End => return Ok(false),
                    // The guard's statement is gone (a `DEALLOCATE`): it is
                    // prepared again with the next batch. Its other errors
                    // (a cancel, a timeout) leave it prepared.
                    Role::Guard if error.server_code() == Some("26000") => {
                        self.state.borrow_mut().read_only_prepared = false;
                    }
                    _ => {}
                }
                if matches!(error.server_code(), Some("55P03" | "40P01" | "40001"))
                    && slot.batch.get() == Role::Member
                {
                    // A lock waited for, a deadlock or a serialization
                    // failure the batch may have caused by holding its
                    // locks: run again alone, where it is as without
                    // batches.
                    if let Kind::Execute { .. } = &slot.kind {
                        inner.alone = true;
                    }
                }
                if error.server_code() == Some("25006") {
                    // It would have run alone: send it alone.
                    if let Kind::Execute { stmt } = &slot.kind {
                        stmt.writes.set(true);
                        inner.alone = true;
                    }
                }
                inner.error = Some(error);
            }
            Backend::ReadyForQuery(status) if slot.batch.get() == Role::End => {
                // The batch's transaction ended, committed or rolled back:
                // the outcome is as outside a transaction.
                inner.status = status;
                drop(inner);
                let (idle, held, failed) = {
                    let mut st = self.state.borrow_mut();
                    st.status = status;
                    st.queue.pop_front();
                    st.extra -= 1;
                    self.head_since
                        .set((!st.queue.is_empty()).then(giong::time::Instant::now));
                    let failed = std::mem::take(&mut st.batch_failed);
                    (st.queue.is_empty(), std::mem::take(&mut st.held), failed)
                };
                for member in &held {
                    if failed {
                        let mut inner = member.inner.borrow_mut();
                        if inner.error.is_none() {
                            // It ran, but what it did was rolled back with
                            // the batch: it runs again, alone.
                            inner.error = Some(Error::new(
                                ErrorKind::Closed,
                                "another statement of this one's batch failed, so the batch \
                                 was rolled back",
                            ));
                            inner.alone = matches!(member.kind, Kind::Execute { .. });
                        }
                    }
                    self.complete(member);
                }
                self.complete(&slot);
                if idle {
                    self.wake_idle();
                }
                return Ok(false);
            }
            Backend::ReadyForQuery(_) => {
                // The batch ended before this statement ran: a statement
                // before it failed, and the server skipped the rest.
                inner.error = Some(Error::new(
                    ErrorKind::Closed,
                    "a statement before this one in its batch failed, so the server skipped it",
                ));
                inner.alone = matches!(slot.kind, Kind::Execute { .. });
                drop(inner);
                self.finish_member(&slot);
                return Ok(true);
            }
            _ => unreachable!("only these three come here"),
        }
        drop(inner);
        self.finish_member(&slot);
        Ok(false)
    }

    /// Works out a finished request's outcome and wakes whoever waits.
    fn complete(&self, slot: &Rc<Slot>) {
        let mut inner = slot.inner.borrow_mut();
        let error = inner.error.take();
        let outcome = match &slot.kind {
            Kind::Prepare { sql, name, cached } => {
                let result = match error {
                    Some(e) => Err(e),
                    None => match inner.params.take() {
                        Some(params) => Ok(Rc::new(Statement {
                            sql: sql.clone(),
                            name: name.clone(),
                            params,
                            columns: inner.columns.take().unwrap_or_default().into(),
                            conn: (!*cached).then(|| self.weak.clone()),
                            closed: Cell::new(false),
                            writes: Cell::new(false),
                        })),
                        None => Err(Error::protocol("the server did not describe the statement")),
                    },
                };
                if *cached {
                    self.settle_cache(sql, slot, &result);
                }
                result.map(Response::Statement)
            }
            Kind::Execute { stmt } => match error {
                Some(e) => {
                    let stale = self.forget_if_stale(stmt, &e);
                    // Failed in Bind (nothing ran) and outside a transaction
                    // (none was aborted): safe to run again.
                    inner.retry = stale && !inner.bound && inner.status == b'I';
                    Err(e)
                }
                None if inner.rows.overflow => Err(Error::new(
                    ErrorKind::TooLarge,
                    format!(
                        "the result is larger than max_result_size ({} bytes); add a LIMIT or \
                         select fewer columns, or raise Config::max_result_size",
                        self.config.max_result_size
                    ),
                )),
                None => {
                    let rows = std::mem::take(&mut inner.rows);
                    Ok(Response::Rows(
                        rows.finish(stmt.columns.clone()),
                        inner.tag.take(),
                    ))
                }
            },
            Kind::Simple => match error {
                Some(e) => Err(e),
                None => Ok(Response::Done(inner.tag.take())),
            },
        };
        inner.outcome = Some(outcome);
        inner.wakers.wake_all();
    }

    /// Takes a cached statement out of the cache when the server says it no
    /// longer fits: the schema changed under it, or something deallocated it.
    /// The next run prepares it afresh. Returns whether the error was one of
    /// those.
    fn forget_if_stale(&self, stmt: &Statement, e: &Error) -> bool {
        if !e.db().is_some_and(is_stale) {
            return false;
        }
        let mut st = self.state.borrow_mut();
        if matches!(st.cache.get(&stmt.sql), Some(Entry::Ready { stmt: s, .. }) if s.name == stmt.name)
        {
            st.cache.remove(&stmt.sql);
        }
        true
    }

    /// Whether the server says it is a standby, or does not say (servers
    /// before PostgreSQL 14 do not report `in_hot_standby`).
    fn on_standby(&self) -> bool {
        let st = self.state.borrow();
        st.server_params
            .iter()
            .find(|(n, _)| n == "in_hot_standby")
            .map_or(true, |(_, v)| v != "off")
    }

    /// Puts a prepared statement in the cache (or takes out a failed one),
    /// closing the least recently used statements when it is full.
    fn settle_cache(&self, sql: &Rc<str>, slot: &Rc<Slot>, result: &Result<Rc<Statement>, Error>) {
        let mut st = self.state.borrow_mut();
        let ours = matches!(st.cache.get(sql), Some(Entry::Preparing(s)) if Rc::ptr_eq(s, slot));
        if !ours {
            return;
        }
        let Ok(stmt) = result else {
            st.cache.remove(sql);
            return;
        };
        st.clock += 1;
        let used = st.clock;
        st.cache.insert(
            sql.clone(),
            Entry::Ready {
                stmt: stmt.clone(),
                used,
            },
        );
        while st.cache.len() > self.config.statement_cache {
            // Only statements nobody is about to use can go.
            let victim = st
                .cache
                .iter()
                .filter_map(|(k, e)| match e {
                    Entry::Ready { stmt, used } if Rc::strong_count(stmt) == 1 => {
                        Some((*used, k.clone()))
                    }
                    _ => None,
                })
                .min();
            let Some((_, key)) = victim else { break };
            if let Some(Entry::Ready { stmt, .. }) = st.cache.remove(&key) {
                // No Sync: the close travels with the next request, whose
                // reply includes the CloseComplete.
                let _ = protocol::close_statement(&mut st.out, &stmt.name);
                // A batch must end `out` to take more statements.
                st.batch = None;
            }
        }
    }
}

async fn read_loop(conn: Rc<Conn>, mut buf: ReadBuf) {
    let err = loop {
        if let Err(e) = conn.process(&mut buf) {
            break e;
        }
        match conn.stream.read_into(&mut buf).await {
            Ok(0) => {
                let closing = conn.state.borrow().closing;
                break Error::closed(if closing {
                    "the connection was closed"
                } else {
                    "the server closed the connection"
                });
            }
            Ok(_) => {}
            Err(e) => break Error::io(ErrorKind::Closed, "reading from the server failed", e),
        }
    };
    conn.fail(err);
}

async fn write_loop(conn: Rc<Conn>) {
    let mut spare = Vec::new();
    loop {
        let next = poll_fn(|cx| {
            let mut st = conn.state.borrow_mut();
            if st.broken.is_some() {
                return Poll::Ready(None);
            }
            if !st.out.is_empty() {
                // What is written cannot grow: a batch ends here.
                st.batch = None;
                return Poll::Ready(Some(std::mem::replace(
                    &mut st.out,
                    std::mem::take(&mut spare),
                )));
            }
            if st.closing {
                return Poll::Ready(None);
            }
            st.writer = Some(cx.waker().clone());
            Poll::Pending
        })
        .await;
        let Some(data) = next else { break };
        let (written, mut data) = conn.stream.write_all(data).await;
        if let Err(e) = written {
            conn.fail(Error::io(
                ErrorKind::Closed,
                "writing to the server failed",
                e,
            ));
            return;
        }
        data.clear();
        spare = data;
    }
    if conn.state.borrow().closing {
        conn.stream.shutdown(Shutdown::Write);
    }
}

/// An open transaction. Statements run through it with the same methods as
/// on [`Client`] (it dereferences to the client).
///
/// Commit it with [`commit`](Self::commit). Dropping it otherwise rolls it
/// back: the `ROLLBACK` is queued at once, ahead of anything the connection
/// runs afterwards.
///
/// A statement given up before its answer came (its future dropped, by a
/// timeout or a `select` say) may still run on the server, so the
/// transaction can no longer be committed: from then on every statement
/// sent through it, [`commit`](Self::commit) included, fails with an
/// [`ErrorKind::Db`] error that says so, and nothing more is sent. Drop the
/// transaction or [`rollback`](Self::rollback) it, and run it again from the
/// start. A statement whose answer had arrived before its future was
/// dropped does not count: its outcome is known.
pub struct Transaction<'a> {
    client: &'a mut Client,
    done: bool,
}

impl Transaction<'_> {
    /// Commits the transaction.
    ///
    /// When a statement in the transaction failed earlier, PostgreSQL rolls
    /// the transaction back instead; this is reported as an error, never as
    /// a successful commit. When a statement in it was given up before its
    /// answer came, `COMMIT` is not sent: the transaction is rolled back and
    /// the error says why (see [`Transaction`]).
    ///
    /// Not cancel safe: if the future is dropped, the transaction may have been
    /// committed or rolled back, and the caller does not learn which.
    pub async fn commit(mut self) -> Result<(), Error> {
        if self.client.conn.tx.get() == Tx::Abandoned {
            // Dropping `self` rolls it back.
            return Err(abandoned());
        }
        self.end();
        let slot = self
            .client
            .conn
            .enqueue(Kind::Simple, |out| protocol::query(out, "COMMIT"))?;
        match (Wait { slot }).await? {
            Response::Done(Some(tag)) if tag.rollback => Err(Error::with_sqlstate(
                "25P02",
                "the transaction was rolled back instead of committed, because a statement in \
                 it failed earlier",
            )),
            _ => Ok(()),
        }
    }

    /// Rolls the transaction back and waits for the server to confirm.
    ///
    /// Cancel safe: if the future is dropped, the transaction is rolled back
    /// all the same.
    pub async fn rollback(mut self) -> Result<(), Error> {
        self.end();
        self.client.batch_execute("ROLLBACK").await
    }

    /// The transaction ends here: what is sent next is outside it.
    fn end(&mut self) {
        self.done = true;
        self.client.conn.tx.set(Tx::None);
    }
}

impl Deref for Transaction<'_> {
    type Target = Client;

    fn deref(&self) -> &Client {
        self.client
    }
}

impl Drop for Transaction<'_> {
    fn drop(&mut self) {
        if !self.done {
            self.end();
            self.client.send_and_forget("ROLLBACK");
        }
    }
}

impl std::fmt::Debug for Transaction<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Transaction")
            .field("client", &self.client)
            .finish()
    }
}

/// Asks the server to cancel what a connection is running.
///
/// It can be sent to another thread. The request goes over a new connection,
/// as the protocol requires; the statement being cancelled fails with SQLSTATE
/// `57014`. With several tasks sharing the connection, the statement running
/// when the request arrives is the one cancelled.
#[derive(Clone)]
pub struct CancelToken {
    /// Where to send the request; without the password, which it does not
    /// need.
    config: Config,
    key: Option<(i32, i32)>,
    /// Set for a token taken from a pooled connection: ended when the
    /// connection goes back to the pool.
    lease: Option<Arc<Lease>>,
}

/// A pooled connection's time with one task, shared with the cancel tokens
/// taken during it: whether it has ended, and how many cancel requests are
/// on their way.
#[derive(Default)]
pub(crate) struct Lease(AtomicU32);

impl Lease {
    /// Set once the connection has gone back to its pool.
    const ENDED: u32 = 1 << 31;

    /// Counts a cancel request on its way, unless the lease has ended.
    fn start_cancel(&self) -> bool {
        let mut v = self.0.load(Ordering::Acquire);
        while v & Self::ENDED == 0 {
            match self
                .0
                .compare_exchange_weak(v, v + 1, Ordering::AcqRel, Ordering::Acquire)
            {
                Ok(_) => return true,
                Err(now) => v = now,
            }
        }
        false
    }

    /// A cancel request that `start_cancel` counted got its answer.
    fn finish_cancel(&self) {
        self.0.fetch_sub(1, Ordering::AcqRel);
    }

    fn is_ended(&self) -> bool {
        self.0.load(Ordering::Acquire) & Self::ENDED != 0
    }

    /// Ends the lease; returns whether a cancel request is still on its way
    /// (or was given up on the way, which counts the same).
    fn end(&self) -> bool {
        self.0.fetch_or(Self::ENDED, Ordering::AcqRel) & !Self::ENDED != 0
    }
}

impl CancelToken {
    /// Sends the cancel request. Success means the server received it, not
    /// that something was cancelled: the statement may have finished first.
    ///
    /// Fails with [`ErrorKind::Closed`], sending nothing, when the token was
    /// taken from a [`PooledClient`](crate::PooledClient) that has gone back
    /// to its pool since.
    ///
    /// Not cancel safe: if the future is dropped, the request may still reach
    /// the server and stop whatever the connection runs then.
    pub async fn cancel(&self) -> Result<(), Error> {
        let gone = || {
            Error::closed(
                "the connection this cancel token was taken from has gone back to its pool, \
                 where other tasks use it, so nothing was sent; take a new token from the next \
                 connection",
            )
        };
        if self.lease.as_ref().is_some_and(|lease| lease.is_ended()) {
            return Err(gone());
        }
        let key = self.key.ok_or_else(|| {
            Error::new(
                ErrorKind::Connect,
                "the server gave this connection no cancel key (a connection pooler may be in \
                 between), so it cannot be cancelled",
            )
        })?;
        let Some(lease) = &self.lease else {
            return connect::cancel(&self.config, key).await;
        };
        // Counted until the answer comes: a connection that goes back to the
        // pool meanwhile is closed rather than lent to a task whose
        // statement the request would stop. A request given up on the way
        // stays counted, for the same reason.
        if !lease.start_cancel() {
            return Err(gone());
        }
        let sent = connect::cancel(&self.config, key).await;
        lease.finish_cancel();
        sent
    }
}

impl std::fmt::Debug for CancelToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CancelToken")
            .field("server", &self.config.target())
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::{is_stale, Tag};
    use crate::error::DbError;

    fn db_error(fields: &[(u8, &str)]) -> DbError {
        let mut body = Vec::new();
        for (field, value) in fields {
            body.push(*field);
            body.extend_from_slice(value.as_bytes());
            body.push(0);
        }
        body.push(0);
        DbError::parse(&body).unwrap()
    }

    #[test]
    fn a_stale_plan_is_recognised_in_any_language() {
        let german = db_error(&[
            (b'S', "FEHLER"),
            (b'V', "ERROR"),
            (b'C', "0A000"),
            (b'M', "gecachter Plan darf den Ergebnistyp nicht ändern"),
            (b'R', "RevalidateCachedQuery"),
        ]);
        assert!(is_stale(&german));
        assert_eq!(german.severity(), "ERROR");
        // A server that sends no routine, in English.
        let english = db_error(&[
            (b'C', "0A000"),
            (b'M', "cached plan must not change result type"),
        ]);
        assert!(is_stale(&english));
        // Another "feature not supported" error.
        let other = db_error(&[
            (b'C', "0A000"),
            (b'M', "nicht unterstützt"),
            (b'R', "transformSelectStmt"),
        ]);
        assert!(!is_stale(&other));
        assert!(is_stale(&db_error(&[(b'C', "26000"), (b'M', "x")])));
    }

    #[test]
    fn command_tags_give_row_counts() {
        assert_eq!(Tag::of("INSERT 0 5").rows, 5);
        assert_eq!(Tag::of("UPDATE 3").rows, 3);
        assert_eq!(Tag::of("SELECT 12").rows, 12);
        assert_eq!(Tag::of("CREATE TABLE").rows, 0);
        assert!(Tag::of("ROLLBACK").rollback && !Tag::of("COMMIT").rollback);
    }
}