Skip to main content

faucet_cli/serve/history/
postgres.rs

1//! Postgres-backed run history (`serve-history-postgres`, Phase 5 of #127).
2//! Connection setup only — the schema, statements, and `RunHistory` impl are
3//! shared with SQLite via [`impl_sql_history!`](super::sql).
4
5use super::HistoryError;
6use super::sql::{DDL, Dialect, Stmts, impl_sql_history};
7use sqlx::postgres::PgPoolOptions;
8use std::time::Duration;
9
10impl_sql_history!(PostgresHistory, sqlx::PgPool);
11
12impl PostgresHistory {
13    /// Connect, create the schema if absent, and return the backend. `lease_ttl`
14    /// and `instance_id` drive instance-fenced orphan recovery (#146 H7).
15    pub async fn connect(
16        url: &str,
17        idem_retention: Duration,
18        lease_ttl: Duration,
19        instance_id: String,
20    ) -> Result<Self, HistoryError> {
21        let pool = PgPoolOptions::new()
22            .max_connections(5)
23            .connect(url)
24            .await
25            .map_err(|e| HistoryError::Backend(format!("Postgres connection failed: {e}")))?;
26        for stmt in DDL {
27            sqlx::query(stmt)
28                .execute(&pool)
29                .await
30                .map_err(|e| HistoryError::Backend(format!("creating run-history schema: {e}")))?;
31        }
32        Ok(Self::from_parts(
33            pool,
34            idem_retention,
35            lease_ttl,
36            instance_id,
37            Stmts::new(Dialect::Postgres),
38        ))
39    }
40}