1use crate::{
7 db::{
8 access::{
9 AccessPlan, PushdownSurfaceEligibility, SecondaryOrderPushdownEligibility,
10 SecondaryOrderPushdownRejection,
11 },
12 predicate::{CoercionSpec, CompareOp, ComparePredicate, MissingRowPolicy, Predicate},
13 query::{
14 explain::{access_projection::write_access_json, writer::JsonWriter},
15 plan::{
16 AccessPlannedQuery, AggregateKind, DeleteLimitSpec, GroupHavingClause,
17 GroupHavingSpec, GroupHavingSymbol, GroupedPlanStrategyHint, LogicalPlan,
18 OrderDirection, OrderSpec, PageSpec, QueryMode, ScalarPlan,
19 grouped_plan_strategy_hint,
20 },
21 },
22 },
23 model::entity::EntityModel,
24 traits::FieldValue,
25 value::Value,
26};
27use std::ops::Bound;
28
29#[derive(Clone, Debug, Eq, PartialEq)]
36pub struct ExplainPlan {
37 pub(crate) mode: QueryMode,
38 pub(crate) access: ExplainAccessPath,
39 pub(crate) predicate: ExplainPredicate,
40 predicate_model: Option<Predicate>,
41 pub(crate) order_by: ExplainOrderBy,
42 pub(crate) distinct: bool,
43 pub(crate) grouping: ExplainGrouping,
44 pub(crate) order_pushdown: ExplainOrderPushdown,
45 pub(crate) page: ExplainPagination,
46 pub(crate) delete_limit: ExplainDeleteLimit,
47 pub(crate) consistency: MissingRowPolicy,
48}
49
50impl ExplainPlan {
51 #[must_use]
53 pub const fn mode(&self) -> QueryMode {
54 self.mode
55 }
56
57 #[must_use]
59 pub const fn access(&self) -> &ExplainAccessPath {
60 &self.access
61 }
62
63 #[must_use]
65 pub const fn predicate(&self) -> &ExplainPredicate {
66 &self.predicate
67 }
68
69 #[must_use]
71 pub const fn order_by(&self) -> &ExplainOrderBy {
72 &self.order_by
73 }
74
75 #[must_use]
77 pub const fn distinct(&self) -> bool {
78 self.distinct
79 }
80
81 #[must_use]
83 pub const fn grouping(&self) -> &ExplainGrouping {
84 &self.grouping
85 }
86
87 #[must_use]
89 pub const fn order_pushdown(&self) -> &ExplainOrderPushdown {
90 &self.order_pushdown
91 }
92
93 #[must_use]
95 pub const fn page(&self) -> &ExplainPagination {
96 &self.page
97 }
98
99 #[must_use]
101 pub const fn delete_limit(&self) -> &ExplainDeleteLimit {
102 &self.delete_limit
103 }
104
105 #[must_use]
107 pub const fn consistency(&self) -> MissingRowPolicy {
108 self.consistency
109 }
110}
111
112impl ExplainPlan {
113 #[must_use]
117 pub(crate) fn predicate_model_for_hash(&self) -> Option<&Predicate> {
118 if let Some(predicate) = &self.predicate_model {
119 debug_assert_eq!(
120 self.predicate,
121 ExplainPredicate::from_predicate(predicate),
122 "explain predicate surface drifted from canonical predicate model"
123 );
124 Some(predicate)
125 } else {
126 debug_assert!(
127 matches!(self.predicate, ExplainPredicate::None),
128 "missing canonical predicate model requires ExplainPredicate::None"
129 );
130 None
131 }
132 }
133
134 #[must_use]
139 pub fn render_text_canonical(&self) -> String {
140 format!(
141 concat!(
142 "mode={:?}\n",
143 "access={:?}\n",
144 "predicate={:?}\n",
145 "order_by={:?}\n",
146 "distinct={}\n",
147 "grouping={:?}\n",
148 "order_pushdown={:?}\n",
149 "page={:?}\n",
150 "delete_limit={:?}\n",
151 "consistency={:?}",
152 ),
153 self.mode(),
154 self.access(),
155 self.predicate(),
156 self.order_by(),
157 self.distinct(),
158 self.grouping(),
159 self.order_pushdown(),
160 self.page(),
161 self.delete_limit(),
162 self.consistency(),
163 )
164 }
165
166 #[must_use]
168 pub fn render_json_canonical(&self) -> String {
169 let mut out = String::new();
170 write_logical_explain_json(self, &mut out);
171
172 out
173 }
174}
175
176#[derive(Clone, Debug, Eq, PartialEq)]
183pub enum ExplainGrouping {
184 None,
185 Grouped {
186 strategy: ExplainGroupedStrategy,
187 group_fields: Vec<ExplainGroupField>,
188 aggregates: Vec<ExplainGroupAggregate>,
189 having: Option<ExplainGroupHaving>,
190 max_groups: u64,
191 max_group_bytes: u64,
192 },
193}
194
195#[derive(Clone, Copy, Debug, Eq, PartialEq)]
202pub enum ExplainGroupedStrategy {
203 HashGroup,
204 OrderedGroup,
205}
206
207impl From<GroupedPlanStrategyHint> for ExplainGroupedStrategy {
208 fn from(value: GroupedPlanStrategyHint) -> Self {
209 match value {
210 GroupedPlanStrategyHint::HashGroup => Self::HashGroup,
211 GroupedPlanStrategyHint::OrderedGroup => Self::OrderedGroup,
212 }
213 }
214}
215
216#[derive(Clone, Debug, Eq, PartialEq)]
223pub struct ExplainGroupField {
224 pub(crate) slot_index: usize,
225 pub(crate) field: String,
226}
227
228impl ExplainGroupField {
229 #[must_use]
231 pub const fn slot_index(&self) -> usize {
232 self.slot_index
233 }
234
235 #[must_use]
237 pub const fn field(&self) -> &str {
238 self.field.as_str()
239 }
240}
241
242#[derive(Clone, Debug, Eq, PartialEq)]
249pub struct ExplainGroupAggregate {
250 pub(crate) kind: AggregateKind,
251 pub(crate) target_field: Option<String>,
252 pub(crate) distinct: bool,
253}
254
255impl ExplainGroupAggregate {
256 #[must_use]
258 pub const fn kind(&self) -> AggregateKind {
259 self.kind
260 }
261
262 #[must_use]
264 pub fn target_field(&self) -> Option<&str> {
265 self.target_field.as_deref()
266 }
267
268 #[must_use]
270 pub const fn distinct(&self) -> bool {
271 self.distinct
272 }
273}
274
275#[derive(Clone, Debug, Eq, PartialEq)]
282pub struct ExplainGroupHaving {
283 pub(crate) clauses: Vec<ExplainGroupHavingClause>,
284}
285
286impl ExplainGroupHaving {
287 #[must_use]
289 pub const fn clauses(&self) -> &[ExplainGroupHavingClause] {
290 self.clauses.as_slice()
291 }
292}
293
294#[derive(Clone, Debug, Eq, PartialEq)]
301pub struct ExplainGroupHavingClause {
302 pub(crate) symbol: ExplainGroupHavingSymbol,
303 pub(crate) op: CompareOp,
304 pub(crate) value: Value,
305}
306
307impl ExplainGroupHavingClause {
308 #[must_use]
310 pub const fn symbol(&self) -> &ExplainGroupHavingSymbol {
311 &self.symbol
312 }
313
314 #[must_use]
316 pub const fn op(&self) -> CompareOp {
317 self.op
318 }
319
320 #[must_use]
322 pub const fn value(&self) -> &Value {
323 &self.value
324 }
325}
326
327#[derive(Clone, Debug, Eq, PartialEq)]
334pub enum ExplainGroupHavingSymbol {
335 GroupField { slot_index: usize, field: String },
336 AggregateIndex { index: usize },
337}
338
339#[derive(Clone, Debug, Eq, PartialEq)]
346pub enum ExplainOrderPushdown {
347 MissingModelContext,
348 EligibleSecondaryIndex {
349 index: &'static str,
350 prefix_len: usize,
351 },
352 Rejected(SecondaryOrderPushdownRejection),
353}
354
355#[derive(Clone, Debug, Eq, PartialEq)]
363pub enum ExplainAccessPath {
364 ByKey {
365 key: Value,
366 },
367 ByKeys {
368 keys: Vec<Value>,
369 },
370 KeyRange {
371 start: Value,
372 end: Value,
373 },
374 IndexPrefix {
375 name: &'static str,
376 fields: Vec<&'static str>,
377 prefix_len: usize,
378 values: Vec<Value>,
379 },
380 IndexMultiLookup {
381 name: &'static str,
382 fields: Vec<&'static str>,
383 values: Vec<Value>,
384 },
385 IndexRange {
386 name: &'static str,
387 fields: Vec<&'static str>,
388 prefix_len: usize,
389 prefix: Vec<Value>,
390 lower: Bound<Value>,
391 upper: Bound<Value>,
392 },
393 FullScan,
394 Union(Vec<Self>),
395 Intersection(Vec<Self>),
396}
397
398#[derive(Clone, Debug, Eq, PartialEq)]
406pub enum ExplainPredicate {
407 None,
408 True,
409 False,
410 And(Vec<Self>),
411 Or(Vec<Self>),
412 Not(Box<Self>),
413 Compare {
414 field: String,
415 op: CompareOp,
416 value: Value,
417 coercion: CoercionSpec,
418 },
419 IsNull {
420 field: String,
421 },
422 IsNotNull {
423 field: String,
424 },
425 IsMissing {
426 field: String,
427 },
428 IsEmpty {
429 field: String,
430 },
431 IsNotEmpty {
432 field: String,
433 },
434 TextContains {
435 field: String,
436 value: Value,
437 },
438 TextContainsCi {
439 field: String,
440 value: Value,
441 },
442}
443
444#[derive(Clone, Debug, Eq, PartialEq)]
451pub enum ExplainOrderBy {
452 None,
453 Fields(Vec<ExplainOrder>),
454}
455
456#[derive(Clone, Debug, Eq, PartialEq)]
463pub struct ExplainOrder {
464 pub(crate) field: String,
465 pub(crate) direction: OrderDirection,
466}
467
468impl ExplainOrder {
469 #[must_use]
471 pub const fn field(&self) -> &str {
472 self.field.as_str()
473 }
474
475 #[must_use]
477 pub const fn direction(&self) -> OrderDirection {
478 self.direction
479 }
480}
481
482#[derive(Clone, Debug, Eq, PartialEq)]
489pub enum ExplainPagination {
490 None,
491 Page { limit: Option<u32>, offset: u32 },
492}
493
494#[derive(Clone, Debug, Eq, PartialEq)]
501pub enum ExplainDeleteLimit {
502 None,
503 Limit { max_rows: u32 },
504}
505
506impl AccessPlannedQuery {
507 #[must_use]
509 #[cfg(test)]
510 pub(crate) fn explain(&self) -> ExplainPlan {
511 self.explain_inner(None)
512 }
513
514 #[must_use]
520 pub(crate) fn explain_with_model(&self, model: &EntityModel) -> ExplainPlan {
521 self.explain_inner(Some(model))
522 }
523
524 fn explain_inner(&self, model: Option<&EntityModel>) -> ExplainPlan {
525 let (logical, grouping) = match &self.logical {
527 LogicalPlan::Scalar(logical) => (logical, ExplainGrouping::None),
528 LogicalPlan::Grouped(logical) => (
529 &logical.scalar,
530 ExplainGrouping::Grouped {
531 strategy: grouped_plan_strategy_hint(self)
532 .map_or(ExplainGroupedStrategy::HashGroup, Into::into),
533 group_fields: logical
534 .group
535 .group_fields
536 .iter()
537 .map(|field_slot| ExplainGroupField {
538 slot_index: field_slot.index(),
539 field: field_slot.field().to_string(),
540 })
541 .collect(),
542 aggregates: logical
543 .group
544 .aggregates
545 .iter()
546 .map(|aggregate| ExplainGroupAggregate {
547 kind: aggregate.kind,
548 target_field: aggregate.target_field.clone(),
549 distinct: aggregate.distinct,
550 })
551 .collect(),
552 having: explain_group_having(logical.having.as_ref()),
553 max_groups: logical.group.execution.max_groups(),
554 max_group_bytes: logical.group.execution.max_group_bytes(),
555 },
556 ),
557 };
558
559 explain_scalar_inner(logical, grouping, model, &self.access)
561 }
562}
563
564fn explain_group_having(having: Option<&GroupHavingSpec>) -> Option<ExplainGroupHaving> {
565 let having = having?;
566
567 Some(ExplainGroupHaving {
568 clauses: having
569 .clauses()
570 .iter()
571 .map(explain_group_having_clause)
572 .collect(),
573 })
574}
575
576fn explain_group_having_clause(clause: &GroupHavingClause) -> ExplainGroupHavingClause {
577 ExplainGroupHavingClause {
578 symbol: explain_group_having_symbol(clause.symbol()),
579 op: clause.op(),
580 value: clause.value().clone(),
581 }
582}
583
584fn explain_group_having_symbol(symbol: &GroupHavingSymbol) -> ExplainGroupHavingSymbol {
585 match symbol {
586 GroupHavingSymbol::GroupField(field_slot) => ExplainGroupHavingSymbol::GroupField {
587 slot_index: field_slot.index(),
588 field: field_slot.field().to_string(),
589 },
590 GroupHavingSymbol::AggregateIndex(index) => {
591 ExplainGroupHavingSymbol::AggregateIndex { index: *index }
592 }
593 }
594}
595
596fn explain_scalar_inner<K>(
597 logical: &ScalarPlan,
598 grouping: ExplainGrouping,
599 model: Option<&EntityModel>,
600 access: &AccessPlan<K>,
601) -> ExplainPlan
602where
603 K: FieldValue,
604{
605 let predicate_model = logical.predicate.clone();
607 let predicate = match &predicate_model {
608 Some(predicate) => ExplainPredicate::from_predicate(predicate),
609 None => ExplainPredicate::None,
610 };
611
612 let order_by = explain_order(logical.order.as_ref());
614 let order_pushdown = explain_order_pushdown(model);
615 let page = explain_page(logical.page.as_ref());
616 let delete_limit = explain_delete_limit(logical.delete_limit.as_ref());
617
618 ExplainPlan {
620 mode: logical.mode,
621 access: ExplainAccessPath::from_access_plan(access),
622 predicate,
623 predicate_model,
624 order_by,
625 distinct: logical.distinct,
626 grouping,
627 order_pushdown,
628 page,
629 delete_limit,
630 consistency: logical.consistency,
631 }
632}
633
634const fn explain_order_pushdown(model: Option<&EntityModel>) -> ExplainOrderPushdown {
635 let _ = model;
636
637 ExplainOrderPushdown::MissingModelContext
639}
640
641impl From<SecondaryOrderPushdownEligibility> for ExplainOrderPushdown {
642 fn from(value: SecondaryOrderPushdownEligibility) -> Self {
643 Self::from(PushdownSurfaceEligibility::from(&value))
644 }
645}
646
647impl From<PushdownSurfaceEligibility<'_>> for ExplainOrderPushdown {
648 fn from(value: PushdownSurfaceEligibility<'_>) -> Self {
649 match value {
650 PushdownSurfaceEligibility::EligibleSecondaryIndex { index, prefix_len } => {
651 Self::EligibleSecondaryIndex { index, prefix_len }
652 }
653 PushdownSurfaceEligibility::Rejected { reason } => Self::Rejected(reason.clone()),
654 }
655 }
656}
657
658impl ExplainPredicate {
659 fn from_predicate(predicate: &Predicate) -> Self {
660 match predicate {
661 Predicate::True => Self::True,
662 Predicate::False => Self::False,
663 Predicate::And(children) => {
664 Self::And(children.iter().map(Self::from_predicate).collect())
665 }
666 Predicate::Or(children) => {
667 Self::Or(children.iter().map(Self::from_predicate).collect())
668 }
669 Predicate::Not(inner) => Self::Not(Box::new(Self::from_predicate(inner))),
670 Predicate::Compare(compare) => Self::from_compare(compare),
671 Predicate::IsNull { field } => Self::IsNull {
672 field: field.clone(),
673 },
674 Predicate::IsNotNull { field } => Self::IsNotNull {
675 field: field.clone(),
676 },
677 Predicate::IsMissing { field } => Self::IsMissing {
678 field: field.clone(),
679 },
680 Predicate::IsEmpty { field } => Self::IsEmpty {
681 field: field.clone(),
682 },
683 Predicate::IsNotEmpty { field } => Self::IsNotEmpty {
684 field: field.clone(),
685 },
686 Predicate::TextContains { field, value } => Self::TextContains {
687 field: field.clone(),
688 value: value.clone(),
689 },
690 Predicate::TextContainsCi { field, value } => Self::TextContainsCi {
691 field: field.clone(),
692 value: value.clone(),
693 },
694 }
695 }
696
697 fn from_compare(compare: &ComparePredicate) -> Self {
698 Self::Compare {
699 field: compare.field.clone(),
700 op: compare.op,
701 value: compare.value.clone(),
702 coercion: compare.coercion.clone(),
703 }
704 }
705}
706
707fn explain_order(order: Option<&OrderSpec>) -> ExplainOrderBy {
708 let Some(order) = order else {
709 return ExplainOrderBy::None;
710 };
711
712 if order.fields.is_empty() {
713 return ExplainOrderBy::None;
714 }
715
716 ExplainOrderBy::Fields(
717 order
718 .fields
719 .iter()
720 .map(|(field, direction)| ExplainOrder {
721 field: field.clone(),
722 direction: *direction,
723 })
724 .collect(),
725 )
726}
727
728const fn explain_page(page: Option<&PageSpec>) -> ExplainPagination {
729 match page {
730 Some(page) => ExplainPagination::Page {
731 limit: page.limit,
732 offset: page.offset,
733 },
734 None => ExplainPagination::None,
735 }
736}
737
738const fn explain_delete_limit(limit: Option<&DeleteLimitSpec>) -> ExplainDeleteLimit {
739 match limit {
740 Some(limit) => ExplainDeleteLimit::Limit {
741 max_rows: limit.max_rows,
742 },
743 None => ExplainDeleteLimit::None,
744 }
745}
746
747fn write_logical_explain_json(explain: &ExplainPlan, out: &mut String) {
748 let mut object = JsonWriter::begin_object(out);
749 object.field_with("mode", |out| write_query_mode_json(explain.mode(), out));
750 object.field_with("access", |out| write_access_json(explain.access(), out));
751 object.field_value_debug("predicate", explain.predicate());
752 object.field_value_debug("order_by", explain.order_by());
753 object.field_bool("distinct", explain.distinct());
754 object.field_value_debug("grouping", explain.grouping());
755 object.field_value_debug("order_pushdown", explain.order_pushdown());
756 object.field_with("page", |out| write_pagination_json(explain.page(), out));
757 object.field_with("delete_limit", |out| {
758 write_delete_limit_json(explain.delete_limit(), out);
759 });
760 object.field_value_debug("consistency", &explain.consistency());
761 object.finish();
762}
763
764fn write_query_mode_json(mode: QueryMode, out: &mut String) {
765 let mut object = JsonWriter::begin_object(out);
766 match mode {
767 QueryMode::Load(spec) => {
768 object.field_str("type", "Load");
769 match spec.limit() {
770 Some(limit) => object.field_u64("limit", u64::from(limit)),
771 None => object.field_null("limit"),
772 }
773 object.field_u64("offset", u64::from(spec.offset()));
774 }
775 QueryMode::Delete(spec) => {
776 object.field_str("type", "Delete");
777 match spec.limit() {
778 Some(limit) => object.field_u64("limit", u64::from(limit)),
779 None => object.field_null("limit"),
780 }
781 }
782 }
783 object.finish();
784}
785
786fn write_pagination_json(page: &ExplainPagination, out: &mut String) {
787 let mut object = JsonWriter::begin_object(out);
788 match page {
789 ExplainPagination::None => {
790 object.field_str("type", "None");
791 }
792 ExplainPagination::Page { limit, offset } => {
793 object.field_str("type", "Page");
794 match limit {
795 Some(limit) => object.field_u64("limit", u64::from(*limit)),
796 None => object.field_null("limit"),
797 }
798 object.field_u64("offset", u64::from(*offset));
799 }
800 }
801 object.finish();
802}
803
804fn write_delete_limit_json(limit: &ExplainDeleteLimit, out: &mut String) {
805 let mut object = JsonWriter::begin_object(out);
806 match limit {
807 ExplainDeleteLimit::None => {
808 object.field_str("type", "None");
809 }
810 ExplainDeleteLimit::Limit { max_rows } => {
811 object.field_str("type", "Limit");
812 object.field_u64("max_rows", u64::from(*max_rows));
813 }
814 }
815 object.finish();
816}