postgres-mcp-readonly 0.1.7

Read-only MCP server for PostgreSQL and TimescaleDB
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
use std::sync::Arc;
use std::time::{Duration, Instant};

use postgres_mcp::encode::{TypeInfo, TypeKind};
use postgres_mcp::pg::pool::Pool;
use postgres_mcp::pg::session::{RunError, RunOutput, SessionSettings, run_readonly};
use postgres_mcp::pg::tls::SslMode;
use postgres_mcp::pg::wire::{ConnectConfig, Connection, FetchLimits, Truncation};
use tokio_util::sync::CancellationToken;

const HOST: &str = "127.0.0.1";
const VERSIONS: [(u16, u32); 3] = [(15432, 18), (15433, 19), (15434, 15)];

fn startup_params() -> Vec<(String, String)> {
    [
        ("application_name", "pgmcp-session-test"),
        ("DateStyle", "ISO, MDY"),
        ("IntervalStyle", "iso_8601"),
        ("TimeZone", "UTC"),
        ("bytea_output", "hex"),
        ("extra_float_digits", "1"),
        ("standard_conforming_strings", "on"),
        ("default_transaction_read_only", "on"),
    ]
    .into_iter()
    .map(|(k, v)| (k.to_string(), v.to_string()))
    .collect()
}

fn config(port: u16, password: &str) -> ConnectConfig {
    ConnectConfig {
        host: HOST.into(),
        port,
        database: "appdb".into(),
        user: "mcp_ro".into(),
        password: Some(password.into()),
        ssl_mode: SslMode::Disable,
        ssl_root_cert: None,
        connect_timeout: Duration::from_secs(5),
        startup_params: startup_params(),
    }
}

fn pool(port: u16, max: usize) -> Pool {
    Pool::new(config(port, "test-only-ro"), max)
}

fn tuned(statement_timeout_ms: u64, max_rows: usize, pool_wait: Duration) -> SessionSettings {
    SessionSettings {
        statement_timeout_ms,
        lock_timeout_ms: 500,
        fetch: FetchLimits {
            max_rows,
            max_bytes: 1 << 20,
            max_value_bytes: 4096,
        },
        pool_wait,
        search_path_catalog_only: false,
    }
}

fn settings() -> SessionSettings {
    tuned(2000, 1000, Duration::from_secs(5))
}

async fn run_with(
    pool: &Pool,
    sql: &str,
    settings: &SessionSettings,
) -> Result<RunOutput, RunError> {
    run_readonly(pool, sql, &[], true, settings, &CancellationToken::new()).await
}

async fn run(pool: &Pool, sql: &str) -> Result<RunOutput, RunError> {
    run_with(pool, sql, &settings()).await
}

fn texts(out: &RunOutput) -> Vec<Vec<Option<String>>> {
    out.result
        .rows
        .iter()
        .map(|row| {
            row.iter()
                .map(|cell| {
                    cell.as_ref()
                        .map(|f| String::from_utf8_lossy(&f.data).into_owned())
                })
                .collect()
        })
        .collect()
}

fn names(out: &RunOutput) -> Vec<String> {
    out.types.iter().map(|t| t.name.clone()).collect()
}

fn s(v: &str) -> Option<String> {
    Some(v.to_string())
}

async fn one(pool: &Pool, sql: &str) -> String {
    let out = run(pool, sql).await.expect("run");
    texts(&out)[0][0].clone().expect("non-null value")
}

fn superuser_config(port: u16) -> ConnectConfig {
    ConnectConfig {
        host: HOST.into(),
        port,
        database: "appdb".into(),
        user: "postgres".into(),
        password: Some("test-only-superuser".into()),
        ssl_mode: SslMode::Disable,
        ssl_root_cert: None,
        connect_timeout: Duration::from_secs(5),
        startup_params: Vec::new(),
    }
}

/// First value of the first row, from a superuser connection outside the pool.
async fn scalar(port: u16, sql: &str) -> String {
    let mut conn = Connection::connect(&superuser_config(port))
        .await
        .expect("superuser connect");
    let result = conn.simple_query(sql).await.expect("superuser query");
    result.rows[0][0].clone().expect("non-null value")
}

/// Polls a superuser count until it reads "0", for up to 2 seconds.
async fn eventually_zero(port: u16, sql: &str) {
    for _ in 0..20 {
        if scalar(port, sql).await == "0" {
            return;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    assert_eq!(scalar(port, sql).await, "0", "{sql}");
}

const ACTIVE_SLEEP_10: &str = "SELECT count(*) FROM pg_stat_activity \
    WHERE application_name = 'pgmcp-session-test' AND query LIKE '%pg_sleep(10)%' AND state = 'active'";

async fn oid_of(port: u16, typname: &str) -> u32 {
    scalar(
        port,
        &format!(
            "SELECT oid::text FROM pg_catalog.pg_type WHERE typname = '{typname}' \
             AND typnamespace = 'sess_test'::regnamespace"
        ),
    )
    .await
    .parse()
    .expect("oid")
}

fn info(oid: u32, name: &str, kind: TypeKind) -> TypeInfo {
    TypeInfo {
        oid,
        name: name.into(),
        kind,
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn select_works_on_all_versions() {
    for (port, major) in VERSIONS {
        let pool = pool(port, 1);
        let out = run(
            &pool,
            "SELECT id, name, qty, price FROM app.items ORDER BY id LIMIT 3",
        )
        .await
        .expect("select");
        assert_eq!(out.server_version_num / 10_000, major, "port {port}");
        assert_eq!(
            texts(&out),
            vec![
                vec![s("1"), s("item 1"), s("1000000000000"), s("1.50")],
                vec![s("2"), s("item 2"), s("2000000000000"), s("3.00")],
                vec![s("3"), s("item 3"), s("3000000000000"), s("4.50")],
            ],
            "port {port}"
        );
        assert_eq!(
            names(&out),
            ["int4", "text", "int8", "numeric"],
            "port {port}"
        );
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn connection_is_reused_and_clean() {
    let pool = pool(15432, 1);
    let mut pids = Vec::new();
    for _ in 0..3 {
        pids.push(one(&pool, "SELECT pg_backend_pid()").await);
    }
    assert!(pids.iter().all(|p| *p == pids[0]), "{pids:?}");
    assert_eq!(pool.idle_count(), 1);
}

#[tokio::test(flavor = "multi_thread")]
async fn writes_are_refused_by_server() {
    let pool = pool(15432, 1);
    // nextval() needs UPDATE on the sequence, which mcp_ro lacks, so PostgreSQL reports 42501 before the read-only check.
    for (sql, code) in [
        (
            "INSERT INTO app.items VALUES (999999,'x',1,1) RETURNING id",
            "25006",
        ),
        (
            "UPDATE app.items SET name='x' WHERE id=1 RETURNING id",
            "25006",
        ),
        ("DELETE FROM app.items WHERE id=1 RETURNING id", "25006"),
        (
            "WITH d AS (DELETE FROM app.items RETURNING id) SELECT * FROM d",
            "25006",
        ),
        ("SELECT nextval('app.item_seq')", "42501"),
        ("SELECT lo_create(0)", "25006"),
    ] {
        match run(&pool, sql).await {
            Err(RunError::Db(e)) => assert_eq!(e.code, code, "{sql}"),
            other => panic!("{sql}: expected Db {code}, got {other:?}"),
        }
    }
    assert_eq!(
        scalar(15432, "SELECT count(*) FROM app.items").await,
        "5000"
    );
    assert_eq!(
        scalar(15432, "SELECT name FROM app.items WHERE id = 1").await,
        "item 1"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn non_row_statements_are_refused() {
    let pool = pool(15432, 1);
    for sql in [
        "COMMIT",
        "ROLLBACK AND CHAIN",
        "PREPARE TRANSACTION 'pgmcp_t1'",
        "SET statement_timeout = 0",
        "SET TRANSACTION READ WRITE",
        "LISTEN ch",
        "DO $$ begin end $$",
        "COPY app.items TO STDOUT",
        "SELECT 1 INTO TEMP zz",
        "CREATE TEMP TABLE zz(x int)",
        "DISCARD ALL",
        "LOCK TABLE app.items IN ACCESS SHARE MODE",
        "PREPARE p AS SELECT 1",
        "DECLARE c CURSOR WITH HOLD FOR SELECT 1",
        "BEGIN",
    ] {
        match run(&pool, sql).await {
            Err(RunError::Refused(m)) => {
                assert_eq!(m, "statement does not return rows", "{sql}")
            }
            other => panic!("{sql}: expected Refused, got {other:?}"),
        }
    }
    assert_eq!(
        scalar(15432, "SELECT count(*) FROM pg_prepared_xacts").await,
        "0"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn multiple_statements_fail() {
    let pool = pool(15432, 1);
    match run(&pool, "SELECT 1; SELECT 2").await {
        Err(RunError::Db(e)) => assert_eq!(e.code, "42601"),
        other => panic!("expected Db 42601, got {other:?}"),
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn placeholders_refused_for_user_sql() {
    let pool = pool(15432, 1);
    match run(&pool, "SELECT $1::int").await {
        Err(RunError::Refused(m)) => assert_eq!(m, "parameter placeholders are not supported"),
        other => panic!("expected Refused, got {other:?}"),
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn params_work_for_internal_sql() {
    let pool = pool(15432, 1);
    let out = run_readonly(
        &pool,
        "SELECT $1::text || 'x'",
        &[Some("a")],
        false,
        &settings(),
        &CancellationToken::new(),
    )
    .await
    .expect("params");
    assert_eq!(texts(&out), vec![vec![s("ax")]]);
}

#[tokio::test(flavor = "multi_thread")]
async fn read_write_cannot_be_enabled() {
    let pool = pool(15432, 1);
    let r = run(
        &pool,
        "SELECT set_config('transaction_read_only','off',true)",
    )
    .await;
    assert!(matches!(r, Err(RunError::Db(_))), "{r:?}");

    run(
        &pool,
        "SELECT set_config('default_transaction_read_only','off',false)",
    )
    .await
    .expect("set_config statement itself succeeds");
    match run(
        &pool,
        "INSERT INTO app.items VALUES (999998,'x',1,1) RETURNING id",
    )
    .await
    {
        Err(RunError::Db(e)) => assert_eq!(e.code, "25006"),
        other => panic!("expected Db 25006, got {other:?}"),
    }
    assert_eq!(
        scalar(15432, "SELECT count(*) FROM app.items").await,
        "5000"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn session_state_does_not_leak() {
    let pool = pool(15432, 1);
    let pid = one(&pool, "SELECT pg_backend_pid()").await;

    run(&pool, "SELECT pg_advisory_lock(424242)")
        .await
        .expect("advisory lock");
    assert_eq!(
        one(
            &pool,
            "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND pid = pg_backend_pid()"
        )
        .await,
        "0"
    );
    assert_eq!(one(&pool, "SELECT pg_backend_pid()").await, pid);

    run(&pool, "SELECT set_config('work_mem','123456kB',false)")
        .await
        .expect("work_mem");
    assert_ne!(
        one(&pool, "SELECT current_setting('work_mem')").await,
        "123456kB"
    );
    assert_eq!(one(&pool, "SELECT pg_backend_pid()").await, pid);

    run(&pool, "SELECT set_config('TimeZone','Asia/Tokyo',false)")
        .await
        .expect("TimeZone");
    assert!(one(&pool, "SELECT now()::text").await.ends_with("+00"));
    assert_eq!(one(&pool, "SELECT pg_backend_pid()").await, pid);

    run(&pool, "SELECT set_config('search_path','sess_test',false)")
        .await
        .expect("search_path");
    assert!(
        !one(&pool, "SELECT current_setting('search_path')")
            .await
            .starts_with("sess_test")
    );
    assert_eq!(one(&pool, "SELECT pg_backend_pid()").await, pid);

    run(&pool, "SELECT set_config('statement_timeout','0',false)")
        .await
        .expect("statement_timeout");
    match run_with(
        &pool,
        "SELECT pg_sleep(4)",
        &tuned(1000, 1000, Duration::from_secs(5)),
    )
    .await
    {
        Err(RunError::Timeout(1000)) => {}
        other => panic!("expected Timeout(1000), got {other:?}"),
    }
    assert_eq!(one(&pool, "SELECT pg_backend_pid()").await, pid);

    run(&pool, "SELECT pg_notify('ch','x')")
        .await
        .expect("notify");
    run(&pool, "SELECT set_config('application_name','evil',false)")
        .await
        .expect("application_name");
    assert_eq!(
        one(&pool, "SELECT current_setting('application_name')").await,
        "pgmcp-session-test"
    );
    assert_eq!(one(&pool, "SELECT pg_backend_pid()").await, pid);
}

#[tokio::test(flavor = "multi_thread")]
async fn statement_timeout_enforced_server_side() {
    let pool = pool(15432, 1);
    let started = Instant::now();
    match run_with(
        &pool,
        "SELECT pg_sleep(10)",
        &tuned(500, 1000, Duration::from_secs(5)),
    )
    .await
    {
        Err(RunError::Timeout(500)) => {}
        other => panic!("expected Timeout(500), got {other:?}"),
    }
    assert!(
        started.elapsed() < Duration::from_secs(3),
        "{:?}",
        started.elapsed()
    );
    eventually_zero(15432, ACTIVE_SLEEP_10).await;
}

#[tokio::test(flavor = "multi_thread")]
async fn client_cancel_stops_server_query() {
    let pool = pool(15432, 1);
    let token = CancellationToken::new();
    let trigger = token.clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(200)).await;
        trigger.cancel();
    });
    let started = Instant::now();
    let r = run_readonly(
        &pool,
        "SELECT pg_sleep(20)",
        &[],
        true,
        &tuned(30_000, 1000, Duration::from_secs(5)),
        &token,
    )
    .await;
    assert!(matches!(r, Err(RunError::Cancelled)), "{r:?}");
    assert!(
        started.elapsed() < Duration::from_secs(3),
        "{:?}",
        started.elapsed()
    );
    eventually_zero(
        15432,
        "SELECT count(*) FROM pg_stat_activity WHERE application_name = 'pgmcp-session-test' \
         AND query LIKE '%pg_sleep(20)%' AND state = 'active'",
    )
    .await;
    assert_eq!(one(&pool, "SELECT 1").await, "1");
}

// PostgreSQL 18 needs about 3.4 s before the first row of this 50M-row series, so the brief's
// 2000 ms statement timeout fires first (see truncation_under_short_timeout_reports_timeout).
#[tokio::test(flavor = "multi_thread")]
async fn truncation_keeps_pool_usable() {
    let pool = pool(15432, 1);
    let out = run_with(
        &pool,
        "SELECT g FROM generate_series(1, 50000000) g",
        &tuned(10_000, 50, Duration::from_secs(5)),
    )
    .await
    .expect("truncated select");
    assert_eq!(out.result.rows.len(), 50);
    assert_eq!(out.result.truncated, Some(Truncation::Rows));
    assert_eq!(names(&out), ["int4"]);
    assert_eq!(one(&pool, "SELECT 1").await, "1");
}

#[tokio::test(flavor = "multi_thread")]
async fn truncation_under_short_timeout_is_timeout_or_truncated() {
    let pool = pool(15432, 1);
    match run_with(
        &pool,
        "SELECT g FROM generate_series(1, 50000000) g",
        &tuned(2000, 50, Duration::from_secs(5)),
    )
    .await
    {
        Err(RunError::Timeout(2000)) => {}
        Ok(out) => assert_eq!(out.result.truncated, Some(Truncation::Rows)),
        other => panic!("expected Timeout(2000) or a truncated result, got {other:?}"),
    }
    assert_eq!(one(&pool, "SELECT 1").await, "1");
}

#[tokio::test(flavor = "multi_thread")]
async fn runaway_recursive_cte_is_bounded() {
    let pool = pool(15432, 1);
    let started = Instant::now();
    let out = run_with(
        &pool,
        "WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM r) SELECT n FROM r",
        &tuned(2000, 100, Duration::from_secs(5)),
    )
    .await
    .expect("bounded recursive query");
    assert_eq!(out.result.truncated, Some(Truncation::Rows));
    assert_eq!(out.result.rows.len(), 100);
    assert!(
        started.elapsed() < Duration::from_secs(5),
        "{:?}",
        started.elapsed()
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn types_resolved_for_non_builtin() {
    let pool = pool(15432, 1);
    let out = run(&pool, "SELECT * FROM sess_test.typed")
        .await
        .expect("select typed");
    let cols: Vec<u32> = out.result.columns.iter().map(|c| c.type_oid).collect();
    assert_eq!(cols[1], 23, "domain column reports its base type");
    let mood = info(cols[0], "sess_test.mood", TypeKind::Text);
    let int4 = info(23, "int4", TypeKind::Int);
    let expected = vec![
        mood.clone(),
        int4.clone(),
        info(cols[2], "sess_test.pair", TypeKind::Text),
        info(
            cols[3],
            "sess_test.mood[]",
            TypeKind::Array {
                elem: Box::new(mood),
                delim: ',',
            },
        ),
        info(
            3904,
            "int4range",
            TypeKind::Range {
                sub: Box::new(int4.clone()),
            },
        ),
        info(
            4451,
            "int4multirange",
            TypeKind::Multirange {
                sub: Box::new(int4),
            },
        ),
        info(22, "int2vector", TypeKind::Text),
        info(
            1020,
            "box[]",
            TypeKind::Array {
                elem: Box::new(info(603, "box", TypeKind::Text)),
                delim: ';',
            },
        ),
        info(cols[8], "hstore", TypeKind::Text),
        info(cols[9], "citext", TypeKind::Text),
    ];
    assert_eq!(out.types, expected);
}

#[tokio::test(flavor = "multi_thread")]
async fn domain_chains_are_depth_limited() {
    let pool = pool(15432, 1);
    let short = oid_of(15432, "dchain3").await;
    let long = oid_of(15432, "dchain10").await;
    let mut lease = pool
        .checkout(Duration::from_secs(5))
        .await
        .expect("checkout");
    let types = pool
        .type_cache()
        .resolve(lease.conn(), &[short, long])
        .await
        .expect("resolve");
    lease.release(true);
    assert_eq!(
        types,
        vec![
            info(short, "sess_test.dchain3", TypeKind::Int),
            info(long, "sess_test.dchain10", TypeKind::Text),
        ]
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn builtin_types_need_no_lookup() {
    let pool = pool(15432, 1);
    let mut lease = pool
        .checkout(Duration::from_secs(5))
        .await
        .expect("checkout");
    let types = pool
        .type_cache()
        .resolve(lease.conn(), &[23, 25, 1020])
        .await
        .expect("resolve");
    lease.release(true);
    assert_eq!(pool.type_cache().lookups(), 0);
    assert_eq!(
        types.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
        ["int4", "text", "box[]"]
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn type_cache_is_reused() {
    let source = pool(15432, 1);
    let out = run(&source, "SELECT * FROM sess_test.typed")
        .await
        .expect("select typed");
    let moods_oid = out.result.columns[3].type_oid;

    let pool = pool(15432, 1);
    let mut lease = pool
        .checkout(Duration::from_secs(5))
        .await
        .expect("checkout");
    let first = pool
        .type_cache()
        .resolve(lease.conn(), &[moods_oid])
        .await
        .expect("first resolve");
    let after_first = pool.type_cache().lookups();
    assert!(after_first > 0, "first resolve must query pg_type");
    let second = pool
        .type_cache()
        .resolve(lease.conn(), &[moods_oid])
        .await
        .expect("second resolve");
    lease.release(true);
    assert_eq!(second, first);
    assert_eq!(pool.type_cache().lookups(), after_first);
}

#[tokio::test(flavor = "multi_thread")]
async fn standard_conforming_strings_pinned() {
    for (port, _) in VERSIONS {
        let pool = pool(port, 1);
        assert_eq!(
            one(
                &pool,
                "SELECT current_setting('standard_conforming_strings')"
            )
            .await,
            "on",
            "port {port}"
        );
        let out = run(&pool, r"SELECT '\' || 'a'").await.expect("backslash");
        assert_eq!(texts(&out), vec![vec![s(r"\a")]], "port {port}");
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn busy_pool_reports_unavailable() {
    let pool = Arc::new(pool(15432, 1));
    let holder = {
        let pool = pool.clone();
        tokio::spawn(async move { run(&pool, "SELECT pg_sleep(1)").await })
    };
    tokio::time::sleep(Duration::from_millis(500)).await;
    let r = run_with(
        &pool,
        "SELECT 1",
        &tuned(2000, 1000, Duration::from_millis(200)),
    )
    .await;
    match r {
        Err(RunError::Unavailable(m)) => assert_eq!(m, "all connections are busy, retry shortly"),
        other => panic!("expected Unavailable, got {other:?}"),
    }
    holder.await.expect("join").expect("holder run");
}

#[tokio::test(flavor = "multi_thread")]
async fn closed_pool_reports_unavailable() {
    let pool = pool(15432, 1);
    pool.close().await;
    match run(&pool, "SELECT 1").await {
        Err(RunError::Unavailable(m)) => assert_eq!(m, "the pool is closed"),
        other => panic!("expected Unavailable, got {other:?}"),
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn bad_password_is_unavailable_without_leak() {
    let pool = Pool::new(config(15432, "not-the-password-xyz"), 1);
    match run(&pool, "SELECT 1").await {
        Err(RunError::Unavailable(m)) => {
            assert!(!m.contains("not-the-password-xyz"), "{m}");
        }
        other => panic!("expected Unavailable, got {other:?}"),
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn unreachable_host_is_unavailable() {
    let pool = Pool::new(config(15999, "test-only-ro"), 1);
    match run(&pool, "SELECT 1").await {
        Err(RunError::Unavailable(_)) => {}
        other => panic!("expected Unavailable, got {other:?}"),
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn stale_idle_connection_is_replaced() {
    let pool = pool(15432, 1);
    let old = one(&pool, "SELECT pg_backend_pid()").await;
    scalar(15432, &format!("SELECT pg_terminate_backend({old})")).await;
    eventually_zero(
        15432,
        &format!("SELECT count(*) FROM pg_stat_activity WHERE pid = {old}"),
    )
    .await;
    let new = one(&pool, "SELECT pg_backend_pid()").await;
    assert_ne!(new, old);
    assert_eq!(one(&pool, "SELECT 1").await, "1");
}

/// Prepared statements, cursors, LISTEN, temp tables, work_mem and advisory locks, in the order of `LEFTOVER_SQL`.
const LEFTOVER_SQL: [&str; 6] = [
    "SELECT count(*) FROM pg_catalog.pg_prepared_statements",
    // Named cursors only: an extended-protocol query lists its own unnamed portal in pg_cursors.
    "SELECT count(*) FROM pg_catalog.pg_cursors WHERE name <> ''",
    "SELECT count(*) FROM pg_catalog.pg_listening_channels()",
    "SELECT count(*) FROM pg_catalog.pg_class WHERE relnamespace = pg_catalog.pg_my_temp_schema()",
    "SELECT pg_catalog.current_setting('work_mem')",
    "SELECT count(*) FROM pg_catalog.pg_locks WHERE locktype = 'advisory' AND pid = pg_catalog.pg_backend_pid()",
];

/// Every value of `LEFTOVER_SQL` on an open connection.
async fn leftovers_on(conn: &mut Connection) -> Vec<String> {
    let mut values = Vec::new();
    for sql in LEFTOVER_SQL {
        let result = conn.simple_query(sql).await.expect("leftover query");
        values.push(result.rows[0][0].clone().expect("non-null value"));
    }
    values
}

/// The leftovers of `leave_state()` run as an ordinary function, and the same function run on the pooled
/// read-only connection, whose next caller must see none of them.
#[tokio::test(flavor = "multi_thread")]
async fn state_left_by_a_function_is_gone_for_the_next_caller() {
    for (port, major) in VERSIONS {
        let work_mem_default = scalar(port, "SHOW work_mem").await;

        // Control: on a plain superuser connection the function's changes persist, so the check can see them.
        let mut plain = Connection::connect(&superuser_config(port))
            .await
            .expect("superuser connect");
        let plain_steps = plain
            .simple_query("SELECT sess_test.leave_state()")
            .await
            .expect("control call");
        assert_eq!(
            plain_steps.rows[0][0].as_deref(),
            Some("7"),
            "control on PostgreSQL {major}"
        );
        assert_eq!(
            leftovers_on(&mut plain).await,
            ["1", "1", "1", "1", "9MB", "1"],
            "control leftovers on PostgreSQL {major}"
        );
        // DISCARD ALL releases the advisory lock the control took, so the pooled call below can take it too.
        plain.simple_query("DISCARD ALL").await.expect("discard");
        drop(plain);

        // Call 1 runs read-only through the pool; the steps PostgreSQL refuses there do not count.
        let pool = pool(port, 1);
        let pid = one(&pool, "SELECT pg_backend_pid()").await;
        let steps = one(&pool, "SELECT sess_test.leave_state()").await;
        assert_eq!(
            steps, "6",
            "steps that succeeded inside the read-only transaction on PostgreSQL {major}"
        );

        // Call 2 reuses the same backend and must find every leftover gone.
        assert_eq!(
            one(&pool, "SELECT pg_backend_pid()").await,
            pid,
            "PostgreSQL {major}"
        );
        for (sql, expected) in
            LEFTOVER_SQL
                .iter()
                .zip(["0", "0", "0", "0", work_mem_default.as_str(), "0"])
        {
            assert_eq!(
                one(&pool, sql).await,
                expected,
                "{sql} on PostgreSQL {major}"
            );
        }
    }
}

/// The mcp_ro configuration with the role default overridden, so only the READ ONLY transaction can stop a write.
fn config_without_role_read_only(port: u16) -> ConnectConfig {
    let mut cfg = config(port, "test-only-ro");
    for (name, value) in &mut cfg.startup_params {
        if name == "default_transaction_read_only" {
            *value = "off".into();
        }
    }
    cfg
}

#[tokio::test]
async fn writes_below_the_gate_fail_in_the_read_only_transaction() {
    for (port, _) in VERSIONS {
        let pool = Pool::new(config_without_role_read_only(port), 1);
        // query_to_xml is STABLE, so PostgreSQL refuses the INSERT before the transaction check (0A000).
        // try_write() is VOLATILE and reaches the READ ONLY transaction check (25006).
        for (sql, expected) in [
            (
                "SELECT query_to_xml('INSERT INTO sess_test.canary VALUES (1)', false, false, '')",
                "0A000",
            ),
            ("SELECT sess_test.try_write()", "25006"),
        ] {
            match run(&pool, sql).await {
                Err(RunError::Db(db)) => {
                    assert_eq!(db.code, expected, "port {port} {sql}: {}", db.message)
                }
                other => panic!("port {port} {sql}: expected SQLSTATE {expected}, got {other:?}"),
            }
        }
        assert_eq!(
            scalar(port, "SELECT count(*)::text FROM sess_test.canary").await,
            "0",
            "port {port}"
        );
    }
}