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, GroupedPlanFallbackReason, LogicalPlan,
18 OrderDirection, OrderSpec, PageSpec, QueryMode, ScalarPlan, grouped_plan_strategy,
19 },
20 },
21 },
22 model::entity::EntityModel,
23 traits::FieldValue,
24 value::Value,
25};
26use std::ops::Bound;
27
28#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct ExplainPlan {
36 pub(crate) mode: QueryMode,
37 pub(crate) access: ExplainAccessPath,
38 pub(crate) predicate: ExplainPredicate,
39 predicate_model: Option<Predicate>,
40 pub(crate) order_by: ExplainOrderBy,
41 pub(crate) distinct: bool,
42 pub(crate) grouping: ExplainGrouping,
43 pub(crate) order_pushdown: ExplainOrderPushdown,
44 pub(crate) page: ExplainPagination,
45 pub(crate) delete_limit: ExplainDeleteLimit,
46 pub(crate) consistency: MissingRowPolicy,
47}
48
49impl ExplainPlan {
50 #[must_use]
52 pub const fn mode(&self) -> QueryMode {
53 self.mode
54 }
55
56 #[must_use]
58 pub const fn access(&self) -> &ExplainAccessPath {
59 &self.access
60 }
61
62 #[must_use]
64 pub const fn predicate(&self) -> &ExplainPredicate {
65 &self.predicate
66 }
67
68 #[must_use]
70 pub const fn order_by(&self) -> &ExplainOrderBy {
71 &self.order_by
72 }
73
74 #[must_use]
76 pub const fn distinct(&self) -> bool {
77 self.distinct
78 }
79
80 #[must_use]
82 pub const fn grouping(&self) -> &ExplainGrouping {
83 &self.grouping
84 }
85
86 #[must_use]
88 pub const fn order_pushdown(&self) -> &ExplainOrderPushdown {
89 &self.order_pushdown
90 }
91
92 #[must_use]
94 pub const fn page(&self) -> &ExplainPagination {
95 &self.page
96 }
97
98 #[must_use]
100 pub const fn delete_limit(&self) -> &ExplainDeleteLimit {
101 &self.delete_limit
102 }
103
104 #[must_use]
106 pub const fn consistency(&self) -> MissingRowPolicy {
107 self.consistency
108 }
109}
110
111impl ExplainPlan {
112 #[must_use]
116 pub(crate) fn predicate_model_for_hash(&self) -> Option<&Predicate> {
117 if let Some(predicate) = &self.predicate_model {
118 debug_assert_eq!(
119 self.predicate,
120 ExplainPredicate::from_predicate(predicate),
121 "explain predicate surface drifted from canonical predicate model"
122 );
123 Some(predicate)
124 } else {
125 debug_assert!(
126 matches!(self.predicate, ExplainPredicate::None),
127 "missing canonical predicate model requires ExplainPredicate::None"
128 );
129 None
130 }
131 }
132
133 #[must_use]
138 pub fn render_text_canonical(&self) -> String {
139 format!(
140 concat!(
141 "mode={:?}\n",
142 "access={:?}\n",
143 "predicate={:?}\n",
144 "order_by={:?}\n",
145 "distinct={}\n",
146 "grouping={:?}\n",
147 "order_pushdown={:?}\n",
148 "page={:?}\n",
149 "delete_limit={:?}\n",
150 "consistency={:?}",
151 ),
152 self.mode(),
153 self.access(),
154 self.predicate(),
155 self.order_by(),
156 self.distinct(),
157 self.grouping(),
158 self.order_pushdown(),
159 self.page(),
160 self.delete_limit(),
161 self.consistency(),
162 )
163 }
164
165 #[must_use]
167 pub fn render_json_canonical(&self) -> String {
168 let mut out = String::new();
169 write_logical_explain_json(self, &mut out);
170
171 out
172 }
173}
174
175#[derive(Clone, Debug, Eq, PartialEq)]
182pub enum ExplainGrouping {
183 None,
184 Grouped {
185 strategy: &'static str,
186 fallback_reason: Option<&'static str>,
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, Debug, Eq, PartialEq)]
202pub struct ExplainGroupField {
203 pub(crate) slot_index: usize,
204 pub(crate) field: String,
205}
206
207impl ExplainGroupField {
208 #[must_use]
210 pub const fn slot_index(&self) -> usize {
211 self.slot_index
212 }
213
214 #[must_use]
216 pub const fn field(&self) -> &str {
217 self.field.as_str()
218 }
219}
220
221#[derive(Clone, Debug, Eq, PartialEq)]
228pub struct ExplainGroupAggregate {
229 pub(crate) kind: AggregateKind,
230 pub(crate) target_field: Option<String>,
231 pub(crate) distinct: bool,
232}
233
234impl ExplainGroupAggregate {
235 #[must_use]
237 pub const fn kind(&self) -> AggregateKind {
238 self.kind
239 }
240
241 #[must_use]
243 pub fn target_field(&self) -> Option<&str> {
244 self.target_field.as_deref()
245 }
246
247 #[must_use]
249 pub const fn distinct(&self) -> bool {
250 self.distinct
251 }
252}
253
254#[derive(Clone, Debug, Eq, PartialEq)]
261pub struct ExplainGroupHaving {
262 pub(crate) clauses: Vec<ExplainGroupHavingClause>,
263}
264
265impl ExplainGroupHaving {
266 #[must_use]
268 pub const fn clauses(&self) -> &[ExplainGroupHavingClause] {
269 self.clauses.as_slice()
270 }
271}
272
273#[derive(Clone, Debug, Eq, PartialEq)]
280pub struct ExplainGroupHavingClause {
281 pub(crate) symbol: ExplainGroupHavingSymbol,
282 pub(crate) op: CompareOp,
283 pub(crate) value: Value,
284}
285
286impl ExplainGroupHavingClause {
287 #[must_use]
289 pub const fn symbol(&self) -> &ExplainGroupHavingSymbol {
290 &self.symbol
291 }
292
293 #[must_use]
295 pub const fn op(&self) -> CompareOp {
296 self.op
297 }
298
299 #[must_use]
301 pub const fn value(&self) -> &Value {
302 &self.value
303 }
304}
305
306#[derive(Clone, Debug, Eq, PartialEq)]
313pub enum ExplainGroupHavingSymbol {
314 GroupField { slot_index: usize, field: String },
315 AggregateIndex { index: usize },
316}
317
318#[derive(Clone, Debug, Eq, PartialEq)]
325pub enum ExplainOrderPushdown {
326 MissingModelContext,
327 EligibleSecondaryIndex {
328 index: &'static str,
329 prefix_len: usize,
330 },
331 Rejected(SecondaryOrderPushdownRejection),
332}
333
334#[derive(Clone, Debug, Eq, PartialEq)]
342pub enum ExplainAccessPath {
343 ByKey {
344 key: Value,
345 },
346 ByKeys {
347 keys: Vec<Value>,
348 },
349 KeyRange {
350 start: Value,
351 end: Value,
352 },
353 IndexPrefix {
354 name: &'static str,
355 fields: Vec<&'static str>,
356 prefix_len: usize,
357 values: Vec<Value>,
358 },
359 IndexMultiLookup {
360 name: &'static str,
361 fields: Vec<&'static str>,
362 values: Vec<Value>,
363 },
364 IndexRange {
365 name: &'static str,
366 fields: Vec<&'static str>,
367 prefix_len: usize,
368 prefix: Vec<Value>,
369 lower: Bound<Value>,
370 upper: Bound<Value>,
371 },
372 FullScan,
373 Union(Vec<Self>),
374 Intersection(Vec<Self>),
375}
376
377#[derive(Clone, Debug, Eq, PartialEq)]
385pub enum ExplainPredicate {
386 None,
387 True,
388 False,
389 And(Vec<Self>),
390 Or(Vec<Self>),
391 Not(Box<Self>),
392 Compare {
393 field: String,
394 op: CompareOp,
395 value: Value,
396 coercion: CoercionSpec,
397 },
398 IsNull {
399 field: String,
400 },
401 IsNotNull {
402 field: String,
403 },
404 IsMissing {
405 field: String,
406 },
407 IsEmpty {
408 field: String,
409 },
410 IsNotEmpty {
411 field: String,
412 },
413 TextContains {
414 field: String,
415 value: Value,
416 },
417 TextContainsCi {
418 field: String,
419 value: Value,
420 },
421}
422
423#[derive(Clone, Debug, Eq, PartialEq)]
430pub enum ExplainOrderBy {
431 None,
432 Fields(Vec<ExplainOrder>),
433}
434
435#[derive(Clone, Debug, Eq, PartialEq)]
442pub struct ExplainOrder {
443 pub(crate) field: String,
444 pub(crate) direction: OrderDirection,
445}
446
447impl ExplainOrder {
448 #[must_use]
450 pub const fn field(&self) -> &str {
451 self.field.as_str()
452 }
453
454 #[must_use]
456 pub const fn direction(&self) -> OrderDirection {
457 self.direction
458 }
459}
460
461#[derive(Clone, Debug, Eq, PartialEq)]
468pub enum ExplainPagination {
469 None,
470 Page { limit: Option<u32>, offset: u32 },
471}
472
473#[derive(Clone, Debug, Eq, PartialEq)]
480pub enum ExplainDeleteLimit {
481 None,
482 Limit { max_rows: u32 },
483 Window { limit: Option<u32>, offset: u32 },
484}
485
486impl AccessPlannedQuery {
487 #[must_use]
489 #[cfg(test)]
490 pub(crate) fn explain(&self) -> ExplainPlan {
491 self.explain_inner(None)
492 }
493
494 #[must_use]
500 pub(crate) fn explain_with_model(&self, model: &EntityModel) -> ExplainPlan {
501 self.explain_inner(Some(model))
502 }
503
504 pub(in crate::db::query::explain) fn explain_inner(
505 &self,
506 model: Option<&EntityModel>,
507 ) -> ExplainPlan {
508 let (logical, grouping) = match &self.logical {
510 LogicalPlan::Scalar(logical) => (logical, ExplainGrouping::None),
511 LogicalPlan::Grouped(logical) => {
512 let grouped_strategy = grouped_plan_strategy(self).expect(
513 "grouped logical explain projection requires planner-owned grouped strategy",
514 );
515
516 (
517 &logical.scalar,
518 ExplainGrouping::Grouped {
519 strategy: grouped_strategy.code(),
520 fallback_reason: grouped_strategy
521 .fallback_reason()
522 .map(GroupedPlanFallbackReason::code),
523 group_fields: logical
524 .group
525 .group_fields
526 .iter()
527 .map(|field_slot| ExplainGroupField {
528 slot_index: field_slot.index(),
529 field: field_slot.field().to_string(),
530 })
531 .collect(),
532 aggregates: logical
533 .group
534 .aggregates
535 .iter()
536 .map(|aggregate| ExplainGroupAggregate {
537 kind: aggregate.kind,
538 target_field: aggregate.target_field.clone(),
539 distinct: aggregate.distinct,
540 })
541 .collect(),
542 having: explain_group_having(logical.having.as_ref()),
543 max_groups: logical.group.execution.max_groups(),
544 max_group_bytes: logical.group.execution.max_group_bytes(),
545 },
546 )
547 }
548 };
549
550 explain_scalar_inner(logical, grouping, model, &self.access)
552 }
553}
554
555fn explain_group_having(having: Option<&GroupHavingSpec>) -> Option<ExplainGroupHaving> {
556 let having = having?;
557
558 Some(ExplainGroupHaving {
559 clauses: having
560 .clauses()
561 .iter()
562 .map(explain_group_having_clause)
563 .collect(),
564 })
565}
566
567fn explain_group_having_clause(clause: &GroupHavingClause) -> ExplainGroupHavingClause {
568 ExplainGroupHavingClause {
569 symbol: explain_group_having_symbol(clause.symbol()),
570 op: clause.op(),
571 value: clause.value().clone(),
572 }
573}
574
575fn explain_group_having_symbol(symbol: &GroupHavingSymbol) -> ExplainGroupHavingSymbol {
576 match symbol {
577 GroupHavingSymbol::GroupField(field_slot) => ExplainGroupHavingSymbol::GroupField {
578 slot_index: field_slot.index(),
579 field: field_slot.field().to_string(),
580 },
581 GroupHavingSymbol::AggregateIndex(index) => {
582 ExplainGroupHavingSymbol::AggregateIndex { index: *index }
583 }
584 }
585}
586
587fn explain_scalar_inner<K>(
588 logical: &ScalarPlan,
589 grouping: ExplainGrouping,
590 model: Option<&EntityModel>,
591 access: &AccessPlan<K>,
592) -> ExplainPlan
593where
594 K: FieldValue,
595{
596 let predicate_model = logical.predicate.clone();
598 let predicate = match &predicate_model {
599 Some(predicate) => ExplainPredicate::from_predicate(predicate),
600 None => ExplainPredicate::None,
601 };
602
603 let order_by = explain_order(logical.order.as_ref());
605 let order_pushdown = explain_order_pushdown(model);
606 let page = explain_page(logical.page.as_ref());
607 let delete_limit = explain_delete_limit(logical.delete_limit.as_ref());
608
609 ExplainPlan {
611 mode: logical.mode,
612 access: ExplainAccessPath::from_access_plan(access),
613 predicate,
614 predicate_model,
615 order_by,
616 distinct: logical.distinct,
617 grouping,
618 order_pushdown,
619 page,
620 delete_limit,
621 consistency: logical.consistency,
622 }
623}
624
625const fn explain_order_pushdown(model: Option<&EntityModel>) -> ExplainOrderPushdown {
626 let _ = model;
627
628 ExplainOrderPushdown::MissingModelContext
630}
631
632impl From<SecondaryOrderPushdownEligibility> for ExplainOrderPushdown {
633 fn from(value: SecondaryOrderPushdownEligibility) -> Self {
634 Self::from(PushdownSurfaceEligibility::from(&value))
635 }
636}
637
638impl From<PushdownSurfaceEligibility<'_>> for ExplainOrderPushdown {
639 fn from(value: PushdownSurfaceEligibility<'_>) -> Self {
640 match value {
641 PushdownSurfaceEligibility::EligibleSecondaryIndex { index, prefix_len } => {
642 Self::EligibleSecondaryIndex { index, prefix_len }
643 }
644 PushdownSurfaceEligibility::Rejected { reason } => Self::Rejected(reason.clone()),
645 }
646 }
647}
648
649impl ExplainPredicate {
650 pub(in crate::db) fn from_predicate(predicate: &Predicate) -> Self {
651 match predicate {
652 Predicate::True => Self::True,
653 Predicate::False => Self::False,
654 Predicate::And(children) => {
655 Self::And(children.iter().map(Self::from_predicate).collect())
656 }
657 Predicate::Or(children) => {
658 Self::Or(children.iter().map(Self::from_predicate).collect())
659 }
660 Predicate::Not(inner) => Self::Not(Box::new(Self::from_predicate(inner))),
661 Predicate::Compare(compare) => Self::from_compare(compare),
662 Predicate::IsNull { field } => Self::IsNull {
663 field: field.clone(),
664 },
665 Predicate::IsNotNull { field } => Self::IsNotNull {
666 field: field.clone(),
667 },
668 Predicate::IsMissing { field } => Self::IsMissing {
669 field: field.clone(),
670 },
671 Predicate::IsEmpty { field } => Self::IsEmpty {
672 field: field.clone(),
673 },
674 Predicate::IsNotEmpty { field } => Self::IsNotEmpty {
675 field: field.clone(),
676 },
677 Predicate::TextContains { field, value } => Self::TextContains {
678 field: field.clone(),
679 value: value.clone(),
680 },
681 Predicate::TextContainsCi { field, value } => Self::TextContainsCi {
682 field: field.clone(),
683 value: value.clone(),
684 },
685 }
686 }
687
688 fn from_compare(compare: &ComparePredicate) -> Self {
689 Self::Compare {
690 field: compare.field.clone(),
691 op: compare.op,
692 value: compare.value.clone(),
693 coercion: compare.coercion.clone(),
694 }
695 }
696}
697
698fn explain_order(order: Option<&OrderSpec>) -> ExplainOrderBy {
699 let Some(order) = order else {
700 return ExplainOrderBy::None;
701 };
702
703 if order.fields.is_empty() {
704 return ExplainOrderBy::None;
705 }
706
707 ExplainOrderBy::Fields(
708 order
709 .fields
710 .iter()
711 .map(|(field, direction)| ExplainOrder {
712 field: field.clone(),
713 direction: *direction,
714 })
715 .collect(),
716 )
717}
718
719const fn explain_page(page: Option<&PageSpec>) -> ExplainPagination {
720 match page {
721 Some(page) => ExplainPagination::Page {
722 limit: page.limit,
723 offset: page.offset,
724 },
725 None => ExplainPagination::None,
726 }
727}
728
729const fn explain_delete_limit(limit: Option<&DeleteLimitSpec>) -> ExplainDeleteLimit {
730 match limit {
731 Some(limit) if limit.offset == 0 => match limit.limit {
732 Some(max_rows) => ExplainDeleteLimit::Limit { max_rows },
733 None => ExplainDeleteLimit::Window {
734 limit: None,
735 offset: 0,
736 },
737 },
738 Some(limit) => ExplainDeleteLimit::Window {
739 limit: limit.limit,
740 offset: limit.offset,
741 },
742 None => ExplainDeleteLimit::None,
743 }
744}
745
746fn write_logical_explain_json(explain: &ExplainPlan, out: &mut String) {
747 let mut object = JsonWriter::begin_object(out);
748 object.field_with("mode", |out| write_query_mode_json(explain.mode(), out));
749 object.field_with("access", |out| write_access_json(explain.access(), out));
750 object.field_value_debug("predicate", explain.predicate());
751 object.field_value_debug("order_by", explain.order_by());
752 object.field_bool("distinct", explain.distinct());
753 object.field_value_debug("grouping", explain.grouping());
754 object.field_value_debug("order_pushdown", explain.order_pushdown());
755 object.field_with("page", |out| write_pagination_json(explain.page(), out));
756 object.field_with("delete_limit", |out| {
757 write_delete_limit_json(explain.delete_limit(), out);
758 });
759 object.field_value_debug("consistency", &explain.consistency());
760 object.finish();
761}
762
763fn write_query_mode_json(mode: QueryMode, out: &mut String) {
764 let mut object = JsonWriter::begin_object(out);
765 match mode {
766 QueryMode::Load(spec) => {
767 object.field_str("type", "Load");
768 match spec.limit() {
769 Some(limit) => object.field_u64("limit", u64::from(limit)),
770 None => object.field_null("limit"),
771 }
772 object.field_u64("offset", u64::from(spec.offset()));
773 }
774 QueryMode::Delete(spec) => {
775 object.field_str("type", "Delete");
776 match spec.limit() {
777 Some(limit) => object.field_u64("limit", u64::from(limit)),
778 None => object.field_null("limit"),
779 }
780 }
781 }
782 object.finish();
783}
784
785fn write_pagination_json(page: &ExplainPagination, out: &mut String) {
786 let mut object = JsonWriter::begin_object(out);
787 match page {
788 ExplainPagination::None => {
789 object.field_str("type", "None");
790 }
791 ExplainPagination::Page { limit, offset } => {
792 object.field_str("type", "Page");
793 match limit {
794 Some(limit) => object.field_u64("limit", u64::from(*limit)),
795 None => object.field_null("limit"),
796 }
797 object.field_u64("offset", u64::from(*offset));
798 }
799 }
800 object.finish();
801}
802
803fn write_delete_limit_json(limit: &ExplainDeleteLimit, out: &mut String) {
804 let mut object = JsonWriter::begin_object(out);
805 match limit {
806 ExplainDeleteLimit::None => {
807 object.field_str("type", "None");
808 }
809 ExplainDeleteLimit::Limit { max_rows } => {
810 object.field_str("type", "Limit");
811 object.field_u64("max_rows", u64::from(*max_rows));
812 }
813 ExplainDeleteLimit::Window { limit, offset } => {
814 object.field_str("type", "Window");
815 object.field_with("limit", |out| match limit {
816 Some(limit) => out.push_str(&limit.to_string()),
817 None => out.push_str("null"),
818 });
819 object.field_u64("offset", u64::from(*offset));
820 }
821 }
822 object.finish();
823}