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