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//!
6//! Copyright (c) systemprompt.io — Business Source License 1.1.
7//! See <https://systemprompt.io> for licensing details.
8
9use crate::error::RuntimeResult;
10use std::sync::Arc;
11use systemprompt_database::{Database, DbPool};
12
13#[derive(Debug, Clone)]
14pub struct DatabaseContext {
15    database: DbPool,
16}
17
18impl DatabaseContext {
19    #[must_use]
20    pub const fn from_pool(pool: DbPool) -> Self {
21        Self { database: pool }
22    }
23
24    pub async fn from_url(database_url: &str) -> RuntimeResult<Self> {
25        let db = Database::new_postgres(database_url).await?;
26        Ok(Self {
27            database: Arc::new(db),
28        })
29    }
30
31    pub async fn from_urls(read_url: &str, write_url: Option<&str>) -> RuntimeResult<Self> {
32        let db = Database::connect(
33            read_url,
34            write_url,
35            &systemprompt_database::PoolConfig::default(),
36        )
37        .await?;
38        Ok(Self {
39            database: Arc::new(db),
40        })
41    }
42
43    pub const fn db_pool(&self) -> &DbPool {
44        &self.database
45    }
46
47    pub fn db_pool_arc(&self) -> DbPool {
48        Arc::clone(&self.database)
49    }
50}