systemprompt_database/lifecycle/
validation.rs1use crate::services::DatabaseProvider;
2use anyhow::{Context, Result};
3
4pub async fn validate_database_connection(db: &dyn DatabaseProvider) -> Result<()> {
5 db.test_connection()
6 .await
7 .context("Failed to establish database connection")
8}
9
10pub async fn validate_table_exists(db: &dyn DatabaseProvider, table_name: &str) -> Result<bool> {
11 let result = db
12 .query_raw_with(
13 &"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = \
14 'public' AND table_name = $1) as exists",
15 vec![serde_json::Value::String(table_name.to_string())],
16 )
17 .await?;
18
19 result
20 .first()
21 .and_then(|row| row.get("exists"))
22 .and_then(serde_json::Value::as_bool)
23 .ok_or_else(|| anyhow::anyhow!("Failed to check table existence for '{}'", table_name))
24}
25
26pub async fn validate_column_exists(
27 db: &dyn DatabaseProvider,
28 table_name: &str,
29 column_name: &str,
30) -> Result<bool> {
31 let result = db
32 .query_raw_with(
33 &"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = \
34 'public' AND table_name = $1 AND column_name = $2) as exists",
35 vec![
36 serde_json::Value::String(table_name.to_string()),
37 serde_json::Value::String(column_name.to_string()),
38 ],
39 )
40 .await?;
41
42 result
43 .first()
44 .and_then(|row| row.get("exists"))
45 .and_then(serde_json::Value::as_bool)
46 .ok_or_else(|| {
47 anyhow::anyhow!(
48 "Failed to check column existence for '{}.{}'",
49 table_name,
50 column_name
51 )
52 })
53}