icydb_core/db/query/
planner.rs

1use crate::{
2    IndexSpec, Key, Value,
3    db::primitives::filter::{Cmp, FilterExpr},
4    obs::metrics,
5    traits::EntityKind,
6};
7use std::fmt::{self, Display};
8
9///
10/// QueryPlan
11///
12
13#[derive(Debug)]
14pub enum QueryPlan {
15    FullScan,
16    Index(IndexPlan),
17    Keys(Vec<Key>),
18    /// Inclusive range over primary keys.
19    Range(Key, Key),
20}
21
22impl fmt::Display for QueryPlan {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            Self::Index(plan) => write!(f, "Index({plan})"),
26
27            Self::Keys(keys) => {
28                // Show up to 5 keys, then ellipsize
29                let preview: Vec<String> = keys.iter().take(5).map(|k| format!("{k:?}")).collect();
30
31                if keys.len() > 5 {
32                    write!(f, "Keys[{}… total {}]", preview.join(", "), keys.len())
33                } else {
34                    write!(f, "Keys[{}]", preview.join(", "))
35                }
36            }
37
38            Self::Range(start, end) => {
39                write!(f, "Range({start:?} → {end:?})")
40            }
41
42            Self::FullScan => write!(f, "FullScan"),
43        }
44    }
45}
46
47///
48/// IndexPlan
49///
50
51#[derive(Debug)]
52pub struct IndexPlan {
53    pub index: &'static IndexSpec,
54    pub values: Vec<Value>,
55}
56
57impl Display for IndexPlan {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        let values: Vec<String> = self.values.iter().map(|v| format!("{v:?}")).collect();
60        write!(f, "index={} values=[{}]", self.index, values.join(", "))
61    }
62}
63
64///
65/// QueryPlanner
66///
67
68#[derive(Debug)]
69pub struct QueryPlanner {
70    pub filter: Option<FilterExpr>,
71}
72
73impl QueryPlanner {
74    #[must_use]
75    /// Create a planner from an optional filter expression.
76    pub fn new(filter: Option<&FilterExpr>) -> Self {
77        Self {
78            filter: filter.cloned(),
79        }
80    }
81
82    #[must_use]
83    /// Generate a query plan for the given entity type.
84    ///
85    /// Index plans are only produced when all equality values are indexable;
86    /// otherwise the planner falls back to a scan.
87    pub fn plan<E: EntityKind>(&self) -> QueryPlan {
88        // If filter is a primary key match
89        // this would handle One and Many queries
90        if let Some(plan) = self.extract_from_filter::<E>() {
91            metrics::with_state_mut(|m| match plan {
92                QueryPlan::Keys(_) => m.ops.plan_keys += 1,
93                QueryPlan::Index(_) => m.ops.plan_index += 1,
94                QueryPlan::Range(_, _) => m.ops.plan_range += 1,
95                QueryPlan::FullScan => m.ops.plan_full_scan += 1,
96            });
97            return plan;
98        }
99
100        // check for index matches
101        // THIS WILL DO THE INDEX LOOKUPS
102        if !E::INDEXES.is_empty()
103            && let Some(plan) = self.extract_from_index::<E>()
104        {
105            metrics::with_state_mut(|m| m.ops.plan_index += 1);
106            return plan;
107        }
108
109        // Fallback: do a full scan
110        metrics::with_state_mut(|m| m.ops.plan_full_scan += 1);
111
112        QueryPlan::FullScan
113    }
114
115    // extract_from_filter
116    fn extract_from_filter<E: EntityKind>(&self) -> Option<QueryPlan> {
117        let Some(filter) = &self.filter else {
118            return None;
119        };
120
121        match filter {
122            FilterExpr::Clause(clause) if clause.field == E::PRIMARY_KEY => match clause.cmp {
123                Cmp::Eq => clause.value.as_key().map(|key| QueryPlan::Keys(vec![key])),
124
125                Cmp::In => {
126                    if let Value::List(values) = &clause.value {
127                        let mut keys = values
128                            .iter()
129                            .filter_map(Value::as_key_coerced)
130                            .collect::<Vec<_>>();
131                        if keys.is_empty() {
132                            return Some(QueryPlan::Keys(Vec::new()));
133                        }
134                        keys.sort_unstable();
135                        keys.dedup();
136                        Some(QueryPlan::Keys(keys))
137                    } else {
138                        None
139                    }
140                }
141
142                _ => None,
143            },
144
145            _ => None,
146        }
147    }
148
149    // extract_from_index: build a leftmost equality prefix in terms of Value.
150    // Skip index planning when any equality value is not indexable.
151    fn extract_from_index<E: EntityKind>(&self) -> Option<QueryPlan> {
152        let Some(filter) = &self.filter else {
153            return None;
154        };
155
156        let mut best: Option<(usize, IndexPlan)> = None;
157
158        for index in E::INDEXES {
159            // Build leftmost equality prefix (only == supported for hashed indexes)
160            let mut values: Vec<Value> = Vec::with_capacity(index.fields.len());
161            let mut unusable = false;
162
163            for field in index.fields {
164                if let Some(v) = Self::find_eq_value(filter, field) {
165                    if v.to_index_fingerprint().is_none() {
166                        unusable = true;
167                        break;
168                    }
169                    values.push(v);
170                } else {
171                    break; // stop at first non-match
172                }
173            }
174
175            // Skip indexes that produced no equality prefix
176            if unusable || values.is_empty() {
177                continue;
178            }
179
180            let score = values.len();
181            let cand = (score, IndexPlan { index, values });
182
183            match &best {
184                Some((best_score, _)) if *best_score >= score => { /* keep current best */ }
185                _ => best = Some(cand),
186            }
187        }
188
189        best.map(|(_, plan)| QueryPlan::Index(plan))
190    }
191
192    /// Find an equality clause (`field == ?`) anywhere in the filter tree and return the Value.
193    fn find_eq_value(filter: &FilterExpr, field: &str) -> Option<Value> {
194        match filter {
195            FilterExpr::Clause(c) if c.field == field && matches!(c.cmp, Cmp::Eq) => {
196                Some(c.value.clone())
197            }
198            // Walk conjunctive subtrees
199            FilterExpr::And(list) => list.iter().find_map(|f| Self::find_eq_value(f, field)),
200            _ => None,
201        }
202    }
203}