lora_database/database/
explain.rs1use std::any::Any;
13use std::collections::BTreeMap;
14
15use lora_compiler::{plan_tree_from_compiled, PlanTree, PlanTreeNode};
16use lora_executor::{classify_stream, plan_result_columns, LoraValue};
17use lora_store::{GraphStats, GraphStorage, GraphStorageMut};
18
19use crate::database::Database;
20use crate::error::LoraError;
21use crate::explain::{PlanShape, QueryPlan};
22
23impl<S> Database<S>
24where
25 S: GraphStorage + GraphStorageMut + Any + Clone + Send + Sync + 'static,
26{
27 pub fn explain(
39 &self,
40 query: &str,
41 _params: Option<BTreeMap<String, LoraValue>>,
42 ) -> Result<QueryPlan, LoraError> {
43 let (store, store_epoch) = self.read_store_with_epoch_deadline(None)?;
44 let compiled = self
45 .compile_query_cached(query, &*store, store_epoch)
46 .map_err(LoraError::from_anyhow)?;
47 let mut tree = plan_tree_from_compiled(&compiled);
48 let stats = store.graph_stats();
49 annotate_estimated_rows(&mut tree, &stats);
50 let shape: PlanShape = classify_stream(&compiled).into();
51 let result_columns = plan_result_columns(&compiled.physical);
52 Ok(QueryPlan {
53 query: query.to_string(),
54 tree,
55 shape,
56 result_columns,
57 })
58 }
59}
60
61pub(crate) fn annotate_estimated_rows(tree: &mut PlanTree, stats: &GraphStats) {
74 annotate_node(&mut tree.root, stats);
75}
76
77fn annotate_node(node: &mut PlanTreeNode, stats: &GraphStats) {
78 node.estimated_rows = match node.operator.as_str() {
79 "NodeScan" => Some(stats.node_count as u64),
80 "NodeByLabelScan" => labels_estimate(node, stats),
81 "NodeByPropertyScan" => property_equality_estimate(node, stats),
82 _ => None,
83 };
84 for child in &mut node.children {
85 annotate_node(child, stats);
86 }
87}
88
89fn labels_estimate(node: &PlanTreeNode, stats: &GraphStats) -> Option<u64> {
90 let labels = node.details.get("labels")?;
91 let trimmed = labels.trim_start_matches(':');
94 let bare = trimmed.split('|').next()?.trim();
95 stats.label_count(bare)
96}
97
98fn property_equality_estimate(node: &PlanTreeNode, stats: &GraphStats) -> Option<u64> {
99 let property = node.details.get("key")?;
100 let labels = node.details.get("labels")?;
101 let trimmed = labels.trim_start_matches(':');
102 let bare = trimmed.split('|').next()?.trim();
103 stats.estimate_node_property_equality(bare, property)
104}