1use crate::{
8 db::{
9 access::AccessPlan,
10 predicate::{CoercionSpec, CompareOp, ComparePredicate, MissingRowPolicy, Predicate},
11 query::{
12 builder::scalar_projection::render_scalar_projection_expr_plan_label,
13 explain::{
14 access_projection::write_access_json_detailed, explain_access_plan,
15 writer::JsonWriter,
16 },
17 plan::{
18 AccessChoiceCandidateExplainSummary, AccessChoiceExplainSnapshot,
19 AccessChoiceResidualBurden, AccessPlannedQuery, AggregateKind, DeleteLimitSpec,
20 GroupedPlanAggregateFamily, GroupedPlanFallbackReason, GroupedPlanStrategy,
21 LogicalPlan, OrderDirection, OrderSpec, PageSpec, QueryMode, ScalarPlan,
22 explain_access_strategy_label, expr::Expr, grouped_plan_strategy,
23 render_scalar_filter_expr_plan_label,
24 },
25 },
26 },
27 traits::KeyValueCodec,
28 value::Value,
29};
30use std::{fmt, ops::Bound};
31
32#[derive(Clone, Eq, PartialEq)]
39pub struct ExplainPlan {
40 pub(in crate::db) mode: QueryMode,
41 pub(in crate::db) access: ExplainAccessPath,
42 pub(in crate::db) access_decision: ExplainAccessDecisionV1,
43 pub(in crate::db) filter_expr: Option<String>,
44 filter_expr_model: Option<Expr>,
45 pub(in crate::db) predicate: ExplainPredicate,
46 predicate_model: Option<Predicate>,
47 pub(in crate::db) order_by: ExplainOrderBy,
48 pub(in crate::db) distinct: bool,
49 pub(in crate::db) grouping: ExplainGrouping,
50 pub(in crate::db) order_pushdown: ExplainOrderPushdown,
51 pub(in crate::db) page: ExplainPagination,
52 pub(in crate::db) delete_limit: ExplainDeleteLimit,
53 pub(in crate::db) consistency: MissingRowPolicy,
54}
55
56#[expect(clippy::missing_fields_in_debug)]
57impl fmt::Debug for ExplainPlan {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 f.debug_struct("ExplainPlan")
60 .field("mode", &self.mode)
61 .field("access", &self.access)
62 .field("filter_expr", &self.filter_expr)
63 .field("filter_expr_model", &self.filter_expr_model)
64 .field("predicate", &self.predicate)
65 .field("predicate_model", &self.predicate_model)
66 .field("order_by", &self.order_by)
67 .field("distinct", &self.distinct)
68 .field("grouping", &self.grouping)
69 .field("order_pushdown", &self.order_pushdown)
70 .field("page", &self.page)
71 .field("delete_limit", &self.delete_limit)
72 .field("consistency", &self.consistency)
73 .finish()
74 }
75}
76
77impl ExplainPlan {
78 #[must_use]
80 pub const fn mode(&self) -> QueryMode {
81 self.mode
82 }
83
84 #[must_use]
86 pub const fn access(&self) -> &ExplainAccessPath {
87 &self.access
88 }
89
90 #[must_use]
92 pub const fn access_decision(&self) -> &ExplainAccessDecisionV1 {
93 &self.access_decision
94 }
95
96 #[must_use]
98 pub fn filter_expr(&self) -> Option<&str> {
99 self.filter_expr.as_deref()
100 }
101
102 #[must_use]
104 pub(in crate::db::query) fn filter_expr_model_for_hash(&self) -> Option<&Expr> {
105 if let Some(filter_expr_model) = &self.filter_expr_model {
106 debug_assert_eq!(
107 self.filter_expr(),
108 Some(render_scalar_filter_expr_plan_label(filter_expr_model).as_str()),
109 "explain scalar filter label drifted from canonical filter model"
110 );
111 Some(filter_expr_model)
112 } else {
113 debug_assert!(
114 self.filter_expr.is_none(),
115 "missing canonical filter model requires filter_expr=None"
116 );
117 None
118 }
119 }
120
121 #[must_use]
123 pub const fn predicate(&self) -> &ExplainPredicate {
124 &self.predicate
125 }
126
127 #[must_use]
129 pub const fn order_by(&self) -> &ExplainOrderBy {
130 &self.order_by
131 }
132
133 #[must_use]
135 pub const fn distinct(&self) -> bool {
136 self.distinct
137 }
138
139 #[must_use]
141 pub const fn grouping(&self) -> &ExplainGrouping {
142 &self.grouping
143 }
144
145 #[must_use]
147 pub const fn order_pushdown(&self) -> &ExplainOrderPushdown {
148 &self.order_pushdown
149 }
150
151 #[must_use]
153 pub const fn page(&self) -> &ExplainPagination {
154 &self.page
155 }
156
157 #[must_use]
159 pub const fn delete_limit(&self) -> &ExplainDeleteLimit {
160 &self.delete_limit
161 }
162
163 #[must_use]
165 pub const fn consistency(&self) -> MissingRowPolicy {
166 self.consistency
167 }
168}
169
170impl ExplainPlan {
171 #[must_use]
177 pub(in crate::db::query) fn predicate_model_for_hash(&self) -> Option<&Predicate> {
178 if let Some(predicate) = &self.predicate_model {
179 debug_assert_eq!(
180 self.predicate,
181 ExplainPredicate::from_predicate(predicate),
182 "explain predicate surface drifted from canonical predicate model"
183 );
184 Some(predicate)
185 } else {
186 debug_assert!(
187 matches!(self.predicate, ExplainPredicate::None),
188 "missing canonical predicate model requires ExplainPredicate::None"
189 );
190 None
191 }
192 }
193
194 #[must_use]
199 pub fn render_text_canonical(&self) -> String {
200 format!(
201 concat!(
202 "mode={:?}\n",
203 "access={:?}\n",
204 "access_decision={}\n",
205 "filter_expr={:?}\n",
206 "predicate={:?}\n",
207 "order_by={:?}\n",
208 "distinct={}\n",
209 "grouping={:?}\n",
210 "order_pushdown={:?}\n",
211 "page={:?}\n",
212 "delete_limit={:?}\n",
213 "consistency={:?}",
214 ),
215 self.mode(),
216 self.access(),
217 self.access_decision().render_compact_summary(),
218 self.filter_expr(),
219 self.predicate(),
220 self.order_by(),
221 self.distinct(),
222 self.grouping(),
223 self.order_pushdown(),
224 self.page(),
225 self.delete_limit(),
226 self.consistency(),
227 )
228 }
229
230 #[must_use]
232 pub fn render_json_canonical(&self) -> String {
233 let mut out = String::new();
234 write_logical_explain_json(self, &mut out);
235
236 out
237 }
238}
239
240#[derive(Clone, Debug, Eq, PartialEq)]
247pub enum ExplainGrouping {
248 None,
249 Grouped {
250 strategy: &'static str,
251 fallback_reason: Option<&'static str>,
252 group_fields: Vec<ExplainGroupField>,
253 aggregates: Vec<ExplainGroupAggregate>,
254 having: Option<ExplainGroupHaving>,
255 max_groups: u64,
256 max_group_bytes: u64,
257 },
258}
259
260#[derive(Clone, Debug, Eq, PartialEq)]
267pub struct ExplainGroupField {
268 pub(in crate::db) slot_index: usize,
269 pub(in crate::db) field: String,
270}
271
272impl ExplainGroupField {
273 #[must_use]
275 pub const fn slot_index(&self) -> usize {
276 self.slot_index
277 }
278
279 #[must_use]
281 pub const fn field(&self) -> &str {
282 self.field.as_str()
283 }
284}
285
286#[derive(Clone, Debug, Eq, PartialEq)]
293pub struct ExplainGroupAggregate {
294 pub(in crate::db) kind: AggregateKind,
295 pub(in crate::db) target_field: Option<String>,
296 pub(in crate::db) input_expr: Option<String>,
297 pub(in crate::db) filter_expr: Option<String>,
298 pub(in crate::db) distinct: bool,
299}
300
301impl ExplainGroupAggregate {
302 #[must_use]
304 pub const fn kind(&self) -> AggregateKind {
305 self.kind
306 }
307
308 #[must_use]
310 pub fn target_field(&self) -> Option<&str> {
311 self.target_field.as_deref()
312 }
313
314 #[must_use]
316 pub fn input_expr(&self) -> Option<&str> {
317 self.input_expr.as_deref()
318 }
319
320 #[must_use]
322 pub fn filter_expr(&self) -> Option<&str> {
323 self.filter_expr.as_deref()
324 }
325
326 #[must_use]
328 pub const fn distinct(&self) -> bool {
329 self.distinct
330 }
331}
332
333#[derive(Clone, Debug, Eq, PartialEq)]
342pub struct ExplainGroupHaving {
343 pub(in crate::db) expr: Expr,
344}
345
346impl ExplainGroupHaving {
347 #[must_use]
349 pub(in crate::db) const fn expr(&self) -> &Expr {
350 &self.expr
351 }
352}
353
354#[derive(Clone, Debug, Eq, PartialEq)]
361pub enum ExplainOrderPushdown {
362 MissingModelContext,
363 EligibleSecondaryIndex { index: String, prefix_len: usize },
364 Rejected(SecondaryOrderPushdownRejection),
365}
366
367#[derive(Clone, Debug, Eq, PartialEq)]
375pub enum SecondaryOrderPushdownRejection {
376 NoOrderBy,
377 AccessPathNotSingleIndexPrefix,
378 AccessPathIndexRangeUnsupported {
379 index: String,
380 prefix_len: usize,
381 },
382 InvalidIndexPrefixBounds {
383 prefix_len: usize,
384 index_field_len: usize,
385 },
386 MissingPrimaryKeyTieBreak {
387 field: String,
388 },
389 PrimaryKeyDirectionNotAscending {
390 field: String,
391 },
392 MixedDirectionNotEligible {
393 field: String,
394 },
395 OrderFieldsDoNotMatchIndex {
396 index: String,
397 prefix_len: usize,
398 expected_suffix: Vec<String>,
399 expected_full: Vec<String>,
400 actual: Vec<String>,
401 },
402 VariablePrefixSuffixOrderUnsupported {
403 index: String,
404 prefix_len: usize,
405 expected_full: Vec<String>,
406 actual: Vec<String>,
407 },
408}
409
410#[derive(Clone, Debug, Eq, PartialEq)]
418pub enum ExplainAccessPath {
419 ByKey {
420 key: Value,
421 },
422 ByKeys {
423 keys: Vec<Value>,
424 },
425 KeyRange {
426 start: Value,
427 end: Value,
428 },
429 IndexPrefix {
430 name: String,
431 fields: Vec<String>,
432 prefix_len: usize,
433 values: Vec<Value>,
434 },
435 IndexMultiLookup {
436 name: String,
437 fields: Vec<String>,
438 values: Vec<Value>,
439 },
440 IndexBranchSet {
441 name: String,
442 fields: Vec<String>,
443 fixed_values: Vec<Value>,
444 branch_values: Vec<Value>,
445 branch_field: Option<String>,
446 ordered_suffix: String,
447 },
448 IndexRange {
449 name: String,
450 fields: Vec<String>,
451 prefix_len: usize,
452 prefix: Vec<Value>,
453 lower: Bound<Value>,
454 upper: Bound<Value>,
455 },
456 FullScan,
457 Union(Vec<Self>),
458 Intersection(Vec<Self>),
459}
460
461#[derive(Clone, Debug, Eq, PartialEq)]
467pub struct ExplainAccessDecisionV1 {
468 pub schema_version: u32,
470 pub selected: ExplainSelectedAccessV1,
472 pub candidates: Vec<ExplainAccessCandidateV1>,
474 pub alternatives: Vec<ExplainEligibleAlternativeV1>,
476 pub rejections: Vec<ExplainRejectedIndexV1>,
478 pub residual: ExplainResidualSummaryV1,
480}
481
482impl ExplainAccessDecisionV1 {
483 const SCHEMA_VERSION: u32 = 1;
484
485 fn from_snapshot(
486 selected_access: &ExplainAccessPath,
487 snapshot: &AccessChoiceExplainSnapshot,
488 ) -> Self {
489 let selected_label = explain_access_strategy_label(selected_access);
490 let selected_candidate = selected_candidate_summary(&selected_label, &snapshot.candidates);
491
492 Self {
493 schema_version: Self::SCHEMA_VERSION,
494 selected: ExplainSelectedAccessV1 {
495 kind: ExplainAccessDecisionKind::from_access_path(selected_access),
496 index_name: selected_index_name(selected_access).map(ToOwned::to_owned),
497 label: selected_label,
498 reason: snapshot.chosen_reason().code(),
499 },
500 candidates: snapshot
501 .candidates
502 .iter()
503 .map(ExplainAccessCandidateV1::from_candidate)
504 .collect(),
505 alternatives: snapshot
506 .alternatives
507 .iter()
508 .map(|index_name| ExplainEligibleAlternativeV1 {
509 index_name: index_name.clone(),
510 })
511 .collect(),
512 rejections: snapshot
513 .rejected
514 .iter()
515 .map(|rejection| ExplainRejectedIndexV1::from_rejection(rejection))
516 .collect(),
517 residual: ExplainResidualSummaryV1::from_selected_access_and_candidate(
518 selected_access,
519 selected_candidate,
520 ),
521 }
522 }
523
524 fn render_compact_summary(&self) -> String {
525 let index = self
526 .selected
527 .index_name
528 .as_deref()
529 .map_or("none", |index| index);
530
531 format!(
532 "kind={} index={} reason={} residual={} candidates={} alternatives={} rejections={}",
533 self.selected.kind.code(),
534 index,
535 self.selected.reason,
536 self.residual.burden_class,
537 self.candidates.len(),
538 self.alternatives.len(),
539 self.rejections.len(),
540 )
541 }
542}
543
544#[derive(Clone, Debug, Eq, PartialEq)]
546pub struct ExplainSelectedAccessV1 {
547 pub kind: ExplainAccessDecisionKind,
549 pub index_name: Option<String>,
551 pub label: String,
553 pub reason: &'static str,
555}
556
557#[derive(Clone, Copy, Debug, Eq, PartialEq)]
559pub enum ExplainAccessDecisionKind {
560 ByKey,
562 ByKeys,
564 KeyRange,
566 IndexPrefix,
568 IndexMultiLookup,
570 IndexBranchSet,
572 IndexRange,
574 FullScan,
576 Union,
578 Intersection,
580}
581
582impl ExplainAccessDecisionKind {
583 const fn from_access_path(access: &ExplainAccessPath) -> Self {
584 match access {
585 ExplainAccessPath::ByKey { .. } => Self::ByKey,
586 ExplainAccessPath::ByKeys { .. } => Self::ByKeys,
587 ExplainAccessPath::KeyRange { .. } => Self::KeyRange,
588 ExplainAccessPath::IndexPrefix { .. } => Self::IndexPrefix,
589 ExplainAccessPath::IndexMultiLookup { .. } => Self::IndexMultiLookup,
590 ExplainAccessPath::IndexBranchSet { .. } => Self::IndexBranchSet,
591 ExplainAccessPath::IndexRange { .. } => Self::IndexRange,
592 ExplainAccessPath::FullScan => Self::FullScan,
593 ExplainAccessPath::Union(_) => Self::Union,
594 ExplainAccessPath::Intersection(_) => Self::Intersection,
595 }
596 }
597
598 const fn code(self) -> &'static str {
599 match self {
600 Self::ByKey => "ByKey",
601 Self::ByKeys => "ByKeys",
602 Self::KeyRange => "KeyRange",
603 Self::IndexPrefix => "IndexPrefix",
604 Self::IndexMultiLookup => "IndexMultiLookup",
605 Self::IndexBranchSet => "IndexBranchSet",
606 Self::IndexRange => "IndexRange",
607 Self::FullScan => "FullScan",
608 Self::Union => "Union",
609 Self::Intersection => "Intersection",
610 }
611 }
612}
613
614#[derive(Clone, Debug, Eq, PartialEq)]
616pub struct ExplainAccessCandidateV1 {
617 pub label: String,
619 pub exact: bool,
621 pub filtered: bool,
623 pub range_bound_count: usize,
625 pub order_compatible: bool,
627 pub residual_burden: &'static str,
629 pub residual_predicate_terms: usize,
631}
632
633impl ExplainAccessCandidateV1 {
634 fn from_candidate(candidate: &AccessChoiceCandidateExplainSummary) -> Self {
635 Self {
636 label: candidate.label.clone(),
637 exact: candidate.exact,
638 filtered: candidate.filtered,
639 range_bound_count: candidate.range_bound_count,
640 order_compatible: candidate.order_compatible,
641 residual_burden: candidate.residual_burden.label(),
642 residual_predicate_terms: candidate.residual_predicate_terms,
643 }
644 }
645}
646
647#[derive(Clone, Debug, Eq, PartialEq)]
649pub struct ExplainEligibleAlternativeV1 {
650 pub index_name: String,
652}
653
654#[derive(Clone, Debug, Eq, PartialEq)]
656pub struct ExplainRejectedIndexV1 {
657 pub index_name: Option<String>,
659 pub reason: Option<String>,
661 pub label: String,
663}
664
665impl ExplainRejectedIndexV1 {
666 fn from_rejection(rejection: &str) -> Self {
667 let (index_name, reason) = parse_rejected_index_label(rejection);
668
669 Self {
670 index_name,
671 reason,
672 label: rejection.to_string(),
673 }
674 }
675}
676
677#[derive(Clone, Debug, Eq, PartialEq)]
679pub struct ExplainResidualSummaryV1 {
680 pub burden_class: &'static str,
682 pub has_residual_filter: bool,
684 pub has_residual_predicate: bool,
686 pub access_bound_predicate_count: usize,
688 pub residual_predicate_count: usize,
690}
691
692impl ExplainResidualSummaryV1 {
693 fn from_selected_access_and_candidate(
694 selected_access: &ExplainAccessPath,
695 selected_candidate: Option<&AccessChoiceCandidateExplainSummary>,
696 ) -> Self {
697 match selected_candidate {
698 Some(candidate) => Self {
699 burden_class: candidate.residual_burden.label(),
700 has_residual_filter: matches!(
701 candidate.residual_burden,
702 AccessChoiceResidualBurden::ScalarExpression
703 ),
704 has_residual_predicate: candidate.residual_predicate_terms > 0,
705 access_bound_predicate_count: access_bound_predicate_count(selected_access),
706 residual_predicate_count: candidate.residual_predicate_terms,
707 },
708 None => Self {
709 burden_class: AccessChoiceResidualBurden::None.label(),
710 has_residual_filter: false,
711 has_residual_predicate: false,
712 access_bound_predicate_count: access_bound_predicate_count(selected_access),
713 residual_predicate_count: 0,
714 },
715 }
716 }
717}
718
719#[derive(Clone, Debug, Eq, PartialEq)]
727pub enum ExplainPredicate {
728 None,
729 True,
730 False,
731 And(Vec<Self>),
732 Or(Vec<Self>),
733 Not(Box<Self>),
734 Compare {
735 field: String,
736 op: CompareOp,
737 value: Value,
738 coercion: CoercionSpec,
739 },
740 CompareFields {
741 left_field: String,
742 op: CompareOp,
743 right_field: String,
744 coercion: CoercionSpec,
745 },
746 IsNull {
747 field: String,
748 },
749 IsNotNull {
750 field: String,
751 },
752 IsMissing {
753 field: String,
754 },
755 IsEmpty {
756 field: String,
757 },
758 IsNotEmpty {
759 field: String,
760 },
761 TextContains {
762 field: String,
763 value: Value,
764 },
765 TextContainsCi {
766 field: String,
767 value: Value,
768 },
769}
770
771#[derive(Clone, Debug, Eq, PartialEq)]
778pub enum ExplainOrderBy {
779 None,
780 Fields(Vec<ExplainOrder>),
781}
782
783#[derive(Clone, Debug, Eq, PartialEq)]
790pub struct ExplainOrder {
791 pub(in crate::db) field: String,
792 pub(in crate::db) direction: OrderDirection,
793}
794
795impl ExplainOrder {
796 #[must_use]
798 pub const fn field(&self) -> &str {
799 self.field.as_str()
800 }
801
802 #[must_use]
804 pub const fn direction(&self) -> OrderDirection {
805 self.direction
806 }
807}
808
809#[derive(Clone, Debug, Eq, PartialEq)]
816pub enum ExplainPagination {
817 None,
818 Page { limit: Option<u32>, offset: u32 },
819}
820
821#[derive(Clone, Debug, Eq, PartialEq)]
828pub enum ExplainDeleteLimit {
829 None,
830 Limit { max_rows: u32 },
831 Window { limit: Option<u32>, offset: u32 },
832}
833
834impl AccessPlannedQuery {
835 #[must_use]
837 pub(in crate::db) fn explain(&self) -> ExplainPlan {
838 self.explain_inner()
839 }
840
841 fn explain_inner(&self) -> ExplainPlan {
842 let (logical, grouping) = match &self.logical {
844 LogicalPlan::Scalar(logical) => (logical, ExplainGrouping::None),
845 LogicalPlan::Grouped(logical) => {
846 let grouped_strategy = grouped_plan_strategy(self).unwrap_or_else(|| {
847 debug_assert!(
848 grouped_plan_strategy(self).is_some(),
849 "grouped logical explain projection requires planner-owned grouped strategy",
850 );
851 GroupedPlanStrategy::hash_group_with_aggregate_family(
852 GroupedPlanFallbackReason::GroupKeyOrderUnavailable,
853 GroupedPlanAggregateFamily::from_grouped_aggregates(
854 logical.group.aggregates.as_slice(),
855 ),
856 )
857 });
858
859 (
860 &logical.scalar,
861 ExplainGrouping::Grouped {
862 strategy: grouped_strategy.code(),
863 fallback_reason: grouped_strategy
864 .fallback_reason()
865 .map(GroupedPlanFallbackReason::code),
866 group_fields: logical
867 .group
868 .group_fields
869 .iter()
870 .map(|field_slot| ExplainGroupField {
871 slot_index: field_slot.index(),
872 field: field_slot.field().to_string(),
873 })
874 .collect(),
875 aggregates: logical
876 .group
877 .aggregates
878 .iter()
879 .map(|aggregate| ExplainGroupAggregate {
880 kind: aggregate.kind,
881 target_field: aggregate.target_field().map(str::to_string),
882 input_expr: aggregate
883 .input_expr()
884 .map(render_scalar_projection_expr_plan_label),
885 filter_expr: aggregate
886 .filter_expr()
887 .map(render_scalar_projection_expr_plan_label),
888 distinct: aggregate.distinct,
889 })
890 .collect(),
891 having: explain_group_having(logical),
892 max_groups: logical.group.execution.max_groups(),
893 max_group_bytes: logical.group.execution.max_group_bytes(),
894 },
895 )
896 }
897 };
898
899 explain_scalar_inner(logical, grouping, &self.access, self.access_choice())
901 }
902}
903
904fn explain_group_having(logical: &crate::db::query::plan::GroupPlan) -> Option<ExplainGroupHaving> {
905 let expr = logical.effective_having_expr()?;
906
907 Some(ExplainGroupHaving {
908 expr: expr.into_owned(),
909 })
910}
911
912fn explain_scalar_inner<K>(
913 logical: &ScalarPlan,
914 grouping: ExplainGrouping,
915 access: &AccessPlan<K>,
916 access_choice: &AccessChoiceExplainSnapshot,
917) -> ExplainPlan
918where
919 K: KeyValueCodec,
920{
921 let filter_expr = logical
923 .filter_expr
924 .as_ref()
925 .map(render_scalar_filter_expr_plan_label);
926 let filter_expr_model = logical.filter_expr.clone();
927 let predicate_model = logical.predicate.clone();
928 let predicate = match &predicate_model {
929 Some(predicate) => ExplainPredicate::from_predicate(predicate),
930 None => ExplainPredicate::None,
931 };
932
933 let order_by = explain_order(logical.order.as_ref());
935 let order_pushdown = explain_order_pushdown();
936 let page = explain_page(logical.page.as_ref());
937 let delete_limit = explain_delete_limit(logical.delete_limit.as_ref());
938
939 let access = explain_access_plan(access);
941 let access_decision = ExplainAccessDecisionV1::from_snapshot(&access, access_choice);
942
943 ExplainPlan {
944 mode: logical.mode,
945 access,
946 access_decision,
947 filter_expr,
948 filter_expr_model,
949 predicate,
950 predicate_model,
951 order_by,
952 distinct: logical.distinct,
953 grouping,
954 order_pushdown,
955 page,
956 delete_limit,
957 consistency: logical.consistency,
958 }
959}
960
961fn selected_candidate_summary<'a>(
962 selected_label: &str,
963 candidates: &'a [AccessChoiceCandidateExplainSummary],
964) -> Option<&'a AccessChoiceCandidateExplainSummary> {
965 candidates
966 .iter()
967 .find(|candidate| candidate.label == selected_label)
968 .or_else(|| (candidates.len() == 1).then(|| &candidates[0]))
969}
970
971const fn selected_index_name(access: &ExplainAccessPath) -> Option<&str> {
972 match access {
973 ExplainAccessPath::IndexPrefix { name, .. }
974 | ExplainAccessPath::IndexMultiLookup { name, .. }
975 | ExplainAccessPath::IndexBranchSet { name, .. }
976 | ExplainAccessPath::IndexRange { name, .. } => Some(name.as_str()),
977 ExplainAccessPath::ByKey { .. }
978 | ExplainAccessPath::ByKeys { .. }
979 | ExplainAccessPath::KeyRange { .. }
980 | ExplainAccessPath::FullScan
981 | ExplainAccessPath::Union(_)
982 | ExplainAccessPath::Intersection(_) => None,
983 }
984}
985
986fn access_bound_predicate_count(access: &ExplainAccessPath) -> usize {
987 match access {
988 ExplainAccessPath::ByKey { .. }
989 | ExplainAccessPath::ByKeys { .. }
990 | ExplainAccessPath::IndexMultiLookup { .. } => 1,
991 ExplainAccessPath::IndexBranchSet {
992 fixed_values,
993 branch_values,
994 ..
995 } => fixed_values.len() + usize::from(!branch_values.is_empty()),
996 ExplainAccessPath::KeyRange { .. } => 2,
997 ExplainAccessPath::IndexPrefix { prefix_len, .. } => *prefix_len,
998 ExplainAccessPath::IndexRange {
999 prefix_len,
1000 lower,
1001 upper,
1002 ..
1003 } => *prefix_len + bound_constraint_count(lower) + bound_constraint_count(upper),
1004 ExplainAccessPath::FullScan => 0,
1005 ExplainAccessPath::Union(children) | ExplainAccessPath::Intersection(children) => {
1006 children.iter().map(access_bound_predicate_count).sum()
1007 }
1008 }
1009}
1010
1011const fn bound_constraint_count(bound: &Bound<Value>) -> usize {
1012 match bound {
1013 Bound::Included(_) | Bound::Excluded(_) => 1,
1014 Bound::Unbounded => 0,
1015 }
1016}
1017
1018fn parse_rejected_index_label(rejection: &str) -> (Option<String>, Option<String>) {
1019 let Some(rest) = rejection.strip_prefix("index:") else {
1020 return (None, None);
1021 };
1022
1023 match rest.split_once('=') {
1024 Some((index_name, reason)) => (Some(index_name.to_string()), Some(reason.to_string())),
1025 None => (Some(rest.to_string()), None),
1026 }
1027}
1028
1029const fn explain_order_pushdown() -> ExplainOrderPushdown {
1030 ExplainOrderPushdown::MissingModelContext
1032}
1033
1034impl ExplainPredicate {
1035 pub(in crate::db) fn from_predicate(predicate: &Predicate) -> Self {
1036 match predicate {
1037 Predicate::True => Self::True,
1038 Predicate::False => Self::False,
1039 Predicate::And(children) => {
1040 Self::And(children.iter().map(Self::from_predicate).collect())
1041 }
1042 Predicate::Or(children) => {
1043 Self::Or(children.iter().map(Self::from_predicate).collect())
1044 }
1045 Predicate::Not(inner) => Self::Not(Box::new(Self::from_predicate(inner))),
1046 Predicate::Compare(compare) => Self::from_compare(compare),
1047 Predicate::CompareFields(compare) => Self::CompareFields {
1048 left_field: compare.left_field().to_string(),
1049 op: compare.op(),
1050 right_field: compare.right_field().to_string(),
1051 coercion: compare.coercion().clone(),
1052 },
1053 Predicate::IsNull { field } => Self::IsNull {
1054 field: field.clone(),
1055 },
1056 Predicate::IsNotNull { field } => Self::IsNotNull {
1057 field: field.clone(),
1058 },
1059 Predicate::IsMissing { field } => Self::IsMissing {
1060 field: field.clone(),
1061 },
1062 Predicate::IsEmpty { field } => Self::IsEmpty {
1063 field: field.clone(),
1064 },
1065 Predicate::IsNotEmpty { field } => Self::IsNotEmpty {
1066 field: field.clone(),
1067 },
1068 Predicate::TextContains { field, value } => Self::TextContains {
1069 field: field.clone(),
1070 value: value.clone(),
1071 },
1072 Predicate::TextContainsCi { field, value } => Self::TextContainsCi {
1073 field: field.clone(),
1074 value: value.clone(),
1075 },
1076 }
1077 }
1078
1079 fn from_compare(compare: &ComparePredicate) -> Self {
1080 Self::Compare {
1081 field: compare.field.clone(),
1082 op: compare.op,
1083 value: compare.value.clone(),
1084 coercion: compare.coercion.clone(),
1085 }
1086 }
1087}
1088
1089fn explain_order(order: Option<&OrderSpec>) -> ExplainOrderBy {
1090 let Some(order) = order else {
1091 return ExplainOrderBy::None;
1092 };
1093
1094 if order.fields.is_empty() {
1095 return ExplainOrderBy::None;
1096 }
1097
1098 ExplainOrderBy::Fields(
1099 order
1100 .fields
1101 .iter()
1102 .map(|term| ExplainOrder {
1103 field: term.rendered_label(),
1104 direction: term.direction(),
1105 })
1106 .collect(),
1107 )
1108}
1109
1110const fn explain_page(page: Option<&PageSpec>) -> ExplainPagination {
1111 match page {
1112 Some(page) => ExplainPagination::Page {
1113 limit: page.limit,
1114 offset: page.offset,
1115 },
1116 None => ExplainPagination::None,
1117 }
1118}
1119
1120const fn explain_delete_limit(limit: Option<&DeleteLimitSpec>) -> ExplainDeleteLimit {
1121 match limit {
1122 Some(limit) if limit.offset == 0 => match limit.limit {
1123 Some(max_rows) => ExplainDeleteLimit::Limit { max_rows },
1124 None => ExplainDeleteLimit::Window {
1125 limit: None,
1126 offset: 0,
1127 },
1128 },
1129 Some(limit) => ExplainDeleteLimit::Window {
1130 limit: limit.limit,
1131 offset: limit.offset,
1132 },
1133 None => ExplainDeleteLimit::None,
1134 }
1135}
1136
1137fn write_logical_explain_json(explain: &ExplainPlan, out: &mut String) {
1138 let mut object = JsonWriter::begin_object(out);
1139 object.field_with("mode", |out| {
1140 let mut object = JsonWriter::begin_object(out);
1141 match explain.mode() {
1142 QueryMode::Load(spec) => {
1143 object.field_str("type", "Load");
1144 match spec.limit() {
1145 Some(limit) => object.field_u64("limit", u64::from(limit)),
1146 None => object.field_null("limit"),
1147 }
1148 object.field_u64("offset", u64::from(spec.offset()));
1149 }
1150 QueryMode::Delete(spec) => {
1151 object.field_str("type", "Delete");
1152 match spec.limit() {
1153 Some(limit) => object.field_u64("limit", u64::from(limit)),
1154 None => object.field_null("limit"),
1155 }
1156 }
1157 }
1158 object.finish();
1159 });
1160 object.field_with("access", |out| {
1161 write_access_json_detailed(explain.access(), out);
1162 });
1163 object.field_with("access_decision", |out| {
1164 write_access_decision_json(explain.access_decision(), out);
1165 });
1166 match explain.filter_expr() {
1167 Some(filter_expr) => object.field_str("filter_expr", filter_expr),
1168 None => object.field_null("filter_expr"),
1169 }
1170 object.field_value_debug("predicate", explain.predicate());
1171 object.field_value_debug("order_by", explain.order_by());
1172 object.field_bool("distinct", explain.distinct());
1173 object.field_value_debug("grouping", explain.grouping());
1174 object.field_value_debug("order_pushdown", explain.order_pushdown());
1175 object.field_with("page", |out| {
1176 let mut object = JsonWriter::begin_object(out);
1177 match explain.page() {
1178 ExplainPagination::None => {
1179 object.field_str("type", "None");
1180 }
1181 ExplainPagination::Page { limit, offset } => {
1182 object.field_str("type", "Page");
1183 match limit {
1184 Some(limit) => object.field_u64("limit", u64::from(*limit)),
1185 None => object.field_null("limit"),
1186 }
1187 object.field_u64("offset", u64::from(*offset));
1188 }
1189 }
1190 object.finish();
1191 });
1192 object.field_with("delete_limit", |out| {
1193 let mut object = JsonWriter::begin_object(out);
1194 match explain.delete_limit() {
1195 ExplainDeleteLimit::None => {
1196 object.field_str("type", "None");
1197 }
1198 ExplainDeleteLimit::Limit { max_rows } => {
1199 object.field_str("type", "Limit");
1200 object.field_u64("max_rows", u64::from(*max_rows));
1201 }
1202 ExplainDeleteLimit::Window { limit, offset } => {
1203 object.field_str("type", "Window");
1204 object.field_with("limit", |out| match limit {
1205 Some(limit) => out.push_str(&limit.to_string()),
1206 None => out.push_str("null"),
1207 });
1208 object.field_u64("offset", u64::from(*offset));
1209 }
1210 }
1211 object.finish();
1212 });
1213 object.field_value_debug("consistency", &explain.consistency());
1214 object.finish();
1215}
1216
1217fn write_access_decision_json(decision: &ExplainAccessDecisionV1, out: &mut String) {
1218 let mut object = JsonWriter::begin_object(out);
1219 object.field_u64("schema_version", u64::from(decision.schema_version));
1220 object.field_with("selected", |out| {
1221 let mut selected = JsonWriter::begin_object(out);
1222 selected.field_str("kind", decision.selected.kind.code());
1223 match decision.selected.index_name.as_deref() {
1224 Some(index_name) => selected.field_str("index_name", index_name),
1225 None => selected.field_null("index_name"),
1226 }
1227 selected.field_str("label", decision.selected.label.as_str());
1228 selected.field_str("reason", decision.selected.reason);
1229 selected.finish();
1230 });
1231 object.field_with("candidates", |out| {
1232 out.push('[');
1233 for (index, candidate) in decision.candidates.iter().enumerate() {
1234 if index > 0 {
1235 out.push(',');
1236 }
1237 write_access_candidate_json(candidate, out);
1238 }
1239 out.push(']');
1240 });
1241 object.field_with("alternatives", |out| {
1242 out.push('[');
1243 for (index, alternative) in decision.alternatives.iter().enumerate() {
1244 if index > 0 {
1245 out.push(',');
1246 }
1247 let mut object = JsonWriter::begin_object(out);
1248 object.field_str("index_name", alternative.index_name.as_str());
1249 object.finish();
1250 }
1251 out.push(']');
1252 });
1253 object.field_with("rejections", |out| {
1254 out.push('[');
1255 for (index, rejection) in decision.rejections.iter().enumerate() {
1256 if index > 0 {
1257 out.push(',');
1258 }
1259 let mut object = JsonWriter::begin_object(out);
1260 match rejection.index_name.as_deref() {
1261 Some(index_name) => object.field_str("index_name", index_name),
1262 None => object.field_null("index_name"),
1263 }
1264 match rejection.reason.as_deref() {
1265 Some(reason) => object.field_str("reason", reason),
1266 None => object.field_null("reason"),
1267 }
1268 object.field_str("label", rejection.label.as_str());
1269 object.finish();
1270 }
1271 out.push(']');
1272 });
1273 object.field_with("residual", |out| {
1274 let mut residual = JsonWriter::begin_object(out);
1275 residual.field_str("burden_class", decision.residual.burden_class);
1276 residual.field_bool("has_residual_filter", decision.residual.has_residual_filter);
1277 residual.field_bool(
1278 "has_residual_predicate",
1279 decision.residual.has_residual_predicate,
1280 );
1281 residual.field_u64(
1282 "access_bound_predicate_count",
1283 decision.residual.access_bound_predicate_count as u64,
1284 );
1285 residual.field_u64(
1286 "residual_predicate_count",
1287 decision.residual.residual_predicate_count as u64,
1288 );
1289 residual.finish();
1290 });
1291 object.finish();
1292}
1293
1294fn write_access_candidate_json(candidate: &ExplainAccessCandidateV1, out: &mut String) {
1295 let mut object = JsonWriter::begin_object(out);
1296 object.field_str("label", candidate.label.as_str());
1297 object.field_bool("exact", candidate.exact);
1298 object.field_bool("filtered", candidate.filtered);
1299 object.field_u64("range_bound_count", candidate.range_bound_count as u64);
1300 object.field_bool("order_compatible", candidate.order_compatible);
1301 object.field_str("residual_burden", candidate.residual_burden);
1302 object.field_u64(
1303 "residual_predicate_terms",
1304 candidate.residual_predicate_terms as u64,
1305 );
1306 object.finish();
1307}