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::{PreparedFluentAggregateExplainStrategy, PreparedFluentProjectionStrategy},
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 pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
227 &self,
228 visible_indexes: &VisibleIndexes<'_>,
229 aggregate: AggregateRouteShape<'_>,
230 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
231 let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
232 let query_explain = plan.explain();
233 let terminal = aggregate.kind();
234 let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate);
235
236 Ok(ExplainAggregateTerminalPlan::new(
237 query_explain,
238 terminal,
239 execution,
240 ))
241 }
242
243 #[inline(never)]
245 pub(in crate::db) fn explain_prepared_aggregate_terminal_with_visible_indexes<S>(
246 &self,
247 visible_indexes: &VisibleIndexes<'_>,
248 strategy: &S,
249 ) -> Result<ExplainAggregateTerminalPlan, QueryError>
250 where
251 S: PreparedFluentAggregateExplainStrategy,
252 {
253 let Some(kind) = strategy.explain_aggregate_kind() else {
254 return Err(QueryError::invariant(
255 "prepared fluent aggregate explain requires an explain-visible aggregate kind",
256 ));
257 };
258 let aggregate = AggregateRouteShape::new_from_fields(
259 kind,
260 strategy.explain_projected_field(),
261 self.model().fields(),
262 self.model().primary_key().name(),
263 );
264
265 self.explain_aggregate_terminal_with_visible_indexes(visible_indexes, aggregate)
266 }
267}
268
269impl<E> Query<E>
270where
271 E: EntityKind,
272{
273 fn prepared_execution_plan_for_visibility(
277 &self,
278 visible_indexes: Option<&VisibleIndexes<'_>>,
279 ) -> Result<PreparedExecutionPlan<E>, QueryError> {
280 let plan = match visible_indexes {
281 Some(visible_indexes) => self
282 .structural()
283 .build_plan_with_visible_indexes(visible_indexes)?,
284 None => self.structural().build_plan()?,
285 };
286
287 Ok(PreparedExecutionPlan::<E>::new(plan))
288 }
289}
290
291impl<E> Query<E>
292where
293 E: EntityValue + EntityKind,
294{
295 fn explain_execution_descriptor_for_visibility(
298 &self,
299 visible_indexes: Option<&VisibleIndexes<'_>>,
300 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
301 match visible_indexes {
302 Some(visible_indexes) => self
303 .structural()
304 .explain_execution_with_visible_indexes(visible_indexes),
305 None => self.structural().explain_execution(),
306 }
307 }
308
309 fn render_execution_descriptor_for_visibility(
312 &self,
313 visible_indexes: Option<&VisibleIndexes<'_>>,
314 render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
315 ) -> Result<String, QueryError> {
316 let descriptor = self.explain_execution_descriptor_for_visibility(visible_indexes)?;
317
318 Ok(render(descriptor))
319 }
320
321 fn explain_execution_verbose_for_visibility(
324 &self,
325 visible_indexes: Option<&VisibleIndexes<'_>>,
326 ) -> Result<String, QueryError> {
327 match visible_indexes {
328 Some(visible_indexes) => self
329 .structural()
330 .explain_execution_verbose_with_visible_indexes(visible_indexes),
331 None => self.structural().explain_execution_verbose(),
332 }
333 }
334
335 pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
337 self.explain_execution_descriptor_for_visibility(None)
338 }
339
340 #[allow(dead_code)]
342 pub(in crate::db) fn explain_execution_with_visible_indexes(
343 &self,
344 visible_indexes: &VisibleIndexes<'_>,
345 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
346 self.explain_execution_descriptor_for_visibility(Some(visible_indexes))
347 }
348
349 pub fn explain_execution_text(&self) -> Result<String, QueryError> {
351 self.render_execution_descriptor_for_visibility(None, |descriptor| {
352 descriptor.render_text_tree()
353 })
354 }
355
356 pub fn explain_execution_json(&self) -> Result<String, QueryError> {
358 self.render_execution_descriptor_for_visibility(None, |descriptor| {
359 descriptor.render_json_canonical()
360 })
361 }
362
363 #[inline(never)]
365 pub fn explain_execution_verbose(&self) -> Result<String, QueryError> {
366 self.explain_execution_verbose_for_visibility(None)
367 }
368
369 #[cfg(test)]
371 #[inline(never)]
372 pub(in crate::db) fn explain_aggregate_terminal(
373 &self,
374 aggregate: AggregateExpr,
375 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
376 self.structural()
377 .explain_aggregate_terminal_with_visible_indexes(
378 &VisibleIndexes::schema_owned(E::MODEL.indexes()),
379 AggregateRouteShape::new_from_fields(
380 aggregate.kind(),
381 aggregate.target_field(),
382 E::MODEL.fields(),
383 E::MODEL.primary_key().name(),
384 ),
385 )
386 }
387
388 pub(in crate::db) fn explain_prepared_aggregate_terminal_with_visible_indexes<S>(
390 &self,
391 visible_indexes: &VisibleIndexes<'_>,
392 strategy: &S,
393 ) -> Result<ExplainAggregateTerminalPlan, QueryError>
394 where
395 S: PreparedFluentAggregateExplainStrategy,
396 {
397 self.structural()
398 .explain_prepared_aggregate_terminal_with_visible_indexes(visible_indexes, strategy)
399 }
400
401 pub(in crate::db) fn explain_bytes_by_with_visible_indexes(
403 &self,
404 visible_indexes: &VisibleIndexes<'_>,
405 target_field: &str,
406 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
407 let executable = self.prepared_execution_plan_for_visibility(Some(visible_indexes))?;
408 let mut descriptor = executable
409 .explain_load_execution_node_descriptor()
410 .map_err(QueryError::execute)?;
411 let projection_mode = executable.bytes_by_projection_mode(target_field);
412 let projection_mode_label =
413 PreparedExecutionPlan::<E>::bytes_by_projection_mode_label(projection_mode);
414
415 descriptor
416 .node_properties
417 .insert("terminal", Value::from("bytes_by"));
418 descriptor
419 .node_properties
420 .insert("terminal_field", Value::from(target_field.to_string()));
421 descriptor.node_properties.insert(
422 "terminal_projection_mode",
423 Value::from(projection_mode_label),
424 );
425 descriptor.node_properties.insert(
426 "terminal_index_only",
427 Value::from(matches!(
428 projection_mode,
429 BytesByProjectionMode::CoveringIndex | BytesByProjectionMode::CoveringConstant
430 )),
431 );
432
433 Ok(descriptor)
434 }
435
436 pub(in crate::db) fn explain_prepared_projection_terminal_with_visible_indexes(
438 &self,
439 visible_indexes: &VisibleIndexes<'_>,
440 strategy: &PreparedFluentProjectionStrategy,
441 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
442 let executable = self.prepared_execution_plan_for_visibility(Some(visible_indexes))?;
443 let mut descriptor = executable
444 .explain_load_execution_node_descriptor()
445 .map_err(QueryError::execute)?;
446 let projection_descriptor = strategy.explain_descriptor();
447
448 descriptor.node_properties.insert(
449 "terminal",
450 Value::from(projection_descriptor.terminal_label()),
451 );
452 descriptor.node_properties.insert(
453 "terminal_field",
454 Value::from(projection_descriptor.field_label().to_string()),
455 );
456 descriptor.node_properties.insert(
457 "terminal_output",
458 Value::from(projection_descriptor.output_label()),
459 );
460
461 Ok(descriptor)
462 }
463}
464
465fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
467 match order_pushdown {
468 ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
469 ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
470 format!("eligible(index={index},prefix_len={prefix_len})")
471 }
472 ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
473 }
474}
475
476fn plan_predicate_pushdown_label(
478 predicate: &ExplainPredicate,
479 access: &ExplainAccessPath,
480) -> String {
481 let access_label = explain_access_kind_label(access);
482 if matches!(predicate, ExplainPredicate::None) {
483 return "none".to_string();
484 }
485 if access_label == "full_scan" {
486 if explain_predicate_contains_non_strict_compare(predicate) {
487 return "fallback(non_strict_compare_coercion)".to_string();
488 }
489 if explain_predicate_contains_empty_prefix_starts_with(predicate) {
490 return "fallback(starts_with_empty_prefix)".to_string();
491 }
492 if explain_predicate_contains_is_null(predicate) {
493 return "fallback(is_null_full_scan)".to_string();
494 }
495 if explain_predicate_contains_text_scan_operator(predicate) {
496 return "fallback(text_operator_full_scan)".to_string();
497 }
498
499 return format!("fallback({access_label})");
500 }
501
502 format!("applied({access_label})")
503}
504
505fn explain_predicate_contains_non_strict_compare(predicate: &ExplainPredicate) -> bool {
507 match predicate {
508 ExplainPredicate::Compare { coercion, .. }
509 | ExplainPredicate::CompareFields { coercion, .. } => coercion.id != CoercionId::Strict,
510 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
511 .iter()
512 .any(explain_predicate_contains_non_strict_compare),
513 ExplainPredicate::Not(inner) => explain_predicate_contains_non_strict_compare(inner),
514 ExplainPredicate::None
515 | ExplainPredicate::True
516 | ExplainPredicate::False
517 | ExplainPredicate::IsNull { .. }
518 | ExplainPredicate::IsNotNull { .. }
519 | ExplainPredicate::IsMissing { .. }
520 | ExplainPredicate::IsEmpty { .. }
521 | ExplainPredicate::IsNotEmpty { .. }
522 | ExplainPredicate::TextContains { .. }
523 | ExplainPredicate::TextContainsCi { .. } => false,
524 }
525}
526
527fn explain_predicate_contains_is_null(predicate: &ExplainPredicate) -> bool {
529 match predicate {
530 ExplainPredicate::IsNull { .. } => true,
531 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => {
532 children.iter().any(explain_predicate_contains_is_null)
533 }
534 ExplainPredicate::Not(inner) => explain_predicate_contains_is_null(inner),
535 ExplainPredicate::None
536 | ExplainPredicate::True
537 | ExplainPredicate::False
538 | ExplainPredicate::Compare { .. }
539 | ExplainPredicate::CompareFields { .. }
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_empty_prefix_starts_with(predicate: &ExplainPredicate) -> bool {
551 match predicate {
552 ExplainPredicate::Compare {
553 op: CompareOp::StartsWith,
554 value: Value::Text(prefix),
555 ..
556 } => prefix.is_empty(),
557 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
558 .iter()
559 .any(explain_predicate_contains_empty_prefix_starts_with),
560 ExplainPredicate::Not(inner) => explain_predicate_contains_empty_prefix_starts_with(inner),
561 ExplainPredicate::None
562 | ExplainPredicate::True
563 | ExplainPredicate::False
564 | ExplainPredicate::Compare { .. }
565 | ExplainPredicate::CompareFields { .. }
566 | ExplainPredicate::IsNull { .. }
567 | ExplainPredicate::IsNotNull { .. }
568 | ExplainPredicate::IsMissing { .. }
569 | ExplainPredicate::IsEmpty { .. }
570 | ExplainPredicate::IsNotEmpty { .. }
571 | ExplainPredicate::TextContains { .. }
572 | ExplainPredicate::TextContainsCi { .. } => false,
573 }
574}
575
576fn explain_predicate_contains_text_scan_operator(predicate: &ExplainPredicate) -> bool {
578 match predicate {
579 ExplainPredicate::Compare {
580 op: CompareOp::EndsWith,
581 ..
582 }
583 | ExplainPredicate::TextContains { .. }
584 | ExplainPredicate::TextContainsCi { .. } => true,
585 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
586 .iter()
587 .any(explain_predicate_contains_text_scan_operator),
588 ExplainPredicate::Not(inner) => explain_predicate_contains_text_scan_operator(inner),
589 ExplainPredicate::Compare { .. }
590 | ExplainPredicate::CompareFields { .. }
591 | ExplainPredicate::None
592 | ExplainPredicate::True
593 | ExplainPredicate::False
594 | ExplainPredicate::IsNull { .. }
595 | ExplainPredicate::IsNotNull { .. }
596 | ExplainPredicate::IsMissing { .. }
597 | ExplainPredicate::IsEmpty { .. }
598 | ExplainPredicate::IsNotEmpty { .. } => false,
599 }
600}