1mod descriptor;
7
8#[cfg(test)]
9use crate::db::query::builder::AggregateExpr;
10use crate::{
11 db::{
12 Query, TraceReuseEvent,
13 executor::{
14 BytesByProjectionMode, PreparedExecutionPlan, planning::route::AggregateRouteShape,
15 },
16 predicate::{CoercionId, CompareOp},
17 query::{
18 builder::{AggregateExplain, ProjectionExplain},
19 explain::{
20 ExplainAccessPath, ExplainAggregateTerminalPlan, ExplainExecutionNodeDescriptor,
21 ExplainExecutionNodeType, ExplainOrderPushdown, ExplainPredicate,
22 FinalizedQueryDiagnostics,
23 },
24 intent::{QueryError, StructuralQuery},
25 plan::{AccessPlannedQuery, VisibleIndexes, explain_access_kind_label},
26 },
27 },
28 traits::{EntityKind, EntityValue},
29 value::Value,
30};
31
32pub(in crate::db) use descriptor::{
33 assemble_aggregate_terminal_execution_descriptor, assemble_load_execution_node_descriptor,
34 assemble_load_execution_node_descriptor_from_route_facts,
35 assemble_load_execution_verbose_diagnostics_from_route_facts,
36 assemble_scalar_aggregate_execution_descriptor_with_projection,
37 freeze_load_execution_route_facts,
38};
39
40impl StructuralQuery {
41 pub(in crate::db) fn explain_execution_descriptor_from_plan(
44 &self,
45 plan: &AccessPlannedQuery,
46 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
47 let route_facts = freeze_load_execution_route_facts(
48 self.model().fields(),
49 self.model().primary_key().name(),
50 plan,
51 )
52 .map_err(QueryError::execute)?;
53
54 Ok(assemble_load_execution_node_descriptor_from_route_facts(
55 plan,
56 &route_facts,
57 ))
58 }
59
60 fn finalized_execution_diagnostics_from_plan(
64 &self,
65 plan: &AccessPlannedQuery,
66 reuse: Option<TraceReuseEvent>,
67 ) -> Result<FinalizedQueryDiagnostics, QueryError> {
68 let route_facts = freeze_load_execution_route_facts(
69 self.model().fields(),
70 self.model().primary_key().name(),
71 plan,
72 )
73 .map_err(QueryError::execute)?;
74 let descriptor =
75 assemble_load_execution_node_descriptor_from_route_facts(plan, &route_facts);
76 let route_diagnostics =
77 assemble_load_execution_verbose_diagnostics_from_route_facts(plan, &route_facts);
78 let explain = plan.explain();
79
80 let mut logical_diagnostics = Vec::new();
82 logical_diagnostics.push(format!(
83 "diag.d.has_top_n_seek={}",
84 descriptor.contains_type(ExplainExecutionNodeType::TopNSeek)
85 ));
86 logical_diagnostics.push(format!(
87 "diag.d.has_index_range_limit_pushdown={}",
88 descriptor.contains_type(ExplainExecutionNodeType::IndexRangeLimitPushdown)
89 ));
90 logical_diagnostics.push(format!(
91 "diag.d.has_index_predicate_prefilter={}",
92 descriptor.contains_type(ExplainExecutionNodeType::IndexPredicatePrefilter)
93 ));
94 logical_diagnostics.push(format!(
95 "diag.d.has_residual_filter={}",
96 descriptor.contains_type(ExplainExecutionNodeType::ResidualFilter)
97 ));
98
99 logical_diagnostics.push(format!("diag.p.mode={:?}", explain.mode()));
101 logical_diagnostics.push(format!(
102 "diag.p.order_pushdown={}",
103 plan_order_pushdown_label(explain.order_pushdown())
104 ));
105 logical_diagnostics.push(format!(
106 "diag.p.predicate_pushdown={}",
107 plan_predicate_pushdown_label(explain.predicate(), explain.access())
108 ));
109 logical_diagnostics.push(format!("diag.p.distinct={}", explain.distinct()));
110 logical_diagnostics.push(format!("diag.p.page={:?}", explain.page()));
111 logical_diagnostics.push(format!("diag.p.consistency={:?}", explain.consistency()));
112
113 Ok(FinalizedQueryDiagnostics::new(
114 descriptor,
115 route_diagnostics,
116 logical_diagnostics,
117 reuse,
118 ))
119 }
120
121 pub(in crate::db) fn finalized_execution_diagnostics_from_plan_with_descriptor_mutator(
124 &self,
125 plan: &AccessPlannedQuery,
126 reuse: Option<TraceReuseEvent>,
127 mutate_descriptor: impl FnOnce(&mut ExplainExecutionNodeDescriptor),
128 ) -> Result<FinalizedQueryDiagnostics, QueryError> {
129 let mut diagnostics = self.finalized_execution_diagnostics_from_plan(plan, reuse)?;
130 mutate_descriptor(&mut diagnostics.execution);
131
132 Ok(diagnostics)
133 }
134
135 fn explain_execution_verbose_from_plan(
138 &self,
139 plan: &AccessPlannedQuery,
140 ) -> Result<String, QueryError> {
141 self.finalized_execution_diagnostics_from_plan(plan, None)
142 .map(|diagnostics| diagnostics.render_text_verbose())
143 }
144
145 fn finalize_explain_access_choice_for_visibility(
148 &self,
149 plan: &mut AccessPlannedQuery,
150 visible_indexes: Option<&VisibleIndexes<'_>>,
151 ) {
152 let visible_indexes = match visible_indexes {
153 Some(visible_indexes) => visible_indexes.as_slice(),
154 None => self.model().indexes(),
155 };
156
157 plan.finalize_access_choice_for_model_with_indexes(self.model(), visible_indexes);
158 }
159
160 fn explain_execution_descriptor_for_visibility(
163 &self,
164 visible_indexes: Option<&VisibleIndexes<'_>>,
165 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
166 let mut plan = match visible_indexes {
167 Some(visible_indexes) => self.build_plan_with_visible_indexes(visible_indexes)?,
168 None => self.build_plan()?,
169 };
170 self.finalize_explain_access_choice_for_visibility(&mut plan, visible_indexes);
171
172 self.explain_execution_descriptor_from_plan(&plan)
173 }
174
175 fn explain_execution_verbose_for_visibility(
178 &self,
179 visible_indexes: Option<&VisibleIndexes<'_>>,
180 ) -> Result<String, QueryError> {
181 let mut plan = match visible_indexes {
182 Some(visible_indexes) => self.build_plan_with_visible_indexes(visible_indexes)?,
183 None => self.build_plan()?,
184 };
185 self.finalize_explain_access_choice_for_visibility(&mut plan, visible_indexes);
186
187 self.explain_execution_verbose_from_plan(&plan)
188 }
189
190 #[inline(never)]
192 pub(in crate::db) fn explain_execution(
193 &self,
194 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
195 self.explain_execution_descriptor_for_visibility(None)
196 }
197
198 #[inline(never)]
200 #[allow(dead_code)]
201 pub(in crate::db) fn explain_execution_with_visible_indexes(
202 &self,
203 visible_indexes: &VisibleIndexes<'_>,
204 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
205 self.explain_execution_descriptor_for_visibility(Some(visible_indexes))
206 }
207
208 #[inline(never)]
211 pub(in crate::db) fn explain_execution_verbose(&self) -> Result<String, QueryError> {
212 self.explain_execution_verbose_for_visibility(None)
213 }
214
215 #[inline(never)]
217 pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
218 &self,
219 visible_indexes: &VisibleIndexes<'_>,
220 ) -> Result<String, QueryError> {
221 self.explain_execution_verbose_for_visibility(Some(visible_indexes))
222 }
223
224 #[inline(never)]
226 #[cfg(test)]
227 pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
228 &self,
229 visible_indexes: &VisibleIndexes<'_>,
230 aggregate: AggregateRouteShape<'_>,
231 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
232 let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
233 let query_explain = plan.explain();
234 let terminal = aggregate.kind();
235 let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate);
236
237 Ok(ExplainAggregateTerminalPlan::new(
238 query_explain,
239 terminal,
240 execution,
241 ))
242 }
243}
244
245impl<E> PreparedExecutionPlan<E>
246where
247 E: EntityValue + EntityKind,
248{
249 pub(in crate::db) fn explain_prepared_aggregate_terminal<S>(
251 &self,
252 strategy: &S,
253 ) -> Result<ExplainAggregateTerminalPlan, QueryError>
254 where
255 S: AggregateExplain,
256 {
257 let Some(kind) = strategy.explain_aggregate_kind() else {
258 return Err(QueryError::invariant(
259 "prepared fluent aggregate explain requires an explain-visible aggregate kind",
260 ));
261 };
262 let aggregate = AggregateRouteShape::new_from_fields(
263 kind,
264 strategy.explain_projected_field(),
265 E::MODEL.fields(),
266 E::MODEL.primary_key().name(),
267 );
268 let execution =
269 assemble_aggregate_terminal_execution_descriptor(self.logical_plan(), aggregate);
270
271 Ok(ExplainAggregateTerminalPlan::new(
272 self.logical_plan().explain(),
273 kind,
274 execution,
275 ))
276 }
277
278 pub(in crate::db) fn explain_bytes_by_terminal(
280 &self,
281 target_field: &str,
282 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
283 let mut descriptor = self
284 .explain_load_execution_node_descriptor()
285 .map_err(QueryError::execute)?;
286 let projection_mode = self.bytes_by_projection_mode(target_field);
287 let projection_mode_label = Self::bytes_by_projection_mode_label(projection_mode);
288
289 descriptor
290 .node_properties
291 .insert("terminal", Value::from("bytes_by"));
292 descriptor
293 .node_properties
294 .insert("terminal_field", Value::from(target_field.to_string()));
295 descriptor.node_properties.insert(
296 "terminal_projection_mode",
297 Value::from(projection_mode_label),
298 );
299 descriptor.node_properties.insert(
300 "terminal_index_only",
301 Value::from(matches!(
302 projection_mode,
303 BytesByProjectionMode::CoveringIndex | BytesByProjectionMode::CoveringConstant
304 )),
305 );
306
307 Ok(descriptor)
308 }
309
310 pub(in crate::db) fn explain_prepared_projection_terminal<S>(
312 &self,
313 strategy: &S,
314 ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
315 where
316 S: ProjectionExplain,
317 {
318 let mut descriptor = self
319 .explain_load_execution_node_descriptor()
320 .map_err(QueryError::execute)?;
321 let projection_descriptor = strategy.explain_projection_descriptor();
322
323 descriptor.node_properties.insert(
324 "terminal",
325 Value::from(projection_descriptor.terminal_label()),
326 );
327 descriptor.node_properties.insert(
328 "terminal_field",
329 Value::from(projection_descriptor.field_label().to_string()),
330 );
331 descriptor.node_properties.insert(
332 "terminal_output",
333 Value::from(projection_descriptor.output_label()),
334 );
335
336 Ok(descriptor)
337 }
338}
339
340impl<E> Query<E>
341where
342 E: EntityValue + EntityKind,
343{
344 fn explain_execution_descriptor_for_visibility(
347 &self,
348 visible_indexes: Option<&VisibleIndexes<'_>>,
349 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
350 match visible_indexes {
351 Some(visible_indexes) => self
352 .structural()
353 .explain_execution_with_visible_indexes(visible_indexes),
354 None => self.structural().explain_execution(),
355 }
356 }
357
358 fn render_execution_descriptor_for_visibility(
361 &self,
362 visible_indexes: Option<&VisibleIndexes<'_>>,
363 render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
364 ) -> Result<String, QueryError> {
365 let descriptor = self.explain_execution_descriptor_for_visibility(visible_indexes)?;
366
367 Ok(render(descriptor))
368 }
369
370 fn explain_execution_verbose_for_visibility(
373 &self,
374 visible_indexes: Option<&VisibleIndexes<'_>>,
375 ) -> Result<String, QueryError> {
376 match visible_indexes {
377 Some(visible_indexes) => self
378 .structural()
379 .explain_execution_verbose_with_visible_indexes(visible_indexes),
380 None => self.structural().explain_execution_verbose(),
381 }
382 }
383
384 pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
386 self.explain_execution_descriptor_for_visibility(None)
387 }
388
389 #[allow(dead_code)]
391 pub(in crate::db) fn explain_execution_with_visible_indexes(
392 &self,
393 visible_indexes: &VisibleIndexes<'_>,
394 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
395 self.explain_execution_descriptor_for_visibility(Some(visible_indexes))
396 }
397
398 pub fn explain_execution_text(&self) -> Result<String, QueryError> {
400 self.render_execution_descriptor_for_visibility(None, |descriptor| {
401 descriptor.render_text_tree()
402 })
403 }
404
405 pub fn explain_execution_json(&self) -> Result<String, QueryError> {
407 self.render_execution_descriptor_for_visibility(None, |descriptor| {
408 descriptor.render_json_canonical()
409 })
410 }
411
412 #[inline(never)]
414 pub fn explain_execution_verbose(&self) -> Result<String, QueryError> {
415 self.explain_execution_verbose_for_visibility(None)
416 }
417
418 #[cfg(test)]
420 #[inline(never)]
421 pub(in crate::db) fn explain_aggregate_terminal(
422 &self,
423 aggregate: AggregateExpr,
424 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
425 self.structural()
426 .explain_aggregate_terminal_with_visible_indexes(
427 &VisibleIndexes::schema_owned(E::MODEL.indexes()),
428 AggregateRouteShape::new_from_fields(
429 aggregate.kind(),
430 aggregate.target_field(),
431 E::MODEL.fields(),
432 E::MODEL.primary_key().name(),
433 ),
434 )
435 }
436}
437
438fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
440 match order_pushdown {
441 ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
442 ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
443 format!("eligible(index={index},prefix_len={prefix_len})")
444 }
445 ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
446 }
447}
448
449fn plan_predicate_pushdown_label(
451 predicate: &ExplainPredicate,
452 access: &ExplainAccessPath,
453) -> String {
454 let access_label = explain_access_kind_label(access);
455 if matches!(predicate, ExplainPredicate::None) {
456 return "none".to_string();
457 }
458 if access_label == "full_scan" {
459 if explain_predicate_contains_non_strict_compare(predicate) {
460 return "fallback(non_strict_compare_coercion)".to_string();
461 }
462 if explain_predicate_contains_empty_prefix_starts_with(predicate) {
463 return "fallback(starts_with_empty_prefix)".to_string();
464 }
465 if explain_predicate_contains_is_null(predicate) {
466 return "fallback(is_null_full_scan)".to_string();
467 }
468 if explain_predicate_contains_text_scan_operator(predicate) {
469 return "fallback(text_operator_full_scan)".to_string();
470 }
471
472 return format!("fallback({access_label})");
473 }
474
475 format!("applied({access_label})")
476}
477
478fn explain_predicate_contains_non_strict_compare(predicate: &ExplainPredicate) -> bool {
480 match predicate {
481 ExplainPredicate::Compare { coercion, .. }
482 | ExplainPredicate::CompareFields { coercion, .. } => coercion.id != CoercionId::Strict,
483 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
484 .iter()
485 .any(explain_predicate_contains_non_strict_compare),
486 ExplainPredicate::Not(inner) => explain_predicate_contains_non_strict_compare(inner),
487 ExplainPredicate::None
488 | ExplainPredicate::True
489 | ExplainPredicate::False
490 | ExplainPredicate::IsNull { .. }
491 | ExplainPredicate::IsNotNull { .. }
492 | ExplainPredicate::IsMissing { .. }
493 | ExplainPredicate::IsEmpty { .. }
494 | ExplainPredicate::IsNotEmpty { .. }
495 | ExplainPredicate::TextContains { .. }
496 | ExplainPredicate::TextContainsCi { .. } => false,
497 }
498}
499
500fn explain_predicate_contains_is_null(predicate: &ExplainPredicate) -> bool {
502 match predicate {
503 ExplainPredicate::IsNull { .. } => true,
504 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => {
505 children.iter().any(explain_predicate_contains_is_null)
506 }
507 ExplainPredicate::Not(inner) => explain_predicate_contains_is_null(inner),
508 ExplainPredicate::None
509 | ExplainPredicate::True
510 | ExplainPredicate::False
511 | ExplainPredicate::Compare { .. }
512 | ExplainPredicate::CompareFields { .. }
513 | ExplainPredicate::IsNotNull { .. }
514 | ExplainPredicate::IsMissing { .. }
515 | ExplainPredicate::IsEmpty { .. }
516 | ExplainPredicate::IsNotEmpty { .. }
517 | ExplainPredicate::TextContains { .. }
518 | ExplainPredicate::TextContainsCi { .. } => false,
519 }
520}
521
522fn explain_predicate_contains_empty_prefix_starts_with(predicate: &ExplainPredicate) -> bool {
524 match predicate {
525 ExplainPredicate::Compare {
526 op: CompareOp::StartsWith,
527 value: Value::Text(prefix),
528 ..
529 } => prefix.is_empty(),
530 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
531 .iter()
532 .any(explain_predicate_contains_empty_prefix_starts_with),
533 ExplainPredicate::Not(inner) => explain_predicate_contains_empty_prefix_starts_with(inner),
534 ExplainPredicate::None
535 | ExplainPredicate::True
536 | ExplainPredicate::False
537 | ExplainPredicate::Compare { .. }
538 | ExplainPredicate::CompareFields { .. }
539 | ExplainPredicate::IsNull { .. }
540 | ExplainPredicate::IsNotNull { .. }
541 | ExplainPredicate::IsMissing { .. }
542 | ExplainPredicate::IsEmpty { .. }
543 | ExplainPredicate::IsNotEmpty { .. }
544 | ExplainPredicate::TextContains { .. }
545 | ExplainPredicate::TextContainsCi { .. } => false,
546 }
547}
548
549fn explain_predicate_contains_text_scan_operator(predicate: &ExplainPredicate) -> bool {
551 match predicate {
552 ExplainPredicate::Compare {
553 op: CompareOp::EndsWith,
554 ..
555 }
556 | ExplainPredicate::TextContains { .. }
557 | ExplainPredicate::TextContainsCi { .. } => true,
558 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
559 .iter()
560 .any(explain_predicate_contains_text_scan_operator),
561 ExplainPredicate::Not(inner) => explain_predicate_contains_text_scan_operator(inner),
562 ExplainPredicate::Compare { .. }
563 | ExplainPredicate::CompareFields { .. }
564 | ExplainPredicate::None
565 | ExplainPredicate::True
566 | ExplainPredicate::False
567 | ExplainPredicate::IsNull { .. }
568 | ExplainPredicate::IsNotNull { .. }
569 | ExplainPredicate::IsMissing { .. }
570 | ExplainPredicate::IsEmpty { .. }
571 | ExplainPredicate::IsNotEmpty { .. } => false,
572 }
573}