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_visibility(
185 &self,
186 plan: &mut AccessPlannedQuery,
187 visible_indexes: Option<&VisibleIndexes<'_>>,
188 ) {
189 let visible_indexes = match visible_indexes {
190 Some(visible_indexes) => visible_indexes.as_slice(),
191 None => self.model().indexes(),
192 };
193
194 plan.finalize_access_choice_for_model_only_with_indexes(self.model(), visible_indexes);
195 }
196
197 fn explain_execution_descriptor_for_visibility(
200 &self,
201 visible_indexes: Option<&VisibleIndexes<'_>>,
202 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
203 let mut plan = match visible_indexes {
204 Some(visible_indexes) => self.build_plan_with_visible_indexes(visible_indexes)?,
205 None => self.build_plan()?,
206 };
207 self.finalize_explain_access_choice_for_visibility(&mut plan, visible_indexes);
208
209 self.explain_execution_descriptor_from_model_only_plan(&plan)
210 }
211
212 fn explain_execution_verbose_for_visibility(
215 &self,
216 visible_indexes: Option<&VisibleIndexes<'_>>,
217 ) -> Result<String, QueryError> {
218 let mut plan = match visible_indexes {
219 Some(visible_indexes) => self.build_plan_with_visible_indexes(visible_indexes)?,
220 None => self.build_plan()?,
221 };
222 self.finalize_explain_access_choice_for_visibility(&mut plan, visible_indexes);
223
224 self.explain_execution_verbose_from_plan(&plan)
225 }
226
227 #[inline(never)]
229 pub(in crate::db) fn explain_execution(
230 &self,
231 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
232 self.explain_execution_descriptor_for_visibility(None)
233 }
234
235 #[inline(never)]
237 pub(in crate::db) fn explain_execution_with_visible_indexes(
238 &self,
239 visible_indexes: &VisibleIndexes<'_>,
240 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
241 self.explain_execution_descriptor_for_visibility(Some(visible_indexes))
242 }
243
244 #[inline(never)]
247 pub(in crate::db) fn explain_execution_verbose(&self) -> Result<String, QueryError> {
248 self.explain_execution_verbose_for_visibility(None)
249 }
250
251 #[inline(never)]
253 pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
254 &self,
255 visible_indexes: &VisibleIndexes<'_>,
256 ) -> Result<String, QueryError> {
257 self.explain_execution_verbose_for_visibility(Some(visible_indexes))
258 }
259
260 #[inline(never)]
262 #[cfg(test)]
263 pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
264 &self,
265 visible_indexes: &VisibleIndexes<'_>,
266 aggregate: AggregateRouteShape<'_>,
267 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
268 let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
269 let query_explain = plan.explain();
270 let terminal = aggregate.kind();
271 let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate);
272
273 Ok(ExplainAggregateTerminalPlan::new(
274 query_explain,
275 terminal,
276 execution,
277 ))
278 }
279}
280
281impl<E> PreparedExecutionPlan<E>
282where
283 E: EntityValue + EntityKind,
284{
285 pub(in crate::db) fn explain_prepared_aggregate_terminal<S>(
287 &self,
288 strategy: &S,
289 ) -> Result<ExplainAggregateTerminalPlan, QueryError>
290 where
291 S: AggregateExplain,
292 {
293 let Some(kind) = strategy.explain_aggregate_kind() else {
294 return Err(QueryError::invariant(
295 "prepared fluent aggregate explain requires an explain-visible aggregate kind",
296 ));
297 };
298 let aggregate = self
299 .authority()
300 .aggregate_route_shape(kind, strategy.explain_projected_field())
301 .map_err(QueryError::execute)?;
302 let execution =
303 assemble_aggregate_terminal_execution_descriptor(self.logical_plan(), aggregate);
304
305 Ok(ExplainAggregateTerminalPlan::new(
306 self.logical_plan().explain(),
307 kind,
308 execution,
309 ))
310 }
311
312 pub(in crate::db) fn explain_bytes_by_terminal(
314 &self,
315 target_field: &str,
316 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
317 let mut descriptor = self
318 .explain_load_execution_node_descriptor()
319 .map_err(QueryError::execute)?;
320 let projection_mode = self.bytes_by_projection_mode(target_field);
321 let projection_mode_label = Self::bytes_by_projection_mode_label(projection_mode);
322
323 descriptor
324 .node_properties
325 .insert("terminal", Value::from("bytes_by"));
326 descriptor
327 .node_properties
328 .insert("terminal_field", Value::from(target_field.to_string()));
329 descriptor.node_properties.insert(
330 "terminal_projection_mode",
331 Value::from(projection_mode_label),
332 );
333 descriptor.node_properties.insert(
334 "terminal_index_only",
335 Value::from(matches!(
336 projection_mode,
337 BytesByProjectionMode::CoveringIndex | BytesByProjectionMode::CoveringConstant
338 )),
339 );
340
341 Ok(descriptor)
342 }
343
344 pub(in crate::db) fn explain_prepared_projection_terminal<S>(
346 &self,
347 strategy: &S,
348 ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
349 where
350 S: ProjectionExplain,
351 {
352 let mut descriptor = self
353 .explain_load_execution_node_descriptor()
354 .map_err(QueryError::execute)?;
355 let projection_descriptor = strategy.explain_projection_descriptor();
356
357 descriptor.node_properties.insert(
358 "terminal",
359 Value::from(projection_descriptor.terminal_label()),
360 );
361 descriptor.node_properties.insert(
362 "terminal_field",
363 Value::from(projection_descriptor.field_label().to_string()),
364 );
365 descriptor.node_properties.insert(
366 "terminal_output",
367 Value::from(projection_descriptor.output_label()),
368 );
369
370 Ok(descriptor)
371 }
372}
373
374impl<E> Query<E>
375where
376 E: EntityValue + EntityKind,
377{
378 fn explain_execution_descriptor_for_visibility(
381 &self,
382 visible_indexes: Option<&VisibleIndexes<'_>>,
383 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
384 match visible_indexes {
385 Some(visible_indexes) => self
386 .structural()
387 .explain_execution_with_visible_indexes(visible_indexes),
388 None => self.structural().explain_execution(),
389 }
390 }
391
392 fn render_execution_descriptor_for_visibility(
395 &self,
396 visible_indexes: Option<&VisibleIndexes<'_>>,
397 render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
398 ) -> Result<String, QueryError> {
399 let descriptor = self.explain_execution_descriptor_for_visibility(visible_indexes)?;
400
401 Ok(render(descriptor))
402 }
403
404 fn explain_execution_verbose_for_visibility(
407 &self,
408 visible_indexes: Option<&VisibleIndexes<'_>>,
409 ) -> Result<String, QueryError> {
410 match visible_indexes {
411 Some(visible_indexes) => self
412 .structural()
413 .explain_execution_verbose_with_visible_indexes(visible_indexes),
414 None => self.structural().explain_execution_verbose(),
415 }
416 }
417
418 pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
420 self.explain_execution_descriptor_for_visibility(None)
421 }
422
423 #[cfg(test)]
425 pub(in crate::db) fn explain_execution_with_visible_indexes(
426 &self,
427 visible_indexes: &VisibleIndexes<'_>,
428 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
429 self.explain_execution_descriptor_for_visibility(Some(visible_indexes))
430 }
431
432 pub fn explain_execution_text(&self) -> Result<String, QueryError> {
434 self.render_execution_descriptor_for_visibility(None, |descriptor| {
435 descriptor.render_text_tree()
436 })
437 }
438
439 pub fn explain_execution_json(&self) -> Result<String, QueryError> {
441 self.render_execution_descriptor_for_visibility(None, |descriptor| {
442 descriptor.render_json_canonical()
443 })
444 }
445
446 #[inline(never)]
448 pub fn explain_execution_verbose(&self) -> Result<String, QueryError> {
449 self.explain_execution_verbose_for_visibility(None)
450 }
451
452 #[cfg(test)]
454 #[inline(never)]
455 pub(in crate::db) fn explain_aggregate_terminal(
456 &self,
457 aggregate: AggregateExpr,
458 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
459 self.structural()
460 .explain_aggregate_terminal_with_visible_indexes(
461 &VisibleIndexes::schema_owned(E::MODEL.indexes()),
462 AggregateRouteShape::new_from_fields(
463 aggregate.kind(),
464 aggregate.target_field(),
465 E::MODEL.fields(),
466 E::MODEL.primary_key().name(),
467 ),
468 )
469 }
470}
471
472fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
474 match order_pushdown {
475 ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
476 ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
477 format!("eligible(index={index},prefix_len={prefix_len})")
478 }
479 ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
480 }
481}
482
483fn plan_predicate_pushdown_label(
485 predicate: &ExplainPredicate,
486 access: &ExplainAccessPath,
487) -> String {
488 let access_label = explain_access_kind_label(access);
489 if matches!(predicate, ExplainPredicate::None) {
490 return "none".to_string();
491 }
492 if access_label == "full_scan" {
493 if explain_predicate_contains_non_strict_compare(predicate) {
494 return "fallback(non_strict_compare_coercion)".to_string();
495 }
496 if explain_predicate_contains_empty_prefix_starts_with(predicate) {
497 return "fallback(starts_with_empty_prefix)".to_string();
498 }
499 if explain_predicate_contains_is_null(predicate) {
500 return "fallback(is_null_full_scan)".to_string();
501 }
502 if explain_predicate_contains_text_scan_operator(predicate) {
503 return "fallback(text_operator_full_scan)".to_string();
504 }
505
506 return format!("fallback({access_label})");
507 }
508
509 format!("applied({access_label})")
510}
511
512fn explain_predicate_contains_non_strict_compare(predicate: &ExplainPredicate) -> bool {
514 match predicate {
515 ExplainPredicate::Compare { coercion, .. }
516 | ExplainPredicate::CompareFields { coercion, .. } => coercion.id != CoercionId::Strict,
517 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
518 .iter()
519 .any(explain_predicate_contains_non_strict_compare),
520 ExplainPredicate::Not(inner) => explain_predicate_contains_non_strict_compare(inner),
521 ExplainPredicate::None
522 | ExplainPredicate::True
523 | ExplainPredicate::False
524 | ExplainPredicate::IsNull { .. }
525 | ExplainPredicate::IsNotNull { .. }
526 | ExplainPredicate::IsMissing { .. }
527 | ExplainPredicate::IsEmpty { .. }
528 | ExplainPredicate::IsNotEmpty { .. }
529 | ExplainPredicate::TextContains { .. }
530 | ExplainPredicate::TextContainsCi { .. } => false,
531 }
532}
533
534fn explain_predicate_contains_is_null(predicate: &ExplainPredicate) -> bool {
536 match predicate {
537 ExplainPredicate::IsNull { .. } => true,
538 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => {
539 children.iter().any(explain_predicate_contains_is_null)
540 }
541 ExplainPredicate::Not(inner) => explain_predicate_contains_is_null(inner),
542 ExplainPredicate::None
543 | ExplainPredicate::True
544 | ExplainPredicate::False
545 | ExplainPredicate::Compare { .. }
546 | ExplainPredicate::CompareFields { .. }
547 | ExplainPredicate::IsNotNull { .. }
548 | ExplainPredicate::IsMissing { .. }
549 | ExplainPredicate::IsEmpty { .. }
550 | ExplainPredicate::IsNotEmpty { .. }
551 | ExplainPredicate::TextContains { .. }
552 | ExplainPredicate::TextContainsCi { .. } => false,
553 }
554}
555
556fn explain_predicate_contains_empty_prefix_starts_with(predicate: &ExplainPredicate) -> bool {
558 match predicate {
559 ExplainPredicate::Compare {
560 op: CompareOp::StartsWith,
561 value: Value::Text(prefix),
562 ..
563 } => prefix.is_empty(),
564 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
565 .iter()
566 .any(explain_predicate_contains_empty_prefix_starts_with),
567 ExplainPredicate::Not(inner) => explain_predicate_contains_empty_prefix_starts_with(inner),
568 ExplainPredicate::None
569 | ExplainPredicate::True
570 | ExplainPredicate::False
571 | ExplainPredicate::Compare { .. }
572 | ExplainPredicate::CompareFields { .. }
573 | ExplainPredicate::IsNull { .. }
574 | ExplainPredicate::IsNotNull { .. }
575 | ExplainPredicate::IsMissing { .. }
576 | ExplainPredicate::IsEmpty { .. }
577 | ExplainPredicate::IsNotEmpty { .. }
578 | ExplainPredicate::TextContains { .. }
579 | ExplainPredicate::TextContainsCi { .. } => false,
580 }
581}
582
583fn explain_predicate_contains_text_scan_operator(predicate: &ExplainPredicate) -> bool {
585 match predicate {
586 ExplainPredicate::Compare {
587 op: CompareOp::EndsWith,
588 ..
589 }
590 | ExplainPredicate::TextContains { .. }
591 | ExplainPredicate::TextContainsCi { .. } => true,
592 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
593 .iter()
594 .any(explain_predicate_contains_text_scan_operator),
595 ExplainPredicate::Not(inner) => explain_predicate_contains_text_scan_operator(inner),
596 ExplainPredicate::Compare { .. }
597 | ExplainPredicate::CompareFields { .. }
598 | ExplainPredicate::None
599 | ExplainPredicate::True
600 | ExplainPredicate::False
601 | ExplainPredicate::IsNull { .. }
602 | ExplainPredicate::IsNotNull { .. }
603 | ExplainPredicate::IsMissing { .. }
604 | ExplainPredicate::IsEmpty { .. }
605 | ExplainPredicate::IsNotEmpty { .. } => false,
606 }
607}