use duckdb::Connection;
use std::sync::{Arc, Mutex};
#[derive(Debug, thiserror::Error)]
pub enum DuckDbConnectionError {
#[error("invalid DuckDB URL: {0}")]
InvalidUrl(String),
#[error("failed to open DuckDB database: {0}")]
Open(#[from] duckdb::Error),
}
pub struct DuckDbExecutor {
conn: Arc<Mutex<Connection>>,
}
impl DuckDbExecutor {
pub fn from_url(url: &str) -> Result<Self, DuckDbConnectionError> {
let path = url
.strip_prefix("duckdb://")
.ok_or_else(|| DuckDbConnectionError::InvalidUrl(
format!("expected duckdb:// prefix, got '{url}'"),
))?;
let conn = match path {
"" | ":memory:" => Connection::open_in_memory()?,
p => Connection::open(p)?,
};
Ok(Self { conn: Arc::new(Mutex::new(conn)) })
}
pub(super) fn conn(&self) -> Arc<Mutex<Connection>> {
Arc::clone(&self.conn)
}
}