1use crate::estimate_relational_access_path_cost;
16use std::collections::BTreeSet;
17
18#[cfg(test)]
19#[path = "relational/cost_tests.rs"]
20mod cost_tests;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
23pub enum RelationalAccessPathKind {
24 FullScan,
25 PrimaryKey,
26 Index,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct RelationalNestedLoopJoinCost {
32 pub outer_rows: usize,
33 pub inner_rows_per_outer: usize,
34 pub estimated_work: usize,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct RelationalAccessPathDescriptor {
39 pub kind: RelationalAccessPathKind,
40 pub name: String,
41 pub index_columns: Vec<String>,
42 pub access_columns: BTreeSet<String>,
43 pub equality_prefix_len: usize,
44 pub order_prefix_len: usize,
45 pub exclusive_range: bool,
46 pub reverse_order: bool,
47 pub unique_point: bool,
48 pub covering: bool,
49 pub requires_row_fetch: bool,
50 pub estimated_rows: usize,
51}
52
53impl RelationalAccessPathDescriptor {
54 pub fn validate(&self) -> Result<(), &'static str> {
55 if self.name.is_empty() {
56 return Err("relational access path name must not be empty");
57 }
58 if self.kind != RelationalAccessPathKind::FullScan && self.index_columns.is_empty() {
59 return Err("relational index access path must contain index columns");
60 }
61 if self.equality_prefix_len > self.index_columns.len() {
62 return Err("relational equality prefix exceeds index columns");
63 }
64 if self
65 .equality_prefix_len
66 .saturating_add(self.order_prefix_len)
67 > self.index_columns.len()
68 {
69 return Err("relational order prefix exceeds remaining index columns");
70 }
71 if (self.exclusive_range || self.reverse_order)
72 && (self.kind != RelationalAccessPathKind::Index || self.order_prefix_len == 0)
73 {
74 return Err("relational range metadata requires an ordered index access");
75 }
76 let expected_access_columns = self.index_columns[..self.equality_prefix_len]
77 .iter()
78 .cloned()
79 .collect::<BTreeSet<_>>();
80 if self.access_columns != expected_access_columns {
81 return Err("relational access columns must equal the constrained leading prefix");
82 }
83 if self.unique_point
84 && (self.kind == RelationalAccessPathKind::FullScan
85 || self.equality_prefix_len != self.index_columns.len())
86 {
87 return Err("relational unique point access must constrain the complete key");
88 }
89 if self.covering && self.requires_row_fetch {
90 return Err("covering relational access must not require a row fetch");
91 }
92 Ok(())
93 }
94
95 fn dominates(&self, other: &Self) -> bool {
96 let access_is_superset = self.access_columns.is_superset(&other.access_columns);
97 let no_worse = access_is_superset
98 && self.equality_prefix_len >= other.equality_prefix_len
99 && self.order_prefix_len >= other.order_prefix_len
100 && (self.exclusive_range || !other.exclusive_range)
101 && (self.unique_point || !other.unique_point)
102 && (self.covering || !other.covering)
103 && (!self.requires_row_fetch || other.requires_row_fetch)
104 && estimate_relational_access_path_cost(self).cost
105 <= estimate_relational_access_path_cost(other).cost
106 && self.estimated_rows <= other.estimated_rows;
107 let strictly_better = self.access_columns != other.access_columns
108 || self.equality_prefix_len > other.equality_prefix_len
109 || self.order_prefix_len > other.order_prefix_len
110 || (self.exclusive_range && !other.exclusive_range)
111 || (self.unique_point && !other.unique_point)
112 || (self.covering && !other.covering)
113 || (!self.requires_row_fetch && other.requires_row_fetch)
114 || self.estimated_rows < other.estimated_rows;
115 no_worse && strictly_better
116 }
117}
118
119pub fn skyline_prune_relational_access_paths(
125 candidates: impl IntoIterator<Item = RelationalAccessPathDescriptor>,
126) -> Result<Vec<RelationalAccessPathDescriptor>, &'static str> {
127 let mut frontier = Vec::<RelationalAccessPathDescriptor>::new();
128 for mut candidate in candidates {
129 candidate.estimated_rows = candidate.estimated_rows.max(1);
130 candidate.validate()?;
131 if frontier
132 .iter()
133 .any(|existing| existing.dominates(&candidate))
134 {
135 continue;
136 }
137 frontier.retain(|existing| !candidate.dominates(existing));
138 frontier.push(candidate);
139 }
140 frontier.sort_by(|left, right| left.name.cmp(&right.name));
141 Ok(frontier)
142}
143
144pub fn select_relational_access_path(
145 candidates: impl IntoIterator<Item = RelationalAccessPathDescriptor>,
146) -> Result<Option<RelationalAccessPathDescriptor>, &'static str> {
147 let frontier = skyline_prune_relational_access_paths(candidates)?;
148 Ok(frontier.into_iter().min_by(|left, right| {
149 estimate_relational_access_path_cost(left)
150 .cost
151 .cmp(&estimate_relational_access_path_cost(right).cost)
152 .then_with(|| left.estimated_rows.cmp(&right.estimated_rows))
153 .then_with(|| right.unique_point.cmp(&left.unique_point))
154 .then_with(|| right.equality_prefix_len.cmp(&left.equality_prefix_len))
155 .then_with(|| right.order_prefix_len.cmp(&left.order_prefix_len))
156 .then_with(|| right.exclusive_range.cmp(&left.exclusive_range))
157 .then_with(|| right.covering.cmp(&left.covering))
158 .then_with(|| left.requires_row_fetch.cmp(&right.requires_row_fetch))
159 .then_with(|| left.index_columns.len().cmp(&right.index_columns.len()))
160 .then_with(|| left.name.cmp(&right.name))
161 }))
162}
163
164pub fn estimate_relational_nested_loop_join_cost(
171 outer: &RelationalAccessPathDescriptor,
172 inner: &RelationalAccessPathDescriptor,
173) -> RelationalNestedLoopJoinCost {
174 let outer_rows = outer.estimated_rows.max(1);
175 let inner_rows_per_outer = inner.estimated_rows.max(1);
176 RelationalNestedLoopJoinCost {
177 outer_rows,
178 inner_rows_per_outer,
179 estimated_work: outer_rows.saturating_add(outer_rows.saturating_mul(inner_rows_per_outer)),
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 fn path(
188 name: &str,
189 columns: &[&str],
190 equality_prefix_len: usize,
191 unique_point: bool,
192 estimated_rows: usize,
193 ) -> RelationalAccessPathDescriptor {
194 RelationalAccessPathDescriptor {
195 kind: RelationalAccessPathKind::Index,
196 name: name.to_string(),
197 index_columns: columns.iter().map(|column| (*column).to_string()).collect(),
198 access_columns: columns[..equality_prefix_len]
199 .iter()
200 .map(|column| (*column).to_string())
201 .collect(),
202 equality_prefix_len,
203 order_prefix_len: 0,
204 exclusive_range: false,
205 reverse_order: false,
206 unique_point,
207 covering: false,
208 requires_row_fetch: true,
209 estimated_rows,
210 }
211 }
212
213 #[test]
214 fn composite_prefix_dominates_a_shorter_access_condition() {
215 let frontier = skyline_prune_relational_access_paths([
216 path("idx_a", &["a"], 1, false, 100),
217 path("idx_a_b", &["a", "b"], 2, false, 10),
218 ])
219 .unwrap();
220
221 assert_eq!(frontier.len(), 1);
222 assert_eq!(frontier[0].name, "idx_a_b");
223 }
224
225 #[test]
226 fn different_predicate_columns_remain_incomparable() {
227 let frontier = skyline_prune_relational_access_paths([
228 path("idx_a", &["a"], 1, false, 10),
229 path("idx_b", &["b"], 1, false, 5),
230 ])
231 .unwrap();
232
233 assert_eq!(
234 frontier
235 .iter()
236 .map(|path| path.name.as_str())
237 .collect::<Vec<_>>(),
238 ["idx_a", "idx_b"]
239 );
240 }
241
242 #[test]
243 fn complete_unique_composite_key_dominates_unique_prefix_when_both_are_bound() {
244 let frontier = skyline_prune_relational_access_paths([
245 path("idx_f", &["f"], 1, true, 1),
246 path("idx_f_g", &["f", "g"], 2, true, 1),
247 ])
248 .unwrap();
249
250 assert_eq!(frontier.len(), 1);
251 assert_eq!(frontier[0].name, "idx_f_g");
252 }
253
254 #[test]
255 fn final_selection_is_deterministic_across_incomparable_paths() {
256 let selected = select_relational_access_path([
257 path("idx_a", &["a"], 1, false, 10),
258 path("idx_b", &["b"], 1, false, 5),
259 ])
260 .unwrap()
261 .unwrap();
262
263 assert_eq!(selected.name, "idx_b");
264 }
265
266 #[test]
267 fn ordered_suffix_must_fit_after_the_equality_prefix() {
268 let mut candidate = path("idx_a_b", &["a", "b"], 1, false, 10);
269 candidate.order_prefix_len = 2;
270
271 assert_eq!(
272 candidate.validate(),
273 Err("relational order prefix exceeds remaining index columns")
274 );
275 }
276
277 #[test]
278 fn zero_row_estimates_are_normalized_before_skyline_comparison() {
279 let frontier =
280 skyline_prune_relational_access_paths([path("idx_empty", &["id"], 1, true, 0)])
281 .unwrap();
282
283 assert_eq!(frontier[0].estimated_rows, 1);
284 }
285
286 #[test]
287 fn nested_loop_cost_prefers_a_selective_outer_with_an_indexed_probe() {
288 let full_outer = RelationalAccessPathDescriptor {
289 kind: RelationalAccessPathKind::FullScan,
290 name: "__full_scan".to_string(),
291 index_columns: Vec::new(),
292 access_columns: BTreeSet::new(),
293 equality_prefix_len: 0,
294 order_prefix_len: 0,
295 exclusive_range: false,
296 reverse_order: false,
297 unique_point: false,
298 covering: false,
299 requires_row_fetch: false,
300 estimated_rows: 100,
301 };
302 let unique_probe = path("documents_pk", &["id"], 1, true, 1);
303 let unique_outer = path("documents_owner", &["owner_kind", "owner_id"], 2, true, 1);
304 let indexed_probe = path(
305 "chunks_document",
306 &["document_id", "ordinal"],
307 1,
308 false,
309 100,
310 );
311
312 let syntax_order = estimate_relational_nested_loop_join_cost(&full_outer, &unique_probe);
313 let reordered = estimate_relational_nested_loop_join_cost(&unique_outer, &indexed_probe);
314
315 assert_eq!(syntax_order.estimated_work, 200);
316 assert_eq!(reordered.estimated_work, 101);
317 }
318
319 #[test]
320 fn nested_loop_cost_saturates_for_untrusted_cardinality_inputs() {
321 let outer = path("outer", &["id"], 1, false, usize::MAX);
322 let inner = path("inner", &["id"], 1, false, usize::MAX);
323
324 assert_eq!(
325 estimate_relational_nested_loop_join_cost(&outer, &inner).estimated_work,
326 usize::MAX
327 );
328 }
329}