// Against a real PostgreSQL (native only): runs when LOUISE_PG_URL is // set (a `postgres://` URL), skipped otherwise. The codec is tested // without a database; this file is the end-to-end check. import postgres as pg import postgres.{type sql, sql} import std/bytes import std/dec.{type Dec} import std/list import std/option import std/os import std/process.{type proc} import std/random.{type random} import std/result import std/test.{assert, assert_equal} import std/time.{type clock} import uuid import config.{Config} import pool.{PoolSettings} @test fn a_long_query_can_be_cancelled :: -> () / { match os.env "LOUISE_PG_URL" { None -> () , Some(url) -> { let cfg = result.expect (pg.config url) "config" let conn = result.expect (pg.connect cfg) "connect" // A 30s query in another actor; cancel it from here. let done = process.subject () let _ = process.spawn fn { let answer = pg.query_on conn "select pg_sleep(30)" [] process.send done answer } process.sleep 300 // let the query reach the server result.expect (pg.cancel conn) "the cancel" match process.receive done 10000 { Some(answer) -> match answer { Ok(_) -> panic "pg_sleep should have been cancelled" , Error(e) -> assert_equal (pg.sqlstate e) Some("57014") } , None -> panic "no answer from the sleeper" } pg.close conn } } } @test fn listen_and_notify :: -> () / { match os.env "LOUISE_PG_URL" { None -> () , Some(url) -> { let cfg = result.expect (pg.config url) "config" let events = process.subject () let listener = result.expect (pg.listen cfg "louise_events" events) "listen" // NOTIFY from a pooled connection (the listener's LISTEN has // already landed: `pg.listen` returns after it). result.expect ( result.expect ( pg.with_connection (result.expect (pg.start_pool cfg 1) "the pool") fn { pg.execute "notify louise_events, 'hello'" [] } ) "notify" ) "the notify" match process.receive events 10000 { Some(n) -> { assert_equal n.channel "louise_events" assert_equal n.payload "hello" } , None -> panic "no notification within the timeout" } pg.unlisten listener } } } @test fn connects_queries_and_closes :: -> () / { match os.env "LOUISE_PG_URL" { None -> () // skipped: no database , Some(url) -> { let cfg = result.expect (pg.config url) "parse the URL" let conn = result.expect (pg.connect cfg) "connect" // A query without parameters, every v0 type in it. let res = result.expect ( pg.query_on conn "select 42 as answer, 'hello' as greeting, true as flag, null::text as nothing, '\\xdeadbeef'::bytea as blob" [] ) "the types query" assert_equal (list.length res.rows) 1 match res.rows { [row] -> { assert_equal (pg.row_int row "answer") Ok(Some(42)) assert_equal (pg.row_text row "greeting") Ok(Some("hello")) assert_equal (pg.row_bool row "flag") Ok(Some(True)) assert_equal (pg.row_text row "nothing") Ok(None) assert ( pg.row_bytea row "blob" == Ok(Some(bytes.from_list [222, 173, 190, 239])) ) "the blob round-trips" } , _ -> panic "one row" } // A parameterized one: the value never enters the SQL text. let counted = result.expect (pg.query_on conn "select $1::int + 1 as n" [pg.int 41]) "parameterized" match counted.rows { [row] -> assert_equal (pg.row_int row "n") Ok(Some(42)) , _ -> panic "one row" } // The same, written as a `sql` template. let via_template = result.expect (pg.query_statement_on conn sql`select {41}::int + 1 as n`) "the template" match via_template.rows { [row] -> assert_equal (pg.row_int row "n") Ok(Some(42)) , _ -> panic "one row" } // uuid and timestamptz values decode. let typed = result.expect ( pg.query_on conn "select 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::uuid as id, '2026-01-02 03:04:05.5+00'::timestamptz as at" [] ) "the typed query" match typed.rows { [row] -> { match pg.row_uuid row "id" { Ok(Some(id)) -> assert_equal (uuid.to_rfc id) "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11" , _ -> panic "the uuid" } match pg.row_timestamptz row "at" { Ok(Some(at)) -> assert_equal (time.format at) "2026-01-02T03:04:05.500Z" , _ -> panic "the timestamp" } } , _ -> panic "one row" } pg.close conn } } } @test fn executes_writes_and_errors_have_sqlstates :: -> () / { match os.env "LOUISE_PG_URL" { None -> () , Some(url) -> { let cfg = result.expect (pg.config url) "parse the URL" let conn = result.expect (pg.connect cfg) "connect" result.expect ( pg.execute_on conn "create table if not exists louise_live (id int primary key, note text)" [] ) "create table" result.expect (pg.execute_on conn "delete from louise_live" []) "delete" let changed = result.expect ( pg.execute_on conn "insert into louise_live (id, note) values ($1, $2), ($3, $4)" [pg.int 1, pg.text "first", pg.int 2, pg.null ()] ) "insert" assert_equal changed 2 // A duplicate key: SQLSTATE 23505. match pg.execute_on conn "insert into louise_live (id, note) values ($1, $2)" [pg.int 1, pg.text "again"] { Ok(_) -> panic "a duplicate key must fail" , Error(e) -> assert_equal (pg.sqlstate e) Some("23505") } // NULL came back as NULL. let res = result.expect ( pg.query_on conn "select note from louise_live where id = $1" [pg.int 2] ) "select" match res.rows { [row] -> assert_equal (pg.row_text row "note") Ok(None) , _ -> panic "one row" } pg.close conn } } } // ---- large bytea (issue gabla108/louise#311) --------------------------------------------------- @test fn a_large_bytea_round_trips_in_binary_and_in_a_template :: -> () / { match os.env "LOUISE_PG_URL" { None -> () , Some(url) -> { let cfg = result.expect (pg.config url) "config" let conn = result.expect (pg.connect cfg) "connect" result.expect ( pg.execute_on conn "create table if not exists louise_bytea (name text primary key, data bytea not null)" [] ) "create table" // 10 MB of deterministic bytes. Before the fix, a 37 MB value took // 20 s and 2.86 GB of RSS: the text form was one list cell and one // 2-character string per byte. let block = bytes.from_list (list.map (list.range 1 1000) fn i { i % 251 }) let data = bytes.concat_all (list.map (list.range 1 10_000) fn _ { block }) assert_equal (bytes.length data) 10_000_000 // The binary path: a `pg.bytea` parameter is declared oid 17 in the // Parse and binds as the raw bytes. let start = time.now () result.expect ( pg.execute_on conn "insert into louise_bytea (name, data) values ($1, $2) on conflict (name) do update set data = excluded.data" [pg.text "binary", pg.bytea data] ) "the binary insert" let binary_ms = time.in_milliseconds (time.since (time.now ()) start) assert (binary_ms < 2000) "a 10 MB bytea binds in binary: {binary_ms} ms (was ~5500)" // The template path: the hole is the `\x…` text form, now built in // one pass. let start = time.now () result.expect ( pg.execute_statement_on conn sql`insert into louise_bytea (name, data) values ({"template"}, {pg.bytea data}) on conflict (name) do update set data = excluded.data` ) "the template insert" let template_ms = time.in_milliseconds (time.since (time.now ()) start) assert (template_ms < 5000) "a 10 MB bytea through a template: {template_ms} ms (was ~5500)" // Both come back byte for byte (a bytea column reads in binary). list.each ["binary", "template"] fn name { let res = result.expect ( pg.query_on conn "select data from louise_bytea where name = $1" [pg.text name] ) "the read back" match res.rows { [row] -> assert (pg.row_bytea row "data" == Ok(Some(data))) "{name}: the 10 MB bytea round-trips" , _ -> panic "one row" } } pg.close conn } } } // ---- numeric (Dec, ADR 0070) ------------------------------------------------------- @test fn numeric_round_trips_without_loss :: -> () / { match os.env "LOUISE_PG_URL" { None -> () , Some(url) -> { let cfg = result.expect (pg.config url) "config" let conn = result.expect (pg.connect cfg) "connect" let price = result.expect (dec.parse "12345.6789") "a price" // A binary parameter (declared OID 1700), and binary results // (1700 is a known binary OID): exact both ways. let res = result.expect ( pg.query_on conn "select $1::numeric as price, 0.1::numeric as tenth, 1.20::numeric as padded" [pg.dec price] ) "the numeric query" match res.rows { [row] -> { assert_equal (pg.row_dec row "price") (Ok(Some(price))) assert_equal (pg.row_dec row "tenth") (Ok(Some(result.expect (dec.parse "0.1") "0.1"))) // 1.20 and 1.2 are one Dec (the fixed scale is canonical). assert_equal (pg.row_dec row "padded") (Ok(Some(result.expect (dec.parse "1.2") "1.2"))) } , _ -> panic "one row" } // Past Dec's range or precision: an Error, never a silent // truncation. 1e24 overflows; 1/3 rounds half-even at 18 places. let bounds = result.expect ( pg.query_on conn "select 1e24::numeric as huge, (1::numeric / 3) as third, 'NaN'::numeric as nan" [] ) "the bounds query" match bounds.rows { [row] -> { match pg.row_dec row "huge" { Error(_) -> () , Ok(v) -> panic "1e24 should not fit a Dec, got {v:?}" } assert_equal (pg.row_dec row "third") (Ok(Some(result.expect (dec.parse "0.333333333333333333") "1/3"))) match pg.row_dec row "nan" { Error(_) -> (), Ok(v) -> panic "NaN is not a Dec, got {v:?}" } } , _ -> panic "one row" } pg.close conn } } } // ---- the pool's knobs (issue gabla108/louise#145 §3) ------------------------------------------ /// The connection's own backend pid. fn backend_pid :: -> Int / { let res = result.expect (pg.query "select pg_backend_pid() as pid" []) "backend_pid" match res.rows { [row] -> option.unwrap_or (result.expect (pg.row_int row "pid") "the pid") 0 , _ -> panic "one row" } } /// The backends `app` has, counted from an outside connection (its own /// application name differs, so it doesn't count itself). fn backends :: observer: pg.Connection app: String -> Int / { let res = result.expect ( pg.query_on observer "select count(*) as n from pg_stat_activity where application_name = $1" [pg.text app] ) "count the backends" match res.rows { [row] -> option.unwrap_or (result.expect (pg.row_int row "n") "the count") 0 , _ -> panic "one row" } } /// `pg_stat_activity` can lag a close by a beat: poll, about 5 s at most. fn wait_backends :: observer: pg.Connection app: String want: Int tries: Int -> () / { if backends observer app == want { () } else if tries <= 0 { assert_equal (backends observer app) want } else { process.sleep 200 wait_backends observer app want (tries - 1) } } @test fn the_pool_reaps_idle_connections_to_min_idle :: -> () / { match os.env "LOUISE_PG_URL" { None -> () , Some(url) -> { let cfg = result.expect (pg.config url) "config" let observer = result.expect (pg.connect cfg) "the observer" let app = "louise-pool-idle" let settings = PoolSettings( ..pg.pool_settings 2 , min_idle: 1 , idle_timeout: 1000 , tick: 250 ) let pl = result.expect (pg.start_pool_with Config(..cfg, application: app) settings) "the pool" wait_backends observer app 2 10 // eager start wait_backends observer app 1 25 // the idle timeout reaps to the floor // the floor stays warm process.sleep 1000 assert_equal (backends observer app) 1 // and the pool still serves result.expect (pg.with_connection pl fn { pg.execute "select 1" [] }) "a query after the reap" pg.close observer } } } @test fn a_connection_past_its_lifetime_is_recycled_on_return :: -> () / { match os.env "LOUISE_PG_URL" { None -> () , Some(url) -> { let cfg = result.expect (pg.config url) "config" let observer = result.expect (pg.connect cfg) "the observer" let app = "louise-pool-life" let settings = PoolSettings(..pg.pool_settings 1, max_lifetime: 800, tick: 250) let pl = result.expect (pg.start_pool_with Config(..cfg, application: app) settings) "the pool" // Held past its lifetime: the return closes it (the tick only // reaps idle connections, never one in use). let first = result.expect ( pg.with_connection pl fn { let pid = backend_pid () process.sleep 1200 pid } ) "the first hold" let second = result.expect (pg.with_connection pl fn { backend_pid () }) "the second" assert (first != 0 && second != 0 && first != second) "the connection was recycled on return" pg.close observer } } } @test fn a_stale_connection_fails_its_ping_and_is_replaced :: -> () / { match os.env "LOUISE_PG_URL" { None -> () , Some(url) -> { let cfg = result.expect (pg.config url) "config" let observer = result.expect (pg.connect cfg) "the observer" let app = "louise-pool-stale" let settings = PoolSettings(..pg.pool_settings 1, check_after: 500, tick: 250) let pl = result.expect (pg.start_pool_with Config(..cfg, application: app) settings) "the pool" let first = result.expect (pg.with_connection pl fn { backend_pid () }) "the first" // The server kills it; the pool doesn't know yet. That's the // point of the check: a connection idle past `check_after` is // pinged before it is handed out. result.expect ( pg.query_on observer "select pg_terminate_backend($1) as killed" [pg.int first] ) "terminate the backend" wait_backends observer app 0 25 process.sleep 1000 // let it sit past check_after let second = result.expect (pg.with_connection pl fn { backend_pid () }) "the replacement" assert (second != 0 && second != first) "a fresh connection replaced the stale one" pg.close observer } } }