Skip to main content

vlorql_core/statistics/
stats.rs

1//! Table- and column-level statistics used for cost estimation.
2//!
3//! These structures describe the shape of the data behind a schema:
4//! how many rows a table holds, how many distinct values a column has,
5//! what fraction of a column is null, and so on. A query planner or
6//! optimizer consumes them to estimate selectivity and cardinality.
7//!
8//! The types are deliberately serialization-friendly (`serde` +
9//! `serde_json::Value` for open-ended bounds) so a
10//! [`StatisticsProvider`](crate::statistics::StatisticsProvider) can
11//! load them from a database system table, a JSON/YAML file, or any
12//! other external source.
13
14use serde::{Deserialize, Serialize};
15use std::collections::HashMap;
16
17/// Statistics describing a single column.
18///
19/// Every field defaults to a neutral value so a partially populated
20/// record (e.g. a provider that only knows `null_fraction`) is still
21/// valid. `min_value`, `max_value`, and `histogram` use
22/// [`serde_json::Value`] because a column can hold any SQL type.
23///
24/// # Examples
25///
26/// ```
27/// use vlorql_core::statistics::ColumnStatistics;
28/// use serde_json::json;
29///
30/// let stats = ColumnStatistics {
31///     null_fraction: 0.1,
32///     distinct_count: 1_000,
33///     min_value: Some(json!(1)),
34///     max_value: Some(json!(9_999)),
35///     avg_column_width: Some(4),
36///     histogram: None,
37/// };
38/// assert_eq!(stats.distinct_count, 1_000);
39/// ```
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
41#[serde(default)]
42pub struct ColumnStatistics {
43    /// Fraction of rows whose value is `NULL`, in the range `0.0..=1.0`.
44    pub null_fraction: f64,
45    /// Estimated number of distinct (non-null) values in the column.
46    pub distinct_count: u64,
47    /// Smallest observed value, if known.
48    pub min_value: Option<serde_json::Value>,
49    /// Largest observed value, if known.
50    pub max_value: Option<serde_json::Value>,
51    /// Average width of a stored value in bytes, if known.
52    pub avg_column_width: Option<u32>,
53    /// Optional equi-depth histogram bucket boundaries.
54    pub histogram: Option<Vec<serde_json::Value>>,
55}
56
57/// Statistics describing a single table and its columns.
58///
59/// # Examples
60///
61/// ```
62/// use vlorql_core::statistics::{ColumnStatistics, TableStatistics};
63///
64/// let mut table = TableStatistics {
65///     row_count: 42,
66///     ..TableStatistics::default()
67/// };
68/// table
69///     .columns
70///     .insert("id".to_owned(), ColumnStatistics::default());
71/// assert_eq!(table.row_count, 42);
72/// assert!(table.columns.contains_key("id"));
73/// ```
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
75#[serde(default)]
76pub struct TableStatistics {
77    /// Estimated number of rows in the table.
78    pub row_count: u64,
79    /// Per-column statistics, keyed by column name.
80    pub columns: HashMap<String, ColumnStatistics>,
81    /// When the statistics were last collected, if known.
82    pub last_analyzed: Option<chrono::DateTime<chrono::Utc>>,
83}
84
85/// A catalog of table statistics for an entire schema.
86///
87/// This is the top-level document a
88/// [`StatisticsProvider`](crate::statistics::StatisticsProvider)
89/// produces and the shape a JSON/YAML statistics file is expected to
90/// have.
91///
92/// # Examples
93///
94/// ```
95/// use vlorql_core::statistics::{StatisticsCatalog, TableStatistics};
96///
97/// let mut catalog = StatisticsCatalog::default();
98/// catalog
99///     .tables
100///     .insert("users".to_owned(), TableStatistics::default());
101/// assert!(catalog.tables.contains_key("users"));
102/// ```
103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
104#[serde(default)]
105pub struct StatisticsCatalog {
106    /// Per-table statistics, keyed by table name.
107    pub tables: HashMap<String, TableStatistics>,
108}
109
110impl StatisticsCatalog {
111    /// Returns the statistics for `table_name`, if present.
112    pub fn table(&self, table_name: &str) -> Option<&TableStatistics> {
113        self.tables.get(table_name)
114    }
115
116    /// Returns the statistics for `table_name.column_name`, if present.
117    pub fn column(&self, table_name: &str, column_name: &str) -> Option<&ColumnStatistics> {
118        self.tables
119            .get(table_name)
120            .and_then(|table| table.columns.get(column_name))
121    }
122}