use std::sync::Arc;
use async_trait::async_trait;
use sqlx::{PgConnection, PgPool};
use systemprompt_traits::{ChangeActor, ChangeSource, ConfigVersionSource, RepositoryError};
use crate::DbPool;
pub type PlaneTransaction = sqlx::Transaction<'static, sqlx::Postgres>;
pub async fn with_change_context(
conn: &mut PgConnection,
actor: &ChangeActor,
reason: Option<&str>,
source: &ChangeSource,
) -> Result<(), RepositoryError> {
let source = source.to_string();
sqlx::query!(
"SELECT set_config('systemprompt.actor', $1, true) AS actor, \
set_config('systemprompt.reason', $2, true) AS reason, \
set_config('systemprompt.source', $3, true) AS source",
actor.label(),
reason.unwrap_or_default(),
source,
)
.fetch_one(conn)
.await?;
Ok(())
}
#[derive(Debug, Clone)]
pub struct PgConfigVersion {
pool: Arc<PgPool>,
}
impl PgConfigVersion {
#[must_use]
pub fn new(db: &DbPool) -> Self {
Self {
pool: db.write_pool(),
}
}
}
#[async_trait]
impl ConfigVersionSource for PgConfigVersion {
async fn current_version(&self) -> Result<i64, RepositoryError> {
let version = sqlx::query_scalar!("SELECT version FROM config_version WHERE id = 1")
.fetch_optional(&*self.pool)
.await?;
Ok(version.unwrap_or(0))
}
}