Skip to main content

systemprompt_runtime/
database_context.rs

1//! Lightweight database-only runtime context.
2//!
3//! [`DatabaseContext`] is used by CLI / tooling paths that need a
4//! `DbPool` without spinning up the full [`crate::AppContext`].
5
6use crate::error::RuntimeResult;
7use std::sync::Arc;
8use systemprompt_database::{Database, DbPool};
9
10#[derive(Debug, Clone)]
11pub struct DatabaseContext {
12    database: DbPool,
13}
14
15impl DatabaseContext {
16    #[must_use]
17    pub const fn from_pool(pool: DbPool) -> Self {
18        Self { database: pool }
19    }
20
21    pub async fn from_url(database_url: &str) -> RuntimeResult<Self> {
22        let db = Database::new_postgres(database_url).await?;
23        Ok(Self {
24            database: Arc::new(db),
25        })
26    }
27
28    pub async fn from_urls(read_url: &str, write_url: Option<&str>) -> RuntimeResult<Self> {
29        let db = Database::from_config_with_write(
30            "postgres",
31            read_url,
32            write_url,
33            &systemprompt_database::PoolConfig::default(),
34        )
35        .await?;
36        Ok(Self {
37            database: Arc::new(db),
38        })
39    }
40
41    pub const fn db_pool(&self) -> &DbPool {
42        &self.database
43    }
44
45    pub fn db_pool_arc(&self) -> DbPool {
46        Arc::clone(&self.database)
47    }
48}