use anyhow::{Result, anyhow};
use once_cell::sync::Lazy;
use sqlx::PgPool;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, warn};
type TableColumnMap = HashMap<String, HashMap<String, String>>;
static COLUMN_CACHE: Lazy<Arc<RwLock<TableColumnMap>>> =
Lazy::new(|| Arc::new(RwLock::new(HashMap::new())));
async fn fetch_table_columns(pool: &PgPool, table_name: &str) -> Result<Vec<String>> {
let query = r#"
SELECT column_name
FROM information_schema.columns
WHERE table_name = $1
AND table_schema = 'public'
ORDER BY ordinal_position
"#;
let rows = sqlx::query_scalar::<_, String>(query)
.bind(table_name)
.fetch_all(pool)
.await
.map_err(|e| anyhow!("Failed to query table columns: {}", e))?;
Ok(rows)
}
#[doc(hidden)]
pub fn find_matching_column(requested: &str, available_columns: &[String]) -> Option<String> {
let requested_lower = requested.to_lowercase();
for col in available_columns {
if col.to_lowercase() == requested_lower {
return Some(col.clone());
}
}
let snake_case_version = crate::utils::format::camel_to_snake_case(requested);
for col in available_columns {
if col.to_lowercase() == snake_case_version.to_lowercase() {
return Some(col.clone());
}
}
let requested_parts: Vec<&str> = requested_lower.split('_').collect();
if requested_parts.len() >= 2 {
let prefix = requested_parts[0];
let mut candidates: Vec<&String> = available_columns
.iter()
.filter(|col| col.to_lowercase().starts_with(prefix))
.collect();
if candidates.len() == 1 {
debug!(
"Fuzzy matched '{}' to '{}' based on prefix '{}' for columns {:?}",
requested, candidates[0], prefix, available_columns
);
return Some(candidates[0].clone());
}
candidates.sort_by_key(|col| col.len());
if let Some(best) = candidates.first() {
debug!(
"Multiple matches for '{}', choosing shortest: '{}'",
requested, best
);
return Some((*best).clone());
}
}
None
}
pub async fn resolve_columns(
pool: &PgPool,
table_name: &str,
requested_columns: &[&str],
) -> Result<Vec<String>> {
{
let cache = COLUMN_CACHE.read().await;
if let Some(table_map) = cache.get(table_name) {
let mut resolved = Vec::new();
for &requested in requested_columns {
if let Some(actual) = table_map.get(requested) {
resolved.push(actual.clone());
} else {
drop(cache);
return refresh_and_resolve(pool, table_name, requested_columns).await;
}
}
return Ok(resolved);
}
}
refresh_and_resolve(pool, table_name, requested_columns).await
}
async fn refresh_and_resolve(
pool: &PgPool,
table_name: &str,
requested_columns: &[&str],
) -> Result<Vec<String>> {
let available_columns = fetch_table_columns(pool, table_name).await?;
if available_columns.is_empty() {
return Err(anyhow!(
"Table '{}' not found or has no columns",
table_name
));
}
let mut table_map: HashMap<String, String> = HashMap::new();
let mut resolved = Vec::new();
for &requested in requested_columns {
if let Some(actual) = find_matching_column(requested, &available_columns) {
table_map.insert(requested.to_string(), actual.clone());
resolved.push(actual);
} else {
warn!(
"Column '{}' not found in table '{}'. Available columns: {:?}",
requested, table_name, available_columns
);
return Err(anyhow!(
"Column '{}' does not exist in table '{}'. Available columns: {:?}",
requested,
table_name,
available_columns
));
}
}
{
let mut cache = COLUMN_CACHE.write().await;
cache.insert(table_name.to_string(), table_map);
}
Ok(resolved)
}
pub async fn clear_cache(table_name: Option<&str>) {
let mut cache = COLUMN_CACHE.write().await;
match table_name {
Some(name) => {
cache.remove(name);
debug!("Cleared column cache for table '{}'", name);
}
None => {
cache.clear();
debug!("Cleared all column caches");
}
}
}