1mod descriptor;
7
8#[cfg(test)]
9use crate::db::executor::planning::route::AggregateRouteShape;
10#[cfg(test)]
11use crate::db::query::builder::AggregateExpr;
12use crate::{
13 db::{
14 Query, TraceReuseEvent,
15 executor::{BytesByProjectionMode, EntityAuthority, PreparedExecutionPlan},
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
32#[cfg(test)]
33pub(in crate::db) use descriptor::assemble_load_execution_node_descriptor;
34use descriptor::assemble_load_execution_verbose_diagnostics_from_route_facts;
35pub(in crate::db) use descriptor::{
36 assemble_aggregate_terminal_execution_descriptor,
37 assemble_load_execution_node_descriptor_for_authority,
38 assemble_load_execution_node_descriptor_from_route_facts,
39 assemble_scalar_aggregate_execution_descriptor_with_projection,
40 freeze_load_execution_route_facts_for_authority,
41 freeze_load_execution_route_facts_for_model_only,
42};
43
44impl StructuralQuery {
45 fn finalized_execution_diagnostics_from_route_facts(
48 plan: &AccessPlannedQuery,
49 route_facts: &crate::db::executor::explain::descriptor::LoadExecutionRouteFacts,
50 reuse: Option<TraceReuseEvent>,
51 ) -> FinalizedQueryDiagnostics {
52 let descriptor =
53 assemble_load_execution_node_descriptor_from_route_facts(plan, route_facts);
54 let route_diagnostics =
55 assemble_load_execution_verbose_diagnostics_from_route_facts(plan, route_facts);
56 let explain = plan.explain();
57
58 let mut logical_diagnostics = Vec::new();
60 logical_diagnostics.push(format!(
61 "diag.d.has_top_n_seek={}",
62 descriptor.contains_type(ExplainExecutionNodeType::TopNSeek)
63 ));
64 logical_diagnostics.push(format!(
65 "diag.d.has_index_range_limit_pushdown={}",
66 descriptor.contains_type(ExplainExecutionNodeType::IndexRangeLimitPushdown)
67 ));
68 logical_diagnostics.push(format!(
69 "diag.d.has_index_predicate_prefilter={}",
70 descriptor.contains_type(ExplainExecutionNodeType::IndexPredicatePrefilter)
71 ));
72 logical_diagnostics.push(format!(
73 "diag.d.has_residual_filter={}",
74 descriptor.contains_type(ExplainExecutionNodeType::ResidualFilter)
75 ));
76
77 logical_diagnostics.push(format!("diag.p.mode={:?}", explain.mode()));
79 logical_diagnostics.push(format!(
80 "diag.p.order_pushdown={}",
81 plan_order_pushdown_label(explain.order_pushdown())
82 ));
83 logical_diagnostics.push(format!(
84 "diag.p.predicate_pushdown={}",
85 plan_predicate_pushdown_label(explain.predicate(), explain.access())
86 ));
87 logical_diagnostics.push(format!("diag.p.distinct={}", explain.distinct()));
88 logical_diagnostics.push(format!("diag.p.page={:?}", explain.page()));
89 logical_diagnostics.push(format!("diag.p.consistency={:?}", explain.consistency()));
90
91 FinalizedQueryDiagnostics::new(descriptor, route_diagnostics, logical_diagnostics, reuse)
92 }
93
94 pub(in crate::db) fn explain_execution_descriptor_from_model_only_plan(
98 &self,
99 plan: &AccessPlannedQuery,
100 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
101 let route_facts = freeze_load_execution_route_facts_for_model_only(
102 self.model().fields(),
103 self.model().primary_key().name(),
104 plan,
105 )
106 .map_err(QueryError::execute)?;
107
108 Ok(assemble_load_execution_node_descriptor_from_route_facts(
109 plan,
110 &route_facts,
111 ))
112 }
113
114 pub(in crate::db) fn explain_execution_descriptor_from_plan_with_authority(
116 &self,
117 plan: &AccessPlannedQuery,
118 authority: &EntityAuthority,
119 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
120 debug_assert_eq!(self.model().path(), authority.entity_path());
121 let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
122 .map_err(QueryError::execute)?;
123
124 Ok(assemble_load_execution_node_descriptor_from_route_facts(
125 plan,
126 &route_facts,
127 ))
128 }
129
130 fn finalized_execution_diagnostics_from_model_only_plan(
135 &self,
136 plan: &AccessPlannedQuery,
137 reuse: Option<TraceReuseEvent>,
138 ) -> Result<FinalizedQueryDiagnostics, QueryError> {
139 let route_facts = freeze_load_execution_route_facts_for_model_only(
140 self.model().fields(),
141 self.model().primary_key().name(),
142 plan,
143 )
144 .map_err(QueryError::execute)?;
145
146 Ok(Self::finalized_execution_diagnostics_from_route_facts(
147 plan,
148 &route_facts,
149 reuse,
150 ))
151 }
152
153 pub(in crate::db) fn finalized_execution_diagnostics_from_plan_with_authority_and_descriptor_mutator(
156 &self,
157 plan: &AccessPlannedQuery,
158 authority: &EntityAuthority,
159 reuse: Option<TraceReuseEvent>,
160 mutate_descriptor: impl FnOnce(&mut ExplainExecutionNodeDescriptor),
161 ) -> Result<FinalizedQueryDiagnostics, QueryError> {
162 debug_assert_eq!(self.model().path(), authority.entity_path());
163 let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
164 .map_err(QueryError::execute)?;
165 let mut diagnostics =
166 Self::finalized_execution_diagnostics_from_route_facts(plan, &route_facts, reuse);
167 mutate_descriptor(&mut diagnostics.execution);
168
169 Ok(diagnostics)
170 }
171
172 fn explain_execution_verbose_from_plan(
175 &self,
176 plan: &AccessPlannedQuery,
177 ) -> Result<String, QueryError> {
178 self.finalized_execution_diagnostics_from_model_only_plan(plan, None)
179 .map(|diagnostics| diagnostics.render_text_verbose())
180 }
181
182 fn finalize_explain_access_choice_for_visible_indexes(
185 &self,
186 plan: &mut AccessPlannedQuery,
187 visible_indexes: &VisibleIndexes<'_>,
188 ) {
189 plan.finalize_access_choice_for_model_only_with_indexes(
190 self.model(),
191 visible_indexes.as_slice(),
192 );
193 }
194
195 fn finalize_explain_access_choice_for_model_only(&self, plan: &mut AccessPlannedQuery) {
199 plan.finalize_access_choice_for_model_only_with_indexes(
200 self.model(),
201 self.model().indexes(),
202 );
203 }
204
205 fn explain_execution_descriptor_for_model_only(
208 &self,
209 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
210 let mut plan = self.build_plan()?;
211 self.finalize_explain_access_choice_for_model_only(&mut plan);
212
213 self.explain_execution_descriptor_from_model_only_plan(&plan)
214 }
215
216 fn explain_execution_descriptor_for_visible_indexes(
219 &self,
220 visible_indexes: &VisibleIndexes<'_>,
221 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
222 let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
223 self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
224
225 self.explain_execution_descriptor_from_model_only_plan(&plan)
226 }
227
228 fn render_execution_verbose_for_model_only(&self) -> Result<String, QueryError> {
231 let mut plan = self.build_plan()?;
232 self.finalize_explain_access_choice_for_model_only(&mut plan);
233
234 self.explain_execution_verbose_from_plan(&plan)
235 }
236
237 fn explain_execution_verbose_for_visible_indexes(
240 &self,
241 visible_indexes: &VisibleIndexes<'_>,
242 ) -> Result<String, QueryError> {
243 let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
244 self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
245
246 self.explain_execution_verbose_from_plan(&plan)
247 }
248
249 #[inline(never)]
251 pub(in crate::db) fn explain_execution_for_model_only(
252 &self,
253 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
254 self.explain_execution_descriptor_for_model_only()
255 }
256
257 #[inline(never)]
259 pub(in crate::db) fn explain_execution_with_visible_indexes(
260 &self,
261 visible_indexes: &VisibleIndexes<'_>,
262 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
263 self.explain_execution_descriptor_for_visible_indexes(visible_indexes)
264 }
265
266 #[inline(never)]
269 pub(in crate::db) fn explain_execution_verbose_for_model_only(
270 &self,
271 ) -> Result<String, QueryError> {
272 self.render_execution_verbose_for_model_only()
273 }
274
275 #[inline(never)]
277 pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
278 &self,
279 visible_indexes: &VisibleIndexes<'_>,
280 ) -> Result<String, QueryError> {
281 self.explain_execution_verbose_for_visible_indexes(visible_indexes)
282 }
283
284 #[inline(never)]
286 #[cfg(test)]
287 pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
288 &self,
289 visible_indexes: &VisibleIndexes<'_>,
290 aggregate: AggregateRouteShape<'_>,
291 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
292 let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
293 let query_explain = plan.explain();
294 let terminal = aggregate.kind();
295 let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate);
296
297 Ok(ExplainAggregateTerminalPlan::new(
298 query_explain,
299 terminal,
300 execution,
301 ))
302 }
303}
304
305impl<E> PreparedExecutionPlan<E>
306where
307 E: EntityValue + EntityKind,
308{
309 pub(in crate::db) fn explain_prepared_aggregate_terminal<S>(
311 &self,
312 strategy: &S,
313 ) -> Result<ExplainAggregateTerminalPlan, QueryError>
314 where
315 S: AggregateExplain,
316 {
317 let Some(kind) = strategy.explain_aggregate_kind() else {
318 return Err(QueryError::invariant(
319 "prepared fluent aggregate explain requires an explain-visible aggregate kind",
320 ));
321 };
322 let aggregate = self
323 .authority()
324 .aggregate_route_shape(kind, strategy.explain_projected_field())
325 .map_err(QueryError::execute)?;
326 let execution =
327 assemble_aggregate_terminal_execution_descriptor(self.logical_plan(), aggregate);
328
329 Ok(ExplainAggregateTerminalPlan::new(
330 self.logical_plan().explain(),
331 kind,
332 execution,
333 ))
334 }
335
336 pub(in crate::db) fn explain_bytes_by_terminal(
338 &self,
339 target_field: &str,
340 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
341 let mut descriptor = self
342 .explain_load_execution_node_descriptor()
343 .map_err(QueryError::execute)?;
344 let projection_mode = self.bytes_by_projection_mode(target_field);
345 let projection_mode_label = Self::bytes_by_projection_mode_label(projection_mode);
346
347 descriptor
348 .node_properties
349 .insert("terminal", Value::from("bytes_by"));
350 descriptor
351 .node_properties
352 .insert("terminal_field", Value::from(target_field.to_string()));
353 descriptor.node_properties.insert(
354 "terminal_projection_mode",
355 Value::from(projection_mode_label),
356 );
357 descriptor.node_properties.insert(
358 "terminal_index_only",
359 Value::from(matches!(
360 projection_mode,
361 BytesByProjectionMode::CoveringIndex | BytesByProjectionMode::CoveringConstant
362 )),
363 );
364
365 Ok(descriptor)
366 }
367
368 pub(in crate::db) fn explain_prepared_projection_terminal<S>(
370 &self,
371 strategy: &S,
372 ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
373 where
374 S: ProjectionExplain,
375 {
376 let mut descriptor = self
377 .explain_load_execution_node_descriptor()
378 .map_err(QueryError::execute)?;
379 let projection_descriptor = strategy.explain_projection_descriptor();
380
381 descriptor.node_properties.insert(
382 "terminal",
383 Value::from(projection_descriptor.terminal_label()),
384 );
385 descriptor.node_properties.insert(
386 "terminal_field",
387 Value::from(projection_descriptor.field_label().to_string()),
388 );
389 descriptor.node_properties.insert(
390 "terminal_output",
391 Value::from(projection_descriptor.output_label()),
392 );
393
394 Ok(descriptor)
395 }
396}
397
398impl<E> Query<E>
399where
400 E: EntityValue + EntityKind,
401{
402 fn explain_execution_descriptor_for_model_only_or_visible_indexes(
405 &self,
406 visible_indexes: Option<&VisibleIndexes<'_>>,
407 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
408 match visible_indexes {
409 Some(visible_indexes) => self
410 .structural()
411 .explain_execution_with_visible_indexes(visible_indexes),
412 None => self.structural().explain_execution_for_model_only(),
413 }
414 }
415
416 fn render_execution_descriptor_for_visibility(
419 &self,
420 visible_indexes: Option<&VisibleIndexes<'_>>,
421 render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
422 ) -> Result<String, QueryError> {
423 let descriptor =
424 self.explain_execution_descriptor_for_model_only_or_visible_indexes(visible_indexes)?;
425
426 Ok(render(descriptor))
427 }
428
429 fn explain_execution_verbose_for_model_only_or_visible_indexes(
432 &self,
433 visible_indexes: Option<&VisibleIndexes<'_>>,
434 ) -> Result<String, QueryError> {
435 match visible_indexes {
436 Some(visible_indexes) => self
437 .structural()
438 .explain_execution_verbose_with_visible_indexes(visible_indexes),
439 None => self.structural().explain_execution_verbose_for_model_only(),
440 }
441 }
442
443 pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
445 self.explain_execution_descriptor_for_model_only_or_visible_indexes(None)
446 }
447
448 #[cfg(test)]
450 pub(in crate::db) fn explain_execution_with_visible_indexes(
451 &self,
452 visible_indexes: &VisibleIndexes<'_>,
453 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
454 self.explain_execution_descriptor_for_model_only_or_visible_indexes(Some(visible_indexes))
455 }
456
457 pub fn explain_execution_text(&self) -> Result<String, QueryError> {
459 self.render_execution_descriptor_for_visibility(None, |descriptor| {
460 descriptor.render_text_tree()
461 })
462 }
463
464 pub fn explain_execution_json(&self) -> Result<String, QueryError> {
466 self.render_execution_descriptor_for_visibility(None, |descriptor| {
467 descriptor.render_json_canonical()
468 })
469 }
470
471 #[inline(never)]
473 pub fn explain_execution_verbose(&self) -> Result<String, QueryError> {
474 self.explain_execution_verbose_for_model_only_or_visible_indexes(None)
475 }
476
477 #[cfg(test)]
479 #[inline(never)]
480 pub(in crate::db) fn explain_aggregate_terminal(
481 &self,
482 aggregate: AggregateExpr,
483 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
484 self.structural()
485 .explain_aggregate_terminal_with_visible_indexes(
486 &VisibleIndexes::schema_owned(E::MODEL.indexes()),
487 AggregateRouteShape::new_from_fields(
488 aggregate.kind(),
489 aggregate.target_field(),
490 E::MODEL.fields(),
491 E::MODEL.primary_key().name(),
492 ),
493 )
494 }
495}
496
497fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
499 match order_pushdown {
500 ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
501 ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
502 format!("eligible(index={index},prefix_len={prefix_len})")
503 }
504 ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
505 }
506}
507
508fn plan_predicate_pushdown_label(
510 predicate: &ExplainPredicate,
511 access: &ExplainAccessPath,
512) -> String {
513 let access_label = explain_access_kind_label(access);
514 if matches!(predicate, ExplainPredicate::None) {
515 return "none".to_string();
516 }
517 if access_label == "full_scan" {
518 if explain_predicate_contains_non_strict_compare(predicate) {
519 return "fallback(non_strict_compare_coercion)".to_string();
520 }
521 if explain_predicate_contains_empty_prefix_starts_with(predicate) {
522 return "fallback(starts_with_empty_prefix)".to_string();
523 }
524 if explain_predicate_contains_is_null(predicate) {
525 return "fallback(is_null_full_scan)".to_string();
526 }
527 if explain_predicate_contains_text_scan_operator(predicate) {
528 return "fallback(text_operator_full_scan)".to_string();
529 }
530
531 return format!("fallback({access_label})");
532 }
533
534 format!("applied({access_label})")
535}
536
537fn explain_predicate_contains_non_strict_compare(predicate: &ExplainPredicate) -> bool {
539 match predicate {
540 ExplainPredicate::Compare { coercion, .. }
541 | ExplainPredicate::CompareFields { coercion, .. } => coercion.id != CoercionId::Strict,
542 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
543 .iter()
544 .any(explain_predicate_contains_non_strict_compare),
545 ExplainPredicate::Not(inner) => explain_predicate_contains_non_strict_compare(inner),
546 ExplainPredicate::None
547 | ExplainPredicate::True
548 | ExplainPredicate::False
549 | ExplainPredicate::IsNull { .. }
550 | ExplainPredicate::IsNotNull { .. }
551 | ExplainPredicate::IsMissing { .. }
552 | ExplainPredicate::IsEmpty { .. }
553 | ExplainPredicate::IsNotEmpty { .. }
554 | ExplainPredicate::TextContains { .. }
555 | ExplainPredicate::TextContainsCi { .. } => false,
556 }
557}
558
559fn explain_predicate_contains_is_null(predicate: &ExplainPredicate) -> bool {
561 match predicate {
562 ExplainPredicate::IsNull { .. } => true,
563 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => {
564 children.iter().any(explain_predicate_contains_is_null)
565 }
566 ExplainPredicate::Not(inner) => explain_predicate_contains_is_null(inner),
567 ExplainPredicate::None
568 | ExplainPredicate::True
569 | ExplainPredicate::False
570 | ExplainPredicate::Compare { .. }
571 | ExplainPredicate::CompareFields { .. }
572 | ExplainPredicate::IsNotNull { .. }
573 | ExplainPredicate::IsMissing { .. }
574 | ExplainPredicate::IsEmpty { .. }
575 | ExplainPredicate::IsNotEmpty { .. }
576 | ExplainPredicate::TextContains { .. }
577 | ExplainPredicate::TextContainsCi { .. } => false,
578 }
579}
580
581fn explain_predicate_contains_empty_prefix_starts_with(predicate: &ExplainPredicate) -> bool {
583 match predicate {
584 ExplainPredicate::Compare {
585 op: CompareOp::StartsWith,
586 value: Value::Text(prefix),
587 ..
588 } => prefix.is_empty(),
589 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
590 .iter()
591 .any(explain_predicate_contains_empty_prefix_starts_with),
592 ExplainPredicate::Not(inner) => explain_predicate_contains_empty_prefix_starts_with(inner),
593 ExplainPredicate::None
594 | ExplainPredicate::True
595 | ExplainPredicate::False
596 | ExplainPredicate::Compare { .. }
597 | ExplainPredicate::CompareFields { .. }
598 | ExplainPredicate::IsNull { .. }
599 | ExplainPredicate::IsNotNull { .. }
600 | ExplainPredicate::IsMissing { .. }
601 | ExplainPredicate::IsEmpty { .. }
602 | ExplainPredicate::IsNotEmpty { .. }
603 | ExplainPredicate::TextContains { .. }
604 | ExplainPredicate::TextContainsCi { .. } => false,
605 }
606}
607
608fn explain_predicate_contains_text_scan_operator(predicate: &ExplainPredicate) -> bool {
610 match predicate {
611 ExplainPredicate::Compare {
612 op: CompareOp::EndsWith,
613 ..
614 }
615 | ExplainPredicate::TextContains { .. }
616 | ExplainPredicate::TextContainsCi { .. } => true,
617 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
618 .iter()
619 .any(explain_predicate_contains_text_scan_operator),
620 ExplainPredicate::Not(inner) => explain_predicate_contains_text_scan_operator(inner),
621 ExplainPredicate::Compare { .. }
622 | ExplainPredicate::CompareFields { .. }
623 | ExplainPredicate::None
624 | ExplainPredicate::True
625 | ExplainPredicate::False
626 | ExplainPredicate::IsNull { .. }
627 | ExplainPredicate::IsNotNull { .. }
628 | ExplainPredicate::IsMissing { .. }
629 | ExplainPredicate::IsEmpty { .. }
630 | ExplainPredicate::IsNotEmpty { .. } => false,
631 }
632}