Skip to main content

wabot_feature_pg/
lib.rs

1//! # wabot-feature-pg
2//!
3//! Postgres foundation — port of `wabot-ts/src/feature/pg`. Provides:
4//!
5//! * [`PgConfig`] / [`PgDatabase`] — pool construction from
6//!   `DATABASE_URL` + `WABOT_PG_*`, registrable as a DI singleton.
7//! * [`PgJsonbStore`] — the JSONB document store every framework table
8//!   uses (`id` / `created_at` / `data` + promoted columns), created
9//!   on first use.
10//! * [`PgLocker`] — distributed [`wabot_core::lock::Locker`] on
11//!   advisory locks; the piece that makes multi-node scheduling safe.
12//!
13//! ## What's ported and what isn't
14//!
15//! wabot-ts's `feature/pg` is much larger — `PgCrudRepository`,
16//! projections, audit log, idempotency, rate limiter, columnar SQL,
17//! the migration runner. This crate ports the **document-storage +
18//! locking core** the framework itself needs, which is what the async
19//! and chat-bot addons sit on. The relational/columnar strategy and
20//! its migration tooling are a separate piece of work; nothing here
21//! forecloses it.
22//!
23//! ```ignore
24//! let db = PgDatabase::connect(PgConfig::from_env()?).await?;
25//! c.register_instance::<PgDatabase>(Arc::new(db));
26//! ```
27
28pub mod columns;
29pub mod config;
30pub mod error;
31pub mod indexes;
32pub mod infra;
33pub mod jsonb;
34pub mod locker;
35pub mod migrations;
36pub mod projection;
37pub mod query_sql;
38pub mod repository;
39pub mod transaction;
40
41pub use columns::PgColumnsStore;
42pub use indexes::build_index_ddl;
43pub use infra::{PgAuditLog, PgIdempotency, PgRateLimiter};
44pub use query_sql::{build_query_sql, BuiltQuery, FieldPlacement, QuerySqlError};
45
46pub use config::PgConfig;
47pub use error::{PgError, PgResult};
48pub use jsonb::{PgJsonbStore, PromotedColumn};
49pub use locker::PgLocker;
50pub use migrations::{MigrationRunner, MigrationStatus};
51pub use projection::PgProjectionRuntime;
52pub use transaction::{in_transaction, with_transaction};
53
54use std::sync::Arc;
55
56use sqlx::PgPool;
57
58/// Owns the connection pool. A thin newtype rather than using
59/// `sqlx::PgPool` directly, because the DI container keys on the
60/// concrete type and a bare `PgPool` would collide with any other
61/// pool an app registers.
62pub struct PgDatabase {
63    pool: PgPool,
64}
65
66impl PgDatabase {
67    /// Open a pool from `config`. Connections are lazy — see
68    /// [`PgDatabase::ping`] for a startup reachability check.
69    pub async fn connect(config: PgConfig) -> PgResult<Self> {
70        Ok(Self {
71            pool: config.connect().await?,
72        })
73    }
74
75    /// Open a pool from `DATABASE_URL` + the `WABOT_PG_*` knobs.
76    pub async fn from_env() -> PgResult<Self> {
77        Self::connect(PgConfig::from_env()?).await
78    }
79
80    pub fn from_pool(pool: PgPool) -> Self {
81        Self { pool }
82    }
83
84    pub fn pool(&self) -> &PgPool {
85        &self.pool
86    }
87
88    pub fn arc(self) -> Arc<Self> {
89        Arc::new(self)
90    }
91
92    /// Round-trip a trivial query. Call at boot when you'd rather fail
93    /// immediately than on the first real request.
94    pub async fn ping(&self) -> PgResult<()> {
95        sqlx::query("SELECT 1").execute(&self.pool).await?;
96        Ok(())
97    }
98
99    /// Close the pool and wait for checked-out connections to return.
100    pub async fn close(&self) {
101        self.pool.close().await;
102    }
103}