vlorql_core/statistics/providers.rs
1//! Pluggable sources of table and column statistics.
2//!
3//! A [`StatisticsProvider`] abstracts *where* statistics come from so
4//! the planner does not care whether they were collected from a live
5//! database, read from a checked-in file, or synthesized for a test.
6//!
7//! Two implementations ship with the crate:
8//!
9//! * [`DummyStatisticsProvider`] serves a fixed in-memory
10//! [`StatisticsCatalog`] and is convenient for tests.
11//! * [`ConfigFileStatisticsProvider`] loads a catalog from a JSON or
12//! YAML file on disk.
13
14use std::path::{Path, PathBuf};
15
16use async_trait::async_trait;
17
18use crate::errors::{ConfigErrorKind, VlorQLError};
19
20use super::stats::{ColumnStatistics, StatisticsCatalog, TableStatistics};
21
22/// A source of table- and column-level statistics.
23///
24/// Implementations are `Send + Sync` so a single provider can be shared
25/// across the async tasks that build and cost query plans.
26#[async_trait]
27pub trait StatisticsProvider: Send + Sync {
28 /// Returns statistics for `table_name`, or `None` if the provider
29 /// has none for that table.
30 async fn get_table_stats(
31 &self,
32 table_name: &str,
33 ) -> Result<Option<TableStatistics>, VlorQLError>;
34
35 /// Returns statistics for `table_name.column_name`, or `None` if the
36 /// provider has none for that column.
37 async fn get_column_stats(
38 &self,
39 table_name: &str,
40 column_name: &str,
41 ) -> Result<Option<ColumnStatistics>, VlorQLError>;
42
43 /// Returns the full statistics catalog known to the provider.
44 async fn get_catalog_stats(&self) -> Result<StatisticsCatalog, VlorQLError>;
45}
46
47/// A [`StatisticsProvider`] backed by a fixed in-memory catalog.
48///
49/// Useful in tests and for supplying hand-authored estimates. Construct
50/// it with a prepared [`StatisticsCatalog`] via [`Self::new`], or with
51/// an empty catalog via [`Default`].
52///
53/// # Examples
54///
55/// ```
56/// # #[tokio::main]
57/// # async fn main() {
58/// use vlorql_core::statistics::{
59/// DummyStatisticsProvider, StatisticsCatalog, StatisticsProvider, TableStatistics,
60/// };
61///
62/// let mut catalog = StatisticsCatalog::default();
63/// catalog.tables.insert(
64/// "users".to_owned(),
65/// TableStatistics {
66/// row_count: 1_000,
67/// ..TableStatistics::default()
68/// },
69/// );
70///
71/// let provider = DummyStatisticsProvider::new(catalog);
72/// let stats = provider.get_table_stats("users").await.unwrap().unwrap();
73/// assert_eq!(stats.row_count, 1_000);
74/// assert!(provider.get_table_stats("missing").await.unwrap().is_none());
75/// # }
76/// ```
77#[derive(Debug, Clone, Default)]
78pub struct DummyStatisticsProvider {
79 catalog: StatisticsCatalog,
80}
81
82impl DummyStatisticsProvider {
83 /// Creates a provider that serves the given catalog.
84 pub fn new(catalog: StatisticsCatalog) -> Self {
85 Self { catalog }
86 }
87}
88
89#[async_trait]
90impl StatisticsProvider for DummyStatisticsProvider {
91 async fn get_table_stats(
92 &self,
93 table_name: &str,
94 ) -> Result<Option<TableStatistics>, VlorQLError> {
95 Ok(self.catalog.table(table_name).cloned())
96 }
97
98 async fn get_column_stats(
99 &self,
100 table_name: &str,
101 column_name: &str,
102 ) -> Result<Option<ColumnStatistics>, VlorQLError> {
103 Ok(self.catalog.column(table_name, column_name).cloned())
104 }
105
106 async fn get_catalog_stats(&self) -> Result<StatisticsCatalog, VlorQLError> {
107 Ok(self.catalog.clone())
108 }
109}
110
111/// The on-disk encoding of a statistics file.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113enum FileFormat {
114 Json,
115 Yaml,
116}
117
118/// A [`StatisticsProvider`] that loads a catalog from a JSON or YAML file.
119///
120/// The file format is inferred from the extension: `.yaml`/`.yml` are
121/// parsed as YAML and anything else is parsed as JSON. The file is read
122/// eagerly when the provider is constructed so later lookups are
123/// infallible reads of the in-memory catalog.
124///
125/// # Examples
126///
127/// ```no_run
128/// # #[tokio::main]
129/// # async fn main() {
130/// use vlorql_core::statistics::{ConfigFileStatisticsProvider, StatisticsProvider};
131///
132/// let provider = ConfigFileStatisticsProvider::load("stats.yaml").unwrap();
133/// let catalog = provider.get_catalog_stats().await.unwrap();
134/// println!("{} tables", catalog.tables.len());
135/// # }
136/// ```
137#[derive(Debug, Clone)]
138pub struct ConfigFileStatisticsProvider {
139 path: PathBuf,
140 catalog: StatisticsCatalog,
141}
142
143impl ConfigFileStatisticsProvider {
144 /// Reads and parses a statistics file, inferring the format from the
145 /// file extension (`.yaml`/`.yml` for YAML, otherwise JSON).
146 ///
147 /// Returns a [`ConfigErrorKind::ConfigFileError`] if the file cannot
148 /// be read or its contents cannot be parsed.
149 pub fn load(path: impl AsRef<Path>) -> Result<Self, VlorQLError> {
150 let path = path.as_ref().to_path_buf();
151 let contents = std::fs::read_to_string(&path)
152 .map_err(|error| Self::file_error(&path, format!("could not read file: {error}")))?;
153 Self::from_str(path, &contents)
154 }
155
156 /// Parses a catalog from an in-memory string, using `path` only to
157 /// choose the format and to build error messages.
158 ///
159 /// This is the I/O-free core of [`Self::load`] and is handy in tests
160 /// that do not want to touch the filesystem.
161 pub fn from_str(path: impl AsRef<Path>, contents: &str) -> Result<Self, VlorQLError> {
162 let path = path.as_ref().to_path_buf();
163 let catalog = match Self::format_of(&path) {
164 FileFormat::Yaml => serde_yaml::from_str(contents)
165 .map_err(|error| Self::file_error(&path, format!("invalid YAML: {error}")))?,
166 FileFormat::Json => serde_json::from_str(contents)
167 .map_err(|error| Self::file_error(&path, format!("invalid JSON: {error}")))?,
168 };
169 Ok(Self { path, catalog })
170 }
171
172 /// Returns the path the catalog was loaded from.
173 pub fn path(&self) -> &Path {
174 &self.path
175 }
176
177 fn format_of(path: &Path) -> FileFormat {
178 match path
179 .extension()
180 .and_then(|extension| extension.to_str())
181 .map(str::to_ascii_lowercase)
182 .as_deref()
183 {
184 Some("yaml" | "yml") => FileFormat::Yaml,
185 _ => FileFormat::Json,
186 }
187 }
188
189 fn file_error(path: &Path, reason: String) -> VlorQLError {
190 VlorQLError::config(
191 ConfigErrorKind::ConfigFileError {
192 path: path.display().to_string(),
193 reason,
194 },
195 serde_json::json!({ "path": path.display().to_string() }),
196 )
197 }
198}
199
200#[async_trait]
201impl StatisticsProvider for ConfigFileStatisticsProvider {
202 async fn get_table_stats(
203 &self,
204 table_name: &str,
205 ) -> Result<Option<TableStatistics>, VlorQLError> {
206 Ok(self.catalog.table(table_name).cloned())
207 }
208
209 async fn get_column_stats(
210 &self,
211 table_name: &str,
212 column_name: &str,
213 ) -> Result<Option<ColumnStatistics>, VlorQLError> {
214 Ok(self.catalog.column(table_name, column_name).cloned())
215 }
216
217 async fn get_catalog_stats(&self) -> Result<StatisticsCatalog, VlorQLError> {
218 Ok(self.catalog.clone())
219 }
220}