Skip to main content

systemprompt_database/lifecycle/
validation.rs

1//! Pre-flight validation helpers used by the boot path and tests.
2//!
3//! Copyright (c) systemprompt.io — Business Source License 1.1.
4//! See <https://systemprompt.io> for licensing details.
5
6use crate::error::{DatabaseResult, RepositoryError};
7use crate::services::DatabaseProvider;
8
9pub async fn validate_database_connection(db: &dyn DatabaseProvider) -> DatabaseResult<()> {
10    db.test_connection().await.map_err(|e| {
11        RepositoryError::Internal(format!("Failed to establish database connection: {e}"))
12    })
13}
14
15pub async fn validate_table_exists(
16    db: &dyn DatabaseProvider,
17    table_name: &str,
18) -> DatabaseResult<bool> {
19    let result = db
20        .query_raw_with(
21            &"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = \
22              'public' AND table_name = $1) as exists",
23            &[&table_name],
24        )
25        .await?;
26
27    result
28        .first()
29        .and_then(|row| row.get("exists"))
30        .and_then(serde_json::Value::as_bool)
31        .ok_or_else(|| {
32            RepositoryError::Internal(format!(
33                "Failed to check table existence for '{table_name}'"
34            ))
35        })
36}
37
38pub async fn validate_column_exists(
39    db: &dyn DatabaseProvider,
40    table_name: &str,
41    column_name: &str,
42) -> DatabaseResult<bool> {
43    let result = db
44        .query_raw_with(
45            &"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = \
46              'public' AND table_name = $1 AND column_name = $2) as exists",
47            &[&table_name, &column_name],
48        )
49        .await?;
50
51    result
52        .first()
53        .and_then(|row| row.get("exists"))
54        .and_then(serde_json::Value::as_bool)
55        .ok_or_else(|| {
56            RepositoryError::Internal(format!(
57                "Failed to check column existence for '{table_name}.{column_name}'"
58            ))
59        })
60}