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