use crate::{DEFAULT_MAX_RETRIES, VlorQl};
use serde_json::json;
use std::path::PathBuf;
use std::sync::Arc;
#[cfg(feature = "vector-search")]
use std::sync::atomic::AtomicBool;
use vlorql_core::cache::{CompileCache, LlmResponseCache, PromptCache, SchemaCache};
use vlorql_core::compile::{RewriteEngine, SqlCompiler, get_compiler};
use vlorql_core::errors::{ConfigErrorKind, VlorQLError};
use vlorql_core::execute::DatabaseExecutor;
use vlorql_core::observability::{TelemetryGuard, VlorqMetrics, init_telemetry};
use vlorql_core::optimizer::QueryOptimizer;
use vlorql_core::policy::PolicyConfig;
use vlorql_core::schema::{
ArcSchemaSnapshot, DialectProfile, IdentifierQuoting, SchemaSnapshot, SqlDialect,
};
use vlorql_core::statistics::StatisticsProvider;
use vlorql_llm::{LlmClient, LlmConfig, create_llm_client};
pub struct VlorQlBuilder {
schema: Option<ArcSchemaSnapshot>,
dialect: Option<DialectProfile>,
dialect_name: Option<String>,
policy: PolicyConfig,
compiler: Option<Box<dyn SqlCompiler>>,
rewrite_engine: Option<RewriteEngine>,
llm_client: Option<Box<dyn LlmClient>>,
llm_config: Option<LlmConfig>,
max_retries: usize,
stats_provider: Option<Arc<dyn StatisticsProvider>>,
schema_cache_config: Option<(u64, u64)>,
compile_cache: Option<Arc<CompileCache>>,
prompt_cache: Option<Arc<PromptCache>>,
llm_cache: Option<LlmResponseCache>,
telemetry_endpoint: Option<String>,
telemetry_guard: Option<TelemetryGuard>,
metrics: Option<Arc<VlorqMetrics>>,
executor: Option<Arc<dyn DatabaseExecutor>>,
vector_search: bool,
#[cfg(feature = "vector-search")]
schema_indexer: Option<Arc<vlorql_core::prompt::schema_index::SchemaIndexer>>,
}
impl Default for VlorQlBuilder {
fn default() -> Self {
Self {
schema: None,
dialect: None,
dialect_name: None,
policy: PolicyConfig::default(),
compiler: None,
rewrite_engine: None,
llm_client: None,
llm_config: None,
max_retries: DEFAULT_MAX_RETRIES,
stats_provider: None,
schema_cache_config: None,
compile_cache: None,
prompt_cache: None,
llm_cache: None,
telemetry_endpoint: None,
telemetry_guard: None,
metrics: None,
executor: None,
vector_search: false,
#[cfg(feature = "vector-search")]
schema_indexer: None,
}
}
}
impl VlorQlBuilder {
#[must_use]
pub fn with_schema(mut self, schema: Arc<SchemaSnapshot>) -> Self {
self.schema = Some(schema);
self
}
#[must_use]
pub fn with_dialect(mut self, dialect: DialectProfile) -> Self {
self.dialect = Some(dialect);
self.dialect_name = None;
self
}
#[must_use]
pub fn with_policy(mut self, policy: PolicyConfig) -> Self {
self.policy = policy;
self
}
#[must_use]
pub fn with_llm_client<C>(mut self, client: C) -> Self
where
C: LlmClient + 'static,
{
self.llm_client = Some(Box::new(client));
self
}
#[must_use]
pub fn with_llm_config(mut self, config: LlmConfig) -> Self {
self.llm_config = Some(config);
self
}
#[must_use]
pub fn with_compiler<C>(mut self, compiler: C) -> Self
where
C: SqlCompiler + 'static,
{
self.compiler = Some(Box::new(compiler));
self
}
#[must_use]
pub fn with_rewrite_engine(mut self, engine: RewriteEngine) -> Self {
self.rewrite_engine = Some(engine);
self
}
#[must_use]
pub fn with_dialect_name(mut self, dialect: impl Into<String>) -> Self {
self.dialect_name = Some(dialect.into());
self.dialect = None;
self
}
#[must_use]
pub fn with_max_retries(mut self, max_retries: usize) -> Self {
self.max_retries = max_retries;
self
}
#[must_use]
pub fn with_statistics_provider(mut self, provider: Arc<dyn StatisticsProvider>) -> Self {
self.stats_provider = Some(provider);
self
}
#[must_use]
pub fn with_schema_cache(mut self, capacity: u64, ttl_seconds: u64) -> Self {
self.schema_cache_config = Some((capacity, ttl_seconds));
self
}
#[must_use]
pub fn with_compile_cache(mut self, max_size: u64, ttl_seconds: u64) -> Self {
self.compile_cache = Some(Arc::new(CompileCache::new(max_size, ttl_seconds)));
self
}
#[must_use]
pub fn with_persistent_compile_cache(
mut self,
max_size: u64,
ttl_seconds: u64,
path: impl Into<PathBuf>,
) -> Self {
let path = path.into();
if let Ok(handle) = tokio::runtime::Handle::try_current() {
let cache = handle.block_on(CompileCache::load(&path, max_size, ttl_seconds));
self.compile_cache = Some(Arc::new(cache));
} else {
self.compile_cache = Some(Arc::new(CompileCache::with_persistence(
max_size,
ttl_seconds,
path,
)));
}
self
}
#[must_use]
pub fn with_prompt_cache(mut self, capacity: u64, ttl_seconds: u64) -> Self {
self.prompt_cache = Some(Arc::new(PromptCache::new(capacity, ttl_seconds)));
self
}
#[must_use]
pub fn with_llm_cache(mut self, max_entries: u64, ttl_seconds: u64) -> Self {
self.llm_cache = Some(LlmResponseCache::new(max_entries, ttl_seconds));
self
}
#[must_use]
pub fn with_telemetry(mut self, otlp_endpoint: String) -> Self {
match init_telemetry("vlorql", &otlp_endpoint) {
Ok(guard) => {
self.telemetry_guard = Some(guard);
}
Err(e) => {
tracing::warn!(error = %e, "failed to initialise OTLP telemetry; continuing without it");
}
}
self.telemetry_endpoint = Some(otlp_endpoint);
self
}
#[must_use]
pub fn with_metrics(mut self, metrics: Arc<VlorqMetrics>) -> Self {
self.metrics = Some(metrics);
self
}
#[must_use]
pub fn with_executor(mut self, executor: Arc<dyn DatabaseExecutor>) -> Self {
self.executor = Some(executor);
self
}
#[cfg(feature = "vector-search")]
#[must_use]
pub fn with_vector_search(mut self, enabled: bool) -> Self {
self.vector_search = enabled;
self
}
#[cfg(feature = "vector-search")]
#[must_use]
pub fn with_schema_indexer(
mut self,
indexer: Arc<vlorql_core::prompt::schema_index::SchemaIndexer>,
) -> Self {
self.schema_indexer = Some(indexer);
self
}
pub fn build(self) -> Result<VlorQl, VlorQLError> {
vlorql_core::observability::init_console_logging();
let schema = self.schema.ok_or_else(|| {
VlorQLError::config(
ConfigErrorKind::MissingSchema,
json!({"component": "schema"}),
)
})?;
let dialect = match (self.dialect, self.dialect_name) {
(Some(dialect), _) => dialect,
(None, Some(name)) => parse_dialect_name(&name)?,
(None, None) => {
return Err(VlorQLError::config(
ConfigErrorKind::InvalidDialect {
dialect: "not configured".to_owned(),
},
json!({"component": "dialect"}),
));
}
};
let compiler = self
.compiler
.unwrap_or_else(|| get_compiler(dialect.dialect));
let llm_client = match (self.llm_client, self.llm_config) {
(Some(client), _) => Some(Arc::from(client)),
(None, Some(config)) => Some(Arc::from(create_llm_client(config)?)),
(None, None) => None,
};
let optimizer = self.stats_provider.map(QueryOptimizer::new);
let schema_cache = self.schema_cache_config.map(|(capacity, ttl_seconds)| {
Arc::new(SchemaCache::new(
capacity,
ttl_seconds,
self.metrics.clone(),
))
});
let vector_search = self.vector_search;
Ok(VlorQl {
schema,
dialect,
policy: self.policy,
compiler: Arc::from(compiler),
rewrite_engine: self.rewrite_engine,
llm_client,
max_retries: self.max_retries,
optimizer,
schema_cache,
compile_cache: self.compile_cache,
prompt_cache: self.prompt_cache,
llm_cache: self
.llm_cache
.unwrap_or_else(|| LlmResponseCache::new(1000, 3600)),
telemetry_guard: self.telemetry_guard,
metrics: self.metrics,
executor: self.executor,
vector_search,
#[cfg(feature = "vector-search")]
schema_indexer: self.schema_indexer,
#[cfg(feature = "vector-search")]
schema_indexed: AtomicBool::new(false),
})
}
}
fn parse_dialect_name(name: &str) -> Result<DialectProfile, VlorQLError> {
let normalized = name.trim().to_ascii_lowercase();
let dialect = match normalized.as_str() {
"postgres" | "postgresql" => SqlDialect::Postgres,
"sqlite" => SqlDialect::Sqlite,
"mysql" | "my_sql" => SqlDialect::MySql,
_ => {
return Err(VlorQLError::config(
ConfigErrorKind::InvalidDialect {
dialect: name.to_owned(),
},
json!({"accepted": ["postgres", "sqlite", "mysql"]}),
));
}
};
let quote_style = if dialect == SqlDialect::MySql {
IdentifierQuoting::Backtick
} else {
IdentifierQuoting::DoubleQuote
};
Ok(DialectProfile {
dialect,
quote_style,
..DialectProfile::default()
})
}