Skip to main content

icydb_core/db/query/explain/
plan.rs

1//! Module: query::explain::plan
2//! Responsibility: deterministic logical-plan projection for EXPLAIN.
3//! Does not own: execution descriptor rendering or access visitor adapters.
4//! Boundary: logical explain DTOs and plan-side projection logic.
5
6use 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, GroupHavingExpr,
17                GroupHavingValueExpr, GroupedPlanFallbackReason, LogicalPlan, OrderDirection,
18                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///
29/// ExplainPlan
30///
31/// Stable, deterministic representation of a planned query for observability.
32///
33
34#[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    /// Return query mode projected by this explain plan.
51    #[must_use]
52    pub const fn mode(&self) -> QueryMode {
53        self.mode
54    }
55
56    /// Borrow projected access-path shape.
57    #[must_use]
58    pub const fn access(&self) -> &ExplainAccessPath {
59        &self.access
60    }
61
62    /// Borrow projected predicate shape.
63    #[must_use]
64    pub const fn predicate(&self) -> &ExplainPredicate {
65        &self.predicate
66    }
67
68    /// Borrow projected ORDER BY shape.
69    #[must_use]
70    pub const fn order_by(&self) -> &ExplainOrderBy {
71        &self.order_by
72    }
73
74    /// Return whether DISTINCT is enabled.
75    #[must_use]
76    pub const fn distinct(&self) -> bool {
77        self.distinct
78    }
79
80    /// Borrow projected grouped-shape metadata.
81    #[must_use]
82    pub const fn grouping(&self) -> &ExplainGrouping {
83        &self.grouping
84    }
85
86    /// Borrow projected ORDER pushdown status.
87    #[must_use]
88    pub const fn order_pushdown(&self) -> &ExplainOrderPushdown {
89        &self.order_pushdown
90    }
91
92    /// Borrow projected pagination status.
93    #[must_use]
94    pub const fn page(&self) -> &ExplainPagination {
95        &self.page
96    }
97
98    /// Borrow projected delete-limit status.
99    #[must_use]
100    pub const fn delete_limit(&self) -> &ExplainDeleteLimit {
101        &self.delete_limit
102    }
103
104    /// Return missing-row consistency policy.
105    #[must_use]
106    pub const fn consistency(&self) -> MissingRowPolicy {
107        self.consistency
108    }
109}
110
111impl ExplainPlan {
112    /// Return the canonical predicate model used for hashing/fingerprints.
113    ///
114    /// The explain projection must remain a faithful rendering of this model.
115    #[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    /// Render this logical explain plan as deterministic canonical text.
134    ///
135    /// This surface is frontend-facing and intentionally stable for SQL/CLI
136    /// explain output and snapshot-style diagnostics.
137    #[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    /// Render this logical explain plan as canonical JSON.
166    #[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///
176/// ExplainGrouping
177///
178/// Grouped-shape annotation for deterministic explain/fingerprint surfaces.
179///
180
181#[expect(clippy::large_enum_variant)]
182#[derive(Clone, Debug, Eq, PartialEq)]
183pub enum ExplainGrouping {
184    None,
185    Grouped {
186        strategy: &'static str,
187        fallback_reason: Option<&'static str>,
188        group_fields: Vec<ExplainGroupField>,
189        aggregates: Vec<ExplainGroupAggregate>,
190        having: Option<ExplainGroupHaving>,
191        max_groups: u64,
192        max_group_bytes: u64,
193    },
194}
195
196///
197/// ExplainGroupField
198///
199/// Stable grouped-key field identity carried by explain/hash surfaces.
200///
201
202#[derive(Clone, Debug, Eq, PartialEq)]
203pub struct ExplainGroupField {
204    pub(crate) slot_index: usize,
205    pub(crate) field: String,
206}
207
208impl ExplainGroupField {
209    /// Return grouped slot index.
210    #[must_use]
211    pub const fn slot_index(&self) -> usize {
212        self.slot_index
213    }
214
215    /// Borrow grouped field name.
216    #[must_use]
217    pub const fn field(&self) -> &str {
218        self.field.as_str()
219    }
220}
221
222///
223/// ExplainGroupAggregate
224///
225/// Stable explain-surface projection of one grouped aggregate terminal.
226///
227
228#[derive(Clone, Debug, Eq, PartialEq)]
229pub struct ExplainGroupAggregate {
230    pub(crate) kind: AggregateKind,
231    pub(crate) target_field: Option<String>,
232    pub(crate) distinct: bool,
233}
234
235impl ExplainGroupAggregate {
236    /// Return grouped aggregate kind.
237    #[must_use]
238    pub const fn kind(&self) -> AggregateKind {
239        self.kind
240    }
241
242    /// Borrow optional grouped aggregate target field.
243    #[must_use]
244    pub fn target_field(&self) -> Option<&str> {
245        self.target_field.as_deref()
246    }
247
248    /// Return whether grouped aggregate uses DISTINCT input semantics.
249    #[must_use]
250    pub const fn distinct(&self) -> bool {
251        self.distinct
252    }
253}
254
255///
256/// ExplainGroupHaving
257///
258/// Deterministic explain projection of grouped HAVING clauses.
259///
260
261#[derive(Clone, Debug, Eq, PartialEq)]
262pub struct ExplainGroupHaving {
263    pub(crate) expr: ExplainGroupHavingExpr,
264}
265
266impl ExplainGroupHaving {
267    /// Borrow widened grouped HAVING expression.
268    #[must_use]
269    pub const fn expr(&self) -> &ExplainGroupHavingExpr {
270        &self.expr
271    }
272}
273
274///
275/// ExplainGroupHavingExpr
276///
277/// Stable explain-surface projection for widened grouped HAVING boolean
278/// expressions.
279///
280
281#[derive(Clone, Debug, Eq, PartialEq)]
282pub enum ExplainGroupHavingExpr {
283    Compare {
284        left: ExplainGroupHavingValueExpr,
285        op: CompareOp,
286        right: ExplainGroupHavingValueExpr,
287    },
288    And(Vec<Self>),
289}
290
291///
292/// ExplainGroupHavingValueExpr
293///
294/// Stable explain-surface projection for grouped HAVING value expressions.
295/// Leaves remain restricted to grouped keys, aggregate outputs, and literals.
296///
297
298#[derive(Clone, Debug, Eq, PartialEq)]
299pub enum ExplainGroupHavingValueExpr {
300    GroupField {
301        slot_index: usize,
302        field: String,
303    },
304    AggregateIndex {
305        index: usize,
306    },
307    Literal(Value),
308    FunctionCall {
309        function: String,
310        args: Vec<Self>,
311    },
312    Binary {
313        op: String,
314        left: Box<Self>,
315        right: Box<Self>,
316    },
317}
318
319///
320/// ExplainOrderPushdown
321///
322/// Deterministic ORDER BY pushdown eligibility reported by explain.
323///
324
325#[derive(Clone, Debug, Eq, PartialEq)]
326pub enum ExplainOrderPushdown {
327    MissingModelContext,
328    EligibleSecondaryIndex {
329        index: &'static str,
330        prefix_len: usize,
331    },
332    Rejected(SecondaryOrderPushdownRejection),
333}
334
335///
336/// ExplainAccessPath
337///
338/// Deterministic projection of logical access path shape for diagnostics.
339/// Mirrors planner-selected structural paths without runtime cursor state.
340///
341
342#[derive(Clone, Debug, Eq, PartialEq)]
343pub enum ExplainAccessPath {
344    ByKey {
345        key: Value,
346    },
347    ByKeys {
348        keys: Vec<Value>,
349    },
350    KeyRange {
351        start: Value,
352        end: Value,
353    },
354    IndexPrefix {
355        name: &'static str,
356        fields: Vec<&'static str>,
357        prefix_len: usize,
358        values: Vec<Value>,
359    },
360    IndexMultiLookup {
361        name: &'static str,
362        fields: Vec<&'static str>,
363        values: Vec<Value>,
364    },
365    IndexRange {
366        name: &'static str,
367        fields: Vec<&'static str>,
368        prefix_len: usize,
369        prefix: Vec<Value>,
370        lower: Bound<Value>,
371        upper: Bound<Value>,
372    },
373    FullScan,
374    Union(Vec<Self>),
375    Intersection(Vec<Self>),
376}
377
378///
379/// ExplainPredicate
380///
381/// Deterministic projection of canonical predicate structure for explain output.
382/// This preserves normalized predicate shape used by hashing/fingerprints.
383///
384
385#[derive(Clone, Debug, Eq, PartialEq)]
386pub enum ExplainPredicate {
387    None,
388    True,
389    False,
390    And(Vec<Self>),
391    Or(Vec<Self>),
392    Not(Box<Self>),
393    Compare {
394        field: String,
395        op: CompareOp,
396        value: Value,
397        coercion: CoercionSpec,
398    },
399    CompareFields {
400        left_field: String,
401        op: CompareOp,
402        right_field: String,
403        coercion: CoercionSpec,
404    },
405    IsNull {
406        field: String,
407    },
408    IsNotNull {
409        field: String,
410    },
411    IsMissing {
412        field: String,
413    },
414    IsEmpty {
415        field: String,
416    },
417    IsNotEmpty {
418        field: String,
419    },
420    TextContains {
421        field: String,
422        value: Value,
423    },
424    TextContainsCi {
425        field: String,
426        value: Value,
427    },
428}
429
430///
431/// ExplainOrderBy
432///
433/// Deterministic projection of canonical ORDER BY shape.
434///
435
436#[derive(Clone, Debug, Eq, PartialEq)]
437pub enum ExplainOrderBy {
438    None,
439    Fields(Vec<ExplainOrder>),
440}
441
442///
443/// ExplainOrder
444///
445/// One canonical ORDER BY field + direction pair.
446///
447
448#[derive(Clone, Debug, Eq, PartialEq)]
449pub struct ExplainOrder {
450    pub(crate) field: String,
451    pub(crate) direction: OrderDirection,
452}
453
454impl ExplainOrder {
455    /// Borrow ORDER BY field name.
456    #[must_use]
457    pub const fn field(&self) -> &str {
458        self.field.as_str()
459    }
460
461    /// Return ORDER BY direction.
462    #[must_use]
463    pub const fn direction(&self) -> OrderDirection {
464        self.direction
465    }
466}
467
468///
469/// ExplainPagination
470///
471/// Explain-surface projection of pagination window configuration.
472///
473
474#[derive(Clone, Debug, Eq, PartialEq)]
475pub enum ExplainPagination {
476    None,
477    Page { limit: Option<u32>, offset: u32 },
478}
479
480///
481/// ExplainDeleteLimit
482///
483/// Explain-surface projection of delete-limit configuration.
484///
485
486#[derive(Clone, Debug, Eq, PartialEq)]
487pub enum ExplainDeleteLimit {
488    None,
489    Limit { max_rows: u32 },
490    Window { limit: Option<u32>, offset: u32 },
491}
492
493impl AccessPlannedQuery {
494    /// Produce a stable, deterministic explanation of this logical plan.
495    #[must_use]
496    #[cfg(test)]
497    pub(crate) fn explain(&self) -> ExplainPlan {
498        self.explain_inner(None)
499    }
500
501    /// Produce a stable, deterministic explanation of this logical plan
502    /// with optional model context for query-layer projections.
503    ///
504    /// Query explain intentionally does not evaluate executor route pushdown
505    /// feasibility to keep query-layer dependencies executor-agnostic.
506    #[must_use]
507    pub(crate) fn explain_with_model(&self, model: &EntityModel) -> ExplainPlan {
508        self.explain_inner(Some(model))
509    }
510
511    pub(in crate::db::query::explain) fn explain_inner(
512        &self,
513        model: Option<&EntityModel>,
514    ) -> ExplainPlan {
515        // Phase 1: project logical plan variant into scalar core + grouped metadata.
516        let (logical, grouping) = match &self.logical {
517            LogicalPlan::Scalar(logical) => (logical, ExplainGrouping::None),
518            LogicalPlan::Grouped(logical) => {
519                let grouped_strategy = grouped_plan_strategy(self).expect(
520                    "grouped logical explain projection requires planner-owned grouped strategy",
521                );
522
523                (
524                    &logical.scalar,
525                    ExplainGrouping::Grouped {
526                        strategy: grouped_strategy.code(),
527                        fallback_reason: grouped_strategy
528                            .fallback_reason()
529                            .map(GroupedPlanFallbackReason::code),
530                        group_fields: logical
531                            .group
532                            .group_fields
533                            .iter()
534                            .map(|field_slot| ExplainGroupField {
535                                slot_index: field_slot.index(),
536                                field: field_slot.field().to_string(),
537                            })
538                            .collect(),
539                        aggregates: logical
540                            .group
541                            .aggregates
542                            .iter()
543                            .map(|aggregate| ExplainGroupAggregate {
544                                kind: aggregate.kind,
545                                target_field: aggregate.target_field.clone(),
546                                distinct: aggregate.distinct,
547                            })
548                            .collect(),
549                        having: explain_group_having(logical),
550                        max_groups: logical.group.execution.max_groups(),
551                        max_group_bytes: logical.group.execution.max_group_bytes(),
552                    },
553                )
554            }
555        };
556
557        // Phase 2: project scalar plan + access path into deterministic explain surface.
558        explain_scalar_inner(logical, grouping, model, &self.access)
559    }
560}
561
562fn explain_group_having(logical: &crate::db::query::plan::GroupPlan) -> Option<ExplainGroupHaving> {
563    let expr = logical.effective_having_expr()?;
564
565    Some(ExplainGroupHaving {
566        expr: explain_group_having_expr(expr.as_ref()),
567    })
568}
569
570fn explain_group_having_expr(expr: &GroupHavingExpr) -> ExplainGroupHavingExpr {
571    match expr {
572        GroupHavingExpr::Compare { left, op, right } => ExplainGroupHavingExpr::Compare {
573            left: explain_group_having_value_expr(left),
574            op: *op,
575            right: explain_group_having_value_expr(right),
576        },
577        GroupHavingExpr::And(children) => {
578            ExplainGroupHavingExpr::And(children.iter().map(explain_group_having_expr).collect())
579        }
580    }
581}
582
583fn explain_group_having_value_expr(expr: &GroupHavingValueExpr) -> ExplainGroupHavingValueExpr {
584    match expr {
585        GroupHavingValueExpr::GroupField(field_slot) => ExplainGroupHavingValueExpr::GroupField {
586            slot_index: field_slot.index(),
587            field: field_slot.field().to_string(),
588        },
589        GroupHavingValueExpr::AggregateIndex(index) => {
590            ExplainGroupHavingValueExpr::AggregateIndex { index: *index }
591        }
592        GroupHavingValueExpr::Literal(value) => ExplainGroupHavingValueExpr::Literal(value.clone()),
593        GroupHavingValueExpr::FunctionCall { function, args } => {
594            ExplainGroupHavingValueExpr::FunctionCall {
595                function: function.sql_label().to_string(),
596                args: args.iter().map(explain_group_having_value_expr).collect(),
597            }
598        }
599        GroupHavingValueExpr::Binary { op, left, right } => ExplainGroupHavingValueExpr::Binary {
600            op: explain_group_having_binary_op_label(*op).to_string(),
601            left: Box::new(explain_group_having_value_expr(left)),
602            right: Box::new(explain_group_having_value_expr(right)),
603        },
604    }
605}
606
607const fn explain_group_having_binary_op_label(
608    op: crate::db::query::plan::expr::BinaryOp,
609) -> &'static str {
610    match op {
611        crate::db::query::plan::expr::BinaryOp::Add => "+",
612        crate::db::query::plan::expr::BinaryOp::Sub => "-",
613        crate::db::query::plan::expr::BinaryOp::Mul => "*",
614        crate::db::query::plan::expr::BinaryOp::Div => "/",
615        #[cfg(test)]
616        crate::db::query::plan::expr::BinaryOp::And => "AND",
617        #[cfg(test)]
618        crate::db::query::plan::expr::BinaryOp::Eq => "=",
619    }
620}
621
622fn explain_scalar_inner<K>(
623    logical: &ScalarPlan,
624    grouping: ExplainGrouping,
625    model: Option<&EntityModel>,
626    access: &AccessPlan<K>,
627) -> ExplainPlan
628where
629    K: FieldValue,
630{
631    // Phase 1: consume canonical predicate model from planner-owned scalar semantics.
632    let predicate_model = logical.predicate.clone();
633    let predicate = match &predicate_model {
634        Some(predicate) => ExplainPredicate::from_predicate(predicate),
635        None => ExplainPredicate::None,
636    };
637
638    // Phase 2: project scalar-plan fields into explain-specific enums.
639    let order_by = explain_order(logical.order.as_ref());
640    let order_pushdown = explain_order_pushdown(model);
641    let page = explain_page(logical.page.as_ref());
642    let delete_limit = explain_delete_limit(logical.delete_limit.as_ref());
643
644    // Phase 3: assemble one stable explain payload.
645    ExplainPlan {
646        mode: logical.mode,
647        access: ExplainAccessPath::from_access_plan(access),
648        predicate,
649        predicate_model,
650        order_by,
651        distinct: logical.distinct,
652        grouping,
653        order_pushdown,
654        page,
655        delete_limit,
656        consistency: logical.consistency,
657    }
658}
659
660const fn explain_order_pushdown(model: Option<&EntityModel>) -> ExplainOrderPushdown {
661    let _ = model;
662
663    // Query explain does not own physical pushdown feasibility routing.
664    ExplainOrderPushdown::MissingModelContext
665}
666
667impl From<SecondaryOrderPushdownEligibility> for ExplainOrderPushdown {
668    fn from(value: SecondaryOrderPushdownEligibility) -> Self {
669        Self::from(PushdownSurfaceEligibility::from(&value))
670    }
671}
672
673impl From<PushdownSurfaceEligibility<'_>> for ExplainOrderPushdown {
674    fn from(value: PushdownSurfaceEligibility<'_>) -> Self {
675        match value {
676            PushdownSurfaceEligibility::EligibleSecondaryIndex { index, prefix_len } => {
677                Self::EligibleSecondaryIndex { index, prefix_len }
678            }
679            PushdownSurfaceEligibility::Rejected { reason } => Self::Rejected(reason.clone()),
680        }
681    }
682}
683
684impl ExplainPredicate {
685    pub(in crate::db) fn from_predicate(predicate: &Predicate) -> Self {
686        match predicate {
687            Predicate::True => Self::True,
688            Predicate::False => Self::False,
689            Predicate::And(children) => {
690                Self::And(children.iter().map(Self::from_predicate).collect())
691            }
692            Predicate::Or(children) => {
693                Self::Or(children.iter().map(Self::from_predicate).collect())
694            }
695            Predicate::Not(inner) => Self::Not(Box::new(Self::from_predicate(inner))),
696            Predicate::Compare(compare) => Self::from_compare(compare),
697            Predicate::CompareFields(compare) => Self::CompareFields {
698                left_field: compare.left_field().to_string(),
699                op: compare.op(),
700                right_field: compare.right_field().to_string(),
701                coercion: compare.coercion().clone(),
702            },
703            Predicate::IsNull { field } => Self::IsNull {
704                field: field.clone(),
705            },
706            Predicate::IsNotNull { field } => Self::IsNotNull {
707                field: field.clone(),
708            },
709            Predicate::IsMissing { field } => Self::IsMissing {
710                field: field.clone(),
711            },
712            Predicate::IsEmpty { field } => Self::IsEmpty {
713                field: field.clone(),
714            },
715            Predicate::IsNotEmpty { field } => Self::IsNotEmpty {
716                field: field.clone(),
717            },
718            Predicate::TextContains { field, value } => Self::TextContains {
719                field: field.clone(),
720                value: value.clone(),
721            },
722            Predicate::TextContainsCi { field, value } => Self::TextContainsCi {
723                field: field.clone(),
724                value: value.clone(),
725            },
726        }
727    }
728
729    fn from_compare(compare: &ComparePredicate) -> Self {
730        Self::Compare {
731            field: compare.field.clone(),
732            op: compare.op,
733            value: compare.value.clone(),
734            coercion: compare.coercion.clone(),
735        }
736    }
737}
738
739fn explain_order(order: Option<&OrderSpec>) -> ExplainOrderBy {
740    let Some(order) = order else {
741        return ExplainOrderBy::None;
742    };
743
744    if order.fields.is_empty() {
745        return ExplainOrderBy::None;
746    }
747
748    ExplainOrderBy::Fields(
749        order
750            .fields
751            .iter()
752            .map(|(field, direction)| ExplainOrder {
753                field: field.clone(),
754                direction: *direction,
755            })
756            .collect(),
757    )
758}
759
760const fn explain_page(page: Option<&PageSpec>) -> ExplainPagination {
761    match page {
762        Some(page) => ExplainPagination::Page {
763            limit: page.limit,
764            offset: page.offset,
765        },
766        None => ExplainPagination::None,
767    }
768}
769
770const fn explain_delete_limit(limit: Option<&DeleteLimitSpec>) -> ExplainDeleteLimit {
771    match limit {
772        Some(limit) if limit.offset == 0 => match limit.limit {
773            Some(max_rows) => ExplainDeleteLimit::Limit { max_rows },
774            None => ExplainDeleteLimit::Window {
775                limit: None,
776                offset: 0,
777            },
778        },
779        Some(limit) => ExplainDeleteLimit::Window {
780            limit: limit.limit,
781            offset: limit.offset,
782        },
783        None => ExplainDeleteLimit::None,
784    }
785}
786
787fn write_logical_explain_json(explain: &ExplainPlan, out: &mut String) {
788    let mut object = JsonWriter::begin_object(out);
789    object.field_with("mode", |out| write_query_mode_json(explain.mode(), out));
790    object.field_with("access", |out| write_access_json(explain.access(), out));
791    object.field_value_debug("predicate", explain.predicate());
792    object.field_value_debug("order_by", explain.order_by());
793    object.field_bool("distinct", explain.distinct());
794    object.field_value_debug("grouping", explain.grouping());
795    object.field_value_debug("order_pushdown", explain.order_pushdown());
796    object.field_with("page", |out| write_pagination_json(explain.page(), out));
797    object.field_with("delete_limit", |out| {
798        write_delete_limit_json(explain.delete_limit(), out);
799    });
800    object.field_value_debug("consistency", &explain.consistency());
801    object.finish();
802}
803
804fn write_query_mode_json(mode: QueryMode, out: &mut String) {
805    let mut object = JsonWriter::begin_object(out);
806    match mode {
807        QueryMode::Load(spec) => {
808            object.field_str("type", "Load");
809            match spec.limit() {
810                Some(limit) => object.field_u64("limit", u64::from(limit)),
811                None => object.field_null("limit"),
812            }
813            object.field_u64("offset", u64::from(spec.offset()));
814        }
815        QueryMode::Delete(spec) => {
816            object.field_str("type", "Delete");
817            match spec.limit() {
818                Some(limit) => object.field_u64("limit", u64::from(limit)),
819                None => object.field_null("limit"),
820            }
821        }
822    }
823    object.finish();
824}
825
826fn write_pagination_json(page: &ExplainPagination, out: &mut String) {
827    let mut object = JsonWriter::begin_object(out);
828    match page {
829        ExplainPagination::None => {
830            object.field_str("type", "None");
831        }
832        ExplainPagination::Page { limit, offset } => {
833            object.field_str("type", "Page");
834            match limit {
835                Some(limit) => object.field_u64("limit", u64::from(*limit)),
836                None => object.field_null("limit"),
837            }
838            object.field_u64("offset", u64::from(*offset));
839        }
840    }
841    object.finish();
842}
843
844fn write_delete_limit_json(limit: &ExplainDeleteLimit, out: &mut String) {
845    let mut object = JsonWriter::begin_object(out);
846    match limit {
847        ExplainDeleteLimit::None => {
848            object.field_str("type", "None");
849        }
850        ExplainDeleteLimit::Limit { max_rows } => {
851            object.field_str("type", "Limit");
852            object.field_u64("max_rows", u64::from(*max_rows));
853        }
854        ExplainDeleteLimit::Window { limit, offset } => {
855            object.field_str("type", "Window");
856            object.field_with("limit", |out| match limit {
857                Some(limit) => out.push_str(&limit.to_string()),
858                None => out.push_str("null"),
859            });
860            object.field_u64("offset", u64::from(*offset));
861        }
862    }
863    object.finish();
864}